Reorganize Go project layout
This commit is contained in:
56
internal/web/handlers.go
Normal file
56
internal/web/handlers.go
Normal file
@ -0,0 +1,56 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"infinite-noodle/internal/assets"
|
||||
"infinite-noodle/internal/noodle"
|
||||
)
|
||||
|
||||
func StaticFiles() fs.FS {
|
||||
return assets.FS
|
||||
}
|
||||
|
||||
func HandleMain(db *noodle.Database, pc *chan noodle.Noodle) func(w http.ResponseWriter, req *http.Request) {
|
||||
tmpl, err := template.ParseFS(assets.FS, "templates/*.html")
|
||||
if err != nil {
|
||||
log.Fatalf("Error parsing templates: %v", err)
|
||||
}
|
||||
return func(w http.ResponseWriter, req *http.Request) {
|
||||
data := db.GetAll()
|
||||
if err := tmpl.ExecuteTemplate(w, "index.html", data); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func HandleDelete(db *noodle.Database, pc *chan noodle.Noodle) func(w http.ResponseWriter, req *http.Request) {
|
||||
return func(w http.ResponseWriter, req *http.Request) {
|
||||
q := req.URL.Query()
|
||||
vals, ok := q["id"]
|
||||
if ok {
|
||||
id := vals[0]
|
||||
item := db.Get(id)
|
||||
item.IsUp = false
|
||||
*pc <- item
|
||||
log.Printf("Deleting noodle=%v", item)
|
||||
db.Delete(item.Id)
|
||||
}
|
||||
|
||||
http.Redirect(w, req, "/", http.StatusTemporaryRedirect)
|
||||
}
|
||||
}
|
||||
|
||||
func HandleAdd(db *noodle.Database, pc *chan noodle.Noodle) func(w http.ResponseWriter, req *http.Request) {
|
||||
return func(w http.ResponseWriter, req *http.Request) {
|
||||
if req.Method != http.MethodPost {
|
||||
http.Error(w, "", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, req, "/", http.StatusTemporaryRedirect)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user