Compare commits

...

3 Commits

Author SHA1 Message Date
weeping 0f6d084c67 fix validate 2025-09-11 18:13:59 +08:00
weeping df04276c08 add ReadAsSSEWithContext 2025-09-11 17:00:10 +08:00
weeping 622f315135 fix sse 2025-08-19 16:58:21 +08:00
6 changed files with 1528 additions and 16 deletions
+33
View File
@@ -184,6 +184,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 {
+144
View File
@@ -193,6 +193,150 @@ func TestConvertType(t *testing.T) {
utils.AssertEqual(t, "test", string(out.Body))
}
// TestConvertChan tests the ConvertChan function
func TestConvertChan(t *testing.T) {
// Test case 1: Successful conversion and sending to channel
t.Run("SuccessfulConversion", func(t *testing.T) {
// Create a channel to receive the converted data
ch := make(chan test, 1)
// Source data to convert
src := map[string]interface{}{
"key": 123,
"body": []byte("test"),
}
// Perform conversion
err := ConvertChan(src, ch)
// Check for errors
if err != nil {
t.Errorf("Expected no error, got %v", err)
}
utils.AssertNil(t, err)
// Check if data was sent to channel
select {
case result := <-ch:
utils.AssertEqual(t, "123", result.Key)
utils.AssertEqual(t, "test", string(result.Body))
}
})
// Test case 2: Invalid destination channel (not a channel)
t.Run("InvalidDestChan", func(t *testing.T) {
src := map[string]interface{}{
"test": "data",
}
// Pass a non-channel type
err := ConvertChan(src, "not_a_channel")
if err == nil {
t.Error("Expected error for invalid channel, got nil")
}
expected := "destChan must be a channel"
if err.Error() != expected {
t.Errorf("Expected error message '%s', got '%s'", expected, err.Error())
}
})
// Test case 3: Send-only channel
t.Run("SendOnlyChannel", func(t *testing.T) {
// Create a send-only channel
ch := make(chan<- map[string]interface{}, 1)
src := map[string]interface{}{
"test": "data",
}
err := ConvertChan(src, ch)
if err == nil {
t.Error("Expected error for send-only channel, got nil")
}
expected := "destChan must be a receive or bidirectional channel"
if err.Error() != expected {
t.Errorf("Expected error message '%s', got '%s'", expected, err.Error())
}
})
// Test case 4: Conversion with struct
t.Run("StructConversion", func(t *testing.T) {
type TestStruct struct {
Name string `json:"name"`
Age int `json:"age"`
}
ch := make(chan TestStruct, 1)
// Source data matching struct fields
src := map[string]interface{}{
"name": "Alice",
"age": 30,
}
err := ConvertChan(src, ch)
if err != nil {
t.Errorf("Expected no error, got %v", err)
}
select {
case result := <-ch:
if result.Name != "Alice" || result.Age != 30 {
t.Errorf("Expected {Name: Alice, Age: 30}, got %v", result)
}
default:
t.Error("Expected data in channel, but channel is empty")
}
})
// Test case 5: Nil source data
t.Run("NilSource", func(t *testing.T) {
ch := make(chan map[string]interface{}, 1)
err := ConvertChan(nil, ch)
// Depending on implementation, this might error or succeed
// Here we're testing it doesn't panic
if err != nil {
// If there's an error, that's fine, just make sure it's handled
t.Logf("Nil source resulted in error (acceptable): %v", err)
} else {
// If no error, check what was sent
select {
case result := <-ch:
if result == nil {
t.Log("Nil source correctly handled")
} else {
t.Errorf("Expected nil or error, got %v", result)
}
default:
t.Log("Channel empty after nil source, which is acceptable")
}
}
})
}
// BenchmarkConvertChan benchmarks the ConvertChan function
func BenchmarkConvertChan(b *testing.B) {
ch := make(chan map[string]interface{}, 1)
src := map[string]interface{}{
"name": "benchmark_test",
"value": 12345,
"active": true,
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = ConvertChan(src, ch)
<-ch // Clear the channel
}
}
func TestRuntimeObject(t *testing.T) {
runtimeobject := NewRuntimeObject(nil)
utils.AssertNil(t, runtimeobject.IgnoreSSL)
+308
View File
File diff suppressed because it is too large Load Diff
+485
View File
File diff suppressed because it is too large Load Diff
+94 -16
View File
@@ -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)
}
}()
}
+464
View File
File diff suppressed because it is too large Load Diff