37 lines
744 B
Go
37 lines
744 B
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"git.workflows.cl/mcabezas/testing-go-example/internal/models"
|
|
)
|
|
|
|
type BookHandler struct {
|
|
books []models.Book
|
|
}
|
|
|
|
func NewBookHandler() *BookHandler {
|
|
return &BookHandler{
|
|
books: []models.Book{
|
|
{ID: "1", Title: "El Quijote", Author: "Cervantes"},
|
|
{ID: "2", Title: "Cien años de soledad", Author: "García Márquez"},
|
|
},
|
|
}
|
|
}
|
|
|
|
func (h *BookHandler) GetBook(w http.ResponseWriter, r *http.Request) {
|
|
id := chi.URLParam(r, "id")
|
|
|
|
for _, book := range h.books {
|
|
if book.ID == id {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(book)
|
|
return
|
|
}
|
|
}
|
|
|
|
http.Error(w, "Book not found", http.StatusNotFound)
|
|
}
|