httplib_service_gateway.go 2.0 KB
package service_gateway

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"

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

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

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

type HttpLibBaseServiceGateway struct {
	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)

	case "post":
		request = httplib.Post(url)

	case "put":
		request = httplib.Put(url)

	case "delete":
		request = httplib.Delete(url)

	case "head":
		request = httplib.Head(url)

	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 {
			if response["data"] == nil {
				data = nil
			} else {
				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)
	}
	if data == nil {
		return nil
	}
	err := json.Unmarshal(result.Data, data)
	if err != nil {
		return err
	}
	return nil
}