http.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package util
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "strings"
  8. "github.com/kubecost/cost-model/pkg/util/mapper"
  9. )
  10. //--------------------------------------------------------------------------
  11. // QueryParams
  12. //--------------------------------------------------------------------------
  13. type QueryParams = mapper.PrimitiveMap
  14. // queryParamsMap is mapper.Map adapter for url.Values
  15. type queryParamsMap struct {
  16. values url.Values
  17. }
  18. // mapper.Getter implementation
  19. func (qpm *queryParamsMap) Get(key string) string {
  20. return qpm.values.Get(key)
  21. }
  22. // mapper.Setter implementation
  23. func (qpm *queryParamsMap) Set(key, value string) error {
  24. qpm.values.Set(key, value)
  25. return nil
  26. }
  27. // NewQueryParams creates a primitive map using the request query parameters
  28. func NewQueryParams(values url.Values) QueryParams {
  29. return mapper.NewMapper(&queryParamsMap{values})
  30. }
  31. //--------------------------------------------------------------------------
  32. // HTTP Context Utilities
  33. //--------------------------------------------------------------------------
  34. const (
  35. ContextWarning string = "Warning"
  36. )
  37. // GetWarning Extracts a warning message from the request context if it exists
  38. func GetWarning(r *http.Request) (warning string, ok bool) {
  39. warning, ok = r.Context().Value(ContextWarning).(string)
  40. return
  41. }
  42. // SetWarning Sets the warning context on the provided request and returns a new instance of the request
  43. // with the new context.
  44. func SetWarning(r *http.Request, warning string) *http.Request {
  45. ctx := context.WithValue(r.Context(), ContextWarning, warning)
  46. return r.WithContext(ctx)
  47. }
  48. //--------------------------------------------------------------------------
  49. // Package Funcs
  50. //--------------------------------------------------------------------------
  51. // HeaderString writes the request/response http.Header to a string.
  52. func HeaderString(h http.Header) string {
  53. var sb strings.Builder
  54. var first bool = true
  55. sb.WriteString("{ ")
  56. for k, vs := range h {
  57. if first {
  58. first = false
  59. } else {
  60. sb.WriteString(", ")
  61. }
  62. fmt.Fprintf(&sb, "%s: [ ", k)
  63. for idx, v := range vs {
  64. sb.WriteString(v)
  65. if idx != len(vs)-1 {
  66. sb.WriteString(", ")
  67. }
  68. }
  69. sb.WriteString(" ]")
  70. }
  71. sb.WriteString(" }")
  72. return sb.String()
  73. }