package main import ( "fmt" "net" "net/http" "time" "blog.bing89.com/go/notify/notify" "github.com/gin-gonic/gin" ) type Client struct { User string ID string msgChan chan string } func (c *Client)Write(msg string){ c.msgChan <- msg } type NServer struct { notifier *notify.Notifier conn net.Conn flusher http.Flusher } var ch = make(chan string) func (n *NServer)Get(c *gin.Context){ user := c.Query("user") id := c.Query("client") if user == "" || id == "" { c.String(http.StatusBadRequest, "failed") return } flusher, ok := c.Writer.(http.Flusher) if !ok { c.String(http.StatusBadRequest, "failed") return } // h, _, err := c.Writer.Hijack() // if err != nil { // c.String(http.StatusBadRequest, err.Error()) // return // } // if n.conn == nil { // n.conn = h // } c.Header("Content-Type", "text/event-stream") c.Header("Cache-Control", "no-cache") c.Header("Connection", "keep-alive") c.Header("Access-Control-Allow-Origin", "*") // if n.flusher == nil { // n.flusher = flusher // } for str := range ch { c.Writer.Write([]byte(fmt.Sprintf("data: %v\n\n", str))) flusher.Flush() } // err := n.notifier.AddConsumer(c) // if err != nil { // fmt.Println("add consumer:", err) // } // c.Next() // time.Sleep(100*time.Second) } func (n *NServer)Run(){ ticker := time.NewTicker(2*time.Second) for t := range ticker.C { str := fmt.Sprintf("data: %v\n\n", t.Format("2006-01-02 15:04:05")) fmt.Println("send data to n") if n.conn != nil { n, err := n.conn.Write([]byte(str)) fmt.Println("sent it length: ", n, " result: ", err) } ch <- str // if n.flusher != nil { // n.flusher.Flush() // } // n.notifier.SendMessage("2", fmt.Sprintf("hello world %d", t.Unix())) } } func main(){ n := NServer{ notifier: notify.NewNotifier(), } // ctx, cancel := context.WithCancel(context.Background()) // defer cancel() // go n.notifier.Run(ctx) engine := gin.Default() engine.GET("/api/notify", n.Get) go n.Run() engine.Run("0.0.0.0:18000") } // package main // import ( // "gopkg.in/antage/eventsource.v1" // "log" // "net/http" // "strconv" // "time" // ) // func main() { // es := eventsource.New(nil, nil) // defer es.Close() // http.Handle("/events", es) // go func() { // id := 1 // for { // es.SendEventMessage("tick", "tick-event", strconv.Itoa(id)) // id++ // time.Sleep(2 * time.Second) // } // }() // log.Fatal(http.ListenAndServe(":18000", nil)) // }