繁体   English   中英

使用 golang 的空白 http 响应体

[英]blank http response body using golang

我正在尝试从谷歌 api 获取信息,但响应正文似乎为空。 它只是将{}输出到控制台。 不确定我哪里出错了,因为我使用文档获取请求的有效负载信息: https://developers.google.com/safe-browsing/v4/lookup-api

package main

import (
    "fmt"

    "encoding/json"
    "io/ioutil"
    "net/http"
    "strings"
)

type payload struct {
    Client     client     `json:"client"`
    ThreatInfo threatInfo `json:"threatInfo"`
}

type client struct {
    ClientId      string `json:"clientId"`
    ClientVersion string `json:"clientVersion"`
}

type threatInfo struct {
    ThreatTypes      []string `json:"threatTypes"`
    PlatformTypes    []string `json:"platformTypes"`
    ThreatEntryTypes []string `json:"threatEntryTypes"`
    ThreatEntries    []entry  `json:"threatEntries"`
}

type entry struct {
    URL string `json:"url"`
}

func checkURLs(urls []string) {

    // populate entries
    var entries = []entry{}
    for _, url := range urls {
        entries = append(entries, entry{URL: url})
    }

    data := payload {
        Client: client{
            ClientId:      "myapp",
            ClientVersion: "0.0.1",
        },
        ThreatInfo: threatInfo{
            ThreatTypes:   []string{"MALWARE", "SOCIAL_ENGINEERING"},
            PlatformTypes: []string{"WINDOWS"},
            ThreatEntryTypes: []string{"URL"},
            ThreatEntries: entries,
        },
    }

    jsonBytes, _ := json.Marshal(data)

    key := "*"
    api := fmt.Sprintf("https://safebrowsing.googleapis.com/v4/threatMatches:find?key=%s", key)
    req, _ := http.NewRequest("POST", api, strings.NewReader(string(jsonBytes)))
    req.Header.Add("Content-Type", "application/json")
    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()

    body, err := ioutil.ReadAll(res.Body)
    fmt.Println(res) // 200 OK 
    fmt.Println(err) // nil
    fmt.Println(string(body)) // {}
}

func main() {
    checkURLs([]string{"http://www.urltocheck1.org/", "http://www.urltocheck2.org/"})
}

我认为这是在文档中说明的

注意:如果没有匹配项(即,如果在请求中指定的任何列表中都找不到请求中指定的 URL),则 HTTP POST 响应仅在响应正文中返回一个空的 object。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM