0

[Golang] HTTP Request With Cookies

 2 years ago
source link: http://siongui.github.io/2018/03/03/go-http-request-with-cookie/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[Golang] HTTP Request With Cookies

March 03, 2018

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:

[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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK