使用Go的net / http软件包连接到YouTube API的问题

I think this may be my first question on SO. I've just been immersing myself in Go. I just got done reading An Introduction to Programming in Go and I wanted to just write a simple program that would query the YT Data API v3.

The issue: when I execute go run request.go I get a 404 Not Found error. However when I take the URL that's passed and paste in my browser or Postman the request works fine. Here's what my func main() {} looks like:

func main() {
    // read in API key
    key, error_ := ioutil.ReadFile("user_data.txt")
    if error_ != nil {
        log.Fatal(error_)
    }
    api_key += string(key)

    // buil url
    url := base_url + query + api_key
    // Uncomment the next line to show that I'm not insane.
    // url = "http://ip.jsontest.com/"

    // make request
    resp, err := http.Get(url)
    if err != nil {
        log.Fatal(err)
    }
    body, error_g := ioutil.ReadAll(resp.Body)
    if error_g != nil {
        fmt.Println(error_g)
    }
    fmt.Println(resp.Status)
    fmt.Println(resp.Request)
    fmt.Println(string(body))
    defer resp.Body.Close()
    // parse response
    var vs Videos
    err = json.NewDecoder(resp.Body).Decode(&vs)
    if err != nil {
        fmt.Printf("%T
", err)
        // fmt.Println("Error:", err)
        log.Fatal(err)
    }
    for _, v := range vs.Items {
        fmt.Println(v.Id.VideoId, v.Snippet.Title)
    }
}

And here is the link to the program in my repo request.go

I'm surprised your example works, assuming that is the whole thing, as you haven't defined base_url or query for url := base_url + query + api_key. I'd rather leave that as a comment than an answer, but I don't have enough rep to do so.

I'm assuming that you've tried this, but I'd print out your built url and double check it looks something like

https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&key=YOUR_API_KEY

The other thing you should consider using, which might indirectly solve your problem, is the net/url package to build your URLs. Then you can do something like:

params := url.Values{}
params.Add("id", video_id)
params.Add("key", api_key)

url := &url.Url{
    Host: 'https://www.googleapis.com/youtube/v3/videos',
    Query: params.Encode()
}

get_url := url.String()

It's a bit more tedious, but the advantage here is that it takes care of all of the encoding and query building for you. My guess is that this is probably where something is going wrong, assuming you're reading in your API key properly, and it is indeed valid for the Data API. Obviously you'd want to bust that logic out into a function call to make it more reusable, but you get the idea.