base_gateway.go 2.0 KB
package gateway

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/mapping"
	"github.com/zeromicro/go-zero/rest/httpc"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

type Service struct {
	Timeout     time.Duration
	host        string
	Interceptor func(msg string)
	ServiceName string
	service     httpc.Service
}

func NewService(name string, host string, timeout time.Duration, opts ...httpc.Option) Service {
	client := &http.Client{}
	//client.Timeout = timeout

	service := Service{
		host:    host,
		service: httpc.NewServiceWithClient(name, client, opts...),
	}
	return service
}

func (gateway Service) Do(ctx context.Context, url string, method string, val interface{}, result interface{}) error {
	var (
		baseResponse = Response{}
		begin        = time.Now()
		body         []byte
	)
	response, err := gateway.service.Do(ctx, method, gateway.host+url, val)
	defer func() {
		jsonParam, _ := json.Marshal(val)
		jsonData, _ := json.Marshal(result)
		if err != nil {
			result = err.Error()
		}
		if gateway.Interceptor != nil {
			gateway.Interceptor(fmt.Sprintf("【网关】%v | %v%v | %v : %v \n-->> %v \n<<-- %v", time.Since(begin), gateway.host, url, strings.ToUpper(method),
				result,
				string(jsonParam),
				string(jsonData),
			))
		}
	}()
	if err != nil {
		return err
	}
	if response.StatusCode != http.StatusOK {
		return HttpError{
			Base: Response{
				Code: response.StatusCode,
				Msg:  response.Status,
			},
		}
	}
	body, err = Bytes(response)
	if err != nil {
		return err
	}
	if err = json.Unmarshal(body, &baseResponse); err != nil {
		return err
	}
	if baseResponse.Code != 0 {
		return HttpError{
			Base: Response{
				Code: baseResponse.Code,
				Msg:  baseResponse.Msg,
			},
		}
	}
	if err = mapping.UnmarshalJsonBytes(baseResponse.Data, result); err != nil {
		return err
	}
	return nil
}

func Bytes(resp *http.Response) ([]byte, error) {
	var body []byte
	if resp.Body == nil {
		return nil, nil
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	return body, err
}