63 lines
1.2 KiB
Go
63 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func main() {
|
|
var addr = flag.String("addr", ":8080", "http service address")
|
|
flag.Parse()
|
|
|
|
// Map of active viewers and their last active time
|
|
var viewers = make(map[string]int64)
|
|
|
|
http.HandleFunc("/viewcount", func(w http.ResponseWriter, r *http.Request) {
|
|
// Get the current time
|
|
var now = time.Now().Unix()
|
|
|
|
// Get the remote address
|
|
var ip = r.RemoteAddr
|
|
|
|
// If behind a proxy, get the real IP
|
|
if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
|
|
ip = fwd
|
|
}
|
|
|
|
// Update the last active time
|
|
viewers[ip] = now
|
|
|
|
// Respond with the number of viewers
|
|
fmt.Fprintf(w, "%d", len(viewers))
|
|
})
|
|
|
|
// Periodically remove inactive viewers
|
|
go func() {
|
|
for {
|
|
time.Sleep(time.Second)
|
|
|
|
// Get the current time
|
|
var now = time.Now().Unix()
|
|
|
|
// Remove any viewers that have not been active in the last 10 seconds
|
|
for ip, lastActive := range viewers {
|
|
if now-lastActive > 10 {
|
|
delete(viewers, ip)
|
|
}
|
|
}
|
|
}
|
|
}()
|
|
|
|
// Handle static files
|
|
http.Handle("/", http.FileServer(http.Dir("./static")))
|
|
|
|
// Start the server
|
|
fmt.Println("Starting server on", *addr)
|
|
err := http.ListenAndServe(*addr, nil)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
}
|