代码改变世界

go https json

2017-09-21 17:22  woodzcl  阅读(512)  评论(0编辑  收藏  举报

好吧,再来一个看起来高档点的吧

自从知道 Go有本地调用后,我就回到windows了

哈哈,以下内容,均在win10下搞定

预备:先做两个文件,服务器端的私钥KEY和公钥证书

1. openssl genrsa -out server.key 2048

2. openssl req -new -x509 -key server.key -out server.crt -days 3650

3.现在你应该有了server.key和server.crt两个文件,因为是自签名证书,所以,把server.crt安装到浏览器受信任证书存储区(这个我不多说了,一堆知识,大家自己去百度吧)

一 GO https server

//https.go

package main

import (
  "fmt"
  "net/http"
  "encoding/json"
)

type MyData struct {
  Name string `json:"item"`
  Other float32 `json:"amount"`
}

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 listens at 8086")
  http.ListenAndServeTLS(":8086", "server.crt", "server.key", nil)
}

//启动服务

go run https.go

二 Go https client

//https -client.go

package main

import (
  "fmt"
  "io/ioutil"
  "net/http"
  "github.com/bitly/go-simplejson"
  "crypto/tls"
  "encoding/json"
)

func main() {
  tr := &http.Transport{
    TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  }
  client := &http.Client{Transport: tr}
  resp, err := client.Get("https://localhost:8086")

  //resp, err := http.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)

  type MyData struct {
    Name string `json:"item"`
    Other float32 `json:"amount"`
  }

  var res MyData
  err = json.Unmarshal([]byte(body), &res)
  fmt.Println(res)
  fmt.Println(res.Name, res.Other)
}

//运行客户端

go run https-client.go

//结果

{"item":"1","amount":2}
*simplejson.Json:&{map[item:1 amount:2]}
{1 2}
1 2

三 browser client

//Microsoft Edge

Finally:

嗯,很好,很强大,可以考虑搞点儿RESTful 服务啦

你呢?

说你呢!

你想干吗?

多说一句:Go 做https客户端,响应速度明显慢于Edge。不知道为啥。还好,一般都用浏览器来干活嘛!无关紧要的啦。哈哈