#How to handle POST request with a JSON body

25 messages · Page 1 of 1 (latest)

lone cipher
#

I also have a GET route:

http.HandleFunc("GET /", getAllBooks)

func getAllBooks(w http.ResponseWriter, req *http.Request) {
    fmt.Println("GET Request - getAllBooks")

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    for i, book := range books {
        json.NewEncoder(w).Encode([]byte(i + ": " + book.title))
    }
}

But when I call it I get this:

sacred grove
#

The issue is with the book struct
the field names should start with uppercase and the json tag should be like json:"title"

lone cipher
#

ahh okay I will give it a try

#

I just noticed I put the cursed books[book.title].title in the code I shared

sacred grove
#

A bit cursed but not the issue

lone cipher
#

Amazing!

#

Okay now I can POST but the get response is still garbled

#

but I prob need to marshall it right

#

ah no mhm idk whats up there, but ill try to figure it out

#

thank you Sha2048

#

you are my favourite encryption algorithm

sacred grove
#

json.NewEncoder(w).Encode([]byte(i + ": " + book.title))
What you're doing is turning this i ": " + book.title bytes, then encoding that as json
Instead you should get the books as slice of books []Book and pass that to the Encoder (once, not multiple times in a loop)

lone cipher
#

yep doing that now

sacred grove
lone cipher
#

oh wow okay!

#

I thought that uppercase export was mainly for like

#

other files I would use

#

so if I had another file called Book.go

#

and declare my struct there

#

okay thats interesting

sacred grove
#

the json package lives in another file

lone cipher
#
func getAllBooks(w http.ResponseWriter, req *http.Request) {
    fmt.Println("GET Request - getAllBooks")

    booksJson, err := json.Marshal(books)

    if err != nil {
        log.Fatal(err)
    }

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    w.Write(booksJson)
}
#

this looking good?

sacred grove
#

Sure 👍