header.go 869 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Copyright 2022 Gin Core Team. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package binding
  5. import (
  6. "net/http"
  7. "net/textproto"
  8. "reflect"
  9. )
  10. type headerBinding struct{}
  11. func (headerBinding) Name() string {
  12. return "header"
  13. }
  14. func (headerBinding) Bind(req *http.Request, obj any) error {
  15. if err := mapHeader(obj, req.Header); err != nil {
  16. return err
  17. }
  18. return validate(obj)
  19. }
  20. func mapHeader(ptr any, h map[string][]string) error {
  21. return mappingByPtr(ptr, headerSource(h), "header")
  22. }
  23. type headerSource map[string][]string
  24. var _ setter = headerSource(nil)
  25. func (hs headerSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (bool, error) {
  26. return setByForm(value, field, hs, textproto.CanonicalMIMEHeaderKey(tagValue), opt)
  27. }