spongy/spongy.cgi/spongy.cgi.go

78 lines
1.5 KiB
Go
Raw Normal View History

2014-07-14 19:30:47 -06:00
package main
import (
"fmt"
"log"
"strings"
2014-07-14 19:30:47 -06:00
"net/http"
"net/http/cgi"
2014-08-05 15:53:03 -06:00
"path"
2014-07-14 19:30:47 -06:00
)
type Handler struct {
cgi.Handler
}
2015-02-20 16:48:52 -07:00
func (h Handler) handleCommand(cfg *Config, w http.ResponseWriter, r *http.Request) {
network := r.FormValue("network")
text := r.FormValue("text")
target := r.FormValue("target")
2014-10-24 22:21:53 -06:00
2015-02-20 16:48:52 -07:00
nw := NewNetwork(path.Join(cfg.BaseDir, network))
2014-08-05 15:53:03 -06:00
2015-02-20 16:48:52 -07:00
var out string
2014-08-05 15:53:03 -06:00
switch {
case strings.HasPrefix(text, "/quote "):
2015-02-20 16:48:52 -07:00
out = text[7:]
2014-08-05 15:53:03 -06:00
case strings.HasPrefix(text, "/me "):
2015-02-20 16:48:52 -07:00
out = fmt.Sprintf("PRIVMSG %s :\001ACTION %s\001", target, text[4:])
2014-08-05 15:53:03 -06:00
default:
2015-02-20 16:48:52 -07:00
out = fmt.Sprintf("PRIVMSG %s :%s", target, text)
2014-08-05 15:53:03 -06:00
}
2015-02-20 16:48:52 -07:00
nw.Write([]byte(out))
2014-07-14 19:30:47 -06:00
fmt.Fprintln(w, "OK")
}
2015-02-20 16:48:52 -07:00
func (h Handler) handleTail(cfg *Config, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
nws := Networks(cfg.BaseDir)
for _, nw := range nws {
fmt.Fprintf(w, "%v\n", nw)
}
}
2014-07-14 19:30:47 -06:00
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
2015-02-20 16:48:52 -07:00
cfg, err := ReadConfig(h.Dir)
if err != nil {
http.Error(w, err.Error(), 500)
2014-08-12 21:41:54 -06:00
}
2015-02-20 16:48:52 -07:00
// Validate authtok
authtok, err := cfg.Get("authtok")
if err != nil {
http.Error(w, err.Error(), 500)
}
if r.FormValue("auth") != authtok {
w.Header().Set("Content-Type", "text/plain")
2014-10-24 23:24:49 -06:00
fmt.Fprintln(w, "NO: Invalid authtok")
return
}
2015-02-20 16:48:52 -07:00
// Switch based on type
2014-07-14 19:30:47 -06:00
switch r.FormValue("type") {
case "command":
2015-02-20 16:48:52 -07:00
h.handleCommand(cfg, w, r)
2014-07-14 19:30:47 -06:00
default:
2015-02-20 16:48:52 -07:00
h.handleTail(cfg, w, r)
2014-07-14 19:30:47 -06:00
}
}
func main() {
h := Handler{}
if err := cgi.Serve(h); err != nil {
log.Fatal(err)
}
}