예제 #1
0
func NewServer(config *config.ServerConfig, store *data.Store, logger logging.Logger) *Server {
	return &Server{
		config: config,
		store:  store,
		logger: logger.WithContext(map[string]interface{}{"package": "server"}),
	}
}
예제 #2
0
func wrap(logger logging.Logger, handler func(req *http.Request) (interface{}, error)) func(resp http.ResponseWriter, req *http.Request) {
	f := func(resp http.ResponseWriter, req *http.Request) {
		logger := logger.WithContext(map[string]interface{}{"url": req.URL, "method": req.Method})
		start := time.Now()
		defer func() {
			logger.Debugf("http: Request (%v)", time.Now().Sub(start))
		}()
		obj, err := handler(req)
		if err != nil {
			sendError(logger, resp, req, err)
			return
		}
		if obj != nil {
			var buf []byte
			buf, err = json.Marshal(obj)
			if err != nil {
				sendError(logger, resp, req, err)
				return
			}
			resp.Header().Set("Content-Type", "application/json")
			resp.Write(buf)
		} else {
			resp.WriteHeader(http.StatusNoContent)
		}
	}
	return f
}
예제 #3
0
func sendError(logger logging.Logger, resp http.ResponseWriter, req *http.Request, err error) {
	logger.ErrorErr(err)
	code := 500
	errMsg := err.Error()
	switch err.(type) {
	case *HTTPError:
		code = err.(*HTTPError).Status
		errMsg = err.(*HTTPError).Message
	}
	resp.WriteHeader(code)
	resp.Write([]byte(errMsg))
	return
}
예제 #4
0
func NewObserverGroup(logger logging.Logger) *ObserverGroup {
	return &ObserverGroup{
		logger: logger.WithContext(map[string]interface{}{"package": "util", "type": "ObserverGroup"}),
	}
}