Golang: http request with cookies example

Submitted by august on Mon, 03/12/2018 - 12:33

This article is about how to use Go lang http package to build a request with cookies.

In this example, first request we will post a request to login and get the response cookies, and the second request will use the authorization cookies to get other information.

The whole example code as below:

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/cookiejar"
	"net/url"
)


func main() {

	cookieJar, _ := cookiejar.New(nil)
	client := &http.Client{
		Jar: cookieJar,
	}

	loginResp, err := client.PostForm("https://eservice.towngas.com/EAccount/Login/SignIn", url.Values{"LoginID": {xxxxxx}, "password": {xxxxxxx}})
	if err != nil {
		// handle error
	}
	defer loginResp.Body.Close()

	var loginCookies = loginResp.Cookies()

	getAccNumReq, _ := http.NewRequest("POST", "https://eservice.towngas.com/Common/GetHostedTGAccountAsync", nil)
	cookieJar.SetCookies(getAccNumReq.URL, loginCookies)
	getAccNumReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	getAccNumResp, err := client.Do(getAccNumReq)

	if err != nil {
		// handle error
	}
	defer getAccNumResp.Body.Close()
}

 

Tags

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.