You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.3 KiB

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