aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--webhooks.go93
1 files changed, 93 insertions, 0 deletions
diff --git a/webhooks.go b/webhooks.go
new file mode 100644
index 0000000..4e0d5b1
--- /dev/null
+++ b/webhooks.go
@@ -0,0 +1,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))
+
+}