podman

Форк
0
126 строк · 3.7 Кб
1
// Copyright 2015 go-swagger maintainers
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//    http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15
package middleware
16

17
import (
18
	"mime"
19
	"net/http"
20
	"strings"
21

22
	"github.com/go-openapi/errors"
23
	"github.com/go-openapi/swag"
24

25
	"github.com/go-openapi/runtime"
26
)
27

28
type validation struct {
29
	context *Context
30
	result  []error
31
	request *http.Request
32
	route   *MatchedRoute
33
	bound   map[string]interface{}
34
}
35

36
// ContentType validates the content type of a request
37
func validateContentType(allowed []string, actual string) error {
38
	debugLog("validating content type for %q against [%s]", actual, strings.Join(allowed, ", "))
39
	if len(allowed) == 0 {
40
		return nil
41
	}
42
	mt, _, err := mime.ParseMediaType(actual)
43
	if err != nil {
44
		return errors.InvalidContentType(actual, allowed)
45
	}
46
	if swag.ContainsStringsCI(allowed, mt) {
47
		return nil
48
	}
49
	if swag.ContainsStringsCI(allowed, "*/*") {
50
		return nil
51
	}
52
	parts := strings.Split(actual, "/")
53
	if len(parts) == 2 && swag.ContainsStringsCI(allowed, parts[0]+"/*") {
54
		return nil
55
	}
56
	return errors.InvalidContentType(actual, allowed)
57
}
58

59
func validateRequest(ctx *Context, request *http.Request, route *MatchedRoute) *validation {
60
	debugLog("validating request %s %s", request.Method, request.URL.EscapedPath())
61
	validate := &validation{
62
		context: ctx,
63
		request: request,
64
		route:   route,
65
		bound:   make(map[string]interface{}),
66
	}
67

68
	validate.contentType()
69
	if len(validate.result) == 0 {
70
		validate.responseFormat()
71
	}
72
	if len(validate.result) == 0 {
73
		validate.parameters()
74
	}
75

76
	return validate
77
}
78

79
func (v *validation) parameters() {
80
	debugLog("validating request parameters for %s %s", v.request.Method, v.request.URL.EscapedPath())
81
	if result := v.route.Binder.Bind(v.request, v.route.Params, v.route.Consumer, v.bound); result != nil {
82
		if result.Error() == "validation failure list" {
83
			for _, e := range result.(*errors.Validation).Value.([]interface{}) {
84
				v.result = append(v.result, e.(error))
85
			}
86
			return
87
		}
88
		v.result = append(v.result, result)
89
	}
90
}
91

92
func (v *validation) contentType() {
93
	if len(v.result) == 0 && runtime.HasBody(v.request) {
94
		debugLog("validating body content type for %s %s", v.request.Method, v.request.URL.EscapedPath())
95
		ct, _, req, err := v.context.ContentType(v.request)
96
		if err != nil {
97
			v.result = append(v.result, err)
98
		} else {
99
			v.request = req
100
		}
101

102
		if len(v.result) == 0 {
103
			if err := validateContentType(v.route.Consumes, ct); err != nil {
104
				v.result = append(v.result, err)
105
			}
106
		}
107
		if ct != "" && v.route.Consumer == nil {
108
			cons, ok := v.route.Consumers[ct]
109
			if !ok {
110
				v.result = append(v.result, errors.New(500, "no consumer registered for %s", ct))
111
			} else {
112
				v.route.Consumer = cons
113
			}
114
		}
115
	}
116
}
117

118
func (v *validation) responseFormat() {
119
	// if the route provides values for Produces and no format could be identify then return an error.
120
	// if the route does not specify values for Produces then treat request as valid since the API designer
121
	// choose not to specify the format for responses.
122
	if str, rCtx := v.context.ResponseFormat(v.request, v.route.Produces); str == "" && len(v.route.Produces) > 0 {
123
		v.request = rCtx
124
		v.result = append(v.result, errors.InvalidResponseFormat(v.request.Header.Get(runtime.HeaderAccept), v.route.Produces))
125
	}
126
}
127

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.