Library/routes/api/v1/books_add.go

37 lines
822 B
Go

package v1
import (
"encoding/json"
"git.mowie.cc/konrad/Library/models"
"github.com/labstack/echo"
"net/http"
"strings"
)
// BookAdd is the handler to add a book
func BookAdd(c echo.Context) error {
// Check for Request Content
book := c.FormValue("book")
if book == "" {
return c.JSON(http.StatusBadRequest, models.Message{"No book model provided"})
}
// Decode the JSON
var bookstruct models.Book
dec := json.NewDecoder(strings.NewReader(book))
err := dec.Decode(&bookstruct)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding book: " + err.Error()})
}
// Insert the book
newBook, err := models.AddBook(bookstruct)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
}
return c.JSON(http.StatusOK, newBook)
}