go語言實現TLS雙向認證的客戶端 程式碼例子

weixin_34082695發表於2018-02-14

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

相關文章