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.

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