七叶笔记 » golang编程 » Go教程34:Go微服务间Http+Json调用

Go教程34:Go微服务间Http+Json调用

这篇文章你可以学习到

  1. Go使用Http 客户端调用
  2. Go语言 序列化 或反序列化 json

1. Go使用Http 客户端调用

package util
 import  (
"apigate/logger"
"encoding/json"
" io /ioutil"
"net/http"
"strings"
"time"
)
const (
JsonType = "application/json"
timeOut = 5 * time.Second
)
func HttpPost(url string, page interface{}) []byte {
timeout := time.Duration(timeOut)
client := http.Client{
Timeout: timeout,
}
data, err := json.Marshal(page)
if err !=  nil  {
logger.Error(err)
return nil
}
resp, err := client.Post(url, JsonType, strings.NewReader(string(data)))
if err != nil {
logger.Error(err)
return nil
}
defer resp.Body. Close ()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.Error(err)
return nil
}
return body
}
 

2. Go语言序列化或反序列化Json

package mang
import (
"apigate/logger"
"apigate/util"
"apigate/vo"
"encoding/json"
"github.com/tidwall/gjson"
"os"
)
func ApiWhiteList(auth int) []vo.ApiWhiteListListVo {
host := os.Getenv("OPERATE_HOST")
if len(host) <= 0 {
host = ""
}
whiteListUrl := host + "/v1/apiWhiteList/page"
query := vo.ApiWhiteListQuery{}
query. Number  = 0
query.Size = 50
query.Auth = auth
rsp := util.HttpPost(whiteListUrl, query)
if rsp == nil {
return nil
}
value := gjson.GetBytes(rsp, "content")
logger.Info(value.String())
var rspVo []vo.ApiWhiteListListVo
err := json.Unmarshal([]byte(value.String()), &rspVo)
if err != nil {
logger.Error(err)
return nil
}
return rspVo
}
 

如果你觉得好,可以使用我发布到iOS APP Store的产品

相关文章