1
0
mirror of https://github.com/aclindsa/moneygo.git synced 2024-10-30 15:50:04 -04:00
moneygo/internal/handlers/handlers.go

66 lines
1.6 KiB
Go
Raw Normal View History

package handlers
import (
"gopkg.in/gorp.v1"
"log"
"net/http"
)
// But who writes the ResponseWriterWriter?
type ResponseWriterWriter interface {
Write(http.ResponseWriter) error
}
type Tx = gorp.Transaction
type TxHandler func(*http.Request, *Tx) ResponseWriterWriter
func TxHandlerFunc(t TxHandler, db *gorp.DbMap) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tx, err := db.Begin()
if err != nil {
log.Print(err)
WriteError(w, 999 /*Internal Error*/)
return
}
defer func() {
if r := recover(); r != nil {
tx.Rollback()
WriteError(w, 999 /*Internal Error*/)
panic(r)
}
}()
writer := t(r, tx)
if e, ok := writer.(*Error); ok {
tx.Rollback()
e.Write(w)
} else {
err = tx.Commit()
if err != nil {
log.Print(err)
WriteError(w, 999 /*Internal Error*/)
} else {
err = writer.Write(w)
if err != nil {
log.Print(err)
WriteError(w, 999 /*Internal Error*/)
}
}
}
}
}
func GetHandler(db *gorp.DbMap) *http.ServeMux {
servemux := http.NewServeMux()
servemux.HandleFunc("/session/", TxHandlerFunc(SessionHandler, db))
servemux.HandleFunc("/user/", TxHandlerFunc(UserHandler, db))
servemux.HandleFunc("/security/", TxHandlerFunc(SecurityHandler, db))
servemux.HandleFunc("/securitytemplate/", SecurityTemplateHandler)
servemux.HandleFunc("/account/", TxHandlerFunc(AccountHandler, db))
servemux.HandleFunc("/transaction/", TxHandlerFunc(TransactionHandler, db))
servemux.HandleFunc("/import/gnucash", TxHandlerFunc(GnucashImportHandler, db))
servemux.HandleFunc("/report/", TxHandlerFunc(ReportHandler, db))
return servemux
}