1
0
mirror of https://github.com/rancher/norman.git synced 2025-09-02 15:54:32 +00:00

APIContext constructor

This commit is contained in:
Darren Shepherd
2018-01-19 21:29:24 -07:00
parent dfade4fcef
commit aa2538a874
2 changed files with 21 additions and 8 deletions

View File

@@ -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

View File

@@ -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)
}