router.go 6.8 KB
Newer Older
E
eoLinker API Management 已提交
1 2 3 4 5
package goku_node

import (
	"fmt"

黄孟柱 已提交
6 7 8 9 10
	log "github.com/eolinker/goku-api-gateway/goku-log"
	access_log "github.com/eolinker/goku-api-gateway/goku-node/access-log"
	"github.com/eolinker/goku-api-gateway/goku-node/handler"
	"github.com/eolinker/goku-api-gateway/goku-node/plugin-flow"
	. "github.com/eolinker/goku-api-gateway/server/access-field"
E
eoLinker API Management 已提交
11 12 13 14 15
	"net/http"
	"strconv"
	"strings"
	"time"

黄孟柱 已提交
16 17
	"github.com/eolinker/goku-api-gateway/goku-node/common"
	monitor_write "github.com/eolinker/goku-api-gateway/server/monitor/monitor-write"
E
eoLinker API Management 已提交
18

黄孟柱 已提交
19 20 21 22 23 24 25
	gateway_manager "github.com/eolinker/goku-api-gateway/goku-node/manager/gateway-manager"
	strategy_api_manager "github.com/eolinker/goku-api-gateway/goku-node/manager/strategy-api-manager"
	strategy_api_plugin_manager "github.com/eolinker/goku-api-gateway/goku-node/manager/strategy-api-plugin-manager"
	strategy_plugin_manager "github.com/eolinker/goku-api-gateway/goku-node/manager/strategy-plugin-manager"
	node_common "github.com/eolinker/goku-api-gateway/goku-node/node-common"
	"github.com/eolinker/goku-api-gateway/goku-node/visit"
	entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
E
eoLinker API Management 已提交
26 27 28 29 30 31 32
	// "time"
)

type Router struct {
	mu map[string]http.HandlerFunc
}

Y
Your Name 已提交
33
func (mux *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
E
eoLinker API Management 已提交
34 35 36 37 38 39 40
	if r.RequestURI == "*" {
		if r.ProtoAtLeast(1, 1) {
			w.Header().Set("Connection", "close")
		}
		w.WriteHeader(http.StatusBadRequest)
		return
	}
Y
Your Name 已提交
41 42 43
	path := r.URL.Path
	h, has := mux.mu[path]
	if has {
E
eoLinker API Management 已提交
44 45 46
		h.ServeHTTP(w, r)
		return
	}
Y
Your Name 已提交
47
	ServeHTTP(w, r)
E
eoLinker API Management 已提交
48 49 50 51 52

}

func NewRouter() http.Handler {

Y
Your Name 已提交
53 54
	r := &Router{
		mu: make(map[string]http.HandlerFunc),
E
eoLinker API Management 已提交
55 56
	}

Y
Your Name 已提交
57
	hs := handler.Handler()
E
eoLinker API Management 已提交
58

Y
Your Name 已提交
59
	for _, h := range hs {
E
eoLinker API Management 已提交
60 61 62
		r.mu[h.Pattern] = h.HandlerFunc
	}

Y
Your Name 已提交
63
	return r
E
eoLinker API Management 已提交
64 65 66 67
}

var systemRequestPath = []string{"/oauth2/token", "/oauth2/authorize", "/oauth2/verify"}

