/
main.go
69 lines (62 loc) · 1.31 KB
/
main.go
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
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/gin-gonic/gin"
"gopkg.in/yaml.v2"
)
type Api struct {
Endpoint string `yaml:"endpoint"`
Method string `yaml:"method"`
Response string `yaml:"response"`
Status int `yaml:"status"`
}
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
renderBackendConfig(r, "./backend.yaml")
r.Run()
}
func check(e error) {
if e != nil {
log.Fatal(e)
}
}
func renderBackendConfig(r *gin.Engine, configFilePath string) *gin.Engine {
data, err := os.ReadFile(configFilePath)
check(err)
var apis []Api
err = yaml.Unmarshal(data, &apis)
check(err)
for _, api := range apis {
_endpoint := api.Endpoint
_handlerFunc := handlerFile(api.Response, api.Status)
switch api.Method {
case "get":
r.GET(_endpoint, _handlerFunc)
case "post":
r.POST(_endpoint, _handlerFunc)
case "delete":
r.DELETE(_endpoint, _handlerFunc)
case "put":
r.DELETE(_endpoint, _handlerFunc)
}
}
return r
}
func handlerFile(sampleResponseFilePath string, status int) gin.HandlerFunc {
return func(c *gin.Context) {
data, err := os.ReadFile(sampleResponseFilePath)
check(err)
var resp interface{}
err = json.Unmarshal(data, &resp)
check(err)
c.JSON(status, resp)
}
}