Skip to content

Instantly share code, notes, and snippets.

View dumindu's full-sized avatar
🦄
One step at a time

Dumindu Madunuwan dumindu

🦄
One step at a time
View GitHub Profile
// import "myapp/model"
func (app *App) HandleCreateBook(w http.ResponseWriter, r *http.Request) {
form := &model.BookForm{}
if err := json.NewDecoder(r.Body).Decode(form); err != nil {
app.logger.Warn().Err(err).Msg("")
w.WriteHeader(http.StatusUnprocessableEntity)
fmt.Fprintf(w, `{"error": "%v"}`, appErrFormDecodingFailure)
return
type BookForm struct {
Title string `json:"title"`
Author string `json:"author"`
PublishedDate string `json:"published_date"`
ImageUrl string `json:"image_url"`
Description string `json:"description"`
}
func (f *BookForm) ToModel() (*Book, error) {
pubDate, err := time.Parse("2006-01-02", f.PublishedDate)
func CreateBook(db *gorm.DB, book *model.Book) (*model.Book, error) {
if err := db.Create(book).Error; err != nil {
return nil, err
}
return book, nil
}
func CreateBook(db *gorm.DB, book *model.Book) (*model.Book, error) {
if err := db.Create(book).Error; err != nil {
return nil, err
}
return book, nil
}
func (app *App) HandleDeleteBook(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 0, 64)
if err != nil || id == 0 {
app.logger.Info().Msgf("can not parse ID: %v", id)
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
if err := repository.DeleteBook(app.db, uint(id)); err != nil {
func DeleteBook(db *gorm.DB, id uint) error {
book := &model.Book{}
if err := db.Where("id = ?", id).Delete(&book).Error; err != nil {
return err
}
return nil
}
import (
"github.com/jinzhu/gorm"
"myapp/model"
)
func ReadBook(db *gorm.DB, id uint) (*model.Book, error) {
book := &model.Book{}
if err := db.Where("id = ?", id).First(&book).Error; err != nil {
return nil, err
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/go-chi/chi"
"github.com/jinzhu/gorm"
"myapp/repository"
const (
appErrDataAccessFailure = "data access failure"
appErrJsonCreationFailure = "json creation failure"
)
import (
"encoding/json"
"fmt"
"net/http"
"myapp/repository"
)
func (app *App) HandleListBooks(w http.ResponseWriter, r *http.Request) {
books, err := repository.ListBooks(app.db)