server.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package http
  2. import (
  3. "net"
  4. "net/http"
  5. "time"
  6. "go-common/library/conf/env"
  7. "go-common/library/log"
  8. bm "go-common/library/net/http/blademaster"
  9. xtime "go-common/library/time"
  10. "github.com/pkg/errors"
  11. )
  12. var (
  13. _defaultAddr string
  14. )
  15. // ServerConfig is the alias to bm ServerConfig
  16. //
  17. // Deprecated: using bm.ServerConfig instead
  18. type ServerConfig = bm.ServerConfig
  19. func init() {
  20. if env.HTTPPort != "" {
  21. _defaultAddr = net.JoinHostPort("0.0.0.0", env.HTTPPort)
  22. } else {
  23. _defaultAddr = "0.0.0.0:8000"
  24. }
  25. }
  26. // Serve listen and serve bm engine by given config.
  27. //
  28. // Deprecated: using Engine.Start instead
  29. func Serve(engine *bm.Engine, conf *ServerConfig) error {
  30. if conf == nil {
  31. conf = &ServerConfig{
  32. Addr: _defaultAddr,
  33. Timeout: xtime.Duration(time.Second),
  34. }
  35. }
  36. l, err := net.Listen("tcp", conf.Addr)
  37. if err != nil {
  38. errors.Wrapf(err, "listen tcp: %d", conf.Addr)
  39. return err
  40. }
  41. if err := engine.SetConfig(conf); err != nil {
  42. return err
  43. }
  44. log.Info("blademaster: start http listen addr: %s", conf.Addr)
  45. server := &http.Server{
  46. ReadTimeout: time.Duration(conf.ReadTimeout),
  47. WriteTimeout: time.Duration(conf.WriteTimeout),
  48. }
  49. go func() {
  50. if err := engine.RunServer(server, l); err != nil {
  51. log.Error("blademaster: engine.ListenServer(%+v, %+v) error(%v)", server, l, err)
  52. }
  53. }()
  54. return nil
  55. }