grim/devweb

move the book api to the top v1 package
draft
2021-01-25, Gary Kramlich
3ea71921fd5f
move the book api to the top v1 package
package v1
import (
"net/http"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"keep.imfreedom.org/grim/devweb/db"
)
func getBook(c *gin.Context) {
bookID := c.Params.ByName("id")
book, err := db.FindBook(bookID)
if err != nil {
c.AbortWithStatus(http.StatusNotFound)
} else {
if c.Request.Method == http.MethodHead {
c.Status(http.StatusOK)
} else {
c.JSON(http.StatusOK, book)
}
}
}
func updateBook(c *gin.Context) {
var book db.Book
c.Bind(&book)
book.ID = c.Params.ByName("id")
err := book.Update()
if err != nil {
log.Errorf("failed to update book %q: %v", book.ID, err)
c.AbortWithStatus(http.StatusBadRequest)
} else {
c.JSON(http.StatusOK, book)
}
}
func deleteBook(c *gin.Context) {
bookID := c.Params.ByName("id")
book, err := db.FindBook(bookID)
if err != nil {
log.Errorf("failed to delete book %q: %v", bookID, err)
c.AbortWithStatus(http.StatusNotFound)
} else {
if err := book.Delete(); err != nil {
log.Errorf("failed to delete book %q: %v", bookID, err)
c.AbortWithStatus(http.StatusInternalServerError)
} else {
c.Status(http.StatusNoContent)
}
}
}