Last active
March 8, 2020 16:21
-
-
Save goldeneggg/bfb6ecf8cfc017402c24 to your computer and use it in GitHub Desktop.
GoでHTTPクライアントを実装する例
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" | |
"strings" | |
"time" | |
) | |
const ( | |
REQ_URL = "http://httpbin.org" | |
) | |
func main() { | |
values := url.Values{} // url.Valuesオブジェクト生成 | |
values.Add("param1", "値1") // key-valueを追加 | |
fmt.Println(values.Encode()) | |
getSimple(values) | |
postSimple(values) | |
client := &http.Client{Timeout: time.Duration(10 * time.Second)} | |
get(client, values) | |
post(client, values) | |
} | |
func getSimple(values url.Values) { | |
// use http.Get (very simple) | |
resp, err := http.Get(REQ_URL + "/get?" + values.Encode()) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
defer resp.Body.Close() | |
execute(resp) | |
} | |
func postSimple(values url.Values) { | |
// use http.PostForm (very simple) | |
resp, err := http.PostForm(REQ_URL+"/post", values) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
defer resp.Body.Close() | |
execute(resp) | |
} | |
func get(client *http.Client, values url.Values) { | |
req, err := http.NewRequest("GET", REQ_URL+"/get", nil) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
req.URL.RawQuery = values.Encode() | |
resp, err := client.Do(req) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
defer resp.Body.Close() | |
execute(resp) | |
} | |
func post(client *http.Client, values url.Values) { | |
req, err := http.NewRequest("POST", REQ_URL+"/post", strings.NewReader(values.Encode())) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
req.Header.Add("Content-Type", "application/x-www-form-urlencoded") | |
resp, err := client.Do(req) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
defer resp.Body.Close() | |
execute(resp) | |
} | |
func execute(resp *http.Response) { | |
// response bodyを文字列で取得するサンプル | |
// ioutil.ReadAllを使う | |
b, err := ioutil.ReadAll(resp.Body) | |
if err == nil { | |
fmt.Println(string(b)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment