Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

carlota #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 155 additions & 17 deletions controllers/library.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"net/http"
"strconv"
"strings"

"cloud.google.com/go/datastore"
"github.com/go-martini/martini"
Expand All @@ -24,30 +25,19 @@ func (lc LibraryController) GetByKey(params martini.Params, w http.ResponseWrite

id, err := strconv.Atoi(params["id"])

if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
HandleError(err, w)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think HandleError needs to be a public method (starting with a H rather than a h).

If err was an error, it would write the error and set the header, but continue on with the rest of the method anyway. You would probably have to move the if block from the handleError method up to this call and have the handleError then write the response and the header

if err != nil {
handleError(err, w)
return
}


var book models.Book
key := datastore.IDKey("Book", int64(id), nil)

err = client.Get(ctx, key, &book)

if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
HandleError(err, w)

jsonStr, err := json.MarshalIndent(book, "", " ")

if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
HandleError(err, w)


w.WriteHeader(http.StatusOK)
w.Write(jsonStr)
Expand All @@ -61,7 +51,7 @@ func (lc LibraryController) ListAll(r *http.Request, w http.ResponseWriter) {

var output []models.Book

it := client.Run(ctx, datastore.NewQuery("Book"))
it := client.Run(ctx, datastore.NewQuery("Book").Order("Id"))
for {
var b models.Book
_, err := it.Next(&b)
Expand All @@ -74,12 +64,160 @@ func (lc LibraryController) ListAll(r *http.Request, w http.ResponseWriter) {

jsonStr, err := json.MarshalIndent(output, "", " ")

HandleError(err, w)

w.WriteHeader(http.StatusOK)
w.Write(jsonStr)
}

func HandleError (err error, w http.ResponseWriter) {
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
w.WriteHeader(http.StatusBadRequest)
return
}
}

func (lc LibraryController) SearchByName(params martini.Params, w http.ResponseWriter) {
ctx := context.Background()
client, _ := datastore.NewClient(ctx, "acme-books")

defer client.Close()

name := strings.ReplaceAll(params["name"], "%20"," ")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://pkg.go.dev/net/url#QueryUnescape would do this for all url encoded chars, rather than just replacing %20 with a space



fmt.Println(name)


//HandleError(err, w)

var output []models.Book

q := datastore.NewQuery("Book").Filter("Title=", name)

it := client.Run(ctx,q)

for {
var b models.Book
_, err := it.Next(&b)
fmt.Println(b)
if err == iterator.Done {
fmt.Println(err)
break
}
output = append(output, b)
}

jsonStr, err := json.MarshalIndent(output, "", " ")

HandleError(err, w)

w.WriteHeader(http.StatusOK)
w.Write(jsonStr)
}

func (lc LibraryController) Borrow (params martini.Params, w http.ResponseWriter) {
ctx := context.Background()
client, _ := datastore.NewClient(ctx, "acme-books")

defer client.Close()

id, err := strconv.Atoi(params["id"])

HandleError(err, w)

var book models.Book
key := datastore.IDKey("Book", int64(id), nil)

err = client.Get(ctx, key, &book)

switch {
case err != nil:
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("invalid id"))
case book.Borrowed:
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("already borrowed"))
default:
book.Borrowed = true
_, err = client.Put(ctx, key, &book)
HandleError(err, w)

jsonStr, err := json.MarshalIndent(book, "", " ")

HandleError(err, w)

w.WriteHeader(http.StatusOK)
w.Write(jsonStr)
}


}

func (lc LibraryController) Return (params martini.Params, w http.ResponseWriter) {
ctx := context.Background()
client, _ := datastore.NewClient(ctx, "acme-books")

defer client.Close()

id, err := strconv.Atoi(params["id"])

HandleError(err, w)

var book models.Book
key := datastore.IDKey("Book", int64(id), nil)

err = client.Get(ctx, key, &book)

switch {
case err != nil:
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("invalid id"))
return
case !book.Borrowed:
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("already returned"))
default:
book.Borrowed = false
_, err = client.Put(ctx, key, &book)
HandleError(err, w)

jsonStr, err := json.MarshalIndent(book, "", " ")

HandleError(err, w)

w.WriteHeader(http.StatusOK)
w.Write(jsonStr)
}
}

func (lc LibraryController) CreateBook (r *http.Request, w http.ResponseWriter) {
ctx := context.Background()
client, _ := datastore.NewClient(ctx, "acme-books")

defer client.Close()

var book models.Book


err := json.NewDecoder(r.Body).Decode(&book)
HandleError(err, w)

key := datastore.IncompleteKey("Book", nil)
fmt.Println(key)

newKey, err := client.Put(ctx, key, &book)
book.Id = newKey.ID
fmt.Println(book)
HandleError(err, w)


jsonStr, err := json.MarshalIndent(book, "", " ")

HandleError(err, w)

w.WriteHeader(http.StatusOK)
w.Write(jsonStr)

}
9 changes: 6 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"log"
"os"
"strings"

"cloud.google.com/go/datastore"

Expand Down Expand Up @@ -44,13 +45,15 @@ func bootstrapBooks() {
books := []models.Book{
{Id: 1, Author: "George Orwell", Title: "1984", Borrowed: false},
{Id: 2, Author: "George Orwell", Title: "Animal Farm", Borrowed: false},
{Id: 3, Author: "Robert Jordan", Title: "Eye of the world", Borrowed: false},
{Id: 4, Author: "Various", Title: "Collins Dictionary", Borrowed: false},
{Id: 3, Author: "Variorewgr4g4gus", Title: "Collins Dictionary", Borrowed: false},
{Id: 4, Author: "Robert Jordan", Title: "Eye of the world", Borrowed: false},
}

var keys []*datastore.Key

for _, book := range books {
for index, book := range books {
books[index].Title = strings.Title(book.Title)
books[index].Author = strings.Title(book.Author)
keys = append(keys, datastore.IDKey("Book", book.Id, nil))
}

Expand Down
4 changes: 4 additions & 0 deletions server/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ func NewRouter() *martini.ClassicMartini {

router.Get("/books", libraryController.ListAll)
router.Get("/books/:id", libraryController.GetByKey)
router.Get("/searchByName/:name", libraryController.SearchByName)
router.Put("/:id/borrow", libraryController.Borrow)
router.Put("/:id/return", libraryController.Return)
router.Post("/book", libraryController.CreateBook)

return router
}