-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupto.go
107 lines (85 loc) · 1.71 KB
/
upto.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"time"
"github.com/Redundancy/upto/store"
"github.com/codegangsta/cli"
)
var app = cli.NewApp()
var extraContentPath string = "./content/"
var mux = http.NewServeMux()
var datastore store.UptoDataStore
func main() {
var handler = &BinaryMessageHandler{}
datastore = &SimpleMemoryStore{}
// start UDP server
serverAddr, _ := net.ResolveUDPAddr("udp", ":8123")
udpServer, err := net.ListenUDP("udp", serverAddr)
if err != nil {
fmt.Fprint(os.Stderr, err)
return
}
waiter := make(chan bool)
go func() {
defer close(waiter)
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
buffer := make([]byte, 1024)
Messages:
for {
oneSecondFromNow := time.Now().Add(time.Second)
if err = udpServer.SetDeadline(oneSecondFromNow); err != nil {
fmt.Fprint(os.Stderr, err)
return
}
select {
case <-interrupt:
return
default:
// don't wait
}
n, remote, err := udpServer.ReadFrom(buffer)
if err != nil {
switch e := err.(type) {
case *net.OpError:
if !e.Timeout() {
fmt.Fprint(os.Stderr, err)
return
}
continue Messages
default:
fmt.Fprint(os.Stderr, err)
return
}
}
var ip string
switch t := remote.(type) {
case *net.UDPAddr:
ip = t.IP.String()
default:
ip = t.String()
}
handler.ReceiveMessage(datastore, ip, buffer[:n])
}
}()
// start HTTP server
go func() {
d := http.Dir(extraContentPath)
fs := http.FileServer(d)
log.Println("Serving content from", extraContentPath)
mux.Handle("/", fs)
log.Println(
http.ListenAndServe(
":8080",
mux,
),
)
return
}()
<-waiter
}