Go语言用例Go知识库

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

2018-02-14  本文已影响218人  CodingCode

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))
}
上一篇下一篇

猜你喜欢

热点阅读