comics/manager.go

119 lines
2.3 KiB
Go

package main
import (
"log"
"fmt"
"strconv"
"strings"
"net/http"
)
type ConfirmContext struct {
Action string
Message string
OnYes string
OnNo string
}
func managerIndexView(w http.ResponseWriter, r * http.Request) {
var err error
defer func() {
if err != nil {
errlog.Println(err)
return500(w,r)
err = nil
return
}
} ()
if len(strings.TrimPrefix(r.URL.Path, "/")) > 0 {
return404(w,r)
return
}
context := Context{
Comics: nil,
Title: "Black Ram Comics Manager",
}
comics, err := allComics()
if err != nil {
return
}
for i, comic := range comics {
context.Comics = append(context.Comics, struct {
No int
Title string
Date string
Image string
}{
Title: comic.Title,
No: i+1,
Date: comic.DateTime,
Image: comic.Image,
})
}
err = executeTemplate(w, "manager", context)
}
func managerRemoveView(w http.ResponseWriter, r * http.Request) {
tmp := strings.TrimPrefix(r.URL.Path, "/remove/")
path := strings.TrimRight(tmp, "/confirmed")
isConfirmed := strings.TrimPrefix(strings.TrimPrefix(tmp, path), "/") == "confirmed"
i, err := strconv.Atoi(path)
if err != nil {
return404(w, r)
return
}
comic, err := getComic(i-1)
if err != nil {
return404(w, r)
return
}
if !isConfirmed {
err = executeTemplate(w, "confirm", ConfirmContext{
Action: fmt.Sprintf("Remove %s", comic.Title),
Message: fmt.Sprintf("Are you sure you want to remove \"%s\"", comic.Title),
OnYes: fmt.Sprintf("/remove/%d/confirmed", i),
OnNo: "/",
})
if err != nil {
return500(w, r)
return
}
return
}
err = deleteComic(comic.ID)
if err != nil {
return500(w, r)
return
}
http.Redirect(w, r, fmt.Sprintf("http://%s:%d", options.Address, options.Port), http.StatusSeeOther)
}
func managerPublishView(w http.ResponseWriter, r * http.Request) {
return500(w, r)
}
func managerEditView(w http.ResponseWriter, r * http.Request) {
}
func startManager(address string, port int, dbPath string, mediaPath string) error {
http.HandleFunc("/", managerIndexView)
http.HandleFunc("/remove/", managerRemoveView)
http.HandleFunc("/publish", managerPublishView)
http.HandleFunc("/edit/", managerEditView)
uri := fmt.Sprintf("%s:%d", address, port)
log.Println("listening to http://" + uri)
return http.ListenAndServe(uri, logRequest(http.DefaultServeMux))
}