e7
1/8/2018 - 9:33 AM

negroni的middleware示例

negroni的middleware示例

type bodyParser struct{
	unused int;
}

func NewBodyParser() (*bodyParser){
	return &bodyParser{}
}

func (m *bodyParser) ServeHTTP(rsp http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	var err error

	rsp.Header().Set("Content-Type", "application/json;charset=utf-8")

	data, _ := ioutil.ReadAll(req.Body)
	dict := make(map[string]string)
	if err = json.Unmarshal(data, &dict); err != nil {
		logrus.Errorf("qiniu replied invalid json:%s", err.Error())
		rsp.WriteHeader(http.StatusBadRequest)
		return
	}

	next(rsp, req.WithContext(
		context.WithValue(req.Context(), "req-map", dict)),
	)
}