package components
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/astaxie/beego/config"
"io"
"io/ioutil"
"net/http"
)
var (
defaultRpcConf config.Configer
)
type RpcResponse struct {
Id string `json:"id"`
Code string `json:"code"`
Message string `json:"message"`
Type string `json:"type"`
Payload interface{} `json:"payload"`
}
//发起远程调用
//TODO 鉴权可以在这里进行
func Request(url string, data io.Reader, payload* interface{}) (*RpcResponse, error) {
req,err := http.NewRequest("POST", url, data)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
str := string(body[:])
fmt.Print(str)
v := RpcResponse{Payload: payload}
json.Unmarshal(body, &v)
return &v,nil
}
func Rpc(name string, data interface{}, payload interface{}) (*RpcResponse, error) {
url := defaultRpcConf.String("urls::test")
requestJson, err := json.Marshal(data)
if err != nil {
return nil, err
}
p, e := Request(url, bytes.NewReader(requestJson), &payload)
if e != nil {
return nil, e
}
return p, nil
}
//rpc 简单调用方法
func RpcWithPayload(name string, data interface{}, payload interface{}) error {
p, e := Rpc(name, data, payload)
if e != nil {
return e
}
//检查rpc返回状态码
if p.Code != "0" {
return errors.New("error code: " + p.Code + " Message: " + p.Message)
}
return nil
}
func init() {
conf, err := config.NewConfig("ini", "../conf/rpc.conf")
if err != nil {
panic(err)
}
defaultRpcConf = conf
}