Unable to read "request.Body" in Go Chi router

Issue

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) does not parse anything as req.Body is empty, no error thrown, it’s about chi’s Render function.

Can anyone help me to disable Render and Bind functions of chi, I would like to parse the body through JSON decoders only.

Solution

Exporting all fields of structs resolved the issue. thanks @mkopriva

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"`

}

Answered By – Alok G.

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.