Skip to content

Instantly share code, notes, and snippets.

@Magicking
Created April 11, 2017 13:53
Show Gist options
  • Save Magicking/a5d64859076c35d83592782934cdcdac to your computer and use it in GitHub Desktop.
Save Magicking/a5d64859076c35d83592782934cdcdac to your computer and use it in GitHub Desktop.
Event Handler
package main
import (
"fmt"
"log"
"time"
"net/http"
)
var c chan string
func watcher(interval time.Duration) {
ticker := time.NewTicker(interval / 2)
sessions := make(map[string]time.Time)
for {
select {
case guid := <-c:
if _, ok := sessions[guid]; !ok {
log.Printf("creating session")
}
sessions[guid] = time.Now().Add(interval)
case now := <-ticker.C:
for guid, t := range(sessions) {
if t.Before(now) {
log.Printf("closing session")
delete(sessions, guid)
}
}
}
}
}
func ping(w http.ResponseWriter, r *http.Request) {
guid := r.URL.Query().Get("guid")
if guid != "" {
c <- guid
}
}
func main() {
c = make(chan string)
http.HandleFunc("/ping", ping)
go watcher(3 * time.Second)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment