service.go 1.9 KB
Newer Older
E
eoLinker API Management 已提交
1 2 3 4
package application

import (
	"fmt"
Y
Your Name 已提交
5
	goku_plugin "github.com/eolinker/goku-plugin"
E
eoLinker API Management 已提交
6 7 8
	"net/http"
	"net/url"
	"time"
Y
Your Name 已提交
9 10 11 12

	"github.com/eolinker/goku-api-gateway/goku-service/common"
	"github.com/eolinker/goku-api-gateway/goku-service/health"
	"github.com/eolinker/goku-api-gateway/utils"
E
eoLinker API Management 已提交
13 14
)

Y
Your Name 已提交
15
//Application 应用
E
eoLinker API Management 已提交
16
type Application struct {
Y
Your Name 已提交
17
	service            *common.Service
E
eoLinker API Management 已提交
18 19 20
	healthCheckHandler health.CheckHandler
}

Y
Your Name 已提交
21
//NewApplication 创建Application
Y
Your Name 已提交
22
func NewApplication(service *common.Service, healthCheckHandler health.CheckHandler) *Application {
E
eoLinker API Management 已提交
23 24 25 26 27 28
	return &Application{
		service:            service,
		healthCheckHandler: healthCheckHandler,
	}

}
Y
Your Name 已提交
29 30

//Send send
Y
Your Name 已提交
31
func (app *Application) Send(ctx goku_plugin.ContextAccess,proto string, method string, path string, querys url.Values, header http.Header, body []byte, timeout time.Duration, retry int) (*http.Response, string, []string, error) {
E
eoLinker API Management 已提交
32

Y
Your Name 已提交
33 34
	var response *http.Response
	var err error
E
eoLinker API Management 已提交
35 36

	FinalTargetServer := ""
Y
Your Name 已提交
37
	RetryTargetServers := make([]string, 0, retry+1)
E
eoLinker API Management 已提交
38 39

	lastIndex := -1
Y
Your Name 已提交
40 41 42
	path = utils.TrimPrefixAll(path, "/")
	for doTrice := retry + 1; doTrice > 0; doTrice-- {
		instance, index, has := app.service.Next(lastIndex)
E
eoLinker API Management 已提交
43
		lastIndex = index
Y
Your Name 已提交
44 45
		if !has {
			return nil, FinalTargetServer, RetryTargetServers, fmt.Errorf("not found instance for app:%s", app.service.Name)
E
eoLinker API Management 已提交
46 47
		}

Y
Your Name 已提交
48 49 50 51 52
		FinalTargetServer = instance.IP
		if instance.Port != 0 {
			FinalTargetServer = fmt.Sprintf("%s:%d", instance.IP, instance.Port)
		}

Y
Your Name 已提交
53
		RetryTargetServers = append(RetryTargetServers, FinalTargetServer)
Y
Your Name 已提交
54
		u := fmt.Sprintf("%s://%s/%s", proto, FinalTargetServer, path)
Y
Your Name 已提交
55
		response, err = request(ctx,method, u, querys, header, body, timeout)
E
eoLinker API Management 已提交
56

Y
Your Name 已提交
57 58
		if err != nil {
			if app.healthCheckHandler.IsNeedCheck() {
E
eoLinker API Management 已提交
59 60
				app.healthCheckHandler.Check(instance)
			}
Y
Your Name 已提交
61 62
		} else {
			return response, FinalTargetServer, RetryTargetServers, err
E
eoLinker API Management 已提交
63 64 65 66
		}

	}

Y
Your Name 已提交
67
	return response, FinalTargetServer, RetryTargetServers, err
E
eoLinker API Management 已提交
68
}