allowances/handlers.go

61 lines
1.5 KiB
Go

package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
"strings"
)
func homeHandler(w http.ResponseWriter, req *http.Request) {
session, _ := store.Get(req, "creds")
loggedIn := session.Values["logged in"]
if loggedIn == nil {
http.Redirect(w, req, "/login", http.StatusSeeOther)
return
}
children := loadChildren(*db_file)
T("index.html").Execute(w, map[string]interface{}{
"children": children})
}
func loginHandler(w http.ResponseWriter, req *http.Request) {
pwAttempt := req.FormValue("passwd")
if check_password(*passes_file, pwAttempt) {
session, _ := store.Get(req, "creds")
session.Values["logged in"] = true
session.Save(req, w)
http.Redirect(w, req, "/", http.StatusSeeOther)
return
}
T("login.html").Execute(w, map[string]interface{}{})
}
func logoutHandler(w http.ResponseWriter, req *http.Request) {
session, _ := store.Get(req, "creds")
delete(session.Values, "logged in")
session.Save(req, w)
http.Redirect(w, req, "/", http.StatusSeeOther)
return
}
func addHandler(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path[len(addPath):]
bits := strings.Split(path, "/")
child := bits[0]
amount, err := strconv.Atoi(bits[1])
if err != nil {
log.Fatal("couldn't parse a dollar amount", err)
}
children := loadChildren(*db_file)
children[child] += amount
defer dumpChildren(*db_file, children)
w.Header().Set("Content-Type", "application/json")
b, err := json.Marshal(map[string]interface{}{
"amount": dollarize(children[child]),
"name": child,
})
w.Write(b)
}