go語言實現(xiàn)TLS雙向認證的客戶端 代碼例子

go語言實現(xiàn)TLS雙向認證的客戶端 代碼例子

client.go

package main

import (
    "crypto/tls"
    "crypto/x509"
    "io/ioutil"
    "fmt"
    "log"
    "strings"
    "net/http"
)

func doGet(client * http.Client) (resp *http.Response, err error) {
    return client.Get("https://localhost:8080/service/hello")
}

func doPost(client * http.Client) (resp *http.Response, err error) {
    requestbody := fmt.Sprintf("{" +
                               " \"id\":"     + "\"" + "1234" + "\"," +
                               " \"status\":" + "\"" + "IDLE" + "\""  +
                               "}")

    return client.Post("https://localhost:8080/service/hello", "application/json", strings.NewReader(requestbody))
}

func doPut(client * http.Client) (resp *http.Response, err error) {
    requestbody := fmt.Sprintf("{" +
                               " \"id\":"     + "\"" + "1234" + "\"," +
                               " \"status\":" + "\"" + "IDLE" + "\""  +
                               "}")
    request, err := http.NewRequest("PUT", "https://localhost:8080/service/hello", strings.NewReader(requestbody))
    if err != nil {
        return nil, err
    }
    request.Header.Set("Content-Type", "application/json")
    return client.Do(request)
}


func main() {
    pool := x509.NewCertPool()
    caCertPath := "caroot.pem"

    caCrt, err := ioutil.ReadFile(caCertPath)
    if err != nil {
        log.Fatal("ReadFile err:", err)
        return
    }
    pool.AppendCertsFromPEM(caCrt)

    cliCrt, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
    if err != nil {
        log.Fatal("LoadX509KeyPair err:", err)
        return
    }

    tr := &http.Transport{
        TLSClientConfig: &tls.Config{
            RootCAs:      pool,
            Certificates: []tls.Certificate{cliCrt},
        },
    }
    client := &http.Client{Transport: tr}

    resp, err := doGet(client)
    //resp, err := doPost(client)
    //resp, err := doPut(client)
    if err != nil {
        log.Fatal("client error:", err)
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    log.Println(string(body))
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容