Basic site running
This commit is contained in:
parent
70fca57571
commit
2e24996510
6 changed files with 161 additions and 2 deletions
59
main.go
59
main.go
|
|
@ -1,7 +1,62 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/fs"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
//go:embed static
|
||||
var staticFiles embed.FS
|
||||
|
||||
func main() {
|
||||
fmt.Println("Saluton, mondo")
|
||||
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
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue