This commit is contained in:
2021-12-21 00:17:09 +01:00
commit 1506a57231
11 changed files with 187 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
package responses
import (
"github.com/go-chi/render"
"net/http"
)
type ErrResponse struct {
Err error `json:"-"` // low-level runtime error
HTTPStatusCode int `json:"-"` // http response status code
StatusText string `json:"status"` // user-level status message
AppCode int64 `json:"code,omitempty"` // application-specific error code
ErrorText string `json:"error,omitempty"` // application-level error message, for debugging
}
func (e ErrResponse) Render(w http.ResponseWriter, r *http.Request) error {
render.Status(r, e.HTTPStatusCode)
return nil
}
func ErrInvalidRequest(err error) render.Renderer {
return &ErrResponse{
Err: err,
HTTPStatusCode: 400,
StatusText: "Invalid request.",
ErrorText: err.Error(),
}
}

View File

@@ -0,0 +1,42 @@
package download
import (
"downloader/internal/app/api/common/responses"
"errors"
"github.com/go-chi/chi"
"github.com/go-chi/render"
"net/http"
)
type api struct{}
func New() *api {
return &api{}
}
func (api *api) SetupDownloadApi(router *chi.Mux) {
router.Route("/downloads", func(r chi.Router) {
r.Post("/", api.requestDownload)
})
}
type requestDownloadRequest struct {
Provider string `json:"provider"`
Link string `json:"link"`
}
func (dr *requestDownloadRequest) Bind(r *http.Request) error {
if dr.Link == "" || dr.Provider == "" {
return errors.New("missing required download request field")
}
return nil
}
func (api *api) requestDownload(w http.ResponseWriter, r *http.Request) {
data := &requestDownloadRequest{}
if err := render.Bind(r, data); err != nil {
_ = render.Render(w, r, responses.ErrInvalidRequest(err))
return
}
}