httplib_service_gateway.go 1.6 KB
package svr

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/httplib"
	"strconv"
	"strings"
	"time"
)

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)
	}
	if strings.Contains(serviceGateway.baseURL, "https") {
		request.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	}
	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)
			data = response
			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
}