idecnode/pkg/api/message.go

63 lines
1.5 KiB
Go

package api
import (
"encoding/base64"
"fmt"
"log"
"net/http"
"strings"
)
func (a *API) getBundleHandler(w http.ResponseWriter, r *http.Request) {
ids := strings.Split(r.PathValue("ids"), "/")
for _, messageID := range ids {
msg, err := a.idec.GetMessage(messageID)
if err != nil {
log.Println("cant read file for message", messageID, err)
continue
}
b64msg := base64.StdEncoding.EncodeToString([]byte(msg.Bundle()))
fmt.Fprintf(w, "%s:%s\n", messageID, b64msg)
}
}
func (a *API) getMessageHandler(w http.ResponseWriter, r *http.Request) {
msgID := r.PathValue("msgID")
msg, err := a.idec.GetMessage(msgID)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
_, err = fmt.Fprintln(w, msg.Bundle())
}
func (a *API) postPointHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
form := r.PostForm
a.savePointMessage(w, form.Get("tmsg"), form.Get("pauth"))
}
func (a *API) getPointHandler(w http.ResponseWriter, r *http.Request) {
a.savePointMessage(w, r.PathValue("tmsg"), r.PathValue("pauth"))
}
func (a *API) savePointMessage(w http.ResponseWriter, rawMessage, auth string) error {
point, err := a.idec.GetPointByAuth(auth)
if err != nil {
fmt.Fprintln(w, "error: no auth - wrong authstring")
return err
}
if err := a.idec.SavePointMessage(point.Username, rawMessage); err != nil {
return err
}
fmt.Fprintln(w, "msg ok")
return nil
}