forked from sashabaranov/go-fastapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfastapi.go
More file actions
74 lines (61 loc) · 1.63 KB
/
fastapi.go
File metadata and controls
74 lines (61 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package fastapi
import (
"log"
"net/http"
"reflect"
"github.com/gin-gonic/gin"
)
func (router *Router) GinHandler(ctx *gin.Context) {
path := ctx.Param("path")
log.Print(path)
handlerFuncPtr, present := router.routes[path]
if !present {
respondWithError(ctx, http.StatusNotFound, "handler not found")
return
}
inputVal, err := bindInput(ctx, handlerFuncPtr)
if err != nil {
respondWithError(ctx, http.StatusBadRequest, "invalid request")
return
}
outputVal, err := callHandler(ctx, handlerFuncPtr, inputVal)
if err != nil {
respondWithError(ctx, http.StatusInternalServerError, err)
return
}
ctx.JSON(http.StatusOK, gin.H{
"response": outputVal.Interface(),
})
}
func (router *Router) GetRoutes() map[string]interface{} {
return router.routes
}
func respondWithError(ctx *gin.Context, code int, message interface{}) {
ctx.JSON(code, gin.H{
"error": message,
"code": code,
})
}
func bindInput(ctx *gin.Context, handlerFuncPtr interface{}) (interface{}, error) {
handlerType := reflect.TypeOf(handlerFuncPtr)
inputType := handlerType.In(1)
inputVal := reflect.New(inputType).Interface()
if err := ctx.BindJSON(inputVal); err != nil {
return nil, err
}
return inputVal, nil
}
func callHandler(c *gin.Context, handlerFuncPtr interface{}, inputVal interface{}) (reflect.Value, error) {
toCall := reflect.ValueOf(handlerFuncPtr)
outputVal := toCall.Call(
[]reflect.Value{
reflect.ValueOf(c),
reflect.ValueOf(inputVal).Elem(),
},
)
returnedErr := outputVal[1].Interface()
if returnedErr != nil || !outputVal[1].IsNil() {
return reflect.Value{}, returnedErr.(error)
}
return outputVal[0], nil
}