Пример #1
0
func contentType(req *http.Request) int {
	str := httputil.NegotiateContentType(req, []string{"text/plain", "application/json"}, "text/plain")
	if str == "application/json" {
		return ContentJSON
	} else {
		return ContentText
	}
}
Пример #2
0
func TestNegotiateContentType(t *testing.T) {
	for _, tt := range negotiateContentTypeTests {
		r := &http.Request{Header: http.Header{"Accept": {tt.s}}}
		actual := httputil.NegotiateContentType(r, tt.offers, tt.defaultOffer)
		if actual != tt.expect {
			t.Errorf("NegotiateContentType(%q, %#v, %q)=%q, want %q", tt.s, tt.offers, tt.defaultOffer, actual, tt.expect)
		}
	}
}
Пример #3
0
// ResponseFormat negotiates the response content type
func (c *Context) ResponseFormat(r *http.Request, offers []string) string {
	if v, ok := context.GetOk(r, ctxResponseFormat); ok {
		if val, ok := v.(string); ok {
			return val
		}
	}

	format := httputil.NegotiateContentType(r, offers, "")
	if format != "" {
		context.Set(r, ctxResponseFormat, format)
	}
	return format
}
Пример #4
0
// EncodeResponse uses registered Encoders to marshal the response body based on the request
// `Accept` header and writes it to the http.ResponseWriter
func (app *Application) EncodeResponse(ctx *Context, v interface{}) error {
	contentType := httputil.NegotiateContentType(ctx.Request(), app.encodableContentTypes, "*/*")
	p := app.encoderPools[contentType]

	// the encoderPool will handle whether or not a pool is actually in use
	encoder := p.Get(ctx)
	if err := encoder.Encode(v); err != nil {
		// TODO: log out error details
		return err
	}
	p.Put(encoder)

	return nil
}
Пример #5
0
// TypeNegotiator returns a content type negotiation handler.
//
// The method takes a list of response MIME types that are supported by the application.
// The negotiator will determine the best response MIME type to use by checking the "Accept" HTTP header.
// If no match is found, the first MIME type will be used.
//
// The negotiator will set the "Content-Type" response header as the chosen MIME type. It will call routing.Context.SetDataWriter()
// to set the appropriate data writer that can write data in the negotiated format.
//
// If you do not specify any supported MIME types, the negotiator will use "text/html" as the response MIME type.
func TypeNegotiator(formats ...string) routing.Handler {
	if len(formats) == 0 {
		formats = []string{HTML}
	}
	for _, format := range formats {
		if _, ok := DataWriters[format]; !ok {
			panic(format + " is not supported")
		}
	}

	return func(c *routing.Context) error {
		format := httputil.NegotiateContentType(c.Request, formats, formats[0])
		DataWriters[format].SetHeader(c.Response)
		c.SetDataWriter(DataWriters[format])
		return nil
	}
}
Пример #6
0
func contentType(req *http.Request) int {
	str := httputil.NegotiateContentType(req, []string{
		"text/plain",
		"application/json",
		"application/yaml",
		"application/x-yaml",
		"text/yaml",
		"text/x-yaml",
	}, "text/plain")

	if strings.Contains(str, "json") {
		return ContentJSON
	} else if strings.Contains(str, "yaml") {
		return ContentYAML
	} else {
		return ContentText
	}
}
Пример #7
0
func selectContentMarshaler(r *http.Request, marshalers map[string]ContentMarshaler) (marshaler ContentMarshaler, contentType string) {
	if _, found := r.Header["Accept"]; found {
		var contentTypes []string
		for ct := range marshalers {
			contentTypes = append(contentTypes, ct)
		}

		contentType = httputil.NegotiateContentType(r, contentTypes, defaultContentTypHeader)
		marshaler = marshalers[contentType]
	} else if contentTypes, found := r.Header["Content-Type"]; found {
		contentType = contentTypes[0]
		marshaler = marshalers[contentType]
	}

	if marshaler == nil {
		contentType = defaultContentTypHeader
		marshaler = JSONContentMarshaler{}
	}

	return
}
Пример #8
0
// BindValidRequest binds a params object to a request but only when the request is valid
// if the request is not valid an error will be returned
func (c *Context) BindValidRequest(request *http.Request, route *MatchedRoute, binder RequestBinder) error {
	var res []error

	// check and validate content type, select consumer
	if httpkit.CanHaveBody(request.Method) {
		ct, _, err := httpkit.ContentType(request.Header)
		if err != nil {
			res = append(res, err)
		} else {
			if err := validateContentType(route.Consumes, ct); err != nil {
				res = append(res, err)
			}
			route.Consumer = route.Consumers[ct]
		}
	}

	// check and validate the response format
	if len(res) == 0 {
		if str := httputil.NegotiateContentType(request, route.Produces, ""); str == "" {
			res = append(res, errors.InvalidResponseFormat(request.Header.Get(httpkit.HeaderAccept), route.Produces))
		}
	}

	// now bind the request with the provided binder
	// it's assumed the binder will also validate the request and return an error if the
	// request is invalid
	if binder != nil && len(res) == 0 {
		if err := binder.BindRequest(request, route); err != nil {
			res = append(res, err)
		}
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}
Пример #9
0
func templateExt(req *http.Request) string {
	if httputil.NegotiateContentType(req, []string{"text/html", "text/plain"}, "text/html") == "text/plain" {
		return ".txt"
	}
	return ".html"
}