utils.go 2.0 KB

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