goでAPIコールするシンプルなプログラム

  • すぐつかそうなシンプルなプログラム作った
package main
​
import (
    "bytes"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "strconv"
    "time"
)
​
// テスト結果格納
type TestResult struct {
    URL           string
    TestCaseName  string
    Method        string
    ExpectStatus  string
    ActualStatus  string
    ErrorMessage  string
    ResultMessage string
}
​
func main() {
    h := HttpClient{}
​
    // テスト結果格納用メンバにリクエストに必要なパラメータをセット
    res := TestResult{}
    res.URL = "https://yahoo.co.jp"
    res.Method = "GET"
    res.TestCaseName = "APIコール"
    h.Request(&res)
    fmt.Printf("result to : %s\n", res.ResultMessage)
}
​
// HTTPリクエスト
type HttpClient struct {
}
​
// リクエスト
func (h *HttpClient) Request(res *TestResult) {
    h.RequestCommon(res, "")
}
​
// リクエスト(RequestBodyを付与)
func (h *HttpClient) RequestWithBody(res *TestResult, jsonStr string) {
    h.RequestCommon(res, jsonStr)
}
​
// リクエスト(RequestBodyを付与)
func (h *HttpClient) RequestCommon(res *TestResult, jsonStr string) {
    // httpClientを作成
    client := &http.Client{Timeout: time.Duration(10) * time.Second}
​
    // リクエスト生成
    req, err := http.NewRequest(res.Method, res.URL, bytes.NewBuffer([]byte(jsonStr)))
​
    // リクエスト生成失敗時エラー​
    if err != nil {
        fmt.Printf("failed to : %s\n%s\n", res.TestCaseName, err.Error())
        res.ErrorMessage = err.Error()
    }
​
    // JWT認証しないからコメントアウト
    // req.Header.Set("jwt", os.Getenv("JWT_TOKEN"))
    req.Header.Set("Content-Type", "application/json")
​
    // リクエスト実行
    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("failed to : %s\n%s\n", res.TestCaseName, err.Error())
        res.ErrorMessage = getContent(resp.Body) + ", error:[" + err.Error() + "]"
        return
    }
​
    defer resp.Body.Close()
    res.ActualStatus = strconv.Itoa(resp.StatusCode)
    res.ResultMessage = getContent(resp.Body)
}
​
// レスポンスを文字列で返す
func getContent(body io.ReadCloser) string {
    b, err := ioutil.ReadAll(body)
    if err != nil {
        panic(err)
    }
    return string(b)
}