Skip to content

Instantly share code, notes, and snippets.

@angch
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angch/d5586362085a0519a674 to your computer and use it in GitHub Desktop.
Save angch/d5586362085a0519a674 to your computer and use it in GitHub Desktop.
excalibr's request for a golang version of first example in http://docs.python-requests.org/en/latest/user/advanced/
//usr/bin/env go run $0 $@ ; exit
// excalibr (from Freenode's #myoss)'s request for a golang version of
// the first example in http://docs.python-requests.org/en/latest/user/advanced/
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
)
func main() {
// cookiejar here is an in-memory cookie jar. We'll need a different implementation
// if we want to store/load them from disk across invocations to this program.
myCookies, _ := cookiejar.New(nil)
myBrowser := &http.Client{
Jar: myCookies,
}
// It normally returns the response and error, but we're lazy and will
// be discarding it.
myBrowser.Get("http://httpbin.org/cookies/set/sessioncookie/123456789")
// Send the set cookies back, and expect the server to echo back the cookie:
// resp is a streamable io object, rather than one big blob of memory globbing
// data. We'll only decode what we need.
// _ means "error, what error?"
resp, _ := myBrowser.Get("http://httpbin.org/cookies")
// Close it when we're done streaming.
defer resp.Body.Close()
// Just kidding! We're lazy, so read everything into memory as an array of bytes
// _ means "error, what error? Got disconnected while downloading the chunked
// body? We'll ignore it!"
body, _ := ioutil.ReadAll(resp.Body)
// Convert the bytes into string (unicode handling and all) and then
// print it. (Otherwise, "fmt" happily outputs the byte stream as space separated
// ascii integers)
fmt.Println(string(body))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment