Question

I'm trying to parse JSON using tags with golang. I don't have any errors, but my field are empty

Here is my code :

type HandleConnection struct {
    session string `json:"session"`
    passwd  int   `json:"field1"`   
    salon string `json:"fied2"`
    color string `json:"field3"`
    state float64 `json:"field4"`
    message string `json:"field5"`

}

func connection(login string, passwd string) (*HandleConnection, error) {

    jsonParsedResponse := &HandleConnection{}

    resp, err := http.PostForm(ajaxUrl, url.Values{
        "q": {"bar"}, 
        "v": {"foo"},
        "identifiant": {login},
        "motdepasse": {passwd},
        "mode": {"0"},
        "decalageHoraire": {"0"},
        "option": {""},
        "salon": {"foo"},
    })

    if err != nil {
        return jsonParsedResponse , err
    }

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)

    if err != nil {
        return jsonParsedResponse, err
    }

    err = json.Unmarshal(body, &jsonParsedResponse)

    if err != nil {
        return jsonParsedResponse, err
    }

    if jsonParsedResponse.state != 2 {
        return jsonParsedResponse, errors.New(jsonParsedResponse.message)
    }

    return jsonParsedResponse, nil
}

the returned json is like that

{
  "field1": "foo",
  "fiel2": "bar",
  ...
}

And I would like to know what's the better way for error handling in go.

Thanks for reading

Était-ce utile?

La solution

You are doing the common mistake of having unexported fields in your struct.

The encoding/json package states (my emphasis):

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.

This is due to Go not allowing reflection on unexported fields.
It should work if you change your struct to the following:

type HandleConnection struct {
    Session string  `json:"session"`
    Passwd  int     `json:"field1"`
    Salon   string  `json:"fied2"`
    Color   string  `json:"field3"`
    State   float64 `json:"field4"`
    Message string  `json:"field5"`
}

Autres conseils

You need to start the struct attributes with Capitals so they are public and unmarshaling has access to those fields.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top