123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- package web
- import (
- "fmt"
- "log"
- "net/http"
- "sync"
- "git.semlanik.org/semlanik/gostfix/common"
- "github.com/gorilla/websocket"
- )
- type websocketChannel struct {
- connection *websocket.Conn
- channel chan *common.Mail
- }
- type webNotifier struct {
- notifiers map[string]*websocketChannel
- notifiersLock sync.Mutex
- }
- func NewWebNotifier() *webNotifier {
- return &webNotifier{
- notifiers: make(map[string]*websocketChannel),
- }
- }
- func (wn *webNotifier) NotifyMaiboxUpdate(email string) {
- if channel, ok := wn.getNotifier(email); ok {
- channel.channel <- &common.Mail{}
- }
- }
- func (wn *webNotifier) NotifyNewMail(email string, m common.Mail) {
-
-
-
-
- }
- var upgrader = websocket.Upgrader{
- ReadBufferSize: 1024,
- WriteBufferSize: 1024,
- }
- func (wn *webNotifier) handleNotifierRequest(w http.ResponseWriter, r *http.Request, email string) {
- fmt.Printf("New web socket session start %s\n", email)
- conn, err := upgrader.Upgrade(w, r, nil)
- if err != nil {
- http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
- return
- }
- c := &websocketChannel{
- connection: conn,
- channel: make(chan *common.Mail, 10),
- }
- wn.addNotifier(email, c)
- conn.SetCloseHandler(func(code int, text string) error {
- fmt.Printf("Web socket session end %s\n", email)
- wn.removeNotifier(email)
- conn.Close()
- return nil
- })
- go wn.handleNotifications(c)
- }
- func (wn *webNotifier) handleNotifications(c *websocketChannel) {
-
- for {
- select {
- case newMail := <-c.channel:
- err := c.connection.WriteJSON(newMail)
- if err != nil {
- log.Println(err.Error())
- return
- }
- }
- }
- }
- func (wn *webNotifier) getNotifier(email string) (channel *websocketChannel, ok bool) {
- wn.notifiersLock.Lock()
- defer wn.notifiersLock.Unlock()
- channel, ok = wn.notifiers[email]
- return
- }
- func (wn *webNotifier) addNotifier(email string, channel *websocketChannel) {
- wn.notifiersLock.Lock()
- defer wn.notifiersLock.Unlock()
- wn.notifiers[email] = channel
- }
- func (wn *webNotifier) removeNotifier(email string) {
- wn.notifiersLock.Lock()
- defer wn.notifiersLock.Unlock()
- delete(wn.notifiers, email)
- }
|