httplib_service_gateway.go 2.0 KB
package service_gateway

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/client/httplib"
	"strconv"
	"strings"
	"time"
)

// MessageCode 消息码
type MessageCode struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

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

type httplibBaseServiceGateway struct {
	baseURL          string
	connectTimeout   time.Duration
	readWriteTimeout time.Duration
}

func (serviceGateway *httplibBaseServiceGateway) createRequest(url string, method string) *httplib.BeegoHTTPRequest {
	var request *httplib.BeegoHTTPRequest
	switch method {
	case "get":
		request = httplib.Get(url)
		break
	case "post":
		request = httplib.Post(url)
		break
	case "put":
		request = httplib.Put(url)
		break
	case "delete":
		request = httplib.Delete(url)
		break
	case "head":
		request = httplib.Head(url)
		break
	default:
		request = httplib.Get(url)
	}
	return request.SetTimeout(serviceGateway.connectTimeout, serviceGateway.readWriteTimeout)
}

func (serviceGateway *httplibBaseServiceGateway) responseHandle(response map[string]interface{}) (map[string]interface{}, error) {
	data := make(map[string]interface{})
	var err error
	if code, ok := response["code"]; ok {
		code := code.(float64)
		if code == 0 {
			data = response["data"].(map[string]interface{})
		} else {
			msg := response["msg"].(string)
			err = fmt.Errorf(strings.Join([]string{strconv.FormatFloat(code, 'f', -1, 64), msg}, " "))
		}
	} else {
		jsonBytes, marshalErr := json.Marshal(response)
		if marshalErr != nil {
			err = marshalErr
		}
		err = fmt.Errorf("无法解析的网关服务数据返回格式:%s", string(jsonBytes))
	}
	return data, err
}

func (serviceGateway *httplibBaseServiceGateway) getResponseData(result GatewayResponse, data interface{}) error {
	if result.Code != 0 {
		return fmt.Errorf(result.Msg)
	}
	err := json.Unmarshal(result.Data, data)
	if err != nil {
		return err
	}
	return nil
}