Ejemplo n.º 1
0
func (s *Server) Handler(w http.ResponseWriter, req *http.Request) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	ctx = context.WithValue(ctx, "app.database", s.DB)
	ctx = context.WithValue(ctx, "app.config", s.Cfg)
	ctx = context.WithValue(ctx, "http.endpoints", api.Endpoints)

	mlog.Handler(api.Handler)(ctx, ahttp.NewResponseWriter(w), req)
}
Ejemplo n.º 2
0
func Handler(fn ahttp.Handler) ahttp.Handler {
	return func(ctx context.Context, resp http.ResponseWriter, req *http.Request) {
		ctx = context.WithValue(ctx, "http.request.method", req.Method)
		ctx = context.WithValue(ctx, "http.request.remoteaddr", req.RemoteAddr)
		ctx = context.WithValue(ctx, "http.request.length", req.ContentLength)
		ctx = context.WithValue(ctx, "http.request.time", time.Now().String())

		defer func() {
			e := logger.GetHTTPEntry(ctx)
			e = e.WithField("http.response.time", time.Now().String())

			if w, ok := resp.(*ahttp.ResponseWriter); ok {
				e = e.WithField("http.response.length", w.ResponseLength)
				e = e.WithField("http.response.status", w.HTTPStatus)
				e = e.WithField("http.response.error", w.HTTPError)
			}
			e.Info(req.URL)
		}()

		fn(ctx, resp, req)
	}
}
Ejemplo n.º 3
0
func Handler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	info, ok := ctx.Value("http.endpoints").(*EndpointsInfo)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain API information from context")
		InternalServerErrorHandler(ctx, w, r)
		return
	}

	p := r.URL.Query()

	for _, a := range info.Endpoints {
		match := a.Regexp.FindStringSubmatch(r.URL.Path)
		if match == nil {
			continue
		}

		for i, name := range a.Regexp.SubexpNames() {
			if i == 0 {
				continue
			}
			p.Set(name, match[i])
		}

		ctx = context.WithValue(ctx, "http.request.query.params", &p)

		var reqHandler ahttp.Handler

		if v, ok := a.Handlers[r.Method]; ok {
			reqHandler = v

			if a.NeedDBHandler {
				reqHandler = db.Handler(reqHandler)
			}

			if a.NeedJSONHandler {
				reqHandler = jsonresponse.Handler(reqHandler)
			}
		} else {
			reqHandler = NotAllowedHandler
		}

		reqHandler(ctx, w, r)
		return
	}

	// Never should be here
	NotFoundHandler(ctx, w, r)
}