Y
Your Name 已提交
68
func ServeHTTP(w http.ResponseWriter, req *http.Request) {
E
eoLinker API Management 已提交
69 70 71 72 73 74
	defer func() {
		if err := recover(); err != nil {
			log.Warn(err)
		}
	}()

Y
Your Name 已提交
75
	timeStart := time.Now()
E
eoLinker API Management 已提交
76

Y
Your Name 已提交
77
	logFields := make(log.Fields)
E
eoLinker API Management 已提交
78 79 80 81 82 83 84

	// 记录访问次数
	requestID := GetRandomString(16)

	ctx := common.NewContext(req, requestID, w)
	proxyStatusCode := 0

Y
Your Name 已提交
85 86 87 88 89 90
	log.Debug(requestID, " url: ", req.URL.String())
	log.Debug(requestID, " header: ", ctx.RequestOrg.Header.String())
	rawBody, err := ctx.RequestOrg.RawBody()
	if err == nil {
		log.Debug(requestID, " body: ", string(rawBody))
	}
E
eoLinker API Management 已提交
91 92

	defer func() {
Y
Your Name 已提交
93
		n, status := ctx.Finish()
E
eoLinker API Management 已提交
94 95 96 97

		if ctx.ProxyResponseHandler != nil {
			proxyStatusCode = ctx.ProxyResponseHandler.StatusCode()
		}
Y
Your Name 已提交
98
		logFields[RequestId] = requestID
E
eoLinker API Management 已提交
99
		logFields[StatusCode] = status
Y
Your Name 已提交
100
		logFields[HttpUserAgent] = fmt.Sprint("\"", req.UserAgent(), "\"")
E
eoLinker API Management 已提交
101 102
		logFields[HttpReferer] = req.Referer()
		logFields[RequestTime] = time.Since(timeStart)
Y
Your Name 已提交
103
		logFields[Request] = fmt.Sprint("\"", req.Method, " ", req.URL.Path, " ", req.Proto, "\"")
E
eoLinker API Management 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
		logFields[BodyBytesSent] = n
		logFields[Host] = req.Host
		access_log.Log(logFields)
		log.WithFields(logFields).Info()

		for _, path := range systemRequestPath {
			if path == req.URL.Path {
				return
			}
		}
		apiId := strconv.Itoa(ctx.ApiID())

		monitor_write.AddMonitor(ctx.StrategyId(), apiId, proxyStatusCode, ctx.StatusCode())
	}()

	remoteAddr := Intercept(req.RemoteAddr, ":")
Y
Your Name 已提交
120
	logFields[RemoteAddr] = remoteAddr
E
eoLinker API Management 已提交
121

Y
Your Name 已提交
122
	if realIp := ctx.GetHeader("X-Real-Ip"); realIp == "" {
E
eoLinker API Management 已提交
123 124
		ctx.ProxyRequest.SetHeader("X-Real-Ip", remoteAddr)
		logFields[HttpXForwardedFor] = remoteAddr
Y
Your Name 已提交
125
	} else {
E
eoLinker API Management 已提交
126 127 128 129 130 131 132
		logFields[HttpXForwardedFor] = realIp
	}

	// 匹配URI前执行函数
	var isBefor bool
	start := time.Now()
	isBefor = plugin_flow.BeforeMatch(ctx)
Y
Your Name 已提交
133
	log.Info(requestID, " BeforeMatch plugin duration:", time.Since(start))
E
eoLinker API Management 已提交
134
	if !isBefor {
Y
Your Name 已提交
135
		log.Info(requestID, " stop by BeforeMatch plugin")
E
eoLinker API Management 已提交
136 137 138 139 140 141 142 143 144 145
		return
	}

	var timeout, retryCount int

	strategyID, ok := retrieveStrategyID(ctx)
	if !ok {
		return
	}

Y
Your Name 已提交
146
	logFields[Strategy] = fmt.Sprintf("\"%s %s\"", strategyID, ctx.StrategyName())
E
eoLinker API Management 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

	requestPath := req.URL.Path
	requestMenthod := ctx.Request().Method()

	var handleFunc []*entity.PluginHandlerExce
	apiInfo, splitURL, param, ok := strategy_api_manager.CheckApiFromStrategy(strategyID, requestPath, req.Method)
	if ok {
		ctx.SetApiID(apiInfo.ApiID)
		retryCount = apiInfo.RetryCount
		//ctx.IsMatch = true
		timeout = apiInfo.Timeout

		ctx.ProxyRequest.SetTargetServer(fmt.Sprintf("%s://%s", apiInfo.Protocol, apiInfo.Target))

		targetUrl := apiInfo.TargetURL + requestPath

		if apiInfo.StripPrefix {
			targetUrl = apiInfo.TargetURL + splitURL
		}
		if apiInfo.StripSlash {
			targetUrl = node_common.FilterSlash(targetUrl)
		}
		if !apiInfo.IsFollow {
			ctx.ProxyRequest.Method = strings.ToUpper(apiInfo.TargetMethod)
		}
		targetUrl = node_common.MatchRestful(targetUrl, param)

		ctx.ProxyRequest.SetTargetURL(targetUrl)

		handleFunc, _ = strategy_api_plugin_manager.GetPluginsOfApi(strategyID, apiInfo.ApiID)

	} else {
		handleFunc, _ = strategy_plugin_manager.GetPluginsOfStrategy(strategyID)
	}
	start = time.Now()
	isAccess, _ := plugin_flow.AccessFunc(ctx, handleFunc)
Y
Your Name 已提交
183
	log.Info(requestID, " Access plugin duration:", time.Since(start))
E
eoLinker API Management 已提交
184 185 186 187 188 189 190
	if !isAccess {

		// todo
		return
	}

	if apiInfo == nil {
Y
Your Name 已提交
191
		log.Info(requestID, " URL dose not exist!")
E
eoLinker API Management 已提交
192 193
		ctx.SetStatus(404, "404")
		ctx.SetBody([]byte("[ERROR]URL dose not exist!"))
Y
Your Name 已提交
194

E
eoLinker API Management 已提交
195 196
		return
	}
Y
Your Name 已提交
197 198
	logFields[Api] = fmt.Sprintf("\"%d %s\"", apiInfo.ApiID, apiInfo.ApiName)
	logFields[Proxy] = fmt.Sprintf("\"%s %s %s\"", ctx.ProxyRequest.Method, ctx.ProxyRequest.TargetURL(), apiInfo.Protocol)
E
eoLinker API Management 已提交
199 200 201
	logFields[Balance] = apiInfo.Target
	start = time.Now()
	err, response := CreateRequest(ctx, apiInfo, timeout, retryCount)
Y
Your Name 已提交
202
	log.Info(requestID, " Proxy request duration:", time.Since(start))
E
eoLinker API Management 已提交
203
	if err != nil {
Y
Your Name 已提交
204
		log.Warn(err.Error())
E
eoLinker API Management 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
	}
	logFields[FinallyServer] = ctx.FinalTargetServer()
	logFields[Retry] = ctx.RetryTargetServers()
	ctx.SetProxyResponse(response)
	form, _ := ctx.RequestOrg.BodyForm()
	if response == nil {
		proxyStatusCode = -1
		// ctx.Proxy
		go visit.UpdateProxyFailureCount(apiInfo,
			requestMenthod, ctx.ProxyRequest.Method,
			ctx.RequestOrg.Headers(),
			ctx.RequestOrg.URL().Query(),
			form,
			504,
			make(map[string][]string),

			ctx)
	} else {
		logFields[ProxyStatusCode] = response.StatusCode
		// w.WriteHeader(ctx.ProxyStatusCode)
		if !gateway_manager.IsSucess(ctx.StatusCode()) {
			go visit.UpdateProxyFailureCount(
				apiInfo,
				requestMenthod,
				ctx.ProxyRequest.Method,
				ctx.RequestOrg.Headers(),
				ctx.RequestOrg.URL().Query(),
				form,
				ctx.ProxyResponseHandler.StatusCode(),
				ctx.ProxyResponseHandler.Headers(),
				ctx)
		}
	}

	start = time.Now()
	isProxy, _ := plugin_flow.ProxyFunc(ctx, handleFunc)
Y
Your Name 已提交
241
	log.Info(requestID, " Proxy plugin Duration:", time.Since(start))
E
eoLinker API Management 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
	if !isProxy {
		return
	}
	// 默认返回插件未开启时,直接返回回复相关内容
	if response != nil {

	} else {
		ctx.SetStatus(504, "504")
		ctx.SetBody([]byte("[ERROR]Fail to get response after proxy!"))
	}

	//logFunc(ctx, handleFunc)

	return
}