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