From cddf7ed45147869a9d2eee2e40f59a97c472ea72 Mon Sep 17 00:00:00 2001 From: Mitch Riedstra Date: Sat, 26 Sep 2020 20:59:34 -0400 Subject: Split up http related stuff out of the page library. Make it an interface. Rename page to be 'local' reflecting that it reads the website off the local disk. Update the build script to include the go version. Switch to gorilla/mux Remove the convert command, since we're no longer utilizing that old layout or have any need to convert from it. --- http/main.go | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 http/main.go (limited to 'http') diff --git a/http/main.go b/http/main.go new file mode 100644 index 0000000..875f4b9 --- /dev/null +++ b/http/main.go @@ -0,0 +1,78 @@ +// A mostly self explanatory package, it handles website specific +// HTTP requests +package http + +import ( + "fmt" + "log" + "net/http" + "os" + "path/filepath" + "strings" + + "git.riedstra.dev/mitch/go-website/local" + "git.riedstra.dev/mitch/go-website/page" + + "github.com/gorilla/mux" +) + +// NewPage is required to specify how we acquire a new page from a given URL +// since an interface is used, you can swap this out with a different +// library to load pages from different sources +var NewPage func(string) page.Page = func(u string) page.Page { + return &local.Page{Path: u} +} + +func GetHandler() http.Handler { + if NewPage == nil { + fmt.Fprintln(os.Stderr, "Warning, global NewPage method is not defined!") + } + + r := mux.NewRouter() + r.HandleFunc("/rebuildIndex/", RebuildIndexHandler) + r.PathPrefix("/static/").Handler(StaticHandler()) + r.PathPrefix("/").HandlerFunc(PageHandler) + return r +} + +func PageHandler(w http.ResponseWriter, r *http.Request) { + u := r.URL.Path + if u == "/" { + u = "/index" + } + u = filepath.Join(".", u) + log.Println(u) + + p := NewPage(u) + err := p.Render(w) + if err != nil { + if strings.HasSuffix(err.Error(), "no such file or directory") { + log.Printf("Page '%s' not found, trying 404", u) + p = NewPage("404") + w.WriteHeader(404) + err := p.Render(w) + if err != nil { + log.Println(err) + http.Error(w, "Internal server error", 500) + return + } + return + } else { + log.Println(err) + http.Error(w, "Internal server error", 500) + return + } + } + +} + +func RebuildIndexHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + p := NewPage("index") + _ = p.RebuildIndex() + } +} + +func StaticHandler() http.Handler { + return http.StripPrefix("/static/", http.FileServer(http.Dir("static"))) +} -- cgit v1.2.3