57 lines
1.1 KiB
Go

package handler
import (
"encoding/json"
"net/http"
"strconv"
"gitea.michaelthomson.dev/mthomson/habits/internal/todo/service"
)
type GetTodoResponse struct {
Id int64 `json:"id"`
Name string `json:"name"`
Done bool `json:"done"`
}
func GetTodoResponseFromTodo(todo service.Todo) GetTodoResponse {
return GetTodoResponse{Id: todo.Id, Name: todo.Name, Done: todo.Done}
}
func HandleTodoGet(todoService TodoGetter) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
idString := r.PathValue("id")
id, err := strconv.ParseInt(idString, 10, 64)
if err != nil {
http.Error(w, "", http.StatusBadRequest)
return
}
todo, err := todoService.GetTodo(id)
if err != nil {
if err == service.ErrNotFound {
http.Error(w, "", http.StatusNotFound)
return
}
http.Error(w, "", http.StatusInternalServerError)
return
}
response := GetTodoResponseFromTodo(todo)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(response)
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
}
}