-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_utils.go
79 lines (69 loc) · 2.19 KB
/
server_utils.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
package pno
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"runtime/debug"
"time"
"github.com/sirupsen/logrus"
)
func httpClientDisallowRedirects(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
}
var (
errHTTPErrorResponse = errors.New("HTTP error response")
)
type httpErrorResp struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (pno *PNOService) respondError(w http.ResponseWriter, code int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
resp := httpErrorResp{code, message}
if err := json.NewEncoder(w).Encode(resp); err != nil {
pno.log.WithField("response", resp).WithError(err).Error("Couldn't write error response")
http.Error(w, "", http.StatusInternalServerError)
}
}
func (pno *PNOService) respondOK(w http.ResponseWriter, response any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(response); err != nil {
pno.log.WithField("response", response).WithError(err).Error("Couldn't write OK response")
http.Error(w, "", http.StatusInternalServerError)
}
}
func LoggingMiddleware(logger *logrus.Entry, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
w.WriteHeader(http.StatusInternalServerError)
method := ""
url := ""
if r != nil {
method = r.Method
url = r.URL.EscapedPath()
}
logger.WithFields(logrus.Fields{
"err": err,
"trace": string(debug.Stack()),
"method": r.Method,
}).Error(fmt.Sprintf("http request panic: %s %s", method, url))
}
}()
start := time.Now()
fmt.Println("\n*******************************")
fmt.Println("*******************************")
logger.Info(r.RequestURI)
next.ServeHTTP(w, r)
logger.WithFields(logrus.Fields{
"method": r.Method,
"path": r.URL.EscapedPath(),
"duration": fmt.Sprintf("%f", time.Since(start).Seconds()),
}).Info(fmt.Sprintf("http: %s %s", r.Method, r.URL.EscapedPath()))
fmt.Println("*******************************")
fmt.Println("*******************************\n")
})
}