golangでk8sクラスタのDeployment一覧APiを叩いて取得したjsonのレスポンスを標準出力に表示します。(SAのトークンを利用します)
依存関係です。
package main
import (
"fmt"
"net/http"
"io/ioutil"
"log"
"crypto/x509"
"crypto/tls"
"encoding/json"
)
リクエスト送付とレスポンス受領するrequest関数です。
func request (endpoint,method,crtpath,token string) int {
//証明書の設定
caCert, _ := ioutil.ReadFile(crtpath)
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
//リクエストの構成
req, _ := http.NewRequest(method, endpoint, nil)
req.Header.Set("Accept","application/json")
req.Header.Set("Content-Type","application/json")
req.Header.Set("Authorization","Bearer "+token)
tr := &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: caCertPool,},
}
client := &http.Client{
Transport: tr,
}
//レスポンスの処理
resp, err := client.Do(req)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
json.Unmarshal([]byte(body),&val)
r,_ := json.MarshalIndent(val,""," ")
//fmt.Println(resp.StatusCode) <-ステータスコード
return string(r)
最後にrequest関数を呼び出すメイン関数です。
(以下コード中のAPIサーバーのエンドポイントの変数apiserver
、証明書パスの変数crtpath
、トークンの変数token
についてはこちらを参照してください。リンク先で、それぞれAPISERVER
、CRTFILE
、TOKEN
変数で格納しています)
func main () {
apiserver := "https://192.168.99.100:8443" //k8sエンドポイント
path := "/apis/apps/v1/namespaces/default/deployments"
endpoint := apiserver+path
method := "GET"
crtpath := "/Users/sota-n/.minikube/ca.crt" //<-証明書
token := xxx... //SAトークンの値
result := request(endpoint,method,crtpath,token)
fmt.Println(result)
あとはビルドしてバイナリを実行するかgo run <以上のコード>.go
を実行します。