common.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package common
  2. import (
  3. "encoding/json"
  4. "log"
  5. "math/rand"
  6. "net"
  7. "sort"
  8. "sync"
  9. "templates"
  10. "github.com/valyala/fasthttp"
  11. )
  12. const worldRowCount = 10000
  13. type JSONResponse struct {
  14. Message string `json:"message"`
  15. }
  16. type World struct {
  17. Id int32 `json:"id"`
  18. RandomNumber int32 `json:"randomNumber"`
  19. }
  20. type Worlds []World
  21. func JSONHandler(ctx *fasthttp.RequestCtx) {
  22. r := jsonResponsePool.Get().(*JSONResponse)
  23. defer jsonResponsePool.Put(r)
  24. r.Message = "Hello, World!"
  25. rb, err := r.MarshalJSON()
  26. if err != nil {
  27. log.Println(err)
  28. return
  29. }
  30. ctx.SetContentType("application/json")
  31. ctx.Write(rb)
  32. }
  33. var jsonResponsePool = &sync.Pool{
  34. New: func() interface{} {
  35. return &JSONResponse{}
  36. },
  37. }
  38. func PlaintextHandler(ctx *fasthttp.RequestCtx) {
  39. ctx.SetContentType("text/plain")
  40. ctx.WriteString("Hello, World!")
  41. }
  42. func JSONMarshal(ctx *fasthttp.RequestCtx, v interface{}) {
  43. ctx.SetContentType("application/json")
  44. if err := json.NewEncoder(ctx).Encode(v); err != nil {
  45. log.Fatalf("error in json.Encoder.Encode: %s", err)
  46. }
  47. }
  48. func RandomWorldNum() int {
  49. return rand.Intn(worldRowCount) + 1
  50. }
  51. func GetQueriesCount(ctx *fasthttp.RequestCtx) int {
  52. n := ctx.QueryArgs().GetUintOrZero("queries")
  53. if n < 1 {
  54. n = 1
  55. } else if n > 500 {
  56. n = 500
  57. }
  58. return n
  59. }
  60. func GetListener(listenAddr string) net.Listener {
  61. ln, err := net.Listen("tcp4", listenAddr)
  62. if err != nil {
  63. log.Fatal(err)
  64. }
  65. return ln
  66. }
  67. func SortFortunesByMessage(fortunes []templates.Fortune) {
  68. sort.Slice(fortunes, func(i, j int) bool { return fortunes[i].Message < fortunes[j].Message })
  69. }
  70. func SortWorldsByID(worlds []World) {
  71. sort.Slice(worlds, func(i, j int) bool { return worlds[i].Id < worlds[j].Id })
  72. }