-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
71 lines (58 loc) · 1.36 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"fmt"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"io"
"log"
"net/http"
"os"
"strconv"
)
var (
port = 8080
logger *zap.Logger
)
func init() {
logger = newZapLogger("log-app", zapcore.DebugLevel)
}
func main() {
if portEnv, ok := os.LookupEnv("FBT_PORT"); ok {
if portInt, err := strconv.Atoi(portEnv); err == nil {
port = portInt
}
}
http.HandleFunc("/", indexHandler)
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
indexPostHandler(w, r)
return
}
io.Copy(io.Discard, r.Body)
r.Body.Close()
w.WriteHeader(http.StatusAccepted)
}
func indexPostHandler(w http.ResponseWriter, r *http.Request) {
b, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("read request: %v", err)))
return
}
defer r.Body.Close()
logger.Info(string(b))
w.WriteHeader(http.StatusCreated)
}
func newZapLogger(appName string, level zapcore.Level) *zap.Logger {
config := zap.NewProductionConfig()
config.EncoderConfig.TimeKey = "ts_app"
config.EncoderConfig.EncodeTime = zapcore.RFC3339NanoTimeEncoder
config.Level.SetLevel(level)
logger, err := config.Build()
if err != nil {
log.Fatalf("initialise zap logger: %v", err)
}
return logger.With(zap.String("app", appName))
}