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

import (
	"bytes"
Y
Your Name 已提交
5
	"crypto/tls"
E
eoLinker API Management 已提交
6 7
	"errors"
	"io"
Y
Your Name 已提交
8
	"net"
E
eoLinker API Management 已提交
9 10
	"net/http"
	"net/url"
Y
Your Name 已提交
11 12 13
	"strconv"

	goku_plugin "github.com/eolinker/goku-plugin"
Y
Your Name 已提交
14 15 16 17 18

	"github.com/eolinker/goku-api-gateway/diting"
	goku_labels "github.com/eolinker/goku-api-gateway/goku-labels"
	"github.com/eolinker/goku-api-gateway/node/monitor"

E
eoLinker API Management 已提交
19 20 21 22
	// "fmt"
	"time"
)

Y
Your Name 已提交
23 24
//Version 版本号
var Version = "2.0"
E
eoLinker API Management 已提交
25

Y
Your Name 已提交
26 27 28 29 30 31 32
var skipCertificate = 0

//SetSkipCertificate 设置跳过证书
func SetSkipCertificate(skip int) {
	skipCertificate = skip
}

Y
Your Name 已提交
33
//Request request
E
eoLinker API Management 已提交
34 35 36 37 38 39 40 41 42 43 44 45
type Request struct {
	client  *http.Client
	method  string
	URL     string
	headers map[string][]string
	body    []byte

	queryParams map[string][]string

	timeout time.Duration
}

Y
Your Name 已提交
46
//NewRequest 创建新请求
E
eoLinker API Management 已提交
47 48 49 50 51 52 53 54
func NewRequest(method string, URL *url.URL) (*Request, error) {
	if method != "GET" && method != "POST" && method != "PUT" && method != "DELETE" &&
		method != "HEAD" && method != "OPTIONS" && method != "PATCH" {
		return nil, errors.New("Unsupported Request Method")
	}
	return newRequest(method, URL)
}

Y
Your Name 已提交
55 56 57 58 59 60 61 62
//URLPath urlPath
func URLPath(url string, query url.Values) string {
	if len(query) < 1 {
		return url
	}
	return url + "?" + query.Encode()
}

E
eoLinker API Management 已提交
63 64 65 66 67 68 69
func newRequest(method string, URL *url.URL) (*Request, error) {
	var urlPath string
	queryParams := make(map[string][]string)
	for key, values := range URL.Query() {
		queryParams[key] = values
	}
	urlPath = URL.Scheme + "://" + URL.Host + URL.Path
Y
Your Name 已提交
70 71 72 73 74 75
	tp := http.DefaultTransport
	if skipCertificate == 1 {
		tp = &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
	}
E
eoLinker API Management 已提交
76
	r := &Request{
Y
Your Name 已提交
77
		client:      &http.Client{Transport: tp},
E
eoLinker API Management 已提交
78 79 80 81 82 83 84 85
		method:      method,
		URL:         urlPath,
		headers:     make(map[string][]string),
		queryParams: queryParams,
	}
	return r, nil
}

Y
Your Name 已提交
86 87
//SetHeader 设置请求头
func (r *Request) SetHeader(key string, values ...string) {
E
eoLinker API Management 已提交
88
	if len(values) > 0 {
Y
Your Name 已提交
89
		r.headers[key] = values[:]
E
eoLinker API Management 已提交
90
	} else {
Y
Your Name 已提交
91
		delete(r.headers, key)
E
eoLinker API Management 已提交
92 93 94
	}
}

Y
Your Name 已提交
95 96
//Headers 获取请求头
func (r *Request) Headers() map[string][]string {
E
eoLinker API Management 已提交
97
	headers := make(map[string][]string)
Y
Your Name 已提交
98
	for key, values := range r.headers {
E
eoLinker API Management 已提交
99 100 101 102 103
		headers[key] = values[:]
	}
	return headers
}

Y
Your Name 已提交
104 105
//SetQueryParam 设置Query参数
func (r *Request) SetQueryParam(key string, values ...string) {
E
eoLinker API Management 已提交
106
	if len(values) > 0 {
Y
Your Name 已提交
107
		r.queryParams[key] = values[:]
E
eoLinker API Management 已提交
108
	} else {
Y
Your Name 已提交
109
		delete(r.queryParams, key)
E
eoLinker API Management 已提交
110 111 112
	}
}

Y
Your Name 已提交
113 114 115
//SetTimeout 设置请求超时时间
func (r *Request) SetTimeout(timeout time.Duration) {
	r.timeout = timeout
E
eoLinker API Management 已提交
116 117 118
}

//// 获取请求超时时间
Y
Your Name 已提交
119 120
//func (r *Request) GetTimeout() time.Duration {
//	return r.timeout
E
eoLinker API Management 已提交
121 122
//}

