main.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package main
  2. import (
  3. "errors"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "os"
  9. "sync/atomic"
  10. "time"
  11. "github.com/tal-tech/go-zero/core/fx"
  12. "github.com/tal-tech/go-zero/core/logx"
  13. )
  14. var (
  15. errServiceUnavailable = errors.New("service unavailable")
  16. total int64
  17. pass int64
  18. fail int64
  19. drop int64
  20. seconds int64 = 1
  21. )
  22. func main() {
  23. flag.Parse()
  24. fp, err := os.Create("result.csv")
  25. logx.Must(err)
  26. defer fp.Close()
  27. fmt.Fprintln(fp, "seconds,total,pass,fail,drop")
  28. go func() {
  29. ticker := time.NewTicker(time.Second)
  30. defer ticker.Stop()
  31. for range ticker.C {
  32. reset(fp)
  33. }
  34. }()
  35. for i := 0; ; i++ {
  36. it := time.NewTicker(time.Second / time.Duration(atomic.LoadInt64(&seconds)))
  37. func() {
  38. for j := 0; j < int(seconds); j++ {
  39. <-it.C
  40. go issueRequest()
  41. }
  42. }()
  43. it.Stop()
  44. cur := atomic.AddInt64(&seconds, 1)
  45. fmt.Println(cur)
  46. }
  47. }
  48. func issueRequest() {
  49. atomic.AddInt64(&total, 1)
  50. err := fx.DoWithTimeout(func() error {
  51. return job()
  52. }, time.Second)
  53. switch err {
  54. case nil:
  55. atomic.AddInt64(&pass, 1)
  56. case errServiceUnavailable:
  57. atomic.AddInt64(&drop, 1)
  58. default:
  59. atomic.AddInt64(&fail, 1)
  60. }
  61. }
  62. func job() error {
  63. resp, err := http.Get("http://localhost:3333/")
  64. if err != nil {
  65. return err
  66. }
  67. defer resp.Body.Close()
  68. switch resp.StatusCode {
  69. case http.StatusOK:
  70. return nil
  71. default:
  72. return errServiceUnavailable
  73. }
  74. }
  75. func reset(writer io.Writer) {
  76. fmt.Fprintf(writer, "%d,%d,%d,%d,%d\n",
  77. atomic.LoadInt64(&seconds),
  78. atomic.SwapInt64(&total, 0),
  79. atomic.SwapInt64(&pass, 0),
  80. atomic.SwapInt64(&fail, 0),
  81. atomic.SwapInt64(&drop, 0),
  82. )
  83. }