-4

I want to make a get request for each param in an params array. The url is static. Is there a way to reuse my custom http client for each iteration? I don't want to reset the header for each request. Ideally, I'd like to do something like client.Do(param) for each iteration.

client := &http.Client{}


for _, param := range params {
    uri := url + param

    req, err := http.NewRequest(http.MethodGet, uri, nil)

    req.Header.Add("Cookie", cookie)

    resp, _ := client.Do(req)

    defer resp.Body.Close()

    // do something...
}
Cezary Butler
  • 807
  • 7
  • 21
David
  • 303
  • 3
  • 8
  • 21
  • 5
    You are reusing the http client already. You have to create a new request for each request. – Burak Serdar Aug 07 '20 at 17:32
  • I'd like to reduce the code in the loop. Can I set a default header? – David Aug 07 '20 at 17:35
  • 4
    Even if you could set a default header, it would be exactly as many lines of code, so you won't achieve your stated goal of reducing lines. And it would also be doing the exact same things in the background, so you wouldn't gain any efficiency, either. – Jonathan Hall Aug 07 '20 at 17:38

1 Answers1

6

I think you are wanting to just keep your cookies, and not have to set it on each request? If that's the case you can do:

import (
    "net/http"
    "net/http/cookiejar"
    "golang.org/x/net/publicsuffix"
)

// All users of cookiejar should import "golang.org/x/net/publicsuffix"
cookieJar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
if err != nil {
    panic(err)
}

var cookies []*http.Cookie
cookies = append(cookies, cookie)

u, err := url.Parse("http://whateversite.com")
if err != nil {
    panic(err)
}

jar.SetCookies(u, cookies)

client := &http.Client{
    Jar: cookieJar,
}
dave
  • 62,300
  • 5
  • 72
  • 93