I'm relatively new to Go, and while I have a pretty good grasp on understanding most of it so far, I can't exactly figure out how JSON is supposed to be handled.
So let's say I have an access token on the front end. I want to pass it go and want to make a request to an API to validate it.
This is the json being passed to the backend:
{ "accessToken": "xxxxxx" } type test_struct struct { AccessToken string `json:"accessToken"` } func validateFacebookLogin(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) var t test_struct err := decoder.Decode(&t) if err != nil { panic(err) } tokenCheck := "xxxxxxxxx|xxxxxxxxxxxxxxxxxxxxxxxxxxx" req, err := http.NewRequest("GET", "https://graph.facebook.com/debug_token", nil) if err != nil { log.Print(err) os.Exit(1) } q := req.URL.Query() q.Add("input_token", t.AccessToken) q.Add("access_token", tokenCheck) req.URL.RawQuery = q.Encode() resp, err := http.Get(req.URL.String()) defer resp.Body.Close() bodyBytes, _ := ioutil.ReadAll(resp.Body) bodyString := string(bodyBytes) fmt.Println(bodyString); json.NewEncoder(w).Encode(map[string]string{"message": "FINE"}) json.NewEncoder(w).Encode(resp) } All documentation I can find seems to indicate that a struct should be created for all JSON responses/requests (unless I'm misunderstanding). Isn't that kind of inconvenient? What if I have an incredibly large nested JSON response? Do I have to create struct of the COMPLETE response?
Is the method I'm using above with ioutil bad practice? Where I could just pass back an entire string representation and manage decoding it on the front-end?
I guess my main question is, when should I be assign my JSON to a struct? What are considered the best practices? If I intent on just returning the response immediately to the front end, is there any point it?
And assuming I do want to maintain the data on the back end, is there any "better" method for handling large responses?
map[string]interface{}. But structs are generally a lot easier to work with, including for large responses (really, especially for large, deeply-nested responses, to avoid a ton of checks and assertions).