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