[Golang] HTTP Request With Cookies
Example of sending HTTP request with cookies via Go standard net/http package.
package main
import (
"errors"
"io/ioutil"
"net/http"
"strconv"
)
func HTTPwithCookies(url, ds_user_id, sessionid, csrftoken string) (b []byte, err error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return
}
req.AddCookie(&http.Cookie{Name: "ds_user_id", Value: ds_user_id})
req.AddCookie(&http.Cookie{Name: "sessionid", Value: sessionid})
req.AddCookie(&http.Cookie{Name: "csrftoken", Value: csrftoken})
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
err = errors.New(url +
"\nresp.StatusCode: " + strconv.Itoa(resp.StatusCode))
return
}
return ioutil.ReadAll(resp.Body)
}
func main() {
b, err := HTTPwithCookies("https://www.instagram.com/", "my_id", "my_sessionid", "my_csrftoken")
if err != nil {
panic(err)
}
println(string(b))
}
If you want to know how to send HTTP request with headers, for example, User-Agent header, please see [1].
Tested on: Ubuntu Linux 17.10, Go 1.10.
References:
[1] | [Golang] HTTP Request With Custom User-Agent |
[2] | soup - Web Scraper for Go with a similar interface to BeautifulSoup : golang |
[3] | Context propagation over HTTP in Go – JBD – Medium : golang |
[4] | GitHub - arrufat/papago: Unofficial wrapper around the Naver translating tool, Papago : golang |