server.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package httpserver
  2. import (
  3. "crypto/tls"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "strconv"
  8. )
  9. type Server struct {
  10. bindAddr string
  11. bindPort int
  12. hanlder 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.hanlder = h
  48. return s
  49. }
  50. }
  51. func WithResponse(resp []byte) Option {
  52. return func(s *Server) *Server {
  53. s.hanlder = 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.hanlder,
  67. TLSConfig: s.tlsConfig,
  68. }
  69. s.hs = hs
  70. if s.tlsConfig == nil {
  71. go hs.Serve(s.l)
  72. } else {
  73. go hs.ServeTLS(s.l, "", "")
  74. }
  75. return nil
  76. }
  77. func (s *Server) Close() error {
  78. if s.hs != nil {
  79. return s.hs.Close()
  80. }
  81. return nil
  82. }
  83. func (s *Server) initListener() (err error) {
  84. s.l, err = net.Listen("tcp", fmt.Sprintf("%s:%d", s.bindAddr, s.bindPort))
  85. return
  86. }
  87. func (s *Server) BindAddr() string {
  88. return s.bindAddr
  89. }
  90. func (s *Server) BindPort() int {
  91. return s.bindPort
  92. }