server.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package httpserver
  2. import (
  3. "fmt"
  4. "net"
  5. "net/http"
  6. "strconv"
  7. )
  8. type Server struct {
  9. bindAddr string
  10. bindPort int
  11. hanlder http.Handler
  12. l net.Listener
  13. hs *http.Server
  14. }
  15. type Option func(*Server) *Server
  16. func New(options ...Option) *Server {
  17. s := &Server{
  18. bindAddr: "127.0.0.1",
  19. }
  20. for _, option := range options {
  21. s = option(s)
  22. }
  23. return s
  24. }
  25. func WithBindAddr(addr string) Option {
  26. return func(s *Server) *Server {
  27. s.bindAddr = addr
  28. return s
  29. }
  30. }
  31. func WithBindPort(port int) Option {
  32. return func(s *Server) *Server {
  33. s.bindPort = port
  34. return s
  35. }
  36. }
  37. func WithHandler(h http.Handler) Option {
  38. return func(s *Server) *Server {
  39. s.hanlder = h
  40. return s
  41. }
  42. }
  43. func (s *Server) Run() error {
  44. if err := s.initListener(); err != nil {
  45. return err
  46. }
  47. addr := net.JoinHostPort(s.bindAddr, strconv.Itoa(s.bindPort))
  48. hs := &http.Server{
  49. Addr: addr,
  50. Handler: s.hanlder,
  51. }
  52. s.hs = hs
  53. go hs.Serve(s.l)
  54. return nil
  55. }
  56. func (s *Server) Close() error {
  57. if s.hs != nil {
  58. return s.hs.Close()
  59. }
  60. return nil
  61. }
  62. func (s *Server) initListener() (err error) {
  63. s.l, err = net.Listen("tcp", fmt.Sprintf("%s:%d", s.bindAddr, s.bindPort))
  64. return
  65. }
  66. func (s *Server) BindAddr() string {
  67. return s.bindAddr
  68. }
  69. func (s *Server) BindPort() int {
  70. return s.bindPort
  71. }