-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_task.go
46 lines (41 loc) · 990 Bytes
/
add_task.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package handler
import (
"encoding/json"
"net/http"
"github.com/afushimi-source/go_todo_app/entity"
"github.com/go-playground/validator/v10"
)
type AddTask struct {
Service AddTaskService
Validator *validator.Validate
}
func (at *AddTask) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var b struct {
Title string `json:"title" validate:"required"`
}
if err := json.NewDecoder(r.Body).Decode(&b); err != nil {
RespondJSON(ctx, w, &ErrResponse{
Message: err.Error(),
}, http.StatusInternalServerError)
return
}
err := validator.New().Struct(b)
if err != nil {
RespondJSON(ctx, w, &ErrResponse{
Message: err.Error(),
}, http.StatusBadRequest)
return
}
t, err := at.Service.AddTask(ctx, b.Title)
if err != nil {
RespondJSON(ctx, w, &ErrResponse{
Message: err.Error(),
}, http.StatusInternalServerError)
return
}
rsp := struct {
ID entity.TaskID `json:"id"`
}{ID: t.ID}
RespondJSON(ctx, w, rsp, http.StatusOK)
}