server.go 1.7 KB

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