-
Notifications
You must be signed in to change notification settings - Fork 2
/
common_controller.go
64 lines (53 loc) · 1.52 KB
/
common_controller.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
package controllers
import (
"net/http"
"github.com/gin-gonic/gin"
"gozen/models"
"gozen/models/json"
)
func middleWares(engine *gin.Engine) {
engine.RouterGroup.Use(
TokenMiddleWare(),
)
}
// JSONを返す共通コントローラー
func jsonController(fn func(*gin.Context) (interface{}, models.Error)) func(*gin.Context) {
return func(c *gin.Context) {
withCORS(c)
repository, err := fn(c)
if err != nil {
errorJSON := json.ErrorJSON{
Code: err.StatusCode(),
Message: err.Message(),
}
c.JSON(errorJSON.Code, errorJSON)
return
}
c.JSON(http.StatusOK, repository)
}
}
// HTMLを返す共通コントローラー
func htmlController(fn func(*gin.Context) (interface{}, error), tmpl string) func(*gin.Context) {
return func(c *gin.Context) {
repository, err := fn(c)
if err != nil {
e, ok := err.(models.Error)
if ok && e != nil {
c.HTML(e.StatusCode(), "error.tmpl.html", e)
}
return
}
c.HTML(http.StatusOK, tmpl, repository)
}
}
func noImpl(c *gin.Context) (interface{}, models.Error) {
return nil, models.NewError(http.StatusNotFound, "no implemt")
}
// CORS ヘッダーを出力する
func withCORS(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Credentials", "true")
c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
c.Header("Access-Control-Allow-Headers", "Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,Content-Type,Authorization")
c.Header("Access-Control-Max-Age", "1728000")
}