goRecommender/serverConfig.go
serverConfig.goRaw
1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "io/ioutil"
7 "log"
8 "net/http"
9 "time"
10
11 "github.com/gorilla/mux"
12)
13
14type Route struct {
15 Name string
16 Method string
17 Pattern string
18 HandlerFunc http.HandlerFunc
19}
20
21//server config
22type ServerConfig struct {
23 ServerIP string `json:"serverIP"`
24 ServerPort string `json:"serverPort"`
25}
26
27var serverConfig ServerConfig
28
29func readServerConfig(path string) {
30 file, err := ioutil.ReadFile(path)
31 if err != nil {
32 fmt.Println("error: ", err)
33 }
34 content := string(file)
35 json.Unmarshal([]byte(content), &serverConfig)
36}
37
38func Logger(inner http.Handler, name string) http.Handler {
39 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
40 start := time.Now()
41
42 inner.ServeHTTP(w, r)
43
44 log.Printf(
45 "%s\t%s\t%s\t%s",
46 r.Method,
47 r.RequestURI,
48 name,
49 time.Since(start),
50 )
51 })
52}
53func NewRouter() *mux.Router {
54 router := mux.NewRouter().StrictSlash(true)
55 for _, route := range routes {
56 var handler http.Handler
57 handler = route.HandlerFunc
58 handler = Logger(handler, route.Name)
59
60 router.
61 Methods(route.Method).
62 Path(route.Pattern).
63 Name(route.Name).
64 Handler(handler)
65 }
66 return router
67}