main.go 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package main
  2. import (
  3. "context"
  4. "bytes"
  5. "log"
  6. "net"
  7. "os"
  8. "os/exec"
  9. "runtime"
  10. "syscall"
  11. "github.com/cloudwego/hertz/pkg/app"
  12. "github.com/cloudwego/hertz/pkg/app/server"
  13. cxcputhread "github.com/cloudxaas/gocpu/thread"
  14. cxstrconv "github.com/cloudxaas/gostrconv"
  15. "github.com/panjf2000/ants/v2"
  16. "golang.org/x/sys/unix"
  17. )
  18. func main() {
  19. var err error
  20. if cxcputhread.CPUThread == 0 {
  21. childs := uint16(runtime.GOMAXPROCS(-1)) // Start a child for each CPU.
  22. ids := make(chan uint16, childs)
  23. var i uint16
  24. for i = 0; i < childs; i++ {
  25. ids <- i + 1
  26. }
  27. for id := range ids {
  28. idP := id
  29. ants.Submit(func() {
  30. cmd := exec.Command(os.Args[0], append(os.Args[1:], "-t="+cxstrconv.Uint16toa(idP))...)
  31. cmd.Stdout = os.Stdout
  32. cmd.Stderr = os.Stderr
  33. log.Printf("id: %d", idP)
  34. err := cmd.Run()
  35. //time.Sleep(1*time.Second)
  36. log.Printf("%s %s child %d exited with error: %v\n", os.Args[0], os.Args[1:], idP, err)
  37. //time.Sleep(100*time.Second)
  38. ids <- idP // When a child dies we just restart it.
  39. })
  40. }
  41. }
  42. runtime.GOMAXPROCS(1)
  43. err = cxcputhread.SetCPUAffinity(cxcputhread.CPUThread)
  44. if err != nil {
  45. panic(err)
  46. }
  47. h := server.New(
  48. server.WithHostPorts("0.0.0.0:8080"),
  49. ///*
  50. server.WithListenConfig(&net.ListenConfig{
  51. Control: func(network, address string, c syscall.RawConn) error {
  52. return c.Control(func(fd uintptr) {
  53. syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEPORT, 1)
  54. })
  55. },
  56. }),
  57. //*/
  58. )
  59. /*
  60. h.GET("/plaintext", func(ctx context.Context, c *app.RequestContext) {
  61. c.String(consts.StatusOK, "get")
  62. })
  63. */
  64. ///*
  65. h.Use(func(cc context.Context, ctx *app.RequestContext) {
  66. HertzHandler(&cc, ctx)
  67. })
  68. //*/
  69. h.Spin()
  70. }
  71. func HertzHandler(cc *context.Context, ctx *app.RequestContext) {
  72. if bytes.EqualFold(ctx.Request.URI().RequestURI(), []byte("/plaintext")) {
  73. ctx.Response.Header.SetStatusCode(200)
  74. ctx.Response.Header.SetContentType("text/plain")
  75. ctx.Response.SetBodyRaw([]byte("Hello World!"))
  76. }
  77. if bytes.EqualFold(ctx.Request.URI().RequestURI(), []byte("/json")) {
  78. ctx.Response.Header.SetStatusCode(200)
  79. ctx.Response.Header.SetContentType("text/json")
  80. ctx.Response.SetBodyRaw([]byte("{\"Hello World!\"}"))
  81. }
  82. }