/
handler.go
62 lines (53 loc) · 1.26 KB
/
handler.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
package src
import (
"database/sql"
"net/http"
"github.com/cateiru/go-http-error/httperror"
"github.com/gin-gonic/gin"
)
type ErrorResponse struct {
Status int `json:"status"`
Message string `json:"message"`
File string `json:"file"`
Line int `json:"line"`
}
type Handler struct {
DB *sql.DB
}
func NewHandler(db *sql.DB) *Handler {
return &Handler{
DB: db,
}
}
// ginでエラー処理を"イイカンジ"にするやつ
func (h *Handler) HandleWrapper(hand func(ctx *gin.Context) error) func(ctx *gin.Context) {
return func(ctx *gin.Context) {
err := hand(ctx)
if err != nil {
if castedErr, ok := httperror.CastHTTPError(err); ok {
ctx.AbortWithStatusJSON(castedErr.StatusCode,
ErrorResponse{
Status: castedErr.StatusCode,
Message: castedErr.Err.Error(),
File: castedErr.FileName,
Line: castedErr.Line,
},
)
} else {
ctx.AbortWithStatusJSON(http.StatusInternalServerError,
ErrorResponse{
Status: http.StatusInternalServerError,
Message: err.Error(),
File: "",
Line: 0,
})
}
}
}
}
// `/` のhandler
// とりあえず接続確認用
func (h *Handler) RootHandler(ctx *gin.Context) error {
ctx.String(http.StatusOK, "Hello World")
return nil
}