-
Notifications
You must be signed in to change notification settings - Fork 0
/
logserver.go
216 lines (178 loc) · 5.42 KB
/
logserver.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
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package main
import (
"bytes"
"compress/gzip"
"context"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"sync/atomic"
"syscall"
"time"
)
var counter int64
var out io.Writer = os.Stdout
var version = "undefined"
var opts struct {
listenAddress string
responseBody string
contentType string
fsPath string
responseCode int
}
func main() {
flag.StringVar(&opts.listenAddress, "a", ":2000", "listen address")
flag.StringVar(&opts.responseBody, "b", "", "response body")
flag.StringVar(&opts.contentType, "t", "", "content type header value")
flag.StringVar(&opts.fsPath, "f", "", "run as file server with specified root directory")
flag.IntVar(&opts.responseCode, "c", 0, "response status code")
flag.Parse()
if addrEnv := os.Getenv("LISTEN_ADDR"); addrEnv != "" {
opts.listenAddress = addrEnv
}
if bodyEnv := os.Getenv("RESPONSE_BODY"); bodyEnv != "" {
opts.responseBody = bodyEnv
}
if contentTypeEnv := os.Getenv("CONTENT_TYPE"); contentTypeEnv != "" {
opts.contentType = contentTypeEnv
}
if fileServerEnv := os.Getenv("FILE_SERVER"); fileServerEnv != "" {
opts.fsPath = fileServerEnv
}
if responseCodeEnv := os.Getenv("RESPONSE_CODE"); responseCodeEnv != "" {
responseCodeEnvInt, errInt := strconv.Atoi(responseCodeEnv)
if errInt != nil {
fmt.Printf("response code must be an interger")
os.Exit(1)
}
opts.responseCode = responseCodeEnvInt
}
if opts.responseCode != 0 && (opts.responseCode < 100 || opts.responseCode > 999) {
fmt.Printf("response code must be in range 100..999 or 0 for default 200")
os.Exit(1)
}
if opts.fsPath != "" && (opts.responseBody != "" || opts.responseCode != 0 || opts.contentType != "") {
fmt.Printf("error: -f and -b/-c/-t options are mutually exclusive\n")
os.Exit(1)
}
err := run()
if err != nil {
fmt.Printf("error run logserver, %s\n", err)
os.Exit(1)
}
fmt.Printf("\ndone\n")
}
func run() error {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer cancel()
for _, pair := range os.Environ() {
fmt.Printf("%s\n", pair)
}
opts.responseBody = strings.Replace(opts.responseBody, "\\t", "\t", -1)
opts.responseBody = strings.Replace(opts.responseBody, "\\n", "\n", -1)
fmt.Printf("----- Options -----\nListen addr:\n%s\nResonse body:\n%s\nResponse code:\n%d\n----------\n", opts.listenAddress, opts.responseBody, opts.responseCode)
fmt.Printf("logserver.%s listen %s\n", version, opts.listenAddress)
ln, errListen := net.Listen("tcp4", opts.listenAddress)
if errListen != nil {
return fmt.Errorf("error listen address, %w", errListen)
}
defer ln.Close()
var h http.Handler
h = middlewarePrintRequest(http.HandlerFunc(handler))
if opts.fsPath != "" {
fmt.Printf("run as FileServer with path: %s\n", opts.fsPath)
fs := middlewarePrintRequest(http.FileServer(http.Dir(opts.fsPath)))
h = fs
}
server := &http.Server{
Handler: h,
}
go func() {
<-ctx.Done()
errShutdown := server.Shutdown(ctx)
if errShutdown != nil && !errors.Is(errShutdown, context.Canceled) && !errors.Is(errShutdown, http.ErrServerClosed) {
fmt.Printf("error shutdown server, %s", errShutdown)
}
}()
errServe := server.Serve(ln)
if errServe != nil && !errors.Is(errServe, http.ErrServerClosed) {
return fmt.Errorf("error serve, %w", errServe)
}
return nil
}
func middlewarePrintRequest(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add("Access-Control-Allow-Origin", "*")
rw.Header().Add("Access-Control-Allow-Methods", "*")
rw.Header().Add("Access-Control-Allow-Headers", "*")
c := atomic.AddInt64(&counter, 1)
fmt.Printf("___________[ %d ]___________\n", c)
fmt.Printf("| %v\n", time.Now())
fmt.Printf("| [%s] %s %s\n| \n", req.RemoteAddr, req.Method, req.RequestURI)
for key, values := range req.Header {
fmt.Printf("| %s: %#v\n", key, values)
}
next.ServeHTTP(rw, req)
})
}
func handler(rw http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
requestBody, err := io.ReadAll(req.Body)
if err != nil {
response(rw, fmt.Errorf("error read request body, %v", err))
return
}
if req.Header.Get("Content-Encoding") == "gzip" {
gzipReader, errGzipReader := gzip.NewReader(bytes.NewReader(requestBody))
if errGzipReader != nil {
response(rw, fmt.Errorf("error init gzip reader, %v", errGzipReader))
return
}
decodedBody, errRead := io.ReadAll(gzipReader)
if errRead != nil {
response(rw, fmt.Errorf("error decode gzip request body, %v", errRead))
return
}
requestBody = decodedBody
}
if len(requestBody) != 0 {
fmt.Printf("\n%s\n", requestBody)
}
response(rw, nil)
}
func response(rw http.ResponseWriter, err error) {
if err != nil {
fmt.Printf("[ERROR] %s\n", err)
return
}
if opts.contentType != "" {
rw.Header().Set("Content-Type", opts.contentType)
}
if opts.responseCode != 0 {
rw.WriteHeader(opts.responseCode)
}
if opts.responseBody != "" {
body := []byte(opts.responseBody)
if strings.HasPrefix(opts.responseBody, "file://") {
var errReadBody error
body, errReadBody = os.ReadFile(strings.TrimPrefix(opts.responseBody, "file://"))
if errReadBody != nil {
log.Printf("error read response body file %s, %v", opts.responseBody, errReadBody)
return
}
}
_, errWrite := rw.Write(body)
if errWrite != nil {
fmt.Printf("[ERROR] error write response, %d", errWrite)
}
}
fmt.Printf("\n")
}