2022-05-20 11:45:18 -05:00
|
|
|
//nolint:unused,deadcode
|
|
|
|
package response
|
|
|
|
|
|
|
|
//NOTE: This file belongs into pkg/web, but due to cyclic imports that are hard to resolve at the current time, it temporarily lives here.
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/grafana/grafana/pkg/models"
|
|
|
|
"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
|
|
|
|
"github.com/grafana/grafana/pkg/web"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
handlerStd = func(http.ResponseWriter, *http.Request)
|
|
|
|
handlerStdCtx = func(http.ResponseWriter, *http.Request, *web.Context)
|
|
|
|
handlerStdReqCtx = func(http.ResponseWriter, *http.Request, *models.ReqContext)
|
|
|
|
handlerReqCtx = func(*models.ReqContext)
|
|
|
|
handlerReqCtxRes = func(*models.ReqContext) Response
|
|
|
|
handlerCtx = func(*web.Context)
|
|
|
|
)
|
|
|
|
|
|
|
|
func wrap_handler(h web.Handler) http.HandlerFunc {
|
|
|
|
switch handle := h.(type) {
|
2022-08-09 07:58:50 -05:00
|
|
|
case http.HandlerFunc:
|
|
|
|
return handle
|
2022-05-20 11:45:18 -05:00
|
|
|
case handlerStd:
|
|
|
|
return handle
|
|
|
|
case handlerStdCtx:
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2022-08-09 07:58:50 -05:00
|
|
|
handle(w, r, webCtx(w, r))
|
2022-05-20 11:45:18 -05:00
|
|
|
}
|
|
|
|
case handlerStdReqCtx:
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2022-08-09 07:58:50 -05:00
|
|
|
handle(w, r, reqCtx(w, r))
|
2022-05-20 11:45:18 -05:00
|
|
|
}
|
|
|
|
case handlerReqCtx:
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2022-08-09 07:58:50 -05:00
|
|
|
handle(reqCtx(w, r))
|
2022-05-20 11:45:18 -05:00
|
|
|
}
|
|
|
|
case handlerReqCtxRes:
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2022-08-09 07:58:50 -05:00
|
|
|
ctx := reqCtx(w, r)
|
2022-05-20 11:45:18 -05:00
|
|
|
res := handle(ctx)
|
2022-05-26 07:34:04 -05:00
|
|
|
if res != nil {
|
|
|
|
res.WriteTo(ctx)
|
|
|
|
}
|
2022-05-20 11:45:18 -05:00
|
|
|
}
|
|
|
|
case handlerCtx:
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2022-08-09 07:58:50 -05:00
|
|
|
handle(webCtx(w, r))
|
2022-05-20 11:45:18 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
panic(fmt.Sprintf("unexpected handler type: %T", h))
|
|
|
|
}
|
|
|
|
|
2022-08-09 07:58:50 -05:00
|
|
|
func webCtx(w http.ResponseWriter, r *http.Request) *web.Context {
|
|
|
|
ctx := web.FromContext(r.Context())
|
|
|
|
if ctx == nil {
|
|
|
|
panic("no *web.Context found")
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.Req = r
|
|
|
|
ctx.Resp = web.Rw(w, r)
|
|
|
|
return ctx
|
|
|
|
}
|
|
|
|
|
|
|
|
func reqCtx(w http.ResponseWriter, r *http.Request) *models.ReqContext {
|
|
|
|
wCtx := webCtx(w, r)
|
|
|
|
reqCtx, ok := wCtx.Req.Context().Value(ctxkey.Key{}).(*models.ReqContext)
|
2022-05-20 11:45:18 -05:00
|
|
|
if !ok {
|
|
|
|
panic("no *models.ReqContext found")
|
|
|
|
}
|
|
|
|
return reqCtx
|
|
|
|
}
|