Home >Backend Development >Golang >Channel not sending data on first API request

Channel not sending data on first API request

WBOY
WBOYforward
2024-02-05 22:06:04707browse

通道未在第一个 API 请求上发送数据

Question content

I have a SSE endpoint that sends data to the frontend and the data is coming from anotherAPI Retrieved by the endpoint. I'm still new to channels in go and it seems like I have to trigger the API endpoint twice in order for the SSE endpoint to send data to the frontend. For now, I haven't written the front-end code to establish an SSE connection because I'm still using channels. Can someone explain why this requires calling the API twice to get SSE to send the data?

Shanghai Stock Exchange Route

func SendSSE(appCtx *fiber.Ctx, dataChannel chan string) error {
    appCtx.Set("Content-Type", "text/event-stream")
    appCtx.Set("Cache-Control", "no-cache")
    appCtx.Set("Connection", "keep-alive")
    appCtx.Set("Transfer-Encoding", "chunked")

    appCtx.Context().SetBodyStreamWriter(fasthttp.StreamWriter(func(w *bufio.Writer) {
        log.Println("SSE Opened")
        for {
            log.Println("Retrieving data channel..")
            fmt.Fprintf(w, "data: Message: %s\n\n", <-dataChannel)
            log.Println(<-dataChannel)

            err := w.Flush()
            if err != nil {
                // Refreshing page in web browser will establish a new
                // SSE connection, but only (the last) one is alive, so
                // dead connections must be closed here.
                fmt.Printf("Error while flushing: %v. Closing http connection.\n", err)

                break
            }

        }
    }))

    fmt.Println("SSE Closed")
    return nil

}

API for sending data to sse

func GetApiData(appCtx *fiber.Ctx, dataChannel chan string) error {
    log.Println("Sending DataChannel data")
    dataChannel <- "Data is passed from api to sse"
    return appCtx.Status(http.StatusOK).SendString("Not Implemented")
}


Correct Answer


The reason you are seeing this is because you used 2 messages in this section

fmt.Fprintf(w, "data: Message: %s\n\n", <-dataChannel)
log.Println(<-dataChannel)

Every odd message will be sent to SSE, and every even message will be logged to the console. Should be changed to

message := <-dataChannel
fmt.Fprintf(w, "data: Message: %s\n\n", message)
log.Println(message)

The above is the detailed content of Channel not sending data on first API request. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete