/
main.go
114 lines (95 loc) · 2.24 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
package main
import (
"compress/gzip"
"compress/zlib"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
)
type Record struct {
Url string
Method string
Header map[string][]string
Body string
}
// Decode request body by content encoding
func decodeRequestBody(r *http.Request) (string, error) {
ce, _ := r.Header["Content-Encoding"]
for _, x := range ce {
switch x {
case "gzip":
gr, e := gzip.NewReader(r.Body)
defer gr.Close()
if e != nil {
return "", e
}
return readAll(gr)
case "deflate":
fr, e := zlib.NewReader(r.Body)
defer fr.Close()
if e != nil {
return "", e
}
return readAll(fr)
}
}
// No Content-Encoding header detected
return readAll(r.Body)
}
// Read from reader to string
func readAll(r io.Reader) (string, error) {
if body, err := ioutil.ReadAll(r); err != nil {
return "", err
} else {
return string(body), nil
}
}
// Handle all request.
func errorHandler(w http.ResponseWriter, r *http.Request, status int) {
// TODO should be configurable?
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"ok":true}`))
if status == http.StatusNotFound {
record := Record{
Url: r.URL.String(),
Header: r.Header,
Method: r.Method,
}
if body, err := decodeRequestBody(r); err != nil {
record.Body = fmt.Sprintf("Parse error: %s", err.Error())
} else {
record.Body = body
}
log.Println("--------------------------------------------------------------------------------")
b, _ := json.Marshal(record)
log.Println(string(b))
}
}
// Default handler, do nothing.
func homeHandler(w http.ResponseWriter, r *http.Request) {
errorHandler(w, r, http.StatusNotFound)
}
func main() {
port := flag.String("port", "8080", "sets service port number")
logParam := flag.String("log", "", "save all request to a log file")
flag.Parse()
// save logs to file if set.
if *logParam != "" {
f, err := os.OpenFile(*logParam, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(fmt.Sprintf("error opening file: %s", err.Error()))
}
defer f.Close()
log.SetOutput(f)
}
http.HandleFunc("/", homeHandler)
err := http.ListenAndServe("0.0.0.0:"+*port, nil)
if err != nil {
fmt.Printf("I think something here could work, but not this")
}
}