rest.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. package rest
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "log"
  9. "net/http"
  10. "strings"
  11. "sync/atomic"
  12. "time"
  13. mjson "git.ali33.ru/fcg-xvii/go-tools/json"
  14. jwt "github.com/dgrijalva/jwt-go"
  15. )
  16. func NewRest(addr string, secret []byte, commands *CommandStore) *Rest {
  17. return &Rest{
  18. commands: commands,
  19. secret: secret,
  20. addr: addr,
  21. }
  22. }
  23. type Rest struct {
  24. secret []byte
  25. addr string
  26. opened atomic.Bool
  27. server *http.Server
  28. commands *CommandStore
  29. }
  30. func (s *Rest) TokenGenerate(m mjson.Map, expire int64) (string, error) {
  31. token := jwt.New(jwt.SigningMethodHS256)
  32. claims := token.Claims.(jwt.MapClaims)
  33. for key, val := range m {
  34. claims[key] = val
  35. }
  36. if expire > 0 {
  37. claims["exp"] = time.Now().Add(time.Minute * 30).Unix()
  38. }
  39. tokenString, err := token.SignedString(s.secret)
  40. return tokenString, err
  41. }
  42. // Listen start server in other goroutine
  43. func (s *Rest) Listen(timeout time.Duration) (err error) {
  44. if s.opened.Swap(true) {
  45. return ErrAlreadyOpened
  46. }
  47. ctx, _ := context.WithTimeout(context.Background(), timeout)
  48. go func() {
  49. mux := http.NewServeMux()
  50. mux.HandleFunc("/", s.handle)
  51. s.server = &http.Server{
  52. Addr: s.addr,
  53. Handler: mux,
  54. }
  55. err = s.server.ListenAndServe()
  56. s.opened.Store(false)
  57. }()
  58. <-ctx.Done()
  59. return
  60. }
  61. // Close
  62. func (s *Rest) Close() error {
  63. if !s.opened.Load() {
  64. return ErrNotOpened
  65. }
  66. return s.server.Close()
  67. }
  68. func responseNotFound(w http.ResponseWriter) {
  69. w.WriteHeader(404)
  70. }
  71. func responseError(w http.ResponseWriter, err error, code int) {
  72. w.WriteHeader(code)
  73. w.Write([]byte(err.Error()))
  74. }
  75. // handle
  76. func (s *Rest) handle(w http.ResponseWriter, r *http.Request) {
  77. log.Println("handle", r.URL.Path)
  78. // Инициализация restRequest
  79. rr := &Request{
  80. Request: r,
  81. data: mjson.Map{},
  82. files: make(map[string]io.ReadCloser),
  83. tokenGenerator: s.TokenGenerate,
  84. }
  85. // Парсим Bearer токен и извлекаем claims
  86. authHeader := r.Header.Get("Authorization")
  87. if authHeader != "" {
  88. if parts := strings.Split(authHeader, " "); len(parts) == 2 && parts[0] == "Bearer" {
  89. tokenString := parts[1]
  90. token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
  91. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  92. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  93. }
  94. return s.secret, nil
  95. })
  96. if err != nil {
  97. log.Printf("Failed to parse JWT: %s", err)
  98. http.Error(w, "Invalid token", http.StatusUnauthorized)
  99. return
  100. }
  101. if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
  102. rr.auth = mjson.Map(claims)
  103. }
  104. }
  105. }
  106. // Если это многокомпонентный запрос, обрабатываем файлы
  107. if strings.Index(r.Header.Get("Content-Type"), "multipart/form-data") == 0 {
  108. err := r.ParseMultipartForm(32 << 20) // max memory 32MB, после этого файлы будут сохранены во временных файлах
  109. if err != nil {
  110. responseError(w, fmt.Errorf("failed to parse multipart form: %w", err), 500)
  111. return
  112. }
  113. multiPartForm := r.MultipartForm
  114. data, check := multiPartForm.Value["data"]
  115. if check {
  116. err := json.NewDecoder(bytes.NewBuffer([]byte(data[0]))).Decode(&rr.data)
  117. if err != nil {
  118. responseError(w, fmt.Errorf("failed to decode JSON: %w", err), 500)
  119. return
  120. }
  121. }
  122. for filename, headers := range multiPartForm.File {
  123. for _, header := range headers {
  124. file, err := header.Open()
  125. if err != nil {
  126. responseError(w, fmt.Errorf("failed to open file %s: %w", filename, err), 500)
  127. }
  128. rr.files[filename] = file
  129. }
  130. }
  131. defer rr.Close()
  132. } else {
  133. err := json.NewDecoder(r.Body).Decode(&rr.data)
  134. if err != nil {
  135. responseError(w, fmt.Errorf("failed to decode JSON: %w", err), 500)
  136. return
  137. }
  138. }
  139. // get command
  140. command, check := s.commands.GetCommand(r.URL.Path)
  141. if !check {
  142. responseNotFound(w)
  143. return
  144. }
  145. // validate
  146. resp := command.Validate(rr)
  147. if resp != nil {
  148. if err := resp.Send(w); err != nil {
  149. responseError(w, err, 500)
  150. }
  151. return
  152. }
  153. // execute
  154. resp = command.Execute(rr)
  155. if err := resp.Send(w); err != nil {
  156. responseError(w, err, 500)
  157. }
  158. resp.Close()
  159. }