request.go 2.3 KB

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