-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmethods.go
63 lines (52 loc) · 1.52 KB
/
methods.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
// Copyright 2019 Nirenjan Krishnan. All rights reserved.
package vanity
import (
"context"
"log"
"net/http"
"time"
)
// methodNotAllowed returns a not allowed response
func methodNotAllowed(w http.ResponseWriter, r *http.Request) {
code := http.StatusMethodNotAllowed
message := http.StatusText(code)
http.Error(w, message, code)
}
type loggingResponseWriter struct {
http.ResponseWriter
statusCode int
}
func (lrw *loggingResponseWriter) WriteHeader(code int) {
lrw.statusCode = code
lrw.ResponseWriter.WriteHeader(code)
}
// getHandler restricts requests to use the GET handler
func getHandler(h func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
lrw := &loggingResponseWriter{w, http.StatusOK}
if r.Method == http.MethodGet {
h(lrw, r)
} else {
// Respond with the error message
methodNotAllowed(lrw, r)
}
t := time.Now()
elapsed := t.Sub(start)
remote := r.Header.Get("X-Forwarded-For")
if remote == "" {
remote = r.RemoteAddr
}
log.Printf("%v \"%v %v %v\" %d %v", remote, r.Method, r.URL.Path, r.Proto, lrw.statusCode, elapsed)
}
}
// handleRobots returns static content for robots.txt requests
func handleRobots(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("User-agent: *\nDisallow:\n"))
}
// ShutDown shuts down the HTTP server and gracefully exits
func (s *Server) ShutDown() {
if err := s.httpServer.Shutdown(context.Background()); err != nil {
log.Fatal(err)
}
}