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
|
package main
import (
"fmt"
"io"
"log"
"net"
"net/http"
"os"
)
const TOKEN_FNAME = "tokens.txt"
const SOCKET_NAME = "./bees.sock"
var tokens map[string]string
func loadTokens() map[string]string {
out := make(map[string]string)
file, err := os.Open(TOKEN_FNAME)
if err != nil {
log.Fatal(err)
}
defer file.Close()
for {
var token, name string
_, err := fmt.Fscanf(file, "%s %s\n", &token, &name)
if err == io.EOF {
break
} else if err != nil {
log.Fatalf("%#v", err)
}
out[token] = name
}
return out
}
type beeMsg struct {
from string
text string
}
func sendSock(msgs <-chan beeMsg, w io.Writer) {
for msg := range msgs {
fmt.Fprintf(w, "%s: %s", msg.from, msg.text)
}
}
func handleHttp(msgch chan<- beeMsg, w http.ResponseWriter, r *http.Request) {
tok := r.FormValue("token")
msg := r.FormValue("msg")
if tok == "" || msg == "" {
w.WriteHeader(400)
fmt.Fprintln(w,"missing form values")
return
}
clientname, ok := tokens[tok]
if !ok {
w.WriteHeader(401)
fmt.Fprintln(w,"unknown token")
return
}
if len(msg) > 300 {
w.WriteHeader(400)
fmt.Fprintln(w,"msg too long")
return
}
msgch <- beeMsg{from: clientname, text:msg}
}
func init() {
tokens = loadTokens()
}
func main() {
msgs := make(chan beeMsg)
fmt.Println("ok")
sock, err := net.Dial("unixgram", SOCKET_NAME)
if err != nil {
fmt.Println(err)
}
go sendSock(msgs, sock)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
handleHttp(msgs,w,r)
})
log.Fatal(http.ListenAndServe(":3236", nil))
}
|