utils.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2014 Manu Martinez-Almeida. 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 gin
  5. import (
  6. "encoding/xml"
  7. "reflect"
  8. "runtime"
  9. "strings"
  10. )
  11. type H map[string]interface{}
  12. // Allows type H to be used with xml.Marshal
  13. func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
  14. start.Name = xml.Name{
  15. Space: "",
  16. Local: "map",
  17. }
  18. if err := e.EncodeToken(start); err != nil {
  19. return err
  20. }
  21. for key, value := range h {
  22. elem := xml.StartElement{
  23. Name: xml.Name{Space: "", Local: key},
  24. Attr: []xml.Attr{},
  25. }
  26. if err := e.EncodeElement(value, elem); err != nil {
  27. return err
  28. }
  29. }
  30. if err := e.EncodeToken(xml.EndElement{Name: start.Name}); err != nil {
  31. return err
  32. }
  33. return nil
  34. }
  35. func filterFlags(content string) string {
  36. for i, char := range content {
  37. if char == ' ' || char == ';' {
  38. return content[:i]
  39. }
  40. }
  41. return content
  42. }
  43. func chooseData(custom, wildcard interface{}) interface{} {
  44. if custom == nil {
  45. if wildcard == nil {
  46. panic("negotiation config is invalid")
  47. }
  48. return wildcard
  49. }
  50. return custom
  51. }
  52. func parseAccept(acceptHeader string) []string {
  53. parts := strings.Split(acceptHeader, ",")
  54. out := make([]string, 0, len(parts))
  55. for _, part := range parts {
  56. index := strings.IndexByte(part, ';')
  57. if index >= 0 {
  58. part = part[0:index]
  59. }
  60. part = strings.TrimSpace(part)
  61. if len(part) > 0 {
  62. out = append(out, part)
  63. }
  64. }
  65. return out
  66. }
  67. func lastChar(str string) uint8 {
  68. size := len(str)
  69. if size == 0 {
  70. panic("The length of the string can't be 0")
  71. }
  72. return str[size-1]
  73. }
  74. func nameOfFunction(f interface{}) string {
  75. return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
  76. }