Created
April 21, 2019 18:06
-
-
Save farhany/51c7cf3253ee9927851a4aea28f98c67 to your computer and use it in GitHub Desktop.
Gorilla Web Sockets Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ( | |
SyncOutput = make(chan string) | |
SyncClients = make(map[*websocket.Conn]bool) | |
SyncClientsLock = sync.RWMutex{} | |
FileSyncing = false | |
FileSyncLock = sync.RWMutex{} | |
) | |
var upgrader = websocket.Upgrader{ | |
ReadBufferSize: 1024, | |
WriteBufferSize: 1024, | |
} | |
go WatchOutPutChannel() | |
func runSync() { | |
cmd := exec.Command("python", "-u", config.SyncFilesScript) | |
stdout, err := cmd.StdoutPipe() | |
if err != nil { | |
fmt.Println(fmt.Sprintf("Error: %s", err)) | |
} | |
FileSyncLock.Lock() | |
FileSyncing = true | |
FileSyncLock.Unlock() | |
err = cmd.Start() | |
go WatchOutPut(stdout) | |
} | |
func WatchOutPut(out io.Reader) { | |
scanner := bufio.NewScanner(out) | |
for scanner.Scan() { | |
SyncOutput <- scanner.Text() | |
} | |
FileSyncLock.Lock() | |
FileSyncing = false | |
FileSyncLock.Unlock() | |
SyncOutput <- "Sync Finished" | |
} | |
func WatchOutPutChannel() { | |
for { | |
output := <-SyncOutput | |
SyncClientsLock.RLock() | |
for client := range SyncClients { | |
client.WriteMessage(1, []byte(output)) | |
} | |
SyncClientsLock.RUnlock() | |
} | |
} | |
func wsHandlerSync(w http.ResponseWriter, r *http.Request) { | |
conn, err := upgrader.Upgrade(w, r, nil) | |
if err != nil { | |
fmt.Println("Failed to set websocket upgrade: %+v", err) | |
return | |
} | |
SyncClientsLock.Lock() | |
SyncClients[conn] = true | |
SyncClientsLock.Unlock() | |
for { | |
_, _, err := conn.ReadMessage() | |
if err != nil { | |
break | |
} | |
} | |
SyncClientsLock.Lock() | |
delete(SyncClients, conn) | |
SyncClientsLock.Unlock() | |
conn.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment