package v1 import ( "encoding/json" "fmt" "git.mowie.cc/konrad/Library/models" "github.com/labstack/echo" "net/http" "strings" ) type bookPayload struct { Book models.Book `json:"book" form:"book"` } // BookAddOrUpdate is the handler to add a book func BookAddOrUpdate(c echo.Context) error { // Check for Request Content bookFromString := c.FormValue("book") var bookToInsert models.Book if bookFromString == "" { b := new(bookPayload) if err := c.Bind(b); err != nil { fmt.Println(err) return c.JSON(http.StatusBadRequest, models.Message{"No book model provided"}) } bookToInsert = b.Book } else { // Decode the JSON dec := json.NewDecoder(strings.NewReader(bookFromString)) err := dec.Decode(&bookToInsert) if err != nil { return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding book: " + err.Error()}) } } // Check if we have at least a title if bookToInsert.Title == "" { return c.JSON(http.StatusBadRequest, models.Message{"You need at least a title to insert a new book!"}) } // Insert the book newBook, err := models.AddOrUpdateBook(bookToInsert) if err != nil { return c.JSON(http.StatusInternalServerError, models.Message{"Error"}) } return c.JSON(http.StatusOK, newBook) }