Last active
December 11, 2015 08:28
-
-
Save hnaohiro/4572830 to your computer and use it in GitHub Desktop.
Golangでcookie機能付きhttpclient
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"net/url" | |
) | |
type Jar struct { | |
cookies []*http.Cookie | |
} | |
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) { | |
jar.cookies = cookies | |
} | |
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie { | |
return jar.cookies | |
} | |
type HttpClient struct { | |
client *http.Client | |
} | |
func NewHttpClient() *HttpClient { | |
client := http.Client{nil, nil, new(Jar)} | |
return &HttpClient{&client} | |
} | |
func (h *HttpClient) Get(url string) ([]byte, error) { | |
resp, err := h.client.Get(url) | |
if err != nil { | |
return nil, err | |
} | |
defer resp.Body.Close() | |
return ioutil.ReadAll(resp.Body) | |
} | |
func (h *HttpClient) Post(url string, data map[string][]string) ([]byte, error) { | |
resp, err := h.client.PostForm(url, data) | |
if err != nil { | |
return nil, err | |
} | |
defer resp.Body.Close() | |
if location, _ := resp.Location(); location != nil { | |
return h.Get(location.String()) | |
} | |
return ioutil.ReadAll(resp.Body) | |
} | |
func main() { | |
client := NewHttpClient() | |
response, err := client.Get("https://github.com/") | |
if err != nil { | |
fmt.Println(err) | |
} else { | |
fmt.Println(string(response)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment