goCaptcha/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 ImgsFolder string `json:"imgsFolder"`
26 NumImgsCaptcha int `json:"numImgsCaptcha"`
27 SuspiciousIPCountLimit int `json:"suspiciousIPCountLimit"`
28 TimeBan float64 `json:"timeBan"`
29}
30
31var serverConfig ServerConfig
32
33func readServerConfig(path string) {
34 file, err := ioutil.ReadFile(path)
35 if err != nil {
36 fmt.Println("error: ", err)
37 }
38 content := string(file)
39 json.Unmarshal([]byte(content), &serverConfig)
40}
41
42func Logger(inner http.Handler, name string) http.Handler {
43 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
44 start := time.Now()
45
46 inner.ServeHTTP(w, r)
47
48 log.Printf(
49 "%s\t%s\t%s\t%s",
50 r.Method,
51 r.RequestURI,
52 name,
53 time.Since(start),
54 )
55 })
56}
57func NewRouter() *mux.Router {
58 router := mux.NewRouter().StrictSlash(true)
59 for _, route := range routes {
60 var handler http.Handler
61 handler = route.HandlerFunc
62 handler = Logger(handler, route.Name)
63
64 router.
65 Methods(route.Method).
66 Path(route.Pattern).
67 Name(route.Name).
68 Handler(handler)
69 }
70 return router
71}