4

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.

WoJ
  • 27,165
  • 48
  • 180
  • 345
Alok G.
  • 1,388
  • 3
  • 15
  • 26
  • How do you know `req.Body` is empty? What does the error returned from `Decode` say? What do you mean it's about Render / Bind? What have those two anything to do with this? – mkopriva Aug 28 '19 at 09:31
  • ... also show how you've defined the `Book` model. – mkopriva Aug 28 '19 at 09:32
  • I have updated questions, no error is thrown by Decode method. – Alok G. Aug 28 '19 at 09:55
  • 3
    ok so the first problem is that your fields are unexported. `encoding/json` doesn't work on unexported fields. First export the fields, try again, and if that doesn't fix it update the question with the progress. – mkopriva Aug 28 '19 at 10:02
  • 1
    https://golang.org/ref/spec#Exported_identifiers – mkopriva Aug 28 '19 at 10:02
  • Ohh, I missed that part, and after exporting fields, it resolved the problem, many thanks. – Alok G. Aug 28 '19 at 10:46

1 Answers1

1

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

}

Alok G.
  • 1,388
  • 3
  • 15
  • 26