mstar-webserver/main.go

62 lines
1.6 KiB
Go

package main
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
)
func (a abc) Open(name string) (http.File, error) {
val, err := a.Open(name)
fmt.Println(err)
return val, err
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defaulting to port %s \n", port)
}
// Custom-ish paths. Includes templates
http.HandleFunc("/", handleRoot)
// static files in /static
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
// .well-known from /well-known
http.Handle("/.well-known/", http.StripPrefix("/.well-known/", http.FileServer(http.Dir("./well-known"))))
// Static files not in /static or /.well-known
http.HandleFunc("/robots.txt", buildHTTPFileReader("robots.txt"))
http.HandleFunc("/humans.txt", buildHTTPFileReader("humans.txt"))
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("templates/index.html")
if err != nil {
http.Error(w, "Couldn't parse template file", http.StatusInternalServerError)
return
}
err = tmpl.Execute(w, "Nothing lol")
if err != nil {
http.Error(w, "Failed to execute template", http.StatusInternalServerError)
}
}
func buildHTTPFileReader(path string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
file, err := os.ReadFile(path)
if err != nil {
http.Error(w, "Failed to load file", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "%s", file)
}
}