美文网首页Go语言用例Go知识库
go语言实现TLS双向认证的客户端 代码例子

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

作者: CodingCode | 来源:发表于2018-02-14 11:52 被阅读218次

    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))
    }
    

    相关文章

      网友评论

        本文标题:go语言实现TLS双向认证的客户端 代码例子

        本文链接:https://www.haomeiwen.com/subject/zsketftx.html