go.sdls.io/sin@v0.0.9/pkg/sin/utils.go (about) 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 5 package sin 6 7 import ( 8 "encoding/xml" 9 "net/http" 10 "path" 11 "reflect" 12 "runtime" 13 ) 14 15 // WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware. 16 func WrapF(f http.HandlerFunc) HandlerFunc { 17 return func(c *Context) { 18 f(c.Writer, c.Request) 19 } 20 } 21 22 // WrapH is a helper function for wrapping http.Handler and returns a Gin middleware. 23 func WrapH(h http.Handler) HandlerFunc { 24 return func(c *Context) { 25 h.ServeHTTP(c.Writer, c.Request) 26 } 27 } 28 29 // H is a shortcut for map[string]interface{} 30 type H map[string]interface{} 31 32 // MarshalXML allows type H to be used with xml.Marshal. 33 func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error { 34 start.Name = xml.Name{ 35 Space: "", 36 Local: "map", 37 } 38 if err := e.EncodeToken(start); err != nil { 39 return err 40 } 41 for key, value := range h { 42 elem := xml.StartElement{ 43 Name: xml.Name{Space: "", Local: key}, 44 Attr: []xml.Attr{}, 45 } 46 if err := e.EncodeElement(value, elem); err != nil { 47 return err 48 } 49 } 50 51 return e.EncodeToken(xml.EndElement{Name: start.Name}) 52 } 53 54 func assert1(guard bool, text string) { 55 if !guard { 56 panic(text) 57 } 58 } 59 60 func filterFlags(content string) string { 61 for i, char := range content { 62 if char == ' ' || char == ';' { 63 return content[:i] 64 } 65 } 66 return content 67 } 68 69 func lastChar(str string) uint8 { 70 if str == "" { 71 panic("The length of the string can't be 0") 72 } 73 return str[len(str)-1] 74 } 75 76 func nameOfFunction(f interface{}) string { 77 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() 78 } 79 80 func joinPaths(absolutePath, relativePath string) string { 81 if relativePath == "" { 82 return absolutePath 83 } 84 85 finalPath := path.Join(absolutePath, relativePath) 86 if lastChar(relativePath) == '/' && lastChar(finalPath) != '/' { 87 return finalPath + "/" 88 } 89 return finalPath 90 }