a.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/gorilla/mux"
  6. "net/http"
  7. "strings"
  8. )
  9. func Run() {
  10. var dir string
  11. flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
  12. flag.Parse() // 初始化Router
  13. r := mux.NewRouter() // 静态文件路由
  14. r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) // 普通路由
  15. r.HandleFunc("/", HomeHandler) // 指定host
  16. r.HandleFunc("/host", HostHandler).Host("localhost") // 带变量的url路由
  17. r.HandleFunc("/users/{id}", GetUserHandler).Methods("Get").Name("user")
  18. url, _ := r.Get("user").URL("id", "5")
  19. fmt.Println("user url: ", url.String()) // 遍历已注册的路由
  20. r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
  21. pathTemplate, err := route.GetPathTemplate()
  22. if err == nil {
  23. fmt.Println("ROUTE:", pathTemplate)
  24. }
  25. pathRegexp, err := route.GetPathRegexp()
  26. if err == nil {
  27. fmt.Println("Path regexp:", pathRegexp)
  28. }
  29. queriesTemplates, err := route.GetQueriesTemplates()
  30. if err == nil {
  31. fmt.Println("Queries templates:", strings.Join(queriesTemplates, ","))
  32. }
  33. queriesRegexps, err := route.GetQueriesRegexp()
  34. if err == nil {
  35. fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ","))
  36. }
  37. methods, err := route.GetMethods()
  38. if err == nil {
  39. fmt.Println("Methods:", strings.Join(methods, ","))
  40. }
  41. fmt.Println()
  42. return nil
  43. })
  44. r.Use(TestMiddleware)
  45. http.ListenAndServe(":3000", r)
  46. }
  47. func HomeHandler(w http.ResponseWriter, r *http.Request) {
  48. w.WriteHeader(http.StatusOK)
  49. fmt.Fprintf(w, "this is home")
  50. }
  51. func HostHandler(w http.ResponseWriter, r *http.Request) {
  52. w.WriteHeader(http.StatusOK)
  53. fmt.Fprintf(w, "the host is localhost")
  54. }
  55. func GetUserHandler(w http.ResponseWriter, r *http.Request) {
  56. vars := mux.Vars(r)
  57. w.WriteHeader(http.StatusOK)
  58. fmt.Fprint(w, "this is get user, and the user id is ", vars["id"])
  59. }
  60. func TestMiddleware(next http.Handler) http.Handler {
  61. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Do stuff here
  62. fmt.Println("middleware print: ", r.RequestURI) // Call the next handler, which can be another middleware in the chain, or the final handler.
  63. next.ServeHTTP(w, r)
  64. })
  65. }