Y
Your Name 已提交
123
//Send 发送请求
Y
Your Name 已提交
124
func (r *Request) Send(ctx goku_plugin.ContextAccess) (*http.Response, error) {
E
eoLinker API Management 已提交
125
	// now := time.Now()
Y
Your Name 已提交
126
	req, err := r.parseBody()
E
eoLinker API Management 已提交
127 128 129
	if err != nil {
		return nil, err
	}
Y
Your Name 已提交
130
	status := 0
Y
Your Name 已提交
131
	start := time.Now()
Y
Your Name 已提交
132
	defer func() {
Y
Your Name 已提交
133 134
		delay := time.Since(start)
		labels := make(diting.Labels)
Y
Your Name 已提交
135 136 137 138 139

		labels[goku_labels.Proto] = req.Proto
		labels[goku_labels.Host] = req.Host
		labels[goku_labels.Path] = req.URL.Path
		labels[goku_labels.Method] = req.Method
Y
Your Name 已提交
140 141 142
		labels[goku_labels.API] = strconv.Itoa(ctx.ApiID())
		labels[goku_labels.Strategy] = ctx.StrategyId()
		labels[goku_labels.Status] = strconv.Itoa(status)
Y
Your Name 已提交
143
		monitor.ProxyMonitor.Observe(float64(delay/time.Millisecond), labels)
Y
Your Name 已提交
144
	}()
E
eoLinker API Management 已提交
145
	req.Header.Set("Accept-Encoding", "gzip")
Y
Your Name 已提交
146
	req.Header = parseHeaders(r.headers)
E
eoLinker API Management 已提交
147

Y
Your Name 已提交
148
	r.client.Timeout = r.timeout
E
eoLinker API Management 已提交
149

Y
Your Name 已提交
150
	httpResponse, err := r.client.Do(req)
E
eoLinker API Management 已提交
151 152

	if err != nil {
Y
Your Name 已提交
153 154 155 156 157 158 159 160 161
		if netErr, ok := err.(net.Error); ok {
			if netErr.Timeout() {
				status = 504
			} else {
				status = 503
			}
		} else {
			status = 503
		}
E
eoLinker API Management 已提交
162 163
		return nil, err
	}
Y
Your Name 已提交
164
	status = httpResponse.StatusCode
E
eoLinker API Management 已提交
165 166 167 168
	return httpResponse, nil

}

Y
Your Name 已提交
169 170
//QueryParams 获取query参数
func (r *Request) QueryParams() map[string][]string {
E
eoLinker API Management 已提交
171
	params := make(map[string][]string)
Y
Your Name 已提交
172
	for key, values := range r.queryParams {
E
eoLinker API Management 已提交
173 174 175 176 177
		params[key] = values[:]
	}
	return params
}

Y
Your Name 已提交
178 179 180 181
//URLPath 获取完整的URL路径
func (r *Request) URLPath() string {
	if len(r.queryParams) > 0 {
		return r.URL + "?" + parseParams(r.queryParams).Encode()
E
eoLinker API Management 已提交
182
	}
Y
Your Name 已提交
183
	return r.URL
E
eoLinker API Management 已提交
184 185
}

Y
Your Name 已提交
186 187 188
//SetURL 设置URL
func (r *Request) SetURL(url string) {
	r.URL = url
E
eoLinker API Management 已提交
189 190
}

Y
Your Name 已提交
191 192 193
//SetRawBody 设置源数据
func (r *Request) SetRawBody(body []byte) {
	r.body = body
E
eoLinker API Management 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
}

// 解析请求头
func parseHeaders(headers map[string][]string) http.Header {
	h := http.Header{}
	for key, values := range headers {
		for _, value := range values {
			h.Add(key, value)
		}
	}

	_, hasAccept := h["Accept"]
	if !hasAccept {
		h.Add("Accept", "*/*")
	}
	_, hasAgent := h["User-Agent"]
	if !hasAgent {
		h.Add("User-Agent", "goku-requests/"+Version)
	}
	return h
}

// 解析请求体
Y
Your Name 已提交
217 218 219 220
func (r *Request) parseBody() (req *http.Request, err error) {
	var body io.Reader
	if len(r.body) > 0 {
		body = bytes.NewBuffer(r.body)
E
eoLinker API Management 已提交
221 222

	}
Y
Your Name 已提交
223
	req, err = http.NewRequest(r.method, r.URLPath(), body)
E
eoLinker API Management 已提交
224
	return
Y
Your Name 已提交
225

E
eoLinker API Management 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
}

// 解析参数
func parseParams(params map[string][]string) url.Values {
	v := url.Values{}
	for key, values := range params {
		for _, value := range values {
			v.Add(key, value)
		}
	}
	return v
}

// 解析URL
func parseURL(urlPath string) (URL *url.URL, err error) {
	URL, err = url.Parse(urlPath)
	if err != nil {
		return nil, err
	}

	if URL.Scheme != "http" && URL.Scheme != "https" {
		urlPath = "http://" + urlPath
		URL, err = url.Parse(urlPath)
		if err != nil {
			return nil, err
		}

		if URL.Scheme != "http" && URL.Scheme != "https" {
			return nil, errors.New("[package requests] only HTTP and HTTPS are accepted")
		}
	}
	return
}