server.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. package httpserver
  2. import (
  3. "crypto/tls"
  4. "net"
  5. "net/http"
  6. "strconv"
  7. "time"
  8. )
  9. type Server struct {
  10. bindAddr string
  11. bindPort int
  12. handler http.Handler
  13. l net.Listener
  14. tlsConfig *tls.Config
  15. hs *http.Server
  16. }
  17. type Option func(*Server) *Server
  18. func New(options ...Option) *Server {
  19. s := &Server{
  20. bindAddr: "127.0.0.1",
  21. }
  22. for _, option := range options {
  23. s = option(s)
  24. }
  25. return s
  26. }
  27. func WithBindAddr(addr string) Option {
  28. return func(s *Server) *Server {
  29. s.bindAddr = addr
  30. return s
  31. }
  32. }
  33. func WithBindPort(port int) Option {
  34. return func(s *Server) *Server {
  35. s.bindPort = port
  36. return s
  37. }
  38. }
  39. func WithTLSConfig(tlsConfig *tls.Config) Option {
  40. return func(s *Server) *Server {
  41. s.tlsConfig = tlsConfig
  42. return s
  43. }
  44. }
  45. func WithHandler(h http.Handler) Option {
  46. return func(s *Server) *Server {
  47. s.handler = h
  48. return s
  49. }
  50. }
  51. func WithResponse(resp []byte) Option {
  52. return func(s *Server) *Server {
  53. s.handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  54. _, _ = w.Write(resp)
  55. })
  56. return s
  57. }
  58. }
  59. func (s *Server) Run() error {
  60. if err := s.initListener(); err != nil {
  61. return err
  62. }
  63. addr := net.JoinHostPort(s.bindAddr, strconv.Itoa(s.bindPort))
  64. hs := &http.Server{
  65. Addr: addr,
  66. Handler: s.handler,
  67. TLSConfig: s.tlsConfig,
  68. ReadHeaderTimeout: time.Minute,
  69. }
  70. s.hs = hs
  71. if s.tlsConfig == nil {
  72. go func() {
  73. _ = hs.Serve(s.l)
  74. }()
  75. } else {
  76. go func() {
  77. _ = hs.ServeTLS(s.l, "", "")
  78. }()
  79. }
  80. return nil
  81. }
  82. func (s *Server) Close() error {
  83. if s.hs != nil {
  84. return s.hs.Close()
  85. }
  86. return nil
  87. }
  88. func (s *Server) initListener() (err error) {
  89. s.l, err = net.Listen("tcp", net.JoinHostPort(s.bindAddr, strconv.Itoa(s.bindPort)))
  90. return
  91. }
  92. func (s *Server) BindAddr() string {
  93. return s.bindAddr
  94. }
  95. func (s *Server) BindPort() int {
  96. return s.bindPort
  97. }