utils.go 2.0 KB

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