-1

Quite new to golang, I am trying to read the post json request body in golang, but it just converts to empty string.

Below is the struct which I am trying to convert by request json body to

type SdpPost struct {
    id string
    sdp string
}

func (s *SdpPost) Id() string {
    return s.id
}

func (s *SdpPost) SetSdp(sdp string) {
    s.sdp = sdp
}

func (s *SdpPost) Sdp() string {
    return s.sdp
}

When I try to print the below snippet, I do see my json request body which I am passing through postman

Dumping the json POST /v1/sdp HTTP/1.1
Host: localhost:8080
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 62
Content-Type: application/json
Postman-Token: 5f0f9961-f058-446a-86e8-7f047c1dc5cc
User-Agent: PostmanRuntime/7.24.1

{
        "sdp":"This is the test sdp",
        "id":"This is the test id"
}

But the below code prints nothing, it is just empty string for Id and sdp

    r.Header.Set("Content-Type", "application/json")
    decoder := json.NewDecoder(r.Body)
    sdp := handler.SdpPost{}
    decoder.Decode(&sdp)
    w.WriteHeader(http.StatusOK)
    fmt.Print(sdp.Id())
    fmt.Println(sdp.Sdp())

Is there anything which I am missing somewhere? I literally searched every where and this is pretty much being used.

log N
  • 925
  • 9
  • 33

1 Answers1

0

Problem is that SdpPost fields are unexported, so json decoder doesn't see them, you can fix that like that:

type SdpPost struct {
    Id string
    Sdp string
}
Grigoriy Mikhalkin
  • 5,035
  • 1
  • 18
  • 36
  • That did work, any way I can make it work just by exposing the getters and setters? – log N May 14 '20 at 20:39
  • @logN You can implement [`json.Unmarshaler`](https://golang.org/pkg/encoding/json/#Unmarshaler) interface(i.e. add method `UnmarshalJSON`). And no, you can't use setters directly for unmarshaling. – Grigoriy Mikhalkin May 14 '20 at 20:44
  • 1
    Thanks @Grigoriy, that did answer it, lots of things to learn for me!! – log N May 14 '20 at 20:45