httplib_service_gateway.go 1.1 KB
package service_gateway

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

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

//GatewayResponse 统一消息返回格式
type GatewayResponse struct {
	Code int             `json:"code"`
	Msg  string          `json:"msg"`
	Data json.RawMessage `json:"data"`
}

type BaseServiceGateway struct {
	connectTimeout   time.Duration
	readWriteTimeout time.Duration
}

func (gateway BaseServiceGateway) 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(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 {
		return err
	}
	return nil
}