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

JSON parsing failed #729

Closed
1 task done
zorro0799 opened this issue Aug 14, 2023 · 7 comments
Closed
1 task done

JSON parsing failed #729

zorro0799 opened this issue Aug 14, 2023 · 7 comments
Assignees
Labels

Comments

@zorro0799
Copy link

zorro0799 commented Aug 14, 2023

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"strconv"

	"github.com/gorilla/mux"
)

// Book struct (Model)
type Book struct {
	ID    string `json:"id"`
	Isbn  string `json:"isbn"`
	Title string `json:"title"`
	//Author *Author `json:"author"`
}

// Author struct
type Author struct {
	Firstname string `json:"firstname"`
	Lastname  string `json:"lastname"`
}

// Init books var as a slice Book struct
var books []Book

// Get all books
func getBooks(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(books)
}

// Get single book
func getBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r) // Gets params
	// Loop through books and find one with the id from the params
	for _, item := range books {
		if item.ID == params["id"] {
			json.NewEncoder(w).Encode(item)
			return
		}
	}
	json.NewEncoder(w).Encode(&Book{})
}

// Add new book
func createBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	var book Book
	var vv error = json.NewDecoder(r.Body).Decode(&book)
	println(vv)
	book.ID = strconv.Itoa(rand.Intn(100000000)) // Mock ID - not safe
	books = append(books, book)
	json.NewEncoder(w).Encode(book)
	fmt.Println("isbn", book.Isbn, "title", book.Title)
}

// Update book
func updateBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	for index, item := range books {
		if item.ID == params["id"] {
			books = append(books[:index], books[index+1:]...)
			var book Book
			_ = json.NewDecoder(r.Body).Decode(&book)
			book.ID = params["id"]
			books = append(books, book)
			json.NewEncoder(w).Encode(book)
			return
		}
	}
}

// Delete book
func deleteBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	for index, item := range books {
		if item.ID == params["id"] {
			books = append(books[:index], books[index+1:]...)
			break
		}
	}
	json.NewEncoder(w).Encode(books)
}

// Main function
func main() {
	// Init router
	r := mux.NewRouter()

	// Hardcoded data - @todo: add database
	//books = append(books, Book{ID: "1", Isbn: "438227", Title: "Book One", Author: &Author{Firstname: "John", Lastname: "Doe"}})
	//books = append(books, Book{ID: "2", Isbn: "454555", Title: "Book Two", Author: &Author{Firstname: "Steve", Lastname: "Smith"}})
	books = append(books, Book{ID: "1", Isbn: "438227", Title: "Book One"})
	books = append(books, Book{ID: "2", Isbn: "454555", Title: "Book Two"})

	// Route handles & endpoints
	r.HandleFunc("/books", getBooks).Methods("GET")
	r.HandleFunc("/books/{id}", getBook).Methods("GET")
	r.HandleFunc("/books", createBook).Methods("POST")
	r.HandleFunc("/books/{id}", updateBook).Methods("PUT")
	r.HandleFunc("/books/{id}", deleteBook).Methods("DELETE")

	// Start server
	log.Fatal(http.ListenAndServe(":8000", r))
}

// Request sample
// {
// "isbn":"4545454",
// "title":"Book Three",
// "author":{"firstname":"Harry","lastname":"White"}
// }

Postman simulates the post event and calls createBook
JSON parsing failed

Expected Behavior

json decode success

Steps To Reproduce

1.mac os Monterey
2.
json data
// Request sample
// {
// "isbn":"4545454",
// "title":"Book Three",
// "author":{"firstname":"Harry","lastname":"White"}
// }

Postman simulates the post event and calls createBook
JSON parsing failed

Anything else?

No response

@coreydaley
Copy link
Contributor

I am not able to reproduce your error using the following curl command:
curl --header "Content-Type: application/json" --request POST --data '{"isbn":"4545454","title":"Book Three","author":{"firstname":"Harry","lastname":"White"}}' http://localhost:8000/books

Can you provide the actual error that you are getting?

@coreydaley coreydaley self-assigned this Aug 14, 2023
@jackgris
Copy link

I tested that and everything works well for me. When I make the POST request with that data, I receive a response like this:

{
    "id": "42982700",
    "isbn": "4545454",
    "title": "Book Three"
}

And also I added log to check the errors when encode the json.

	err := json.NewEncoder(w).Encode(book)
	if err != nil {
		log.Println(err)
	}

@coreydaley
Copy link
Contributor

It could be a problem with your postman setup, I am guessing this is what you are using?
https://www.postman.com/

@zorro0799
Copy link
Author

可能是你的postman设置有问题,我猜你用的是这个? https://www.postman.com/

Indeed, I am using postman, my environment is,
macos 12.6.8, go version go1.21.0
I tried to use RapidApi to simulate the post request, the result is correct, but the shopping store is always lost with postman
截屏2023-08-15 21 28 29
截屏2023-08-15 21 24 27
截屏2023-08-15 21 25 07

@coreydaley
Copy link
Contributor

coreydaley commented Aug 15, 2023

Does postman persist your application? Does it keep it running in the background? If not, and it restarts it for every request, that would remove the data that you just submitted from memory since you are not using a persistent data store.

I have never used postman so I have no idea how it works, but it seems like this is not an issue with the mux library.

@zorro0799
Copy link
Author

Does postman persist your application? Does it keep it running in the background? If not, and it restarts it for every request, that would remove the data that you just submitted from memory since you are not using a persistent data store.

I have never used postman so I have no idea how it works, but it seems like this is not an issue with the mux library.

I confirm that I clean up the process every time I test, and then run a new instance, the same program, simulated with other tools, such as RApidApi (Paw), there is no problem, it seems to be a problem with postman, thank you for your answer

@zorro0799
Copy link
Author

I tested that and everything works well for me. When I make the POST request with that data, I receive a response like this:

{
    "id": "42982700",
    "isbn": "4545454",
    "title": "Book Three"
}

And also I added log to check the errors when encode the json.

	err := json.NewEncoder(w).Encode(book)
	if err != nil {
		log.Println(err)
	}

Thank you for your answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: ✅ Done
Development

No branches or pull requests

3 participants