github.com/gospider007/requests@v0.0.0-20240506025355-c73d46169a23/test/protocol/sse_test.go (about)

     1  package main
     2  
     3  import (
     4  	"io"
     5  	"log"
     6  	"net/http"
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/gospider007/requests"
    11  )
    12  
    13  func TestSse(t *testing.T) {
    14  	// Start the server
    15  	go func() {
    16  		err := http.ListenAndServe(":3333", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    17  			w.Header().Set("Content-Type", "text/event-stream")
    18  			w.Header().Set("Cache-Control", "no-cache")
    19  			w.Header().Set("Connection", "keep-alive")
    20  			w.Header().Set("Access-Control-Allow-Origin", "*")
    21  			// SSE event format
    22  			event := "message"
    23  			data := "testing"
    24  			// Start SSE loop
    25  			for i := 0; i < 3; i++ {
    26  				// Send SSE event
    27  				_, err := w.Write([]byte("event: " + event + "\n"))
    28  				if err != nil {
    29  					log.Println("Error writing SSE event:", err)
    30  					return
    31  				}
    32  				_, err = w.Write([]byte("data: " + data + "\n\n"))
    33  				if err != nil {
    34  					log.Println("Error writing SSE data:", err)
    35  					return
    36  				}
    37  				// Flush the response writer
    38  				if f, ok := w.(http.Flusher); ok {
    39  					f.Flush()
    40  				}
    41  				// Delay before sending the next event
    42  				time.Sleep(1 * time.Second)
    43  			}
    44  		}))
    45  		if err != nil {
    46  			t.Error(err)
    47  		}
    48  	}()
    49  	time.Sleep(time.Second * 3)
    50  	response, err := requests.Get(nil, "http://127.0.0.1:3333/events") // Send WebSocket request
    51  	if err != nil {
    52  		t.Error(err)
    53  	}
    54  	defer response.CloseBody()
    55  	sseCli := response.Sse()
    56  	if sseCli == nil {
    57  		t.Error("not is sseCli")
    58  	}
    59  	for {
    60  		data, err := sseCli.Recv()
    61  		if err != nil {
    62  			if err != io.EOF {
    63  				t.Error(err)
    64  			}
    65  			break
    66  		}
    67  		if data.Data != "testing" {
    68  			t.Error("testing")
    69  		}
    70  	}
    71  }