main.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package main
  2. import (
  3. "flag"
  4. "net/http"
  5. "zero-examples/chat/internal"
  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/rest"
  9. )
  10. var (
  11. port = flag.Int("port", 3333, "the port to listen")
  12. timeout = flag.Int64("timeout", 0, "timeout of milliseconds")
  13. cpu = flag.Int64("cpu", 500, "cpu threshold")
  14. )
  15. func main() {
  16. flag.Parse()
  17. logx.Disable()
  18. engine := rest.MustNewServer(rest.RestConf{
  19. ServiceConf: service.ServiceConf{
  20. Log: logx.LogConf{
  21. Mode: "console",
  22. },
  23. },
  24. Port: *port,
  25. Timeout: *timeout,
  26. CpuThreshold: *cpu,
  27. })
  28. defer engine.Stop()
  29. hub := internal.NewHub()
  30. go hub.Run()
  31. engine.AddRoute(rest.Route{
  32. Method: http.MethodGet,
  33. Path: "/",
  34. Handler: func(w http.ResponseWriter, r *http.Request) {
  35. if r.URL.Path != "/" {
  36. http.Error(w, "Not found", http.StatusNotFound)
  37. return
  38. }
  39. if r.Method != "GET" {
  40. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  41. return
  42. }
  43. http.ServeFile(w, r, "home.html")
  44. },
  45. })
  46. engine.AddRoute(rest.Route{
  47. Method: http.MethodGet,
  48. Path: "/ws",
  49. Handler: func(w http.ResponseWriter, r *http.Request) {
  50. internal.ServeWs(hub, w, r)
  51. },
  52. })
  53. engine.Start()
  54. }