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 tensorrt 推理 yolov8框出现错误
  • ¥15 用hc 05,做蓝牙控制小车 小车只能说初始遥控方向影响,后续不能更改
  • ¥15 51单片机怎么把每次输入键值保存到数组作为我的确认键的判断条件呢
  • ¥45 easy photo不能使用,求帮助
  • ¥15 c语言字符串单词入门问题报错
  • ¥30 我现在是双非人工智能专业不知道要不要转到软件工程专业
  • ¥15 请问12脉波整流机组的外特性曲线具体是如何推导
  • ¥15 abaqus里的python算法
  • ¥100 如何在思科模拟器中进入CEF模式