Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
180 lines (157 loc) · 4.09 KB
/
Copy pathmain.go
File metadata and controls
180 lines (157 loc) · 4.09 KB
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package main
import (
"context"
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"flag"
"fmt"
"io"
"log"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"runtime/debug"
"strings"
"syscall"
"time"
)
var (
version = "dev"
commit = "none"
)
func buildInfo() (string, string) {
v, c := version, commit
if info, ok := debug.ReadBuildInfo(); ok {
for _, s := range info.Settings {
if s.Key == "vcs.revision" && c == "none" {
c = s.Value
}
}
}
return v, c
}
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 {
Host string `json:"host"`
Proto string `json:"proto"`
ContentLength int64 `json:"content_length"`
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"`
JSON jsontext.Value `json:"json,omitempty"`
}
func parseRemoteAddr(remoteAddress string) RemoteAddress {
address, port, err := net.SplitHostPort(remoteAddress)
if err != nil {
return RemoteAddress{Address: remoteAddress}
}
return RemoteAddress{
Address: address,
Port: port,
}
}
func echo(extras Extras) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
contentType := r.Header.Get("Content-Type")
var jsonBody jsontext.Value
if err := r.ParseForm(); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if strings.Contains(contentType, "application/json") {
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if len(body) > 0 {
jsonBody = jsontext.Value(body)
if !jsonBody.IsValid() {
w.WriteHeader(http.StatusBadRequest)
return
}
}
}
response := Response{
Host: r.Host,
Proto: r.Proto,
ContentLength: r.ContentLength,
Path: r.URL.Path,
Method: r.Method,
Headers: r.Header,
Form: r.PostForm,
Query: r.URL.Query(),
Remote: parseRemoteAddr(r.RemoteAddr),
ContentType: contentType,
JSON: jsonBody,
Extras: extras,
}
out, err := json.Marshal(response)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if _, err := w.Write(out); err != nil {
slog.Error("failed to write response", "error", err)
}
slog.Info("", "response", response)
}
}
func main() {
showVersion := flag.Bool("version", false, "print version and exit")
flag.Parse()
v, c := buildInfo()
if *showVersion {
fmt.Printf("echo-server %s (%s)\n", v, c)
return
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("version", v, "commit", c)
slog.SetDefault(logger)
extras := Extras{
AppName: os.Getenv("APP_NAME"),
}
if os.Getenv("SHOW_ENVS") == "1" {
extras.Envs = map[string]string{}
for _, kv := range os.Environ() {
k, v, _ := strings.Cut(kv, "=")
extras.Envs[k] = v
}
}
mux := http.NewServeMux()
mux.HandleFunc("/", echo(extras))
port := os.Getenv("PORT")
if port == "" {
port = "5000"
}
server := &http.Server{Addr: net.JoinHostPort("0.0.0.0", port), Handler: mux}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
defer stop()
go func() {
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
log.Fatal(err)
}
}