-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
125 lines (105 loc) · 2.54 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"bytes"
"flag"
"log"
"strconv"
"github.com/gin-gonic/gin"
"github.com/gotokatsuya/apidoc"
)
type ginBodyWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w ginBodyWriter) Body() []byte {
return w.body.Bytes()
}
func (w ginBodyWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
func (w ginBodyWriter) WriteString(s string) (int, error) {
w.body.WriteString(s)
return w.ResponseWriter.WriteString(s)
}
func newGinBodyWriter(w gin.ResponseWriter) *ginBodyWriter {
return &ginBodyWriter{body: bytes.NewBufferString(""), ResponseWriter: w}
}
func apidocMiddleware(c *gin.Context) {
if apidoc.IsDisabled() {
return
}
api := apidoc.NewAPI()
api.SuppressedRequestHeaders("Cache-Control", "Content-Length", "X-Request-Id", "ETag", "Set-Cookie")
api.ReadRequest(c.Request, false)
gbw := newGinBodyWriter(c.Writer)
c.Writer = gbw
// before processing request
c.Next()
// after processing request
api.SuppressedResponseHeaders("Cache-Control", "Content-Length", "X-Request-Id", "X-Runtime", "X-XSS-Protection", "ETag")
api.ReadResponseHeader(c.Writer.Header())
api.WrapResponseBody(gbw.Body())
api.ResponseStatusCode = c.Writer.Status()
apidoc.Gen(api)
}
func getEngine() *gin.Engine {
r := gin.Default()
r.Use(apidocMiddleware)
type user struct {
ID int `json:"id"`
Name string `json:"name"`
}
r.GET("/users", func(c *gin.Context) {
limit := c.Query("limit")
c.JSON(200, gin.H{
"limit": limit,
"users": []user{
user{ID: 1, Name: "test1"},
user{ID: 2, Name: "test2"}},
})
})
r.GET("/users/:id", func(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
log.Println(err)
return
}
c.JSON(200, gin.H{"user": user{ID: id, Name: "test"}})
})
r.POST("/users", func(c *gin.Context) {
name := c.PostForm("name")
c.JSON(200, gin.H{"user": user{ID: 1, Name: name}})
})
r.PUT("/users", func(c *gin.Context) {
type req struct {
Name string `form:"name" json:"name" binding:"required"`
}
var r req
if err := c.BindJSON(&r); err != nil {
log.Println(err)
return
}
c.JSON(200, gin.H{"user": user{ID: 1, Name: r.Name}})
})
return r
}
func init() {
d := flag.Bool("d", false, "disable api doc")
flag.Parse()
if *d {
apidoc.Disable()
}
if apidoc.IsDisabled() {
return
}
apidoc.Init(apidoc.Project{
DocumentTitle: "example-gin",
DocumentPath: "custom-apidoc.html",
TemplatePath: "custom.tpl.html",
})
}
func main() {
// Listen and Server in 0.0.0.0:8080
getEngine().Run(":8080")
}