hello.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/cloudwego/hertz/pkg/app"
  6. "github.com/cloudwego/hertz/pkg/app/server"
  7. "github.com/cloudwego/hertz/pkg/app/server/render"
  8. "github.com/cloudwego/hertz/pkg/common/config"
  9. "github.com/cloudwego/hertz/pkg/protocol"
  10. "github.com/cloudwego/hertz/pkg/protocol/consts"
  11. "github.com/goccy/go-json"
  12. "github.com/jackc/pgx/v5"
  13. "github.com/jackc/pgx/v5/pgxpool"
  14. "math/rand"
  15. "runtime"
  16. "sort"
  17. "sync"
  18. "unsafe"
  19. )
  20. var (
  21. db *pgxpool.Pool
  22. )
  23. const (
  24. // Database
  25. helloworld = "Hello, World!"
  26. worldSelect = "SELECT id, randomNumber FROM World WHERE id = $1"
  27. worldUpdate = "UPDATE World SET randomNumber = $1 WHERE id = $2"
  28. fortuneSelect = "SELECT id, message FROM Fortune;"
  29. worldRowCount = 10000
  30. jsonpath = "/json"
  31. dbpath = "/db"
  32. dbspath = "/dbs"
  33. fortunespath = "/fortunes"
  34. updatepath = "/update"
  35. plaintextpath = "/plaintext"
  36. )
  37. var helloworldRaw = []byte("Hello, World!")
  38. type World struct {
  39. Id int32 `json:"id"`
  40. RandomNumber int32 `json:"randomNumber"`
  41. }
  42. type Fortune struct {
  43. Id uint16 `json:"id"`
  44. Message string `json:"message"`
  45. }
  46. type Fortunes []*Fortune
  47. type Worlds []World
  48. func (s Fortunes) Len() int { return len(s) }
  49. func (s Fortunes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  50. type ByMessage struct{ Fortunes }
  51. func (s ByMessage) Less(i, j int) bool { return s.Fortunes[i].Message < s.Fortunes[j].Message }
  52. func parseQueries(c context.Context, ctx *app.RequestContext) int {
  53. n := GetUintOrZeroFromArgs(ctx.QueryArgs(), "queries")
  54. if n < 1 {
  55. n = 1
  56. } else if n > 500 {
  57. n = 500
  58. }
  59. return n
  60. }
  61. // / Test 1: JSON serialization
  62. func jsonhandler(c context.Context, ctx *app.RequestContext) {
  63. m := AcquireJSON()
  64. m.Message = helloworld
  65. ctx.JSON(200, &m)
  66. ReleaseJSON(m)
  67. }
  68. // / Test 2: Single database query
  69. func dbHandler(c context.Context, ctx *app.RequestContext) {
  70. world := AcquireWorld()
  71. db.QueryRow(context.Background(), worldSelect, RandomWorld()).Scan(&world.Id, &world.RandomNumber)
  72. ctx.JSON(200, &world)
  73. ReleaseWorld(world)
  74. }
  75. // / Test 3: Multiple database queries
  76. func dbs(c context.Context, ctx *app.RequestContext) {
  77. n := parseQueries(c, ctx)
  78. worlds := AcquireWorlds()[:n]
  79. for i := 0; i < n; i++ {
  80. w := &worlds[i]
  81. db.QueryRow(context.Background(), worldSelect, RandomWorld()).Scan(&w.Id, &w.RandomNumber)
  82. }
  83. ctx.JSON(200, &worlds)
  84. ReleaseWorlds(worlds)
  85. }
  86. // / Test 4: Fortunes
  87. func fortunes(c context.Context, ctx *app.RequestContext) {
  88. rows, _ := db.Query(context.Background(), fortuneSelect)
  89. fortunes := make(Fortunes, 0)
  90. for rows.Next() { //Fetch rows
  91. fortune := Fortune{}
  92. _ = rows.Scan(&fortune.Id, &fortune.Message)
  93. fortunes = append(fortunes, &fortune)
  94. }
  95. fortunes = append(fortunes, &Fortune{Message: "Additional fortune added at request time."})
  96. sort.Slice(fortunes, func(i, j int) bool {
  97. return fortunes[i].Message < fortunes[j].Message
  98. })
  99. ctx.HTML(200, "fortune.html", fortunes)
  100. }
  101. // / Test 5: Database updates
  102. func update(c context.Context, ctx *app.RequestContext) {
  103. n := parseQueries(c, ctx)
  104. worlds := AcquireWorlds()[:n]
  105. for i := 0; i < n; i++ {
  106. w := &worlds[i]
  107. db.QueryRow(context.Background(), worldSelect, RandomWorld()).Scan(&w.Id, &w.RandomNumber)
  108. w.RandomNumber = int32(RandomWorld())
  109. }
  110. // sorting is required for insert deadlock prevention.
  111. sort.Slice(worlds, func(i, j int) bool {
  112. return worlds[i].Id < worlds[j].Id
  113. })
  114. batch := pgx.Batch{}
  115. for _, w := range worlds {
  116. batch.Queue(worldUpdate, w.RandomNumber, w.Id)
  117. }
  118. db.SendBatch(context.Background(), &batch).Close()
  119. ctx.JSON(200, &worlds)
  120. ReleaseWorlds(worlds)
  121. }
  122. // / Test 6: plaintext
  123. func plaintext(c context.Context, ctx *app.RequestContext) {
  124. ctx.SetStatusCode(consts.StatusOK)
  125. ctx.Response.SetBodyString(helloworld)
  126. }
  127. func main() {
  128. h := server.New(config.Option{F: func(o *config.Options) {
  129. o.Addr = ":8080"
  130. o.DisableHeaderNamesNormalizing = true
  131. }})
  132. render.ResetJSONMarshal(json.Marshal)
  133. h.Use(func(c context.Context, ctx *app.RequestContext) {
  134. switch b2s(ctx.Path()) {
  135. case plaintextpath:
  136. plaintext(c, ctx)
  137. case jsonpath:
  138. jsonhandler(c, ctx)
  139. case dbpath:
  140. dbHandler(c, ctx)
  141. case dbspath:
  142. dbs(c, ctx)
  143. case updatepath:
  144. update(c, ctx)
  145. case fortunespath:
  146. fortunes(c, ctx)
  147. }
  148. })
  149. h.LoadHTMLGlob("/templates/fortune.html")
  150. h.Spin()
  151. }
  152. func init() {
  153. maxConn := runtime.NumCPU() * 4
  154. var err error
  155. db, err = pgxpool.New(context.Background(),
  156. fmt.Sprintf(
  157. "host=%s port=%d user=%s password=%s dbname=%s pool_max_conns=%d",
  158. "tfb-database", 5432,
  159. "benchmarkdbuser",
  160. "benchmarkdbpass",
  161. "hello_world",
  162. maxConn,
  163. ))
  164. if err != nil {
  165. panic(err)
  166. }
  167. }
  168. type Message struct {
  169. Message string `json:"message"`
  170. }
  171. // JSONpool ...
  172. var JSONpool = sync.Pool{
  173. New: func() interface{} {
  174. return new(Message)
  175. },
  176. }
  177. // AcquireJSON ...
  178. func AcquireJSON() *Message {
  179. return JSONpool.Get().(*Message)
  180. }
  181. // ReleaseJSON ...
  182. func ReleaseJSON(json *Message) {
  183. json.Message = ""
  184. JSONpool.Put(json)
  185. }
  186. // WorldPool ...
  187. var WorldPool = sync.Pool{
  188. New: func() interface{} {
  189. return new(World)
  190. },
  191. }
  192. // AcquireWorld ...
  193. func AcquireWorld() *World {
  194. return WorldPool.Get().(*World)
  195. }
  196. // ReleaseWorld ...
  197. func ReleaseWorld(w *World) {
  198. w.Id = 0
  199. w.RandomNumber = 0
  200. WorldPool.Put(w)
  201. }
  202. // WorldsPool ...
  203. var WorldsPool = sync.Pool{
  204. New: func() interface{} {
  205. return make(Worlds, 0, 500)
  206. },
  207. }
  208. // AcquireWorlds ...
  209. func AcquireWorlds() Worlds {
  210. return WorldsPool.Get().(Worlds)
  211. }
  212. // ReleaseWorlds ...ReleaseWorlds
  213. func ReleaseWorlds(w Worlds) {
  214. w = w[:0]
  215. WorldsPool.Put(w)
  216. }
  217. func b2s(b []byte) string {
  218. return unsafe.String(unsafe.SliceData(b), len(b))
  219. }
  220. // RandomWorld :
  221. func RandomWorld() int {
  222. return rand.Intn(worldRowCount) + 1
  223. }
  224. func GetUintOrZeroFromArgs(a *protocol.Args, key string) int {
  225. b := a.Peek(key)
  226. n := len(b)
  227. if n == 0 {
  228. return 0
  229. }
  230. v := 0
  231. for i := 0; i < n; i++ {
  232. c := b[i]
  233. k := c - '0'
  234. if k > 9 {
  235. return 0
  236. }
  237. vNew := 10*v + int(k)
  238. if vNew < v {
  239. return 0
  240. }
  241. v = vNew
  242. }
  243. return v
  244. }