简体   繁体   中英

blank http response body using golang

I'm trying to get information from a google api, but the response body appears to be empty. it just outputs {} to the console. Not sure where I went wrong as I used the docs to get the payload information for the request: 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/"})
}

I think this was stated in the docs

Note: If there are no matches (that is, if none of the URLs specified in the request are found on any of the lists specified in a request), the HTTP POST response simply returns an empty object in the response body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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