go语言实现TLS双向认证的客户端 代码例子

go语言实现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))
}
    原文作者:CodingCode
    原文地址: https://www.jianshu.com/p/0dbb7dccfb6e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