server.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package main
  2. import (
  3. "net/http"
  4. "runtime"
  5. "time"
  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/core/stat"
  9. "github.com/tal-tech/go-zero/core/syncx"
  10. "github.com/tal-tech/go-zero/rest"
  11. )
  12. func main() {
  13. logx.Disable()
  14. stat.SetReporter(nil)
  15. server := rest.MustNewServer(rest.RestConf{
  16. ServiceConf: service.ServiceConf{
  17. Name: "breaker",
  18. Log: logx.LogConf{
  19. Mode: "console",
  20. },
  21. },
  22. Host: "0.0.0.0",
  23. Port: 8080,
  24. MaxConns: 1000,
  25. Timeout: 3000,
  26. })
  27. latch := syncx.NewLimit(10)
  28. server.AddRoute(rest.Route{
  29. Method: http.MethodGet,
  30. Path: "/heavy",
  31. Handler: func(w http.ResponseWriter, r *http.Request) {
  32. if latch.TryBorrow() {
  33. defer latch.Return()
  34. runtime.LockOSThread()
  35. defer runtime.UnlockOSThread()
  36. begin := time.Now()
  37. for {
  38. if time.Now().Sub(begin) > time.Millisecond*50 {
  39. break
  40. }
  41. }
  42. } else {
  43. w.WriteHeader(http.StatusInternalServerError)
  44. }
  45. },
  46. })
  47. server.AddRoute(rest.Route{
  48. Method: http.MethodGet,
  49. Path: "/good",
  50. Handler: func(w http.ResponseWriter, r *http.Request) {
  51. w.WriteHeader(http.StatusOK)
  52. },
  53. })
  54. defer server.Stop()
  55. server.Start()
  56. }