Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cdfd54484c | |||
| af5f206bd8 | |||
| 5c6eb77b42 | |||
| 0f6d084c67 | |||
| df04276c08 | |||
| 622f315135 | |||
| 31de98dc53 |
+179
-17
@@ -34,6 +34,7 @@ type RuntimeOptions = util.RuntimeOptions
|
||||
type ExtendsParameters = util.ExtendsParameters
|
||||
|
||||
var debugLog = debug.Init("dara")
|
||||
|
||||
type HttpRequest interface {
|
||||
}
|
||||
|
||||
@@ -93,6 +94,7 @@ type RuntimeObject struct {
|
||||
IgnoreSSL *bool `json:"ignoreSSL" xml:"ignoreSSL"`
|
||||
ReadTimeout *int `json:"readTimeout" xml:"readTimeout"`
|
||||
ConnectTimeout *int `json:"connectTimeout" xml:"connectTimeout"`
|
||||
IdleTimeout *int `json:"idleTimeout" xml:"idleTimeout"`
|
||||
LocalAddr *string `json:"localAddr" xml:"localAddr"`
|
||||
HttpProxy *string `json:"httpProxy" xml:"httpProxy"`
|
||||
HttpsProxy *string `json:"httpsProxy" xml:"httpsProxy"`
|
||||
@@ -113,7 +115,7 @@ type RuntimeObject struct {
|
||||
|
||||
func (r *RuntimeObject) getClientTag(domain string) string {
|
||||
return strconv.FormatBool(BoolValue(r.IgnoreSSL)) + strconv.Itoa(IntValue(r.ReadTimeout)) +
|
||||
strconv.Itoa(IntValue(r.ConnectTimeout)) + StringValue(r.LocalAddr) + StringValue(r.HttpProxy) +
|
||||
strconv.Itoa(IntValue(r.ConnectTimeout)) + strconv.Itoa(IntValue(r.IdleTimeout)) + StringValue(r.LocalAddr) + StringValue(r.HttpProxy) +
|
||||
StringValue(r.HttpsProxy) + StringValue(r.NoProxy) + StringValue(r.Socks5Proxy) + StringValue(r.Socks5NetWork) + domain
|
||||
}
|
||||
|
||||
@@ -127,6 +129,7 @@ func NewRuntimeObject(runtime map[string]interface{}) *RuntimeObject {
|
||||
IgnoreSSL: TransInterfaceToBool(runtime["ignoreSSL"]),
|
||||
ReadTimeout: TransInterfaceToInt(runtime["readTimeout"]),
|
||||
ConnectTimeout: TransInterfaceToInt(runtime["connectTimeout"]),
|
||||
IdleTimeout: TransInterfaceToInt(runtime["idleTimeout"]),
|
||||
LocalAddr: TransInterfaceToString(runtime["localAddr"]),
|
||||
HttpProxy: TransInterfaceToString(runtime["httpProxy"]),
|
||||
HttpsProxy: TransInterfaceToString(runtime["httpsProxy"]),
|
||||
@@ -183,6 +186,39 @@ func Convert(in interface{}, out interface{}) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// ConvertChan converts the source data to the target type and sends it to the specified channel.
|
||||
// @param src - source data
|
||||
// @param destChan - target channel
|
||||
// @return error - error during the conversion process
|
||||
func ConvertChan(src interface{}, destChan interface{}) error {
|
||||
destChanValue := reflect.ValueOf(destChan)
|
||||
if destChanValue.Kind() != reflect.Chan {
|
||||
return fmt.Errorf("destChan must be a channel")
|
||||
}
|
||||
|
||||
if destChanValue.Type().ChanDir() == reflect.SendDir {
|
||||
return fmt.Errorf("destChan must be a receive or bidirectional channel")
|
||||
}
|
||||
|
||||
elemType := destChanValue.Type().Elem()
|
||||
|
||||
destValue := reflect.New(elemType).Interface()
|
||||
|
||||
err := Convert(src, destValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
destValueElem := reflect.ValueOf(destValue).Elem()
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
}
|
||||
}()
|
||||
|
||||
destChanValue.TrySend(destValueElem)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Recover is used to format error
|
||||
func Recover(in interface{}) error {
|
||||
if in == nil {
|
||||
@@ -287,7 +323,7 @@ func DoRequest(request *Request, runtimeObject *RuntimeObject) (response *Respon
|
||||
if !defaultClient.ifInit || defaultClient.httpClient.Transport == nil {
|
||||
defaultClient.httpClient.Transport = trans
|
||||
}
|
||||
defaultClient.httpClient.Timeout = time.Duration(IntValue(runtimeObject.ReadTimeout)) * time.Millisecond
|
||||
defaultClient.httpClient.Timeout = time.Duration(IntValue(runtimeObject.ConnectTimeout)+IntValue(runtimeObject.ReadTimeout)) * time.Millisecond
|
||||
defaultClient.ifInit = true
|
||||
defaultClient.Unlock()
|
||||
}
|
||||
@@ -341,8 +377,134 @@ func DoRequest(request *Request, runtimeObject *RuntimeObject) (response *Respon
|
||||
return
|
||||
}
|
||||
|
||||
func DoRequestWithCtx(ctx context.Context, request *Request, runtimeObject *RuntimeObject) (response *Response, err error) {
|
||||
if runtimeObject == nil {
|
||||
runtimeObject = &RuntimeObject{}
|
||||
}
|
||||
fieldMap := make(map[string]string)
|
||||
utils.InitLogMsg(fieldMap)
|
||||
defer func() {
|
||||
if runtimeObject.Logger != nil {
|
||||
runtimeObject.Logger.PrintLog(fieldMap, err)
|
||||
}
|
||||
}()
|
||||
if request.Method == nil {
|
||||
request.Method = String("GET")
|
||||
}
|
||||
|
||||
if request.Protocol == nil {
|
||||
request.Protocol = String("http")
|
||||
} else {
|
||||
request.Protocol = String(strings.ToLower(StringValue(request.Protocol)))
|
||||
}
|
||||
|
||||
requestURL := ""
|
||||
request.Domain = request.Headers["host"]
|
||||
if request.Port != nil {
|
||||
request.Domain = String(fmt.Sprintf("%s:%d", StringValue(request.Domain), IntValue(request.Port)))
|
||||
}
|
||||
requestURL = fmt.Sprintf("%s://%s%s", StringValue(request.Protocol), StringValue(request.Domain), StringValue(request.Pathname))
|
||||
queryParams := request.Query
|
||||
// sort QueryParams by key
|
||||
q := url.Values{}
|
||||
for key, value := range queryParams {
|
||||
q.Add(key, StringValue(value))
|
||||
}
|
||||
querystring := q.Encode()
|
||||
if len(querystring) > 0 {
|
||||
if strings.Contains(requestURL, "?") {
|
||||
requestURL = fmt.Sprintf("%s&%s", requestURL, querystring)
|
||||
} else {
|
||||
requestURL = fmt.Sprintf("%s?%s", requestURL, querystring)
|
||||
}
|
||||
}
|
||||
debugLog("> %s %s", StringValue(request.Method), requestURL)
|
||||
|
||||
httpRequest, err := http.NewRequestWithContext(ctx, StringValue(request.Method), requestURL, request.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
httpRequest.Host = StringValue(request.Domain)
|
||||
|
||||
var client HttpClient
|
||||
if runtimeObject.HttpClient == nil {
|
||||
client = getDaraClient(runtimeObject.getClientTag(StringValue(request.Domain)))
|
||||
} else {
|
||||
client = runtimeObject.HttpClient
|
||||
}
|
||||
|
||||
trans, err := getHttpTransport(request, runtimeObject)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if defaultClient, ok := client.(*daraClient); ok {
|
||||
defaultClient.Lock()
|
||||
if !defaultClient.ifInit || defaultClient.httpClient.Transport == nil {
|
||||
defaultClient.httpClient.Transport = trans
|
||||
}
|
||||
defaultClient.httpClient.Timeout = time.Duration(IntValue(runtimeObject.ConnectTimeout)+IntValue(runtimeObject.ReadTimeout)) * time.Millisecond
|
||||
defaultClient.ifInit = true
|
||||
defaultClient.Unlock()
|
||||
}
|
||||
|
||||
for key, value := range request.Headers {
|
||||
if value == nil || key == "content-length" {
|
||||
continue
|
||||
} else if key == "host" {
|
||||
httpRequest.Header["Host"] = []string{*value}
|
||||
delete(httpRequest.Header, "host")
|
||||
} else if key == "user-agent" {
|
||||
httpRequest.Header["User-Agent"] = []string{*value}
|
||||
delete(httpRequest.Header, "user-agent")
|
||||
} else {
|
||||
httpRequest.Header[key] = []string{*value}
|
||||
}
|
||||
debugLog("> %s: %s", key, StringValue(value))
|
||||
}
|
||||
contentlength, _ := strconv.Atoi(StringValue(request.Headers["content-length"]))
|
||||
event := utils.NewProgressEvent(utils.TransferStartedEvent, 0, int64(contentlength), 0)
|
||||
utils.PublishProgress(runtimeObject.Listener, event)
|
||||
|
||||
putMsgToMap(fieldMap, httpRequest)
|
||||
startTime := time.Now()
|
||||
fieldMap["{start_time}"] = startTime.Format("2006-01-02 15:04:05")
|
||||
res, err := hookDo(client.Call)(httpRequest, trans)
|
||||
fieldMap["{cost}"] = time.Since(startTime).String()
|
||||
completedBytes := int64(0)
|
||||
if runtimeObject.Tracker != nil {
|
||||
completedBytes = runtimeObject.Tracker.CompletedBytes
|
||||
}
|
||||
if err != nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
err = TeaSDKError(ctx.Err())
|
||||
default:
|
||||
}
|
||||
|
||||
event = utils.NewProgressEvent(utils.TransferFailedEvent, completedBytes, int64(contentlength), 0)
|
||||
utils.PublishProgress(runtimeObject.Listener, event)
|
||||
return
|
||||
}
|
||||
|
||||
event = utils.NewProgressEvent(utils.TransferCompletedEvent, completedBytes, int64(contentlength), 0)
|
||||
utils.PublishProgress(runtimeObject.Listener, event)
|
||||
|
||||
response = NewResponse(res)
|
||||
fieldMap["{code}"] = strconv.Itoa(res.StatusCode)
|
||||
fieldMap["{res_headers}"] = Stringify(res.Header)
|
||||
debugLog("< HTTP/1.1 %s", res.Status)
|
||||
for key, value := range res.Header {
|
||||
debugLog("< %s: %s", key, strings.Join(value, ""))
|
||||
if len(value) != 0 {
|
||||
response.Headers[strings.ToLower(key)] = String(value[0])
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func getHttpTransport(req *Request, runtime *RuntimeObject) (*http.Transport, error) {
|
||||
trans := new(http.Transport)
|
||||
trans.ResponseHeaderTimeout = time.Duration(IntValue(runtime.ReadTimeout)) * time.Millisecond
|
||||
httpProxy, err := getHttpProxy(StringValue(req.Protocol), StringValue(req.Domain), runtime)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -396,7 +558,7 @@ func getHttpTransport(req *Request, runtime *RuntimeObject) (*http.Transport, er
|
||||
Password: password,
|
||||
}
|
||||
}
|
||||
dialer, err := proxy.SOCKS5(strings.ToLower(StringValue(runtime.Socks5NetWork)), socks5Proxy.String(), auth,
|
||||
dialer, err := proxy.SOCKS5(strings.ToLower(StringValue(runtime.Socks5NetWork)), socks5Proxy.Host, auth,
|
||||
&net.Dialer{
|
||||
Timeout: time.Duration(IntValue(runtime.ConnectTimeout)) * time.Millisecond,
|
||||
DualStack: true,
|
||||
@@ -414,6 +576,9 @@ func getHttpTransport(req *Request, runtime *RuntimeObject) (*http.Transport, er
|
||||
trans.MaxIdleConns = IntValue(runtime.MaxIdleConns)
|
||||
trans.MaxIdleConnsPerHost = IntValue(runtime.MaxIdleConns)
|
||||
}
|
||||
if runtime.IdleTimeout != nil && *runtime.IdleTimeout > 0 {
|
||||
trans.IdleConnTimeout = time.Duration(IntValue(runtime.IdleTimeout)) * time.Millisecond
|
||||
}
|
||||
return trans, nil
|
||||
}
|
||||
|
||||
@@ -532,7 +697,7 @@ func getSocks5Proxy(runtime *RuntimeObject) (proxy *url.URL, err error) {
|
||||
func getLocalAddr(localAddr string) (addr *net.TCPAddr) {
|
||||
if localAddr != "" {
|
||||
addr = &net.TCPAddr{
|
||||
IP: []byte(localAddr),
|
||||
IP: net.ParseIP(localAddr),
|
||||
}
|
||||
}
|
||||
return addr
|
||||
@@ -540,20 +705,17 @@ func getLocalAddr(localAddr string) (addr *net.TCPAddr) {
|
||||
|
||||
func setDialContext(runtime *RuntimeObject) func(cxt context.Context, net, addr string) (c net.Conn, err error) {
|
||||
return func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if runtime.LocalAddr != nil && StringValue(runtime.LocalAddr) != "" {
|
||||
netAddr := &net.TCPAddr{
|
||||
IP: []byte(StringValue(runtime.LocalAddr)),
|
||||
}
|
||||
return (&net.Dialer{
|
||||
Timeout: time.Duration(IntValue(runtime.ConnectTimeout)) * time.Second,
|
||||
DualStack: true,
|
||||
LocalAddr: netAddr,
|
||||
}).DialContext(ctx, network, address)
|
||||
timeout := time.Duration(IntValue(runtime.ConnectTimeout)) * time.Millisecond
|
||||
dialer := &net.Dialer{
|
||||
Timeout: timeout,
|
||||
Resolver: &net.Resolver{
|
||||
PreferGo: false,
|
||||
},
|
||||
}
|
||||
return (&net.Dialer{
|
||||
Timeout: time.Duration(IntValue(runtime.ConnectTimeout)) * time.Second,
|
||||
DualStack: true,
|
||||
}).DialContext(ctx, network, address)
|
||||
if runtime.LocalAddr != nil && StringValue(runtime.LocalAddr) != "" {
|
||||
dialer.LocalAddr = getLocalAddr(StringValue(runtime.LocalAddr))
|
||||
}
|
||||
return dialer.DialContext(ctx, network, address)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+300
-2
File diff suppressed because it is too large
Load Diff
+308
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+94
-16
@@ -3,44 +3,63 @@ package dara
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// 定义 Event 结构体
|
||||
type SSEEvent struct {
|
||||
ID *string
|
||||
Id *string
|
||||
Event *string
|
||||
Data *string
|
||||
Retry *int
|
||||
}
|
||||
|
||||
// 解析单个事件
|
||||
func parseEvent(lines []string) *SSEEvent {
|
||||
event := &SSEEvent{}
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(line, "data: ") {
|
||||
data := strings.TrimPrefix(line, "data: ") + "\n"
|
||||
if strings.HasPrefix(line, "data:") {
|
||||
var data string
|
||||
if strings.HasPrefix(line, "data: ") {
|
||||
data = strings.TrimPrefix(line, "data: ") + "\n"
|
||||
} else {
|
||||
data = strings.TrimPrefix(line, "data:") + "\n"
|
||||
}
|
||||
if event.Data == nil {
|
||||
event.Data = new(string)
|
||||
}
|
||||
*event.Data += data
|
||||
} else if strings.HasPrefix(line, "event: ") {
|
||||
eventName := strings.TrimPrefix(line, "event: ")
|
||||
} else if strings.HasPrefix(line, "event:") {
|
||||
var eventName string
|
||||
if strings.HasPrefix(line, "event: ") {
|
||||
eventName = strings.TrimPrefix(line, "event: ")
|
||||
} else {
|
||||
eventName = strings.TrimPrefix(line, "event:")
|
||||
}
|
||||
event.Event = &eventName
|
||||
} else if strings.HasPrefix(line, "id: ") {
|
||||
id := strings.TrimPrefix(line, "id: ")
|
||||
event.ID = &id
|
||||
} else if strings.HasPrefix(line, "retry: ") {
|
||||
} else if strings.HasPrefix(line, "id:") {
|
||||
var id string
|
||||
if strings.HasPrefix(line, "id: ") {
|
||||
id = strings.TrimPrefix(line, "id: ")
|
||||
} else {
|
||||
id = strings.TrimPrefix(line, "id:")
|
||||
}
|
||||
event.Id = &id
|
||||
} else if strings.HasPrefix(line, "retry:") {
|
||||
var retryStr string
|
||||
if strings.HasPrefix(line, "retry: ") {
|
||||
retryStr = strings.TrimPrefix(line, "retry: ")
|
||||
} else {
|
||||
retryStr = strings.TrimPrefix(line, "retry:")
|
||||
}
|
||||
var retry int
|
||||
fmt.Sscanf(strings.TrimPrefix(line, "retry: "), "%d", &retry)
|
||||
fmt.Sscanf(retryStr, "%d", &retry)
|
||||
event.Retry = &retry
|
||||
}
|
||||
}
|
||||
// Remove last newline from data
|
||||
if event.Data != nil {
|
||||
data := strings.TrimRight(*event.Data, "\n")
|
||||
event.Data = &data
|
||||
@@ -132,6 +151,65 @@ func ReadAsSSE(body io.ReadCloser, eventChannel chan *SSEEvent, errorChannel cha
|
||||
eventLines = append(eventLines, line)
|
||||
}
|
||||
}()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func ReadAsSSEWithContext(ctx context.Context, body io.ReadCloser, eventChannel chan *SSEEvent, errorChannel chan error) {
|
||||
|
||||
go func() {
|
||||
defer func() {
|
||||
body.Close()
|
||||
close(eventChannel)
|
||||
}()
|
||||
|
||||
reader := bufio.NewReader(body)
|
||||
var eventLines []string
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
errorChannel <- ctx.Err()
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
// Handle the end of the stream and possibly pending event
|
||||
if len(eventLines) > 0 {
|
||||
event := parseEvent(eventLines)
|
||||
select {
|
||||
case eventChannel <- event:
|
||||
case <-ctx.Done():
|
||||
errorChannel <- ctx.Err()
|
||||
return
|
||||
}
|
||||
}
|
||||
errorChannel <- nil
|
||||
return
|
||||
}
|
||||
errorChannel <- err
|
||||
return
|
||||
}
|
||||
|
||||
line = strings.TrimRight(line, "\n")
|
||||
|
||||
if line == "" {
|
||||
// End of an SSE event
|
||||
if len(eventLines) > 0 {
|
||||
event := parseEvent(eventLines)
|
||||
select {
|
||||
case eventChannel <- event:
|
||||
case <-ctx.Done():
|
||||
errorChannel <- ctx.Err()
|
||||
return
|
||||
}
|
||||
eventLines = []string{} // Reset for the next event
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
eventLines = append(eventLines, line)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+15
-16
@@ -386,7 +386,7 @@ func DoRequest(request *Request, requestRuntime map[string]interface{}) (respons
|
||||
if !defaultClient.ifInit || defaultClient.httpClient.Transport == nil {
|
||||
defaultClient.httpClient.Transport = trans
|
||||
}
|
||||
defaultClient.httpClient.Timeout = time.Duration(IntValue(runtimeObject.ReadTimeout)) * time.Millisecond
|
||||
defaultClient.httpClient.Timeout = time.Duration(IntValue(runtimeObject.ConnectTimeout)+IntValue(runtimeObject.ReadTimeout)) * time.Millisecond
|
||||
defaultClient.ifInit = true
|
||||
defaultClient.Unlock()
|
||||
}
|
||||
@@ -442,6 +442,7 @@ func DoRequest(request *Request, requestRuntime map[string]interface{}) (respons
|
||||
|
||||
func getHttpTransport(req *Request, runtime *RuntimeObject) (*http.Transport, error) {
|
||||
trans := new(http.Transport)
|
||||
trans.ResponseHeaderTimeout = time.Duration(IntValue(runtime.ReadTimeout)) * time.Millisecond
|
||||
httpProxy, err := getHttpProxy(StringValue(req.Protocol), StringValue(req.Domain), runtime)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -495,7 +496,7 @@ func getHttpTransport(req *Request, runtime *RuntimeObject) (*http.Transport, er
|
||||
Password: password,
|
||||
}
|
||||
}
|
||||
dialer, err := proxy.SOCKS5(strings.ToLower(StringValue(runtime.Socks5NetWork)), socks5Proxy.String(), auth,
|
||||
dialer, err := proxy.SOCKS5(strings.ToLower(StringValue(runtime.Socks5NetWork)), socks5Proxy.Host, auth,
|
||||
&net.Dialer{
|
||||
Timeout: time.Duration(IntValue(runtime.ConnectTimeout)) * time.Millisecond,
|
||||
DualStack: true,
|
||||
@@ -602,7 +603,7 @@ func getSocks5Proxy(runtime *RuntimeObject) (proxy *url.URL, err error) {
|
||||
func getLocalAddr(localAddr string) (addr *net.TCPAddr) {
|
||||
if localAddr != "" {
|
||||
addr = &net.TCPAddr{
|
||||
IP: []byte(localAddr),
|
||||
IP: net.ParseIP(localAddr),
|
||||
}
|
||||
}
|
||||
return addr
|
||||
@@ -610,20 +611,18 @@ func getLocalAddr(localAddr string) (addr *net.TCPAddr) {
|
||||
|
||||
func setDialContext(runtime *RuntimeObject) func(cxt context.Context, net, addr string) (c net.Conn, err error) {
|
||||
return func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if runtime.LocalAddr != nil && StringValue(runtime.LocalAddr) != "" {
|
||||
netAddr := &net.TCPAddr{
|
||||
IP: []byte(StringValue(runtime.LocalAddr)),
|
||||
}
|
||||
return (&net.Dialer{
|
||||
Timeout: time.Duration(IntValue(runtime.ConnectTimeout)) * time.Second,
|
||||
DualStack: true,
|
||||
LocalAddr: netAddr,
|
||||
}).DialContext(ctx, network, address)
|
||||
}
|
||||
return (&net.Dialer{
|
||||
Timeout: time.Duration(IntValue(runtime.ConnectTimeout)) * time.Second,
|
||||
timeout := time.Duration(IntValue(runtime.ConnectTimeout)) * time.Millisecond
|
||||
dialer := &net.Dialer{
|
||||
Timeout: timeout,
|
||||
Resolver: &net.Resolver{
|
||||
PreferGo: false,
|
||||
},
|
||||
DualStack: true,
|
||||
}).DialContext(ctx, network, address)
|
||||
}
|
||||
if runtime.LocalAddr != nil && StringValue(runtime.LocalAddr) != "" {
|
||||
dialer.LocalAddr = getLocalAddr(StringValue(runtime.LocalAddr))
|
||||
}
|
||||
return dialer.DialContext(ctx, network, address)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -560,12 +560,37 @@ func Test_DoRequest(t *testing.T) {
|
||||
return mockResponse(200, ``, nil)
|
||||
}
|
||||
}
|
||||
// Test socks5 proxy with user:password@host format
|
||||
runtimeObj["socks5Proxy"] = "socks5://someuser:somepassword@ecs.aliyun.com"
|
||||
runtimeObj["localAddr"] = "127.0.0.1"
|
||||
resp, err = DoRequest(request, runtimeObj)
|
||||
utils.AssertNil(t, err)
|
||||
utils.AssertEqual(t, "test", StringValue(resp.Headers["tea"]))
|
||||
|
||||
// Test socks5 proxy with explicit port
|
||||
runtimeObj["socks5Proxy"] = "socks5://someuser:somepassword@ecs.aliyun.com:1080"
|
||||
resp, err = DoRequest(request, runtimeObj)
|
||||
utils.AssertNil(t, err)
|
||||
utils.AssertEqual(t, "test", StringValue(resp.Headers["tea"]))
|
||||
|
||||
// Test socks5 proxy without authentication
|
||||
runtimeObj["socks5Proxy"] = "socks5://proxy.example.com:1080"
|
||||
resp, err = DoRequest(request, runtimeObj)
|
||||
utils.AssertNil(t, err)
|
||||
utils.AssertEqual(t, "test", StringValue(resp.Headers["tea"]))
|
||||
|
||||
// Test socks5 proxy with IPv6 address
|
||||
runtimeObj["socks5Proxy"] = "socks5://[::1]:1080"
|
||||
resp, err = DoRequest(request, runtimeObj)
|
||||
utils.AssertNil(t, err)
|
||||
utils.AssertEqual(t, "test", StringValue(resp.Headers["tea"]))
|
||||
|
||||
// Test socks5 proxy with IPv6 and authentication
|
||||
runtimeObj["socks5Proxy"] = "socks5://user:pass@[2001:db8::1]:1080"
|
||||
resp, err = DoRequest(request, runtimeObj)
|
||||
utils.AssertNil(t, err)
|
||||
utils.AssertEqual(t, "test", StringValue(resp.Headers["tea"]))
|
||||
|
||||
runtimeObj["key"] = "private rsa key"
|
||||
runtimeObj["cert"] = "private certification"
|
||||
runtimeObj["ca"] = "private ca"
|
||||
@@ -942,3 +967,49 @@ func Test_TransInt32AndInt(t *testing.T) {
|
||||
b := ToInt32(a)
|
||||
utils.AssertEqual(t, Int32Value(b), int32(10))
|
||||
}
|
||||
|
||||
func Test_getLocalAddr(t *testing.T) {
|
||||
// Test empty address
|
||||
addr := getLocalAddr("")
|
||||
utils.AssertNil(t, addr)
|
||||
|
||||
// Test valid IPv4 address
|
||||
addr = getLocalAddr("127.0.0.1")
|
||||
utils.AssertNotNil(t, addr)
|
||||
utils.AssertEqual(t, "127.0.0.1", addr.IP.String())
|
||||
|
||||
// Test valid IPv6 address
|
||||
addr = getLocalAddr("::1")
|
||||
utils.AssertNotNil(t, addr)
|
||||
utils.AssertEqual(t, "::1", addr.IP.String())
|
||||
|
||||
// Test invalid IP
|
||||
addr = getLocalAddr("invalid")
|
||||
utils.AssertNotNil(t, addr)
|
||||
utils.AssertNil(t, addr.IP)
|
||||
}
|
||||
|
||||
func Test_setDialContext(t *testing.T) {
|
||||
runtime := &RuntimeObject{
|
||||
ConnectTimeout: Int(1000),
|
||||
LocalAddr: String("127.0.0.1"),
|
||||
}
|
||||
dialerFunc := setDialContext(runtime)
|
||||
utils.AssertNotNil(t, dialerFunc)
|
||||
}
|
||||
|
||||
func Test_TimeoutLogic(t *testing.T) {
|
||||
runtime := &RuntimeObject{
|
||||
ConnectTimeout: Int(1000),
|
||||
ReadTimeout: Int(2000),
|
||||
}
|
||||
|
||||
req := &Request{
|
||||
Protocol: String("http"),
|
||||
Domain: String("localhost"),
|
||||
}
|
||||
trans, err := getHttpTransport(req, runtime)
|
||||
utils.AssertNil(t, err)
|
||||
utils.AssertNotNil(t, trans)
|
||||
utils.AssertEqual(t, time.Duration(2000)*time.Millisecond, trans.ResponseHeaderTimeout)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user