base_service_gateway.go 2.8 KB
package api

import (
	rawjson "encoding/json"
	"fmt"
	"github.com/linmadan/egglib-go/utils/json"
	"net/http"
	"strings"
	"time"

	"github.com/beego/beego/v2/client/httplib"
)

type MessageCode struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

//Response 统一消息返回格式
type Response struct {
	MessageCode
	Data rawjson.RawMessage `json:"data"`
}

type BaseServiceGateway struct {
	ConnectTimeout   time.Duration
	ReadWriteTimeout time.Duration
	host             string
	Interceptor      func(msg string)
}

type Request struct {
	Url    string
	Method string
	Param  interface{}
}

func (gateway BaseServiceGateway) CreateRequest(url string, method string) *httplib.BeegoHTTPRequest {
	var request *httplib.BeegoHTTPRequest
	method = strings.ToUpper(method)
	switch method {
	case http.MethodGet:
		request = httplib.Get(url)
	case http.MethodPost:
		request = httplib.Post(url)
	case http.MethodPut:
		request = httplib.Put(url)
	case http.MethodDelete:
		request = httplib.Delete(url)
	case http.MethodHead:
		request = httplib.Head(url)
	default:
		request = httplib.Get(url)
	}
	return request.SetTimeout(gateway.ConnectTimeout, gateway.ReadWriteTimeout)
}

func (gateway BaseServiceGateway) GetResponseData(result Response, data interface{}) error {
	err := json.Unmarshal(result.Data, data)
	if err != nil {
		return NewErrCodeMsg(JsonUnMarshError, err.Error())
	}
	return nil
}

func (gateway BaseServiceGateway) FastDoRequest(url, method string, param interface{}, data interface{}) error {
	begin := time.Now()
	var err error
	var result = "success"
	defer func() {
		jsonParam, _ := json.Marshal(param)
		jsonData, _ := json.Marshal(data)
		if err != nil {
			result = err.Error()
		}
		if gateway.Interceptor != nil {
			gateway.Interceptor(fmt.Sprintf("%v | %v | %v : %v \n request:%v \n response:%v", time.Since(begin), url, strings.ToUpper(method),
				result,
				string(jsonParam),
				string(jsonData),
			))
		}
	}()
	err = gateway.DoRequest(Request{
		Url:    url,
		Method: method,
		Param:  param,
	}, &data)
	if err != nil {
		return err
	}
	return nil
}

func (gateway BaseServiceGateway) DoRequest(requestParam Request, val interface{}) error {
	r := gateway.CreateRequest(requestParam.Url, requestParam.Method)
	req, err := r.JSONBody(requestParam.Param)
	if err != nil {
		return err
	}
	byteResult, err := req.Bytes()
	if err != nil {
		return err
	}
	var result Response
	err = json.Unmarshal(byteResult, &result)
	if err != nil {
		return err
	}
	if result.Code != 0 && len(result.Msg) > 0 {
		return NewErrCodeMsg(result.Code, result.Msg)
	}
	return gateway.GetResponseData(result, val)
}

func (gateway BaseServiceGateway) Host() string {
	return gateway.host
}

func NewBaseServiceGateway(host string) BaseServiceGateway {
	return BaseServiceGateway{
		host: host,
	}
}