-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
47 lines (39 loc) · 997 Bytes
/
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
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
"os"
)
func BootServer() {
port := os.Getenv("PORT")
if port == "" {
port = "80"
}
router := mux.NewRouter()
router.Use(commonMiddleware)
router.HandleFunc("/{word}", GetDictWord)
router.HandleFunc("/", GetHome)
fmt.Println(fmt.Sprintf("Server ready and listening at port %s", port))
http.ListenAndServe(fmt.Sprintf(":%s", port), router)
}
func commonMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println(fmt.Sprintf("Incoming request: %s %s from %s", r.Method, r.RequestURI, getRequestIP(r)))
w.Header().Add("Content-Type", "application/json")
next.ServeHTTP(w, r)
})
}
func getRequestIP(r *http.Request) string {
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
return IPAddress
}
func main() {
BootServer()
}