-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
86 lines (73 loc) · 1.77 KB
/
main.go
File metadata and controls
86 lines (73 loc) · 1.77 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
package main
import (
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
type LogRecord struct {
http.ResponseWriter
status int
}
func (r *LogRecord) Write(p []byte) (int, error) {
return r.ResponseWriter.Write(p)
}
func (r *LogRecord) WriteHeader(status int) {
r.status = status
r.ResponseWriter.WriteHeader(status)
}
func answer(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func printHeaders(logger *log.Logger, r *http.Request) {
logger.Println("Recieved headers")
for header, value := range r.Header {
logger.Println(` `, header, strings.Join(value[:], ","))
}
}
func printBody(logger *log.Logger, r *http.Request) {
logger.Println("Recieved body")
body, err := ioutil.ReadAll(r.Body)
if err != nil {
logger.Printf(err.Error())
return
}
logger.Println(string(body))
return
}
func logging(logger *log.Logger) func(f http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
record := &LogRecord{
ResponseWriter: w,
}
defer func() {
printHeaders(logger, req)
printBody(logger, req)
logger.Println(req.Method, req.URL.Path, record.status, req.RemoteAddr, req.UserAgent())
}()
next.ServeHTTP(record, req)
})
}
}
func main() {
logger := log.New(os.Stdout, "http: ", log.LstdFlags)
router := http.NewServeMux()
port := os.Getenv("APPLICATION_PORT")
router.HandleFunc("/", answer)
if len(port) == 0 {
port = "9999"
}
server := &http.Server{
Addr: ":" + port,
Handler: (logging(logger)(router)),
ErrorLog: logger,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 15 * time.Second,
}
logger.Println("Listening on port", port)
server.ListenAndServe()
}