下面是我依据网上资料的实操过程,记录以作备忘。该示例给出了https通信并处理json文件的例子。
平台:Ubuntu 16.04.3 LTS
go版本:1.10
1.生成自签名的服务器端的私钥KEY和公钥证书
openssl genrsa -out server.key 2048
2.编写https通信的服务器和客户端程序
server.go
package main import ( "encoding/json" "fmt" "net/http" ) type MyData struct { Name string `json:"item"` Other float32 `json:"amount"` } //仅是构造一个json数据并发送给客户端 func handler(w http.ResponseWriter,r *http.Request) { var detail MyData detail.Name = "1" detail.Other = 2 body,err := json.Marshal(detail) if err != nil { panic(err.Error()) } fmt.Fprintf(w,string(body)) } func main() { http.HandleFunc("/",handler) fmt.Println("http server listen at 8086") http.ListenAndServeTLS(":8086","server.crt","server.key",nil) }client.go
package main import ( "crypto/tls" "encoding/json" "fmt" "github.com/bitly/go-simplejson" "io/IoUtil" "net/http" ) type MyData struct { Name string `json:"item"` Other float32 `json:"amount"` } func main() { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},} client := &http.Client{Transport: tr} resp,err := client.Get("https://localhost:8086") if err != nil { fmt.Println("error:",err) return } defer resp.Body.Close() body,err := IoUtil.ReadAll(resp.Body) fmt.Println(string(body)) //decode json js,err := simplejson.NewJson(body) if err != nil { panic(err.Error()) } fmt.Printf("%T:%v\n",js,js) var res MyData err = json.Unmarshal([]byte(body),&res) fmt.Println(res) fmt.Println(res.Name,res.Other) }
3.安装client.go中需要的依赖库go-simplejson
go get -v -u -t github.com/bitly/go-simplejson
4.编译生成服务器和客户端程序
go build server.go
go build client.go
5.运行并看到结果
打开两个终端,分别运行server和client程序
./server
参考文献 [1].https://www.cnblogs.com/woodzcl/p/7569668.html