Newer
Older
"github.com/jmoiron/sqlx"
_ "modernc.org/sqlite" // Imported for side effects: registers DB driver
)
//go:embed templates/*.tpl
var templateFS embed.FS
var templates = template.Must(template.ParseFS(templateFS, "templates/*.tpl"))
//go:embed static/*
var staticFS embed.FS
func httpError(w http.ResponseWriter, msg string, err error, status int) {
log.Println(msg)
http.Error(w, msg+": "+err.Error(), status)
}
db, err := sqlx.Open("sqlite", "vino.sqlite")
if err != nil {
log.Fatalln("can't open DB:", err)
}
defer db.Close()
err = initDB(db)
if err != nil {
log.Fatalln("can't initialize DB:", err)
}
http.Handle("/static/", http.FileServer(http.FS(staticFS)))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Println("handling", r.Method, r.URL, "from", r.RemoteAddr)
if r.Method == "GET" {
httpError(w, "can't list wines", err, http.StatusInternalServerError)
data := struct {
Wines []Vino
}{wines}
err = templates.ExecuteTemplate(w, "index.tpl", data)
if err != nil {
log.Println("can't execute index template:", err)
}
return
}
httpError(w, "invalid method", errors.New(r.Method), http.StatusMethodNotAllowed)
return
}
// TODO: load/store image
name := r.FormValue("name")
if name == "" {
httpError(w, "bad name", errors.New("empty or missing"), http.StatusBadRequest)
httpError(w, "bad name", errors.New("name too long, max length is 80"), http.StatusBadRequest)
var rating int
if ratingVal != "" {
rating, err = strconv.Atoi(ratingVal)
if err != nil {
httpError(w, "can't convert rating", err, http.StatusBadRequest)
return
}
}
picFile, picHdr, err := r.FormFile("picture")
if err != nil {
httpError(w, "can't load picture file", err, http.StatusInternalServerError)
return
}
defer picFile.Close()
log.Println("picture", picHdr.Size, picHdr.Header.Get("Content-Type"))
picData, err := ioutil.ReadAll(picFile)
httpError(w, "can't read picture file", err, http.StatusInternalServerError)
Name: name,
Rating: rating,
Picture: picData,
httpError(w, fmt.Sprintf("can't store wine %q", vino), err, http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther) // TODO: Is this the correct status?