func_createapi.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package authorized
  2. import (
  3. "net/http"
  4. "github.com/xinliangnote/go-gin-api/internal/code"
  5. "github.com/xinliangnote/go-gin-api/internal/pkg/core"
  6. "github.com/xinliangnote/go-gin-api/internal/services/authorized"
  7. )
  8. type createAPIRequest struct {
  9. Id string `form:"id"` // HashID
  10. Method string `form:"method"` // 请求方法
  11. API string `form:"api"` // 请求地址
  12. }
  13. type createAPIResponse struct {
  14. Id int32 `json:"id"` // 主键ID
  15. }
  16. // CreateAPI 授权调用方接口地址
  17. // @Summary 授权调用方接口地址
  18. // @Description 授权调用方接口地址
  19. // @Tags API.authorized
  20. // @Accept application/x-www-form-urlencoded
  21. // @Produce json
  22. // @Param id formData string true "HashID"
  23. // @Param method formData string true "请求方法"
  24. // @Param api formData string true "请求地址"
  25. // @Success 200 {object} createAPIResponse
  26. // @Failure 400 {object} code.Failure
  27. // @Router /api/authorized_api [post]
  28. // @Security LoginToken
  29. func (h *handler) CreateAPI() core.HandlerFunc {
  30. return func(c core.Context) {
  31. req := new(createAPIRequest)
  32. res := new(createAPIResponse)
  33. if err := c.ShouldBindForm(req); err != nil {
  34. c.AbortWithError(core.Error(
  35. http.StatusBadRequest,
  36. code.ParamBindError,
  37. code.Text(code.ParamBindError)).WithError(err),
  38. )
  39. return
  40. }
  41. ids, err := h.hashids.HashidsDecode(req.Id)
  42. if err != nil {
  43. c.AbortWithError(core.Error(
  44. http.StatusBadRequest,
  45. code.HashIdsDecodeError,
  46. code.Text(code.HashIdsDecodeError)).WithError(err),
  47. )
  48. return
  49. }
  50. id := int32(ids[0])
  51. // 通过 id 查询出 business_key
  52. authorizedInfo, err := h.authorizedService.Detail(c, id)
  53. if err != nil {
  54. c.AbortWithError(core.Error(
  55. http.StatusBadRequest,
  56. code.AuthorizedDetailError,
  57. code.Text(code.AuthorizedDetailError)).WithError(err),
  58. )
  59. return
  60. }
  61. createAPIData := new(authorized.CreateAuthorizedAPIData)
  62. createAPIData.BusinessKey = authorizedInfo.BusinessKey
  63. createAPIData.Method = req.Method
  64. createAPIData.API = req.API
  65. createId, err := h.authorizedService.CreateAPI(c, createAPIData)
  66. if err != nil {
  67. c.AbortWithError(core.Error(
  68. http.StatusBadRequest,
  69. code.AuthorizedCreateAPIError,
  70. code.Text(code.AuthorizedCreateAPIError)).WithError(err),
  71. )
  72. return
  73. }
  74. res.Id = createId
  75. c.Payload(res)
  76. }
  77. }