Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 750c1d6363 | |||
| 40fd48a7bb |
@@ -26,8 +26,6 @@ jobs:
|
||||
|
||||
- name: Build Darabonba
|
||||
run: go build ./dara
|
||||
- name: Build Tea
|
||||
run: go build ./tea
|
||||
- name: Build Util
|
||||
run: go build ./utils
|
||||
|
||||
|
||||
+2
-22
@@ -294,28 +294,8 @@ func ConcatArr(arr1 interface{}, arr2 interface{}) interface{} {
|
||||
}
|
||||
|
||||
// ArrAppend inserts a new pointer at a specified index in a pointer array.
|
||||
func ArrAppend(arr interface{}, value interface{}, index int) {
|
||||
arrV := reflect.ValueOf(arr)
|
||||
if arrV.Kind() != reflect.Ptr || arrV.Elem().Kind() != reflect.Slice {
|
||||
return
|
||||
}
|
||||
|
||||
sliceV := arrV.Elem()
|
||||
|
||||
if index < 0 || index > sliceV.Len() {
|
||||
return
|
||||
}
|
||||
|
||||
valueV := reflect.ValueOf(value)
|
||||
|
||||
// 创建一个容纳新值的切片
|
||||
newSlice := reflect.Append(sliceV, reflect.Zero(sliceV.Type().Elem()))
|
||||
reflect.Copy(newSlice.Slice(index+1, newSlice.Len()), newSlice.Slice(index, newSlice.Len()-1))
|
||||
newSlice.Index(index).Set(valueV)
|
||||
|
||||
// 更新原始切片
|
||||
sliceV.Set(newSlice)
|
||||
return
|
||||
func ArrAppend(arr interface{}, value interface{}) {
|
||||
ArrPush(arr, value)
|
||||
}
|
||||
|
||||
// ArrRemove removes an element from the array
|
||||
|
||||
@@ -405,54 +405,6 @@ func TestConcatArr(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestArrAppend(t *testing.T) {
|
||||
// 测试用例1:插入中间位置
|
||||
t.Run("Append to middle of an array", func(t *testing.T) {
|
||||
numbers := []*int{new(int), new(int), new(int)}
|
||||
for i := range numbers {
|
||||
*numbers[i] = i + 1
|
||||
}
|
||||
|
||||
// 将 9 插入到索引 1
|
||||
valueToInsert := new(int)
|
||||
*valueToInsert = 9
|
||||
|
||||
// 期望的结果
|
||||
expected := []*int{new(int), new(int), new(int), new(int)}
|
||||
*expected[0], *expected[1], *expected[2], *expected[3] = 1, 9, 2, 3
|
||||
|
||||
defer func() {
|
||||
if !reflect.DeepEqual(numbers, expected) {
|
||||
t.Errorf("Expected %+v, but got %+v", expected, numbers)
|
||||
}
|
||||
}()
|
||||
|
||||
ArrAppend(&numbers, valueToInsert, 1)
|
||||
})
|
||||
|
||||
// 测试用例2: 尝试在越界处插入
|
||||
t.Run("Index out of bounds", func(t *testing.T) {
|
||||
numbers := []*int{new(int), new(int), new(int)}
|
||||
for i := range numbers {
|
||||
*numbers[i] = i + 1
|
||||
}
|
||||
|
||||
defer func() {
|
||||
// Defer 检查:越界情况下,数组应保持不变
|
||||
expected := []*int{new(int), new(int), new(int)}
|
||||
*expected[0], *expected[1], *expected[2] = 1, 2, 3
|
||||
if !reflect.DeepEqual(numbers, expected) {
|
||||
t.Errorf("Index out of bounds should not modify array, but got %+v", numbers)
|
||||
}
|
||||
}()
|
||||
|
||||
valueToInsert := new(int)
|
||||
*valueToInsert = 9
|
||||
ArrAppend(&numbers, valueToInsert, 10) // 超出范围
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
func TestArrRemove(t *testing.T) {
|
||||
// Create test data for string pointer array
|
||||
str1 := "A"
|
||||
|
||||
+40
-283
File diff suppressed because it is too large
Load Diff
+11
-429
File diff suppressed because it is too large
Load Diff
+6
-47
@@ -7,22 +7,18 @@ import (
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"github.com/alibabacloud-go/tea/tea"
|
||||
)
|
||||
|
||||
type BaseError interface {
|
||||
error
|
||||
GetName() *string
|
||||
GetCode() *string
|
||||
ErrorName() *string
|
||||
ErrorCode() *string
|
||||
}
|
||||
|
||||
type ResponseError interface {
|
||||
BaseError
|
||||
GetRetryAfter() *int64
|
||||
GetStatusCode() *int
|
||||
GetAccessDeniedDetail() map[string]interface{}
|
||||
GetDescription() *string
|
||||
GetData() map[string]interface{}
|
||||
ErrorRetryAfter() *int
|
||||
ErrorStatusCode() *int
|
||||
}
|
||||
|
||||
// SDKError struct is used save error code and message
|
||||
@@ -44,43 +40,6 @@ type CastError struct {
|
||||
Message *string
|
||||
}
|
||||
|
||||
func TeaSDKError(err error) error {
|
||||
if(err == nil) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if te, ok := err.(*SDKError); ok {
|
||||
return tea.NewSDKError(map[string]interface{}{
|
||||
"code": StringValue(te.Code),
|
||||
"statusCode": IntValue(te.StatusCode),
|
||||
"message": StringValue(te.Message),
|
||||
"data": te.Data,
|
||||
"description": StringValue(te.Description),
|
||||
"accessDeniedDetail": te.AccessDeniedDetail,
|
||||
})
|
||||
}
|
||||
|
||||
if respErr, ok := err.(ResponseError); ok {
|
||||
return tea.NewSDKError(map[string]interface{}{
|
||||
"code": StringValue(respErr.GetCode()),
|
||||
"statusCode": IntValue(respErr.GetStatusCode()),
|
||||
"message": respErr.Error(),
|
||||
"description": StringValue(respErr.GetDescription()),
|
||||
"data": respErr.GetData(),
|
||||
"accessDeniedDetail": respErr.GetAccessDeniedDetail(),
|
||||
})
|
||||
}
|
||||
|
||||
if baseErr, ok := err.(BaseError); ok {
|
||||
return tea.NewSDKError(map[string]interface{}{
|
||||
"code": StringValue(baseErr.GetCode()),
|
||||
"message": baseErr.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// NewSDKError is used for shortly create SDKError object
|
||||
func NewSDKError(obj map[string]interface{}) *SDKError {
|
||||
err := &SDKError{}
|
||||
@@ -90,7 +49,7 @@ func NewSDKError(obj map[string]interface{}) *SDKError {
|
||||
} else if val, ok := obj["code"].(string); ok {
|
||||
err.Code = String(val)
|
||||
}
|
||||
|
||||
|
||||
if obj["message"] != nil {
|
||||
err.Message = String(obj["message"].(string))
|
||||
}
|
||||
@@ -161,7 +120,7 @@ func (err *SDKError) ErrorMessage() *string {
|
||||
return err.Message
|
||||
}
|
||||
|
||||
func (err *SDKError) GetCode() *string {
|
||||
func (err *SDKError) ErrorCode() *string {
|
||||
return err.Code
|
||||
}
|
||||
|
||||
|
||||
+3
-23
@@ -6,7 +6,6 @@ import (
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"github.com/modern-go/reflect2"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"math"
|
||||
"reflect"
|
||||
"strconv"
|
||||
@@ -333,28 +332,9 @@ func (decoder *nullableFuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jso
|
||||
}
|
||||
}
|
||||
|
||||
func Stringify(a interface{}) string {
|
||||
switch v := a.(type) {
|
||||
case *string:
|
||||
return StringValue(v)
|
||||
case string:
|
||||
return v
|
||||
case []byte:
|
||||
return string(v)
|
||||
case io.Reader:
|
||||
byt, err := ioutil.ReadAll(v)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(byt)
|
||||
}
|
||||
byt := bytes.NewBuffer([]byte{})
|
||||
jsonEncoder := json.NewEncoder(byt)
|
||||
jsonEncoder.SetEscapeHTML(false)
|
||||
if err := jsonEncoder.Encode(a); err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(bytes.TrimSpace(byt.Bytes()))
|
||||
func Stringify(m interface{}) string {
|
||||
byt, _ := json.Marshal(m)
|
||||
return string(byt)
|
||||
}
|
||||
|
||||
func ParseJSON(a string) interface{} {
|
||||
|
||||
@@ -3,7 +3,6 @@ package dara
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
"strings"
|
||||
|
||||
"github.com/alibabacloud-go/tea/utils"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
@@ -879,42 +878,3 @@ func TestUnmarshalWithDefaultDecoders(t *testing.T) {
|
||||
err = jsoniter.Unmarshal(from, toUint64)
|
||||
utils.AssertNotNil(t, err)
|
||||
}
|
||||
|
||||
func Test_Stringify(t *testing.T) {
|
||||
// interface
|
||||
str := Stringify(map[string]interface{}{"test": "ok"})
|
||||
utils.AssertEqual(t, `{"test":"ok"}`, str)
|
||||
// string
|
||||
str = Stringify("test")
|
||||
utils.AssertEqual(t, "test", str)
|
||||
// []byte
|
||||
str = Stringify([]byte("test"))
|
||||
utils.AssertEqual(t, "test", str)
|
||||
// io.Reader
|
||||
str = Stringify(strings.NewReader("test"))
|
||||
utils.AssertEqual(t, "test", str)
|
||||
|
||||
str = Stringify("test")
|
||||
utils.AssertEqual(t, "test", str)
|
||||
}
|
||||
|
||||
|
||||
func Test_ParseJSON(t *testing.T) {
|
||||
obj := ParseJSON(`{"test":"ok"}`).(map[string]interface{})
|
||||
utils.AssertEqual(t, "ok", obj["test"])
|
||||
|
||||
obj1 := ParseJSON(`["test1", "test2", "test3"]`).([]interface{})
|
||||
utils.AssertEqual(t, "test2", obj1[1])
|
||||
|
||||
num := ParseJSON(`10`).(int)
|
||||
utils.AssertEqual(t, 10, num)
|
||||
|
||||
boolVal := ParseJSON(`true`).(bool)
|
||||
utils.AssertEqual(t, true, boolVal)
|
||||
|
||||
float64Val := ParseJSON(`1.00`).(float64)
|
||||
utils.AssertEqual(t, 1.00, float64Val)
|
||||
|
||||
null := ParseJSON(`}}}}`)
|
||||
utils.AssertEqual(t, nil, null)
|
||||
}
|
||||
-308
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+10
-10
@@ -273,12 +273,12 @@ func ShouldRetry(options *RetryOptions, ctx *RetryPolicyContext) bool {
|
||||
|
||||
for _, condition := range conditions {
|
||||
for _, exc := range condition.Exception {
|
||||
if exc == StringValue(baseErr.GetName()) {
|
||||
if exc == StringValue(baseErr.ErrorName()) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, code := range condition.ErrorCode {
|
||||
if code == StringValue(baseErr.GetCode()) {
|
||||
if code == StringValue(baseErr.ErrorCode()) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -287,7 +287,7 @@ func ShouldRetry(options *RetryOptions, ctx *RetryPolicyContext) bool {
|
||||
conditions = options.RetryCondition
|
||||
for _, condition := range conditions {
|
||||
for _, exc := range condition.Exception {
|
||||
if exc == StringValue(baseErr.GetName()) {
|
||||
if exc == StringValue(baseErr.ErrorName()) {
|
||||
if retriesAttempted >= condition.MaxAttempts {
|
||||
return false
|
||||
}
|
||||
@@ -295,7 +295,7 @@ func ShouldRetry(options *RetryOptions, ctx *RetryPolicyContext) bool {
|
||||
}
|
||||
}
|
||||
for _, code := range condition.ErrorCode {
|
||||
if code == StringValue(baseErr.GetCode()) {
|
||||
if code == StringValue(baseErr.ErrorCode()) {
|
||||
if retriesAttempted >= condition.MaxAttempts {
|
||||
return false
|
||||
}
|
||||
@@ -323,13 +323,13 @@ func GetBackoffDelay(options *RetryOptions, ctx *RetryPolicyContext) int {
|
||||
if baseErr, ok := ex.(BaseError); ok {
|
||||
for _, condition := range conditions {
|
||||
for _, exc := range condition.Exception {
|
||||
if exc == StringValue(baseErr.GetName()) {
|
||||
if exc == StringValue(baseErr.ErrorName()) {
|
||||
maxDelay := condition.MaxDelay
|
||||
// Simulated "retryAfter" from an error response
|
||||
if respErr, ok := ex.(ResponseError); ok {
|
||||
retryAfter := Int64Value(respErr.GetRetryAfter())
|
||||
retryAfter := IntValue(respErr.ErrorRetryAfter())
|
||||
if retryAfter != 0 {
|
||||
return min(int(retryAfter), maxDelay)
|
||||
return min(retryAfter, maxDelay)
|
||||
}
|
||||
}
|
||||
// This would be set properly based on your error handling
|
||||
@@ -342,13 +342,13 @@ func GetBackoffDelay(options *RetryOptions, ctx *RetryPolicyContext) int {
|
||||
}
|
||||
|
||||
for _, code := range condition.ErrorCode {
|
||||
if code == StringValue(baseErr.GetCode()) {
|
||||
if code == StringValue(baseErr.ErrorCode()) {
|
||||
maxDelay := condition.MaxDelay
|
||||
// Simulated "retryAfter" from an error response
|
||||
if respErr, ok := ex.(ResponseError); ok {
|
||||
retryAfter := Int64Value(respErr.GetRetryAfter())
|
||||
retryAfter := IntValue(respErr.ErrorRetryAfter())
|
||||
if retryAfter != 0 {
|
||||
return min(int(retryAfter), maxDelay)
|
||||
return min(retryAfter, maxDelay)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+12
-12
@@ -29,11 +29,11 @@ func (err *AErr) New(obj map[string]interface{}) *AErr {
|
||||
return err
|
||||
}
|
||||
|
||||
func (err *AErr) GetCode() *string {
|
||||
func (err *AErr) ErrorCode() *string {
|
||||
return err.Code
|
||||
}
|
||||
|
||||
func (err *AErr) GetName() *string {
|
||||
func (err *AErr) ErrorName() *string {
|
||||
return err.Name
|
||||
}
|
||||
|
||||
@@ -59,11 +59,11 @@ func (err *BErr) New(obj map[string]interface{}) *BErr {
|
||||
return err
|
||||
}
|
||||
|
||||
func (err *BErr) GetCode() *string {
|
||||
func (err *BErr) ErrorCode() *string {
|
||||
return err.Code
|
||||
}
|
||||
|
||||
func (err *BErr) GetName() *string {
|
||||
func (err *BErr) ErrorName() *string {
|
||||
return err.Name
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ type CErr struct {
|
||||
Code *string
|
||||
Name *string
|
||||
Message *string
|
||||
RetryAfter *int64
|
||||
RetryAfter *int
|
||||
StatusCode *int
|
||||
}
|
||||
|
||||
@@ -91,26 +91,26 @@ func (err *CErr) New(obj map[string]interface{}) *CErr {
|
||||
err.StatusCode = Int(statusCode)
|
||||
}
|
||||
|
||||
if retryAfter, ok := obj["RetryAfter"].(int64); ok {
|
||||
err.RetryAfter = Int64(retryAfter)
|
||||
if retryAfter, ok := obj["RetryAfter"].(int); ok {
|
||||
err.RetryAfter = Int(retryAfter)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (err *CErr) GetCode() *string {
|
||||
func (err *CErr) ErrorCode() *string {
|
||||
return err.Code
|
||||
}
|
||||
|
||||
func (err *CErr) GetName() *string {
|
||||
func (err *CErr) ErrorName() *string {
|
||||
return err.Name
|
||||
}
|
||||
|
||||
func (err *CErr) GetRetryAfter() *int64 {
|
||||
func (err *CErr) ErrorRetryAfter() *int {
|
||||
return err.RetryAfter
|
||||
}
|
||||
|
||||
func (err *CErr) GetStatusCode() *int {
|
||||
func (err *CErr) ErrorStatusCode() *int {
|
||||
return err.StatusCode
|
||||
}
|
||||
|
||||
@@ -584,7 +584,7 @@ func TestRetryAfter(t *testing.T) {
|
||||
RetriesAttempted: 2,
|
||||
Exception: new(CErr).New(map[string]interface{}{
|
||||
"Code": "CErr",
|
||||
"RetryAfter": int64(3000),
|
||||
"RetryAfter": 3000,
|
||||
}),
|
||||
}
|
||||
|
||||
|
||||
+22
-127
@@ -3,67 +3,35 @@ package dara
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 定义 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 {
|
||||
// 解析单个事件
|
||||
func parseEvent(eventLines []string) *SSEEvent {
|
||||
var event *SSEEvent
|
||||
var data string
|
||||
var id string
|
||||
|
||||
for _, line := range eventLines {
|
||||
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:") {
|
||||
var eventName string
|
||||
if strings.HasPrefix(line, "event: ") {
|
||||
eventName = strings.TrimPrefix(line, "event: ")
|
||||
} else {
|
||||
eventName = strings.TrimPrefix(line, "event:")
|
||||
}
|
||||
event.Event = &eventName
|
||||
data += strings.TrimPrefix(line, "data:") + "\n"
|
||||
} 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(retryStr, "%d", &retry)
|
||||
event.Retry = &retry
|
||||
id += strings.TrimPrefix(line, "data:") + "\n"
|
||||
}
|
||||
}
|
||||
if event.Data != nil {
|
||||
data := strings.TrimRight(*event.Data, "\n")
|
||||
event.Data = &data
|
||||
}
|
||||
|
||||
event.Data = String(data)
|
||||
event.ID = String(id)
|
||||
return event
|
||||
}
|
||||
|
||||
@@ -109,107 +77,34 @@ func ReadAsString(body io.Reader) (string, error) {
|
||||
return string(byt), nil
|
||||
}
|
||||
|
||||
func ReadAsSSE(body io.ReadCloser, eventChannel chan *SSEEvent, errorChannel chan error) {
|
||||
func ReadAsSSE(body io.ReadCloser) (<-chan *SSEEvent, <-chan error) {
|
||||
eventChannel := make(chan *SSEEvent)
|
||||
|
||||
// 启动 Goroutine 解析 SSE 数据
|
||||
go func() {
|
||||
defer func() {
|
||||
body.Close()
|
||||
close(eventChannel)
|
||||
}()
|
||||
defer body.Close()
|
||||
defer close(eventChannel)
|
||||
var eventLines []string
|
||||
|
||||
reader := bufio.NewReader(body)
|
||||
var eventLines []string
|
||||
|
||||
for {
|
||||
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)
|
||||
eventChannel <- event
|
||||
}
|
||||
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)
|
||||
eventChannel <- event
|
||||
eventLines = []string{} // Reset for the next event
|
||||
eventLines = []string{}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
eventLines = append(eventLines, line)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}()
|
||||
return eventChannel, nil
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,6 +6,7 @@ require (
|
||||
github.com/alibabacloud-go/debug v1.0.0
|
||||
github.com/alibabacloud-go/tea-utils/v2 v2.0.7
|
||||
github.com/clbanning/mxj/v2 v2.7.0
|
||||
github.com/google/go-cmp v0.6.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12
|
||||
github.com/modern-go/reflect2 v1.0.2
|
||||
golang.org/x/net v0.26.0
|
||||
|
||||
@@ -25,7 +25,6 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||
golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
@@ -35,13 +34,12 @@ golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ=
|
||||
@@ -59,7 +57,6 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
@@ -69,7 +66,6 @@ golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9sn
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
{
|
||||
"scope": "darabonba",
|
||||
"name": "HttpClient",
|
||||
"version": "0.0.1",
|
||||
"main": "./main.dara",
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "Alibaba Cloud SDK",
|
||||
"email": "sdk-team@alibabacloud.com"
|
||||
}
|
||||
],
|
||||
"libraries": {
|
||||
},
|
||||
"releases": {
|
||||
"go": "github.com/alibabacloud-go/tea/tea:v1.2.3-0.20240605082020-e6e537a31150"
|
||||
},
|
||||
"go": {
|
||||
"interface": true,
|
||||
"clientName": "HttpClient",
|
||||
"typedef": {
|
||||
"HttpRequest": {
|
||||
"import": "net/http",
|
||||
"type": "http.Request"
|
||||
},
|
||||
"HttpResponse": {
|
||||
"import": "net/http",
|
||||
"type": "http.Response"
|
||||
},
|
||||
"HttpTransport": {
|
||||
"import": "net/http",
|
||||
"type": "http.Transport"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
typedef HttpRequest;
|
||||
typedef HttpResponse;
|
||||
typedef HttpTransport;
|
||||
|
||||
init(){
|
||||
}
|
||||
|
||||
async function call(request: HttpRequest, transport: HttpTransport): HttpResponse;
|
||||
@@ -1,35 +0,0 @@
|
||||
{
|
||||
"scope": "darabonba",
|
||||
"name": "HttpClientV2",
|
||||
"version": "0.0.1",
|
||||
"main": "./main.dara",
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "Alibaba Cloud SDK",
|
||||
"email": "sdk-team@alibabacloud.com"
|
||||
}
|
||||
],
|
||||
"libraries": {
|
||||
},
|
||||
"releases": {
|
||||
"go": "github.com/alibabacloud-go/tea/dara:v1.3.5"
|
||||
},
|
||||
"go": {
|
||||
"interface": true,
|
||||
"clientName": "HttpClient",
|
||||
"typedef": {
|
||||
"HttpRequest": {
|
||||
"import": "net/http",
|
||||
"type": "http.Request"
|
||||
},
|
||||
"HttpResponse": {
|
||||
"import": "net/http",
|
||||
"type": "http.Response"
|
||||
},
|
||||
"HttpTransport": {
|
||||
"import": "net/http",
|
||||
"type": "http.Transport"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
typedef HttpRequest;
|
||||
typedef HttpResponse;
|
||||
typedef HttpTransport;
|
||||
|
||||
init(){
|
||||
}
|
||||
|
||||
async function call(request: HttpRequest, transport: HttpTransport): HttpResponse;
|
||||
+32
-59
@@ -31,28 +31,7 @@ import (
|
||||
|
||||
var debugLog = debug.Init("tea")
|
||||
|
||||
type HttpRequest interface {
|
||||
}
|
||||
|
||||
type HttpResponse interface {
|
||||
}
|
||||
|
||||
type HttpClient interface {
|
||||
Call(request *http.Request, transport *http.Transport) (response *http.Response, err error)
|
||||
}
|
||||
|
||||
type teaClient struct {
|
||||
sync.Mutex
|
||||
httpClient *http.Client
|
||||
ifInit bool
|
||||
}
|
||||
|
||||
func (client *teaClient) Call(request *http.Request, transport *http.Transport) (response *http.Response, err error) {
|
||||
response, err = client.httpClient.Do(request)
|
||||
return
|
||||
}
|
||||
|
||||
var hookDo = func(fn func(req *http.Request, transport *http.Transport) (*http.Response, error)) func(req *http.Request, transport *http.Transport) (*http.Response, error) {
|
||||
var hookDo = func(fn func(req *http.Request) (*http.Response, error)) func(req *http.Request) (*http.Response, error) {
|
||||
return fn
|
||||
}
|
||||
|
||||
@@ -118,7 +97,12 @@ type RuntimeObject struct {
|
||||
Listener utils.ProgressListener `json:"listener" xml:"listener"`
|
||||
Tracker *utils.ReaderTracker `json:"tracker" xml:"tracker"`
|
||||
Logger *utils.Logger `json:"logger" xml:"logger"`
|
||||
HttpClient
|
||||
}
|
||||
|
||||
type teaClient struct {
|
||||
sync.Mutex
|
||||
httpClient *http.Client
|
||||
ifInit bool
|
||||
}
|
||||
|
||||
var clientPool = &sync.Map{}
|
||||
@@ -159,9 +143,6 @@ func NewRuntimeObject(runtime map[string]interface{}) *RuntimeObject {
|
||||
if runtime["logger"] != nil {
|
||||
runtimeObject.Logger = runtime["logger"].(*utils.Logger)
|
||||
}
|
||||
if runtime["httpClient"] != nil {
|
||||
runtimeObject.HttpClient = runtime["httpClient"].(HttpClient)
|
||||
}
|
||||
return runtimeObject
|
||||
}
|
||||
|
||||
@@ -370,27 +351,18 @@ func DoRequest(request *Request, requestRuntime map[string]interface{}) (respons
|
||||
}
|
||||
httpRequest.Host = StringValue(request.Domain)
|
||||
|
||||
var client HttpClient
|
||||
if runtimeObject.HttpClient == nil {
|
||||
client = getTeaClient(runtimeObject.getClientTag(StringValue(request.Domain)))
|
||||
} else {
|
||||
client = runtimeObject.HttpClient
|
||||
}
|
||||
|
||||
trans, err := getHttpTransport(request, runtimeObject)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if defaultClient, ok := client.(*teaClient); ok {
|
||||
defaultClient.Lock()
|
||||
if !defaultClient.ifInit || defaultClient.httpClient.Transport == nil {
|
||||
defaultClient.httpClient.Transport = trans
|
||||
client := getTeaClient(runtimeObject.getClientTag(StringValue(request.Domain)))
|
||||
client.Lock()
|
||||
if !client.ifInit {
|
||||
trans, err := getHttpTransport(request, runtimeObject)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defaultClient.httpClient.Timeout = time.Duration(IntValue(runtimeObject.ConnectTimeout)+IntValue(runtimeObject.ReadTimeout)) * time.Millisecond
|
||||
defaultClient.ifInit = true
|
||||
defaultClient.Unlock()
|
||||
client.httpClient.Timeout = time.Duration(IntValue(runtimeObject.ReadTimeout)) * time.Millisecond
|
||||
client.httpClient.Transport = trans
|
||||
client.ifInit = true
|
||||
}
|
||||
|
||||
client.Unlock()
|
||||
for key, value := range request.Headers {
|
||||
if value == nil || key == "content-length" {
|
||||
continue
|
||||
@@ -412,7 +384,7 @@ func DoRequest(request *Request, requestRuntime map[string]interface{}) (respons
|
||||
putMsgToMap(fieldMap, httpRequest)
|
||||
startTime := time.Now()
|
||||
fieldMap["{start_time}"] = startTime.Format("2006-01-02 15:04:05")
|
||||
res, err := hookDo(client.Call)(httpRequest, trans)
|
||||
res, err := hookDo(client.httpClient.Do)(httpRequest)
|
||||
fieldMap["{cost}"] = time.Since(startTime).String()
|
||||
completedBytes := int64(0)
|
||||
if runtimeObject.Tracker != nil {
|
||||
@@ -442,7 +414,6 @@ 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
|
||||
@@ -496,7 +467,7 @@ func getHttpTransport(req *Request, runtime *RuntimeObject) (*http.Transport, er
|
||||
Password: password,
|
||||
}
|
||||
}
|
||||
dialer, err := proxy.SOCKS5(strings.ToLower(StringValue(runtime.Socks5NetWork)), socks5Proxy.Host, auth,
|
||||
dialer, err := proxy.SOCKS5(strings.ToLower(StringValue(runtime.Socks5NetWork)), socks5Proxy.String(), auth,
|
||||
&net.Dialer{
|
||||
Timeout: time.Duration(IntValue(runtime.ConnectTimeout)) * time.Millisecond,
|
||||
DualStack: true,
|
||||
@@ -603,7 +574,7 @@ func getSocks5Proxy(runtime *RuntimeObject) (proxy *url.URL, err error) {
|
||||
func getLocalAddr(localAddr string) (addr *net.TCPAddr) {
|
||||
if localAddr != "" {
|
||||
addr = &net.TCPAddr{
|
||||
IP: net.ParseIP(localAddr),
|
||||
IP: []byte(localAddr),
|
||||
}
|
||||
}
|
||||
return addr
|
||||
@@ -611,18 +582,20 @@ 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) {
|
||||
timeout := time.Duration(IntValue(runtime.ConnectTimeout)) * time.Millisecond
|
||||
dialer := &net.Dialer{
|
||||
Timeout: timeout,
|
||||
Resolver: &net.Resolver{
|
||||
PreferGo: false,
|
||||
},
|
||||
DualStack: true,
|
||||
}
|
||||
if runtime.LocalAddr != nil && StringValue(runtime.LocalAddr) != "" {
|
||||
dialer.LocalAddr = getLocalAddr(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 dialer.DialContext(ctx, network, address)
|
||||
return (&net.Dialer{
|
||||
Timeout: time.Duration(IntValue(runtime.ConnectTimeout)) * time.Second,
|
||||
DualStack: true,
|
||||
}).DialContext(ctx, network, address)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+10
-113
@@ -487,36 +487,11 @@ func Test_GetBackoffTime(t *testing.T) {
|
||||
utils.AssertEqual(t, true, IntValue(ms) <= 3)
|
||||
}
|
||||
|
||||
type httpClient struct {
|
||||
HttpClient
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
func newHttpClient() (*httpClient, error) {
|
||||
client := new(httpClient)
|
||||
err := client.Init()
|
||||
return client, err
|
||||
}
|
||||
|
||||
func (client *httpClient) Init() (_err error) {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (client *httpClient) Call(request *http.Request, transport *http.Transport) (_result *http.Response, _err error) {
|
||||
if transport != nil {
|
||||
trans := transport.Clone()
|
||||
client.httpClient.Transport = trans
|
||||
} else {
|
||||
client.httpClient.Transport = http.DefaultTransport.(*http.Transport).Clone()
|
||||
}
|
||||
return client.httpClient.Do(request)
|
||||
}
|
||||
|
||||
func Test_DoRequest(t *testing.T) {
|
||||
origTestHookDo := hookDo
|
||||
defer func() { hookDo = origTestHookDo }()
|
||||
hookDo = func(fn func(req *http.Request, transport *http.Transport) (*http.Response, error)) func(req *http.Request, transport *http.Transport) (*http.Response, error) {
|
||||
return func(req *http.Request, transport *http.Transport) (*http.Response, error) {
|
||||
hookDo = func(fn func(req *http.Request) (*http.Response, error)) func(req *http.Request) (*http.Response, error) {
|
||||
return func(req *http.Request) (*http.Response, error) {
|
||||
return mockResponse(200, ``, errors.New("Internal error"))
|
||||
}
|
||||
}
|
||||
@@ -555,42 +530,17 @@ func Test_DoRequest(t *testing.T) {
|
||||
utils.AssertNil(t, resp)
|
||||
utils.AssertContains(t, err.Error(), ` invalid URL escape "%gf"`)
|
||||
|
||||
hookDo = func(fn func(req *http.Request, transport *http.Transport) (*http.Response, error)) func(req *http.Request, transport *http.Transport) (*http.Response, error) {
|
||||
return func(req *http.Request, transport *http.Transport) (*http.Response, error) {
|
||||
hookDo = func(fn func(req *http.Request) (*http.Response, error)) func(req *http.Request) (*http.Response, error) {
|
||||
return func(req *http.Request) (*http.Response, error) {
|
||||
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"
|
||||
@@ -629,8 +579,8 @@ func Test_DoRequest(t *testing.T) {
|
||||
utils.AssertNil(t, err)
|
||||
utils.AssertEqual(t, "test", StringValue(resp.Headers["tea"]))
|
||||
|
||||
hookDo = func(fn func(req *http.Request, transport *http.Transport) (*http.Response, error)) func(req *http.Request, transport *http.Transport) (*http.Response, error) {
|
||||
return func(req *http.Request, transport *http.Transport) (*http.Response, error) {
|
||||
hookDo = func(fn func(req *http.Request) (*http.Response, error)) func(req *http.Request) (*http.Response, error) {
|
||||
return func(req *http.Request) (*http.Response, error) {
|
||||
utils.AssertEqual(t, "tea-cn-hangzhou.aliyuncs.com:1080", req.Host)
|
||||
return mockResponse(200, ``, errors.New("Internal error"))
|
||||
}
|
||||
@@ -642,20 +592,13 @@ func Test_DoRequest(t *testing.T) {
|
||||
resp, err = DoRequest(request, runtimeObj)
|
||||
utils.AssertNil(t, resp)
|
||||
utils.AssertEqual(t, `Internal error`, err.Error())
|
||||
|
||||
httpClient, err := newHttpClient()
|
||||
utils.AssertNil(t, err)
|
||||
runtimeObj["httpClient"] = httpClient
|
||||
resp, err = DoRequest(request, runtimeObj)
|
||||
utils.AssertNil(t, resp)
|
||||
utils.AssertEqual(t, `Internal error`, err.Error())
|
||||
}
|
||||
|
||||
func Test_DoRequestWithConcurrent(t *testing.T) {
|
||||
origTestHookDo := hookDo
|
||||
defer func() { hookDo = origTestHookDo }()
|
||||
hookDo = func(fn func(req *http.Request, transport *http.Transport) (*http.Response, error)) func(req *http.Request, transport *http.Transport) (*http.Response, error) {
|
||||
return func(req *http.Request, transport *http.Transport) (*http.Response, error) {
|
||||
hookDo = func(fn func(req *http.Request) (*http.Response, error)) func(req *http.Request) (*http.Response, error) {
|
||||
return func(req *http.Request) (*http.Response, error) {
|
||||
return mockResponse(200, ``, nil)
|
||||
}
|
||||
}
|
||||
@@ -751,11 +694,11 @@ func Test_SetDialContext(t *testing.T) {
|
||||
}
|
||||
|
||||
func Test_hookdo(t *testing.T) {
|
||||
fn := func(req *http.Request, transport *http.Transport) (*http.Response, error) {
|
||||
fn := func(req *http.Request) (*http.Response, error) {
|
||||
return nil, errors.New("hookdo")
|
||||
}
|
||||
result := hookDo(fn)
|
||||
resp, err := result(nil, nil)
|
||||
resp, err := result(nil)
|
||||
utils.AssertNil(t, resp)
|
||||
utils.AssertEqual(t, "hookdo", err.Error())
|
||||
}
|
||||
@@ -967,49 +910,3 @@ 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