-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
100 lines (74 loc) · 1.79 KB
/
http.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
package jrpc
import (
"fmt"
"io"
"log/slog"
"net/http"
)
type HTTPOption func(*HTTPRouter)
type HTTPRouter struct {
srv *http.Server
endPoint string
logger *slog.Logger
*Router
}
func NewHTTPRouter(addr string, opts ...HTTPOption) *HTTPRouter {
router := &HTTPRouter{
srv: &http.Server{
Addr: addr,
},
}
for _, opt := range opts {
opt(router)
}
if router.logger == nil {
router.logger = slog.Default()
}
router.Router = NewRouter(router.logger)
if router.endPoint == "" {
router.endPoint = "/"
}
return router
}
func WithLogger(logger *slog.Logger) HTTPOption {
return func(router *HTTPRouter) {
router.logger = logger
}
}
func WithEndPoint(endPoint string) HTTPOption {
return func(router *HTTPRouter) {
router.endPoint = endPoint
}
}
func (httpRouter *HTTPRouter) Run() error {
mux := http.NewServeMux()
mux.HandleFunc(httpRouter.endPoint, func(w http.ResponseWriter, req *http.Request) {
if req.RequestURI != httpRouter.endPoint {
http.Error(w, "404 page not found", http.StatusNotFound)
return
}
httpRouter.Handle(w, req)
})
httpRouter.srv.Handler = mux
return httpRouter.srv.ListenAndServe()
}
func (httpRouter *HTTPRouter) Close() error {
return httpRouter.srv.Close()
}
func (httpRouter *HTTPRouter) Handle(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
bts, err := io.ReadAll(r.Body)
if err != nil {
_, err = w.Write(errorParsingJSONString)
if err != nil {
httpRouter.logger.Error(fmt.Sprintf("error during write into ResponseWriter: %v", err.Error()))
return
}
}
res := httpRouter.Router.engine.handle(r.Context(), bts)
_, err = w.Write(res)
if err != nil {
httpRouter.logger.Error(fmt.Sprintf("error during write into ResponseWriter: %v", err.Error()))
return
}
}