feat: initial project setup
This commit is contained in:
36
internal/handlers/book_handler.go
Normal file
36
internal/handlers/book_handler.go
Normal file
@@ -0,0 +1,36 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user