-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
133 lines (109 loc) · 2.81 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
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
126
127
128
129
130
131
132
133
package http
import (
"io/fs"
"net/http"
"time"
"github.com/DeanThompson/ginpprof"
"github.com/gin-gonic/gin"
"github.com/mvrilo/torresmo/errors"
"github.com/mvrilo/torresmo/log"
"github.com/mvrilo/torresmo/stream"
"github.com/mvrilo/torresmo/torrent"
)
type handler struct {
*gin.Engine
stream stream.Publisher
client torrent.Client
logger log.Logger
}
var _ http.Handler = &handler{}
type AddTorrentRequest struct {
URI string `json:"uri" binding:"required,uri"`
}
func (h *handler) AddTorrent(ctx *gin.Context) {
var params AddTorrentRequest
if err := ctx.ShouldBindJSON(¶ms); err != nil {
ctx.Error(errors.ErrBadRequest.Wrap(err))
return
}
torrent, err := h.client.AddURI(params.URI)
if err != nil {
ctx.Error(errors.ErrInternal.Wrap(err))
return
}
ctx.JSON(http.StatusCreated, <-torrent)
}
func (h *handler) Torrents(ctx *gin.Context) {
ctx.JSON(http.StatusOK, h.client.Torrents())
}
func (h *handler) Stats(ctx *gin.Context) {
ctx.JSON(http.StatusOK, h.client.Stats())
}
// error handling middleware
func (h *handler) errorHandlingMiddleware(ctx *gin.Context) {
ctx.Next()
err := ctx.Errors.Last()
if err == nil {
return
}
switch er := err.Err.(type) {
case *errors.Error:
ctx.AbortWithStatusJSON(er.Code, er.Error())
default:
}
}
// custom logging log middleware
func (h *handler) loggingMiddleware(ctx *gin.Context) {
start := time.Now()
log := h.logger
req := ctx.Request
path := req.URL.Path
if raw := req.URL.RawQuery; raw != "" {
path = path + "?" + raw
}
ctx.Next()
w := ctx.Writer
status := w.Status()
latency := time.Since(start)
log = log.With(
"status", status,
"method", req.Method,
"path", path,
"ip", ctx.ClientIP(),
"latency", latency.String(),
"user-agent", req.UserAgent(),
)
if status == http.StatusNotFound || status == http.StatusUnauthorized || status < http.StatusBadRequest {
log.Info("Request")
return
}
err := ctx.Errors.Last()
if err != nil {
log.Error(err)
}
}
// NewHandler returns a default handler implemented with gin
func NewHandler(cli torrent.Client, logger log.Logger, staticFiles fs.FS, downloadedFiles fs.FS, publisher stream.Publisher, debug bool) http.Handler {
gin.SetMode(gin.ReleaseMode)
router := gin.New()
h := &handler{
Engine: router,
stream: publisher,
client: cli,
logger: logger,
}
if debug {
ginpprof.Wrap(router)
}
router.Use(h.loggingMiddleware)
router.Use(h.errorHandlingMiddleware)
if downloadedFiles != nil {
router.Any("/downloads/*any", gin.WrapH(http.StripPrefix("/downloads/", http.FileServer(http.FS(downloadedFiles)))))
}
router.GET("/api/stats/", h.Stats)
router.GET("/api/torrents/", h.Torrents)
router.POST("/api/torrents/", h.AddTorrent)
router.GET("/api/events/", gin.WrapH(h.stream.Serve()))
router.Use(gin.WrapH(http.FileServer(http.FS(staticFiles))))
return h
}