easybridge/appservice/server.go

80 lines
1.7 KiB
Go
Raw Normal View History

2020-02-16 18:30:49 +00:00
package appservice
import (
"encoding/json"
"fmt"
"strings"
"log"
"net/http"
"git.deuxfleurs.fr/Deuxfleurs/easybridge/mxlib"
"github.com/gorilla/mux"
)
type Config struct {
HttpBindAddr string
Server string
DbType string
DbPath string
2020-02-16 21:07:41 +00:00
MatrixDomain string
2020-02-16 18:30:49 +00:00
}
var registration *mxlib.Registration
var config *Config
func Start(r *mxlib.Registration, c *Config) (chan error, error) {
registration = r
config = c
err := InitDb()
if err != nil {
return nil, err
}
router := mux.NewRouter()
router.HandleFunc("/_matrix/app/v1/transactions/{txnId}", handleTxn)
2020-02-16 21:07:41 +00:00
router.HandleFunc("/transactions/{txnId}", handleTxn)
2020-02-16 18:30:49 +00:00
errch := make(chan error)
go func() {
log.Printf("Starting HTTP server on %s", config.HttpBindAddr)
err := http.ListenAndServe(config.HttpBindAddr, checkTokenAndLog(router))
if err != nil {
errch <- err
}
}()
return errch, nil
}
func checkTokenAndLog(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
if strings.Join(r.Form["access_token"], "") != registration.HsToken {
http.Error(w, "Wrong or no token provided", http.StatusUnauthorized)
return
}
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func handleTxn(w http.ResponseWriter, r *http.Request) {
2020-02-16 21:57:30 +00:00
if r.Method == "PUT" {
var txn mxlib.Transaction
err := json.NewDecoder(r.Body).Decode(&txn)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
log.Printf("JSON decode error: %s\n", err)
return
}
2020-02-16 18:30:49 +00:00
2020-02-16 21:57:30 +00:00
log.Printf("Got transaction %#v\n", txn)
fmt.Fprintf(w, "{}\n")
} else {
http.Error(w, "Expected PUT request", http.StatusBadRequest)
}
2020-02-16 18:30:49 +00:00
}