server.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package rest
  2. import (
  3. "context"
  4. "errors"
  5. "net/http"
  6. "sync/atomic"
  7. "time"
  8. "git.ali33.ru/fcg-xvii/go-tools/json"
  9. "github.com/dgrijalva/jwt-go"
  10. )
  11. type IServer interface {
  12. Addr() string
  13. Secret() []byte
  14. HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
  15. Listen(timeout time.Duration) error
  16. TokenGenerate(m json.Map, expire int64) (string, error)
  17. Close() error
  18. Context() context.Context
  19. }
  20. func NewServer(addr string, secret []byte) IServer {
  21. return &Server{
  22. secret: secret,
  23. server: &http.Server{
  24. Addr: addr,
  25. Handler: http.NewServeMux(),
  26. },
  27. }
  28. }
  29. type Server struct {
  30. secret []byte
  31. server *http.Server
  32. opened atomic.Bool
  33. ctx context.Context
  34. }
  35. func (s *Server) Context() context.Context {
  36. return s.ctx
  37. }
  38. func (s *Server) Close() error {
  39. if !s.opened.Load() {
  40. return errors.New("ErrNotOpened")
  41. }
  42. return s.server.Close()
  43. }
  44. func (s *Server) Listen(timeout time.Duration) (err error) {
  45. if s.opened.Swap(true) {
  46. return errors.New("ErrAlreadyOpened")
  47. }
  48. ctx, _ := context.WithTimeout(context.Background(), timeout)
  49. go func() {
  50. var cancel context.CancelFunc
  51. s.ctx, cancel = context.WithCancel(context.Background())
  52. err = s.server.ListenAndServe()
  53. s.opened.Store(false)
  54. cancel()
  55. }()
  56. <-ctx.Done()
  57. return
  58. }
  59. func (s *Server) TokenGenerate(m json.Map, expire int64) (string, error) {
  60. token := jwt.New(jwt.SigningMethodHS256)
  61. claims := token.Claims.(jwt.MapClaims)
  62. for key, val := range m {
  63. claims[key] = val
  64. }
  65. if expire > 0 {
  66. claims["exp"] = time.Now().Add(time.Minute * 30).Unix()
  67. }
  68. tokenString, err := token.SignedString(s.Secret())
  69. return tokenString, err
  70. }
  71. func (s *Server) Addr() string {
  72. return s.server.Addr
  73. }
  74. func (s *Server) Secret() []byte {
  75. return s.secret
  76. }
  77. func (s *Server) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
  78. s.server.Handler.(*http.ServeMux).HandleFunc(pattern, handler)
  79. }