From feaff725cec0798e31fe3258f6be99c4dff3eb40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E8=B6=85?= <17805310388@139.com> Date: Thu, 7 Nov 2024 10:09:53 +0800 Subject: [PATCH] test sse --- conf/config.go | 7 +++++++ main.go | 24 +++++++++++++++++++++++- templates/index.tmpl | 25 +++++++++++++++---------- 3 files changed, 45 insertions(+), 11 deletions(-) diff --git a/conf/config.go b/conf/config.go index 4a26251..9a66018 100644 --- a/conf/config.go +++ b/conf/config.go @@ -11,6 +11,7 @@ import ( "log" "time" + "github.com/fsnotify/fsnotify" "github.com/go-ini/ini" "github.com/spf13/viper" ) @@ -81,6 +82,12 @@ func SetUp1() { log.Fatalf("Error reading config file, %s", err) } + viper.WatchConfig() + viper.OnConfigChange(func(e fsnotify.Event) { + // 配置文件发生变更之后会调用的回调函数 + fmt.Println("Config file changed:", e.Name) + }) + // 获取配置值 mysqlHost := viper.GetString("mysql.Host") jwtSecretKey := viper.GetString("jwt.SecretKey") diff --git a/main.go b/main.go index f33ce57..c2652f5 100644 --- a/main.go +++ b/main.go @@ -2,9 +2,11 @@ package main import ( "flag" + "fmt" "go_blog/conf" "go_blog/controllers" "go_blog/models" + "log" "net/http" "strconv" @@ -35,7 +37,7 @@ func init() { flag.BoolVar(&isOrmDebug, "orm", true, "是否开启gorm的debug信息") flag.Parse() - conf.SetUp() + //conf.SetUp() conf.SetUp1() models.SetUp(isOrmDebug) } @@ -46,8 +48,28 @@ func main() { r.LoadHTMLGlob(templatePath) // 注册WebSocket路由 registerRoutes(r) + r.GET("/events", esSSE) r.Run(":8080") } +func esSSE(c *gin.Context) { + w := c.Writer + + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("Connection", "keep-alive") + w.Header().Set("Access-Control-Allow-Origin", "*") + + _, ok := w.(http.Flusher) + + if !ok { + log.Panic("server not support") //浏览器不兼容 + } + + _, err := fmt.Fprintf(w, "data: %s\n\n", "dsdf") + if err != nil { + return + } +} func registerRoutes(r *gin.Engine) { diff --git a/templates/index.tmpl b/templates/index.tmpl index d6f09c6..46586b8 100644 --- a/templates/index.tmpl +++ b/templates/index.tmpl @@ -5,6 +5,9 @@