首页 > 其他分享 >gofiber sse

gofiber sse

时间:2024-07-23 12:19:47浏览次数:10  
标签:fiber fmt gofiber time sse app

package main

import (
	"bufio"
	"fmt"
	"log"
	"time"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/valyala/fasthttp"
)

var index = []byte(`<!DOCTYPE html>
<html>
<body>

<h1>SSE Messages</h1>
<div id="result"></div>

<script>
if(typeof(EventSource) !== "undefined") {
  var source = new EventSource("http://127.0.0.1:3000/sse");
  source.onmessage = function(event) {
    document.getElementById("result").innerHTML += event.data + "<br>";
  };
} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

</body>
</html>
`)

func main() {
	// Fiber instance
	app := fiber.New()

	// CORS for external resources
	app.Use(cors.New(cors.Config{
		AllowOrigins:     "http://127.0.0.1,http://localhost",
		AllowHeaders:     "Cache-Control",
		AllowCredentials: true,
	}))

	app.Get("/", func(c *fiber.Ctx) error {
		c.Response().Header.SetContentType(fiber.MIMETextHTMLCharsetUTF8)

		return c.Status(fiber.StatusOK).Send(index)
	})

	app.Get("/sse", func(c *fiber.Ctx) error {
		c.Set("Content-Type", "text/event-stream")
		c.Set("Cache-Control", "no-cache")
		c.Set("Connection", "keep-alive")
		c.Set("Transfer-Encoding", "chunked")

		c.Status(fiber.StatusOK).Context().SetBodyStreamWriter(fasthttp.StreamWriter(func(w *bufio.Writer) {
			fmt.Println("WRITER")
			var i int
			for {
				i++
				msg := fmt.Sprintf("%d - the time is %v", i, time.Now())
				fmt.Fprintf(w, "data: Message: %s\n\n", msg)
				fmt.Println(msg)

				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
				}
				time.Sleep(2 * time.Second)
			}
		}))

		return nil
	})

	// Start server
	log.Fatal(app.Listen(":3000"))
}

标签:fiber,fmt,gofiber,time,sse,app
From: https://www.cnblogs.com/soarowl/p/18318037

相关文章

  • 【数据结构】排序算法——Lessen1
    Hi~!这里是奋斗的小羊,很荣幸您能阅读我的文章,诚请评论指点,欢迎欢迎~~......
  • PyTorch LSTM 模型上的 CrossEntropyLoss,每个时间步一分类
    我正在尝试创建一个LSTM模型来检测时间序列数据中的异常情况。它需要5个输入并产生1个布尔输出(如果检测到异常则为True/False)。异常模式通常连续3-4个时间步长。与大多数LSTM示例不同,它们预测未来数据或对整个数据序列进行分类,我尝试在每个时间步输出True/False检......
  • REASSESSMENT TASK
    ResubmissionAssessmentTitle:ResubmissionassignmentUnitLevel:6ReassessmentNumber:1of1CreditValueofUnit:20DateIssued:04/07/2024UnitLeader:PaulDeVriezeSubmissionDueDate:01/08/2024Time:12:30PMOtherMarker(s):N/ASubmissionLocati......
  • dnssec
    ###DNSSEC(DNSSecurityExtensions)**DNSSEC**是一组扩展DNS协议的安全机制,用于确保DNS数据的完整性和真实性。它主要包括以下几个方面:1.**数据完整性**:DNSSEC通过数字签名验证DNS响应的数据是否被篡改,确保从DNS服务器获得的数据未被修改。2.**数据来源认证**:通过DNSSEC,客......
  • Error: Assertion failed (nimages > 0) in cv::calibrateCameraRO, file D:\opencv4
    报错信息:Error:Assertionfailed(nimages>0)incv::calibrateCameraRO,fileD:\opencv4\opencv\opencv-4.1.0\modules\calib3d\src\calibration.cpp,line3691  原因:①图片路径问题,没有指向包含棋盘格的图片②图片中不包含棋盘格或者图片模糊等问题,导致查找棋盘......
  • 猫头虎分享已解决Bug ||Asset validation failed (90296) App sandbox not enabled. T
    ......
  • 2024-07-17 前端项目中assets文件夹和public文件夹的区别(来源:GPT)
    在前端项目中,assets文件夹和public文件夹都扮演着存储静态资源的重要角色,但它们之间存在一些关键的区别。以下是对这两个文件夹区别的详细分析:assets文件夹内容与用途:assets文件夹通常用于存放项目中可能会变动的静态资源,如图片、样式表(CSS文件)、JavaScript脚本、字体文件等......
  • go 实现sse
    packagechatimport( "encoding/json" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest/httpx" "log" "net/http" "X/common/response" "X/common/util" &q......
  • 流媒体资源 (Streaming Assets)
    Unity中的大多数资源在构建时都会合并到项目中。但是,将文件放入目标计算机上的普通文件系统以使其可通过路径名访问有时会很有用。这方面的一个例子是在iOS设备上部署电影文件;原始电影文件必须位于文件系统中的某个位置以便由 PlayMovie 函数进行播放。放置在Unity项目中......
  • 【java】实现sse调用websocket接口,忽略wss证书并控制sse吐字速度
    maven<dependency><groupId>org.java-websocket</groupId><artifactId>Java-WebSocket</artifactId><version>1.5.3</version></dependency>AsyncConfigpackag......