1、生成ca证书、服务端公钥、服务端私钥
1、openssl genrsa -out ca.key 2048?
2、openssl req -x509 -new -nodes -key ca.key -subj "/CN=192.168.1.106" -days 5000 -out ca.crt
3、openssl genrsa -out server.key 2048
4、openssl req -new -key server.key -subj "/CN=192.168.1.106" -out server.csr
5、echo subjectAltName = IP:192.168.1.106 > extfile.cnf
6、openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -extfile extfile.cnf -out server.crt -days 5000
2、server端
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi, This is an example of http service in golang!")
}
func handler2(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w,
"Hi, This is an example of http service in golang2222!")
}
func main() {
http.HandleFunc("/h2", handler2)
http.HandleFunc("/", handler)
http.ListenAndServeTLS(":8081",
"./server/server.crt",
"./server/server.key",
nil)
}
3、client端
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
pool := x509.NewCertPool()
caCertPath := "ca.crt"
caCrt, err := ioutil.ReadFile(caCertPath)
if err != nil {
fmt.Println("ReadFile err:", err)
return
}
pool.AppendCertsFromPEM(caCrt)
tr := &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: pool,
},
DisableCompression: true,
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://192.168.1.106:8081")
if err != nil {
fmt.Println("Get error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
|