func JSONHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) { resp, ok := w.(*ahttp.ResponseWriter) if !ok { panic("ResponseWriter is not ahttp.ResponseWriter") } jsonresponse.Handler(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { w.Write([]byte(fmt.Sprintf(`{"status":%d,"title":"%s","detail":"%s"}`, resp.HTTPStatus, http.StatusText(resp.HTTPStatus), resp.HTTPError))) })(ctx, w, r) }
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) }