我知道的是, 是一个 http长连接, 有着类websocket的api;
后端示例代码:
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
r.GET("/events", func(c *gin.Context) { c.Header("Content-Type", "text/event-stream") c.Header("Cache-Control", "no-cache") c.Header("Connection", "keep-alive") for i := 0; i < 5; i++ { c.SSEvent("message", "This is a message") time.Sleep(2 * time.Second) } })
router.Run(":8080")
}
前端使用 ssevent有着类似于 ws的api;
前端示例代码:
const memdumpFun = (loading) => {
// new 他
let eventSource = new EventSource(
"http://127.0.0.1:8080/memdump/",
{
withCredentials: true,
}
);
eventSource.onopen = function (e) {
console.log("sse打开");
};
// progress、speed、timeout.... 是后端定的
eventSource.addEventListener("progress", function (e) {
console.log(e.data);
s.value = e.data;
});
eventSource.addEventListener("speed", function (e) {
console.log(e.data);
speed.value = e.data;
});
eventSource.addEventListener("timeout", function (e) {
console.log(e.data);
over("sse超时");
ElMessage({
type: "warning",
message: "读取超时",
});
});
eventSource.addEventListener("error", function (e) {
console.log(e);
over("sse失败");
ElMessage({
type: "error",
message: "读取失败",
});
});
eventSource.addEventListener("ok", function (e) {
console.log(e.data);
over("sse成功");
ElMessage({
type: "success",
message: "读取成功",
});
});
eventRef.value = eventSource;
const over = (t) => {
loading.close();
eventSource.close();
console.log(t);
showTime.value = false;
s.value = 0;
clearInterval(st.value);
};
};
标签:function,console,log,SSEVENT,value,eventSource,Go,gin
From: https://www.cnblogs.com/runninginsilence/p/17970037