去处理JSON响应和请求

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?

In most cases, you'll want to simply utilize json.Unmarshal. This usecase works most of the time:

var myClient = &http.Client{Timeout: 10 * time.Second}

func getJson(url string, target interface{}) error {
    r, err := myClient.Get(url)
    if err != nil {
        return err
    }
    defer r.Body.Close()

    return json.NewDecoder(r.Body).Decode(target)
}

foo := Foo{}
getJson("http://example.com", &foo2)
fmt.Printf("%+v
", foo)

However, if you're truly working with a large dataset, check out https://golang.org/pkg/encoding/json/#example_Decoder_Decode_stream

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "strings"
)

func main() {
    const jsonStream = `
    [
        {"Name": "Ed", "Text": "Knock knock."},
        {"Name": "Sam", "Text": "Who's there?"},
        {"Name": "Ed", "Text": "Go fmt."},
        {"Name": "Sam", "Text": "Go fmt who?"},
        {"Name": "Ed", "Text": "Go fmt yourself!"}
    ]
`
    type Message struct {
        Name, Text string
    }
    dec := json.NewDecoder(strings.NewReader(jsonStream))

    // read open bracket
    t, err := dec.Token()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%T: %v
", t, t)

    // while the array contains values
    for dec.More() {
        var m Message
        // decode an array value (Message)
        err := dec.Decode(&m)
        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("%v: %v
", m.Name, m.Text)
    }

    // read closing bracket
    t, err = dec.Token()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%T: %v
", t, t)

}

This will allow you to work in a more memory efficient way.

To more of your question:

  1. Do I have to unmarshal to a full response struct? - Not really, you only have to define what you want to use in the struct, the rest will be ignored
  2. Are you doing it right? - You're not doing anything inherently wrong?

If there's something I didn't answer, please let me know.

Edit: To your usage of ioutil.ReadAll - Generally speaking, you'll want to unmarshal into a struct so you can actually use the data, and benefit from type safety via your structs. If you literally just need the string, what you're doing is fine, but usually that's not the case.