Consider the following code in main/entry function
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Post("/book", controllers.CreateBook)
http.ListenAndServe(":3333", r)
and CreateBook Function defined as
func CreateBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
var bookObj models.Book
err := json.NewDecoder(r.Body).Decode(&bookObj)
spew.Dump(bookObj)
collection := db.Client.Database("bookdb").Collection("book")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
insertResult, err := collection.InsertOne(ctx, bookObj)
if err != nil {
log.Fatal(err)
}
json.NewEncoder(w).Encode(insertResult)
}
Book Model
//exporting attributes here solved the issue
type Book struct {
ID primitive.ObjectID json:"id,omitempty" bson:"id,omitempty"
name string json:"name,omitempty" bson:"name,omitempty"
author string json:"author,omitempty" bson:"author,omitempty"
isbn string json:"isbn,omitempty" bson:"isbn,omitempty"
}
However json.NewDecoder(r.Body).Decode(&bookObj)
dont parse any things as req.Body is empty, no error thrown, its about chi's Render function, Can anyone help me to disable Render and Bind functions of Chi, I would like to parse body through JSON decoders only.
Thanks.