lessmore/node/api.go

122 lines
2.1 KiB
Go
Raw Normal View History

2017-02-12 13:19:02 +03:00
package node
import (
"github.com/gorilla/mux"
"log"
"net/http"
2017-02-13 14:31:18 +03:00
"strings"
2017-02-12 13:19:02 +03:00
"time"
)
// ListTXTHandler ...
func (es ESConf) ListTXTHandler(w http.ResponseWriter, r *http.Request) {
2017-02-13 14:31:18 +03:00
LogRequest(r)
2017-02-13 10:24:21 +03:00
ch := make(chan []byte)
2017-02-12 13:19:02 +03:00
// Get echolist
2017-02-13 10:24:21 +03:00
go func() {
ch <- es.GetListTXT()
}()
echoes := <-ch
2017-02-12 13:19:02 +03:00
w.WriteHeader(200)
w.Write(echoes)
}
2017-02-13 14:31:18 +03:00
// XFeaturesHandler list supported features
func XFeaturesHandler(w http.ResponseWriter, r *http.Request) {
2017-02-14 00:05:12 +03:00
features := []string{"list.txt", "u/e"}
2017-02-13 14:31:18 +03:00
LogRequest(r)
w.WriteHeader(200)
w.Write([]byte(strings.Join(features, "\n")))
}
// EHandler /e/ schema
func (es ESConf) EHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
echo := vars["echo"]
LogRequest(r)
ch := make(chan []string)
// Get echolist
go func() {
ch <- es.GetEchoMessageHashes(echo)
}()
messages := <-ch
w.WriteHeader(200)
w.Write([]byte(strings.Join(messages, "\n")))
}
2017-02-14 00:05:12 +03:00
// UEHandler /u/e/ schema
func (es ESConf) UEHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
e := vars["echoes"]
log.Print("/u/e/ vars: ", e)
LogRequest(r)
ch := make(chan []string)
// Get echolist
go func() {
ch <- es.GetUEchoMessageHashes(e)
}()
messages := <-ch
w.WriteHeader(200)
w.Write([]byte(strings.Join(messages, "\n")))
}
2017-02-13 14:56:35 +03:00
// MHandler /m/ schema
func (es ESConf) MHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
msgid := vars["msgid"]
LogRequest(r)
ch := make(chan []byte)
// Get echolist
go func() {
ch <- es.GetPlainTextMessage(msgid)
}()
message := <-ch
w.WriteHeader(200)
w.Write(message)
}
2017-02-12 13:19:02 +03:00
// Serve ...
func Serve(listen string, es ESConf) {
r := mux.NewRouter()
r.HandleFunc("/list.txt", es.ListTXTHandler)
2017-02-13 14:31:18 +03:00
r.HandleFunc("/x/features", XFeaturesHandler)
// Standart schemas
r.HandleFunc("/e/{echo}", es.EHandler)
2017-02-13 14:56:35 +03:00
r.HandleFunc("/m/{msgid}", es.MHandler)
2017-02-13 14:31:18 +03:00
2017-02-14 00:05:12 +03:00
// Extensions
r.HandleFunc("/u/e/{echoes:[a-z0-9-_/.:]+}", es.UEHandler)
2017-02-13 14:31:18 +03:00
http.Handle("/", r)
2017-02-12 13:19:02 +03:00
srv := http.Server{
Handler: r,
Addr: listen,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
2017-02-13 18:28:02 +03:00
log.Print("Listening IDEC API on ", listen)
2017-02-12 13:19:02 +03:00
log.Fatal(srv.ListenAndServe())
}