我們編寫一個Go程序來嘗試與這個HTTPS server建立連接並通信。
//gohttps/4-https/client1.go
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://localhost:8081")
if err != nil {
fmt.Println("error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
運行這個client,我們得到如下錯誤:
$go run client1.go
error: Get https://localhost:8081: x509: certificate signed by unknown authority
此時服務端也給出了錯誤日志提示:
2015/04/30 16:03:31 http: TLS handshake error from 127.0.0.1:62004: remote error: bad certificate
顯然從客戶端日志來看,go實現的Client端默認也是要對服務端傳過來的數字證書進行校驗的,但客戶端提示:這個證書是由不知名CA簽發 的!
我們可以修改一下client1.go的代碼,讓client端略過對證書的校驗:
//gohttps/4-https/client2.go
package main
import (
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://localhost:8081")
if err != nil {
fmt.Println("error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
通過設置tls.Config的InsecureSkipVerify為true,client將不再對服務端的證書進行校驗。執行后的結果 也證實了這一點:
$go run client2.go
Hi, This is an example of http service in golang!