-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
56 lines (46 loc) · 1.43 KB
/
main.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
package main
import (
"fmt"
"net/http"
"time"
"github.com/MadAppGang/httplog"
)
const jsonBody = `{"str": "foo","num": 100,"bool": false,"null": null,"array": ["foo", "bar", "baz"],"obj": { "a": 1, "b": 2 }}`
func happyHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(jsonBody))
}
func notJSONHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("I am not a JSON"))
}
func emptyHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(""))
}
func main() {
logger := httplog.LoggerWithConfig(httplog.LoggerConfig{
RouterName: "FillBodyFormatter",
Formatter: httplog.DefaultLogFormatterWithResponseHeadersAndBody,
CaptureBody: true,
})
// setup routes
http.Handle("/empty", logger(http.HandlerFunc(emptyHandler)))
http.Handle("/wrong", logger(http.HandlerFunc(notJSONHandler)))
http.Handle("/happy", logger(http.HandlerFunc(happyHandler)))
go func() {
fmt.Println("Server started at port 3333")
err := http.ListenAndServe(":3333", nil)
if err != nil {
fmt.Printf("Server stopped because of error %s\n", err.Error())
}
}()
// let server to start
time.Sleep(time.Second * 2)
// let's make couple of request
// empty body
_, err := http.Get("https://localhost:3333/wrong")
if err != nil {
fmt.Printf("Error: %+v", err)
}
_, _ = http.Get("https://localhost:3333/empty")
_, _ = http.Get("https://localhost:3333/happy")
fmt.Println("All done, thank you and see you soon 👋")
}