gin.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package common
  2. import (
  3. "bytes"
  4. "github.com/gin-gonic/gin"
  5. "io"
  6. "one-api/constant"
  7. "strings"
  8. "time"
  9. )
  10. const KeyRequestBody = "key_request_body"
  11. func GetRequestBody(c *gin.Context) ([]byte, error) {
  12. requestBody, _ := c.Get(KeyRequestBody)
  13. if requestBody != nil {
  14. return requestBody.([]byte), nil
  15. }
  16. requestBody, err := io.ReadAll(c.Request.Body)
  17. if err != nil {
  18. return nil, err
  19. }
  20. _ = c.Request.Body.Close()
  21. c.Set(KeyRequestBody, requestBody)
  22. return requestBody.([]byte), nil
  23. }
  24. func UnmarshalBodyReusable(c *gin.Context, v any) error {
  25. requestBody, err := GetRequestBody(c)
  26. if err != nil {
  27. return err
  28. }
  29. contentType := c.Request.Header.Get("Content-Type")
  30. if strings.HasPrefix(contentType, "application/json") {
  31. err = UnmarshalJson(requestBody, &v)
  32. } else {
  33. // skip for now
  34. // TODO: someday non json request have variant model, we will need to implementation this
  35. }
  36. if err != nil {
  37. return err
  38. }
  39. // Reset request body
  40. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  41. return nil
  42. }
  43. func SetContextKey(c *gin.Context, key constant.ContextKey, value any) {
  44. c.Set(string(key), value)
  45. }
  46. func GetContextKey(c *gin.Context, key constant.ContextKey) (any, bool) {
  47. return c.Get(string(key))
  48. }
  49. func GetContextKeyString(c *gin.Context, key constant.ContextKey) string {
  50. return c.GetString(string(key))
  51. }
  52. func GetContextKeyInt(c *gin.Context, key constant.ContextKey) int {
  53. return c.GetInt(string(key))
  54. }
  55. func GetContextKeyBool(c *gin.Context, key constant.ContextKey) bool {
  56. return c.GetBool(string(key))
  57. }
  58. func GetContextKeyStringSlice(c *gin.Context, key constant.ContextKey) []string {
  59. return c.GetStringSlice(string(key))
  60. }
  61. func GetContextKeyStringMap(c *gin.Context, key constant.ContextKey) map[string]any {
  62. return c.GetStringMap(string(key))
  63. }
  64. func GetContextKeyTime(c *gin.Context, key constant.ContextKey) time.Time {
  65. return c.GetTime(string(key))
  66. }