diff --git a/parse/parse.go b/parse/parse.go index f234b169..946e1faa 100644 --- a/parse/parse.go +++ b/parse/parse.go @@ -69,14 +69,9 @@ func DefaultURLParser(schemas *types.Schemas, url *url.URL) (ParsedURL, error) { func Parse(rw http.ResponseWriter, req *http.Request, schemas *types.Schemas, urlParser URLParser, resolverFunc ResolverFunc) (*types.APIContext, error) { var err error - result := &types.APIContext{ - Schemas: schemas, - Request: req, - Response: rw, - Method: parseMethod(req), - ResponseFormat: parseResponseFormat(req), - } - + result := types.NewAPIContext(req, rw, schemas) + result.Method = parseMethod(req) + result.ResponseFormat = parseResponseFormat(req) result.URLBuilder, _ = urlbuilder.New(req, types.APIVersion{}, schemas) // The response format is guarenteed to be set even in the event of an error diff --git a/types/server_types.go b/types/server_types.go index 0c609f25..ccbe607d 100644 --- a/types/server_types.go +++ b/types/server_types.go @@ -1,6 +1,7 @@ package types import ( + "context" "encoding/json" "net/http" "net/url" @@ -100,6 +101,23 @@ type APIContext struct { Response http.ResponseWriter } +type apiContextKey struct{} + +func NewAPIContext(req *http.Request, resp http.ResponseWriter, schemas *Schemas) *APIContext { + apiCtx := &APIContext{ + Response: resp, + Schemas: schemas, + } + ctx := context.WithValue(req.Context(), apiContextKey{}, apiCtx) + apiCtx.Request = req.WithContext(ctx) + return apiCtx +} + +func GetAPIContext(ctx context.Context) *APIContext { + apiContext, _ := ctx.Value(apiContextKey{}).(*APIContext) + return apiContext +} + func (r *APIContext) WriteResponse(code int, obj interface{}) { r.ResponseWriter.Write(r, code, obj) }