-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
154 lines (132 loc) · 3.54 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
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package main
import (
"context"
"encoding/json"
"io"
"log"
"log/slog"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"go.uber.org/automaxprocs/maxprocs"
)
type RemoteAddress struct {
Address string `json:"address"`
Port string `json:"port"`
}
type Extras struct {
Envs map[string]string `json:"envs,omitempty"`
AppName string `json:"app_name,omitempty"`
}
type Response struct {
Headers map[string][]string `json:"headers"`
Form map[string][]string `json:"form"`
Query map[string][]string `json:"query"`
Remote RemoteAddress `json:"remote"`
Path string `json:"path"`
Method string `json:"method"`
ContentType string `json:"content-type,omitempty"`
Extras Extras `json:"extras,omitempty"`
Json json.RawMessage `json:"json,omitempty"`
}
func parseRemoteAddr(remoteAddress string) RemoteAddress {
lastIndex := strings.LastIndex(remoteAddress, ":")
address := remoteAddress[:lastIndex]
port := remoteAddress[lastIndex+1:]
return RemoteAddress{
Address: address,
Port: port,
}
}
func echo(extras Extras) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
contentType := r.Header.Get("Content-Type")
var jsonBody json.RawMessage = []byte("")
if r.Body != nil {
defer r.Body.Close()
if strings.Contains(contentType, "application/json") {
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
jsonBody = json.RawMessage(body)
}
}
response := Response{
Path: r.URL.Path,
Method: r.Method,
Headers: r.Header,
Form: r.Form,
Query: r.URL.Query(),
Remote: parseRemoteAddr(r.RemoteAddr),
ContentType: r.Header.Get("Content-Type"),
Json: jsonBody,
Extras: extras,
}
bytes, err := json.Marshal(response)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, err = w.Write(bytes)
if err != nil {
slog.Error(err.Error())
}
slog.Info("", "response", response)
}
}
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
slog.SetDefault(logger)
_, _ = maxprocs.Set(maxprocs.Logger(log.Printf))
extras := Extras{
AppName: os.Getenv("APP_NAME"),
}
showEnvs := os.Getenv("SHOW_ENVS")
if showEnvs == "1" {
extras.Envs = map[string]string{}
for _, kv := range os.Environ() {
kvSlice := strings.SplitN(kv, "=", 2)
k := kvSlice[0]
v := kvSlice[1]
extras.Envs[k] = v
}
}
mux := http.NewServeMux()
mux.HandleFunc("/", echo(extras))
port := os.Getenv("PORT")
if port == "" {
port = "5000"
}
server := &http.Server{Addr: "0.0.0.0:" + port, Handler: mux}
serverCtx, serverStopCtx := context.WithCancel(context.Background())
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
<-sig
shutdownCtx, shutdownCtxCancel := context.WithTimeout(serverCtx, 30*time.Second)
defer shutdownCtxCancel()
go func() {
<-shutdownCtx.Done()
if shutdownCtx.Err() == context.DeadlineExceeded {
log.Fatal("graceful shutdown timed out.. forcing exit.")
}
}()
err := server.Shutdown(shutdownCtx)
if err != nil {
log.Fatal(err)
}
serverStopCtx()
}()
err := server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
<-serverCtx.Done()
}