main.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "flag"
  4. "math"
  5. "net/http"
  6. "time"
  7. "github.com/tal-tech/go-zero/core/logx"
  8. "github.com/tal-tech/go-zero/core/service"
  9. "github.com/tal-tech/go-zero/rest"
  10. "github.com/tal-tech/go-zero/rest/httpx"
  11. )
  12. var (
  13. port = flag.Int("port", 3333, "the port to listen")
  14. timeout = flag.Int64("timeout", 1000, "timeout of milliseconds")
  15. cpu = flag.Int64("cpu", 500, "cpu threshold")
  16. )
  17. type Request struct {
  18. User string `form:"user,optional"`
  19. }
  20. func handle(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. var result float64
  28. for i := 0; i < 30000; i++ {
  29. result += math.Sqrt(float64(i))
  30. }
  31. time.Sleep(time.Millisecond * 5)
  32. httpx.OkJson(w, result)
  33. }
  34. func main() {
  35. flag.Parse()
  36. logx.Disable()
  37. engine := rest.MustNewServer(rest.RestConf{
  38. ServiceConf: service.ServiceConf{
  39. Log: logx.LogConf{
  40. Mode: "console",
  41. },
  42. },
  43. Port: *port,
  44. Timeout: *timeout,
  45. CpuThreshold: *cpu,
  46. })
  47. defer engine.Stop()
  48. engine.AddRoute(rest.Route{
  49. Method: http.MethodGet,
  50. Path: "/",
  51. Handler: handle,
  52. })
  53. engine.Start()
  54. }