doupiao1893 2019-01-13 22:40
浏览 220
已采纳

去处理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?

  • 写回答

1条回答 默认 最新

  • dongmo1708 2019-01-13 23:39
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)