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 main() {
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" {
wines, err := ListWines(r.Context(), db)
if err != nil {
http.Error(w, "can't list wines: "+err.Error(), http.StatusInternalServerError)
return
}
data := struct {
Wines []Vino
}{wines}
err = templates.ExecuteTemplate(w, "index.tpl", data)
if err != nil {
log.Println("can't execute index template:", err)
}
return
}
if r.Method != "POST" {
http.Error(w, "invalid method:"+r.Method, http.StatusMethodNotAllowed)
return
}
// TODO: load/store image
name := r.FormValue("name")
if name == "" {
http.Error(w, "name empty or missing", http.StatusBadRequest)
return
}
if len(name) > 80 {
http.Error(w, "name too long, max length is 80", http.StatusBadRequest)
return
}
ratingVal := r.FormValue("rating")
rating, err := strconv.Atoi(ratingVal)
if err != nil {
http.Error(w, "can't convert rating:"+err.Error(), http.StatusBadRequest)
return
}
vino := Vino{
Name: name,
Rating: rating,
}
err = vino.Store(r.Context(), db)
if err != nil {
http.Error(w, fmt.Sprintf("can't store wine %q: %s", vino, err), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther) // TODO: Is this the correct status?
})
const listenAddr = "127.0.0.1:7878"
log.Printf("here we go, listening on http://%s", listenAddr)