|
| 1 | +package transport |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + |
| 8 | + appErr "example/internal/errors" |
| 9 | + "example/internal/users" |
| 10 | + |
| 11 | + "github.com/labstack/echo/v4" |
| 12 | +) |
| 13 | + |
| 14 | +type HTTPConfig struct { |
| 15 | + Port int |
| 16 | + UsersService users.Service |
| 17 | +} |
| 18 | + |
| 19 | +type HTTPServer struct { |
| 20 | + e *echo.Echo |
| 21 | + port int |
| 22 | +} |
| 23 | + |
| 24 | +func NewHTTPServer(config *HTTPConfig) *HTTPServer { |
| 25 | + e := echo.New() |
| 26 | + registerHTTPRoutes(e, config.UsersService) |
| 27 | + return &HTTPServer{ |
| 28 | + e: e, |
| 29 | + port: config.Port, |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +func (server *HTTPServer) Start() { |
| 34 | + server.e.Logger.Fatal(server.e.Start(fmt.Sprintf(":%d", server.port))) |
| 35 | +} |
| 36 | + |
| 37 | +func registerHTTPRoutes(e *echo.Echo, usersService users.Service) { |
| 38 | + e.PUT("/users/:id", updateUser(usersService)) |
| 39 | +} |
| 40 | + |
| 41 | +type updateUserRequest struct { |
| 42 | + ID string `param:"id"` |
| 43 | + FirstName string `json:"first_name"` |
| 44 | + LastName string `json:"last_name"` |
| 45 | +} |
| 46 | + |
| 47 | +type updateUserResponse struct { |
| 48 | + ID string `json:"id"` |
| 49 | + FirstName string `json:"first_name"` |
| 50 | + LastName string `json:"last_name"` |
| 51 | +} |
| 52 | + |
| 53 | +func updateUser(usersService users.Service) echo.HandlerFunc { |
| 54 | + return func(c echo.Context) error { |
| 55 | + var request updateUserRequest |
| 56 | + err := c.Bind(&request) |
| 57 | + if err != nil { |
| 58 | + return c.NoContent(http.StatusBadRequest) |
| 59 | + } |
| 60 | + |
| 61 | + resp, err := usersService.UpdateUser(users.UpdateUserRequest{ |
| 62 | + ID: request.ID, |
| 63 | + FirstName: request.FirstName, |
| 64 | + LastName: request.LastName, |
| 65 | + }) |
| 66 | + |
| 67 | + if err != nil { |
| 68 | + return c.NoContent(MapErrorToHTTPStatus(err)) |
| 69 | + } |
| 70 | + return c.JSON(http.StatusOK, updateUserResponse{ |
| 71 | + ID: resp.ID, |
| 72 | + FirstName: resp.FirstName, |
| 73 | + LastName: resp.LastName, |
| 74 | + }) |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +func MapErrorToHTTPStatus(err error) int { |
| 79 | + switch { |
| 80 | + case errors.Is(err, appErr.ErrNotFound): |
| 81 | + return http.StatusNotFound |
| 82 | + case errors.Is(err, appErr.ErrBadRequest): |
| 83 | + return http.StatusNotFound |
| 84 | + } |
| 85 | + return http.StatusInternalServerError |
| 86 | +} |
0 commit comments