httplib_service_gateway.go 2.9 KB
package service_gateway

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

	"github.com/beego/beego/v2/client/httplib"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/log"
)

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

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

type BaseServiceGateway struct {
	ConnectTimeout   time.Duration
	ReadWriteTimeout time.Duration
	CompanyId        int64
	OrgId            int64
	InOrgIds         []int64
	UserId           int64
	UserBaseId       int64
}

func (gateway BaseServiceGateway) CreateRequest(url string, method string) *httplib.BeegoHTTPRequest {
	var request *httplib.BeegoHTTPRequest
	switch method {
	case "get", "GET":
		request = httplib.Get(url)
	case "post", "POST":
		request = httplib.Post(url)
	case "put", "PUT":
		request = httplib.Put(url)
	case "delete", "DELETE":
		request = httplib.Delete(url)
	case "head", "HEADER":
		request = httplib.Head(url)
	default:
		request = httplib.Get(url)
	}
	request.Header("companyId", strconv.FormatInt(gateway.CompanyId, 10))
	request.Header("orgId", strconv.FormatInt(gateway.OrgId, 10))
	request.Header("userId", strconv.FormatInt(gateway.UserId, 10))
	request.Header("userBaseId", strconv.FormatInt(gateway.UserBaseId, 10))
	return request.SetTimeout(gateway.ConnectTimeout, gateway.ReadWriteTimeout)
}

func (gateway BaseServiceGateway) GetResponseData(result GatewayResponse, data interface{}) error {
	if result.Code != 0 {
		return fmt.Errorf(result.Msg)
	}
	err := json.Unmarshal(result.Data, data)
	if err != nil {
		log.Logger.Debug("get GetResponseData:" + string(result.Data))
		log.Logger.Debug("get GetResponseData err:" + err.Error())
		return err
	}
	return nil
}

func (gateway BaseServiceGateway) FastDoRequest(url, method string, param interface{}, data interface{}) error {
	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)
	if len(gateway.InOrgIds) > 0 {
		r.Header("orgIds", strings.Join(ToArrayString(gateway.InOrgIds), ","))
	}
	req, err := r.JSONBody(requestParam.Param)
	if err != nil {
		return err
	}
	byteResult, err := req.Bytes()
	if err != nil {
		return err
	}
	var result GatewayResponse
	err = json.Unmarshal(byteResult, &result)
	if err != nil {
		return err
	}
	err = gateway.GetResponseData(result, val)
	return nil
}

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

func ToArrayString(inputs []int64) []string {
	result := make([]string, 0)
	for i := range inputs {
		result = append(result, strconv.Itoa(int(inputs[i])))
	}
	return result
}