utils.go 2.1 KB

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