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