main.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "flag"
  4. "net/http"
  5. "github.com/tal-tech/go-zero/core/logx"
  6. "github.com/tal-tech/go-zero/core/service"
  7. "github.com/tal-tech/go-zero/rest"
  8. "github.com/tal-tech/go-zero/rest/httpx"
  9. )
  10. var (
  11. port = flag.Int("port", 3333, "the port to listen")
  12. timeout = flag.Int64("timeout", 0, "timeout of milliseconds")
  13. )
  14. type Request struct {
  15. User string `form:"user,options=a|b"`
  16. }
  17. func first(next http.HandlerFunc) http.HandlerFunc {
  18. return func(w http.ResponseWriter, r *http.Request) {
  19. w.Header().Add("X-Middleware", "first")
  20. next(w, r)
  21. }
  22. }
  23. func second(next http.HandlerFunc) http.HandlerFunc {
  24. return func(w http.ResponseWriter, r *http.Request) {
  25. w.Header().Add("X-Middleware", "second")
  26. next(w, r)
  27. }
  28. }
  29. func handle(w http.ResponseWriter, r *http.Request) {
  30. var req Request
  31. err := httpx.Parse(r, &req)
  32. if err != nil {
  33. http.Error(w, err.Error(), http.StatusBadRequest)
  34. return
  35. }
  36. httpx.OkJson(w, "helllo, "+req.User)
  37. }
  38. func main() {
  39. flag.Parse()
  40. engine := rest.MustNewServer(rest.RestConf{
  41. ServiceConf: service.ServiceConf{
  42. Log: logx.LogConf{
  43. Mode: "console",
  44. },
  45. },
  46. Port: *port,
  47. Timeout: *timeout,
  48. MaxConns: 500,
  49. }, rest.WithNotAllowedHandler(rest.CorsHandler()))
  50. defer engine.Stop()
  51. engine.Use(first)
  52. engine.Use(second)
  53. engine.AddRoute(rest.Route{
  54. Method: http.MethodGet,
  55. Path: "/",
  56. Handler: handle,
  57. })
  58. engine.Start()
  59. }