blob: 87b73da45c2ebd89269c1eca381cb4b28dc2f5e4 [file] [log] [blame]
Serge Bazanskicc25bdf2018-10-25 14:02:58 +02001// 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
15package runtime
16
17import (
18 "io"
19 "net/http"
20 "strings"
21
22 "github.com/go-openapi/swag"
23)
24
25// CanHaveBody returns true if this method can have a body
26func CanHaveBody(method string) bool {
27 mn := strings.ToUpper(method)
28 return mn == "POST" || mn == "PUT" || mn == "PATCH" || mn == "DELETE"
29}
30
31// IsSafe returns true if this is a request with a safe method
32func IsSafe(r *http.Request) bool {
33 mn := strings.ToUpper(r.Method)
34 return mn == "GET" || mn == "HEAD"
35}
36
37// AllowsBody returns true if the request allows for a body
38func AllowsBody(r *http.Request) bool {
39 mn := strings.ToUpper(r.Method)
40 return mn != "HEAD"
41}
42
43// HasBody returns true if this method needs a content-type
44func HasBody(r *http.Request) bool {
45 return len(r.TransferEncoding) > 0 || r.ContentLength > 0
46}
47
48// JSONRequest creates a new http request with json headers set
49func JSONRequest(method, urlStr string, body io.Reader) (*http.Request, error) {
50 req, err := http.NewRequest(method, urlStr, body)
51 if err != nil {
52 return nil, err
53 }
54 req.Header.Add(HeaderContentType, JSONMime)
55 req.Header.Add(HeaderAccept, JSONMime)
56 return req, nil
57}
58
59// Gettable for things with a method GetOK(string) (data string, hasKey bool, hasValue bool)
60type Gettable interface {
61 GetOK(string) ([]string, bool, bool)
62}
63
64// ReadSingleValue reads a single value from the source
65func ReadSingleValue(values Gettable, name string) string {
66 vv, _, hv := values.GetOK(name)
67 if hv {
68 return vv[len(vv)-1]
69 }
70 return ""
71}
72
73// ReadCollectionValue reads a collection value from a string data source
74func ReadCollectionValue(values Gettable, name, collectionFormat string) []string {
75 v := ReadSingleValue(values, name)
76 return swag.SplitByFormat(v, collectionFormat)
77}