cal/main.go

63 lines
1.6 KiB
Go
Raw Permalink Normal View History

2024-08-05 17:22:20 +00:00
package main
2024-08-05 19:26:04 +00:00
import (
"embed"
"fmt"
"html/template"
"io"
"io/fs"
"mime"
"net/http"
"path/filepath"
)
//go:embed static
var staticFiles embed.FS
2024-08-05 17:22:20 +00:00
func main() {
2024-08-05 19:26:04 +00:00
staticFS := fs.FS(staticFiles)
http.HandleFunc("GET /", index)
http.Handle("GET /static/{file}", http.FileServer(http.FS(staticFS)))
if err := http.ListenAndServe(":4321", nil); err != nil {
fmt.Printf("Unable to serve: %v\n", err)
}
}
func serveFile(system fs.FS) func(w http.ResponseWriter, r http.Request) {
return func(w http.ResponseWriter, r http.Request) {
file := r.PathValue("file")
reader, err := system.Open(file)
if err != nil {
http.Error(w, "File not found", 404)
return
}
defer reader.Close()
cont, err := io.ReadAll(reader)
handleHTTPError("Error reading file", err, w)
contType := mime.TypeByExtension(filepath.Ext(file))
w.Header().Add("Content-Type", contType)
_, err = w.Write(cont)
handleHTTPError("Error writing HTTP resp", err, w)
}
}
func index(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf8")
tmpl, err := template.ParseFiles("./tmpl/index.html", "./tmpl/base.html")
handleHTTPError("Error parsing template", err, w)
err = tmpl.Execute(w, nil)
handleHTTPError("Error executing on template", err, w)
}
func handleHTTPError(msg string, err error, w http.ResponseWriter) {
if err != nil {
fmt.Printf("%v: %v", msg, err)
http.Error(w, "Internal server error", 500)
return
}
2024-08-05 17:22:20 +00:00
}