main.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "net/http"
  6. "github.com/tal-tech/go-zero/core/logx"
  7. "github.com/tal-tech/go-zero/core/service"
  8. "github.com/tal-tech/go-zero/rest"
  9. "github.com/tal-tech/go-zero/rest/httpx"
  10. )
  11. var (
  12. port = flag.Int("port", 3333, "the port to listen")
  13. timeout = flag.Int64("timeout", 0, "timeout of milliseconds")
  14. )
  15. type Request struct {
  16. User string `json:"user"`
  17. }
  18. func handleGet(w http.ResponseWriter, r *http.Request) {
  19. }
  20. func handlePost(w http.ResponseWriter, r *http.Request) {
  21. var req Request
  22. err := httpx.Parse(r, &req)
  23. if err != nil {
  24. http.Error(w, err.Error(), http.StatusBadRequest)
  25. return
  26. }
  27. httpx.OkJson(w, fmt.Sprintf("Content-Length: %d, UserLen: %d", r.ContentLength, len(req.User)))
  28. }
  29. func main() {
  30. flag.Parse()
  31. engine := rest.MustNewServer(rest.RestConf{
  32. ServiceConf: service.ServiceConf{
  33. Log: logx.LogConf{
  34. Mode: "console",
  35. },
  36. },
  37. Port: *port,
  38. Timeout: *timeout,
  39. MaxConns: 500,
  40. MaxBytes: 50,
  41. CpuThreshold: 500,
  42. })
  43. defer engine.Stop()
  44. engine.AddRoute(rest.Route{
  45. Method: http.MethodGet,
  46. Path: "/",
  47. Handler: handleGet,
  48. })
  49. engine.AddRoute(rest.Route{
  50. Method: http.MethodPost,
  51. Path: "/",
  52. Handler: handlePost,
  53. })
  54. engine.Start()
  55. }