Created
April 11, 2017 13:53
-
-
Save Magicking/a5d64859076c35d83592782934cdcdac to your computer and use it in GitHub Desktop.
Event Handler
This file contains 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
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