|
| 1 | +package gonylon |
| 2 | + |
| 3 | +import ( |
| 4 | + "reflect" |
| 5 | + "regexp" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/gin-gonic/gin" |
| 9 | +) |
| 10 | + |
| 11 | +// Router x |
| 12 | +func Router(router *gin.Engine, baseURL string, ct interface{}) { |
| 13 | + |
| 14 | + routeValue := reflect.ValueOf(ct) |
| 15 | + routeType := routeValue.Type() |
| 16 | + |
| 17 | + for i := 0; i < routeType.NumMethod(); i++ { |
| 18 | + method := routeValue.Method(i) |
| 19 | + m, p := methodToRoute(routeType.Method(i).Name) |
| 20 | + url := baseURL + "/" + p |
| 21 | + // fmt.Println(m, p) |
| 22 | + switch m { |
| 23 | + case "Get": |
| 24 | + router.GET(url, contextAgent(method)) |
| 25 | + case "Post": |
| 26 | + router.POST(url, contextAgent(method)) |
| 27 | + case "Put": |
| 28 | + router.PUT(url, contextAgent(method)) |
| 29 | + case "Patch": |
| 30 | + router.PATCH(url, contextAgent(method)) |
| 31 | + case "Delete": |
| 32 | + router.DELETE(url, contextAgent(method)) |
| 33 | + } |
| 34 | + |
| 35 | + // router.GET("/x", contextAgent(method)) |
| 36 | + |
| 37 | + } |
| 38 | + |
| 39 | +} |
| 40 | + |
| 41 | +func contextAgent(method reflect.Value) func(*gin.Context) { |
| 42 | + return func(c *gin.Context) { |
| 43 | + rv := reflect.ValueOf(c) |
| 44 | + method.Call([]reflect.Value{rv}) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +func methodToRoute(methodName string) (method string, path string) { |
| 49 | + var camel = regexp.MustCompile("(^[^A-Z0-9]*|[A-Z0-9]*)([A-Z0-9][^A-Z]+|$)") |
| 50 | + var a []string |
| 51 | + for _, sub := range camel.FindAllStringSubmatch(methodName, -1) { |
| 52 | + if sub[1] != "" { |
| 53 | + a = append(a, sub[1]) |
| 54 | + } |
| 55 | + if sub[2] != "" { |
| 56 | + a = append(a, sub[2]) |
| 57 | + } |
| 58 | + } |
| 59 | + //fmt.Println(a) |
| 60 | + return a[0], strings.ToLower(strings.Join(a[1:len(a)], "/")) |
| 61 | +} |
0 commit comments