Skip to content

Instantly share code, notes, and snippets.

@mohae
Last active February 16, 2016 03:24
Show Gist options
  • Select an option

  • Save mohae/80a35b1d06d6f28974f0 to your computer and use it in GitHub Desktop.

Select an option

Save mohae/80a35b1d06d6f28974f0 to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type Client struct {
host string
endpoint string
client http.Client
}
func redirectPolicyFunc(*http.Request, []*http.Request) error {
return errors.New("disabled")
}
func main() {
client := http.Client{CheckRedirect: redirectPolicyFunc}
cl := Client{"https://golang.org/", "pkg/net/http/", client}
req := cl.getRequest()
res, err := cl.getResponse(req)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Status: %d\n", res.StatusCode)
str, err := getVersion(res)
if err != nil {
log.Fatal(err)
}
fmt.Println(str)
}
func (c *Client) getRequest() *http.Request {
url := c.host + c.endpoint
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil
}
return req
}
func (c *Client) getResponse(req *http.Request) (*http.Response, error) {
return c.client.Do(req)
}
func getVersion(res *http.Response) (string, error) {
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil || res.StatusCode != 200 {
return "", err
}
return string(body), err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment