aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMitchell Riedstra <mitch@riedstra.dev>2021-02-15 15:31:37 -0500
committerMitchell Riedstra <mitch@riedstra.dev>2021-02-15 15:32:05 -0500
commitfe9ec7a0b45c9fd23a615a8b95ade3e9c1ea2d12 (patch)
tree80844a62d5d18b30862cfdc610aae88713fe97d9
parentd83f4bca3f7026696a41225caac11807ed06fc2f (diff)
downloadgo-website-fe9ec7a0b45c9fd23a615a8b95ade3e9c1ea2d12.tar.gz
go-website-fe9ec7a0b45c9fd23a615a8b95ade3e9c1ea2d12.tar.xz
Another re-structure. Deleting code is wonderful.v0.0.12
-rw-r--r--cmd/server/main.go16
-rw-r--r--http/main.go71
-rw-r--r--page/index.go (renamed from local/index.go)35
-rw-r--r--page/main.go13
-rw-r--r--page/page.go (renamed from local/page.go)18
-rw-r--r--page/pagelist.go (renamed from local/pagelist.go)4
-rw-r--r--page/render.go (renamed from http/render.go)33
-rw-r--r--page/time.go (renamed from local/time.go)2
8 files changed, 74 insertions, 118 deletions
diff --git a/cmd/server/main.go b/cmd/server/main.go
index c900234..9ec96da 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -8,8 +8,7 @@ import (
"os"
"time"
- siteHttp "riedstra.dev/mitch/go-website/http"
- "riedstra.dev/mitch/go-website/local"
+ "riedstra.dev/mitch/go-website/page"
)
var VersionString = ""
@@ -24,9 +23,9 @@ func main() {
listen := fl.String("l", "0.0.0.0:8001", "Listening address")
directory := fl.String("d", ".", "Directory to serve.")
version := fl.Bool("v", false, "Print the version then exit")
- fl.StringVar(&local.TimeFormat, "T", local.TimeFormat, "Print the version then exit")
- fl.StringVar(&siteHttp.ReindexRedirectTo, "r",
- siteHttp.ReindexRedirectTo, "Page to redirect to after reindex")
+ fl.StringVar(&page.TimeFormat, "T", page.TimeFormat, "Print the version then exit")
+ indexPath := fl.String("i", "/reIndex",
+ "Path in which, when called will rebuild the index and clear the cache")
_ = fl.Parse(os.Args[1:])
if *version {
@@ -37,8 +36,13 @@ func main() {
log.Fatal(err)
}
+ app := &App{
+ ReIndexPath: *indexPath,
+ StaticDirectory: "static",
+ }
+
srv := &http.Server{
- Handler: siteHttp.GetHandler(),
+ Handler: app,
Addr: *listen,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
diff --git a/http/main.go b/http/main.go
deleted file mode 100644
index c4726d8..0000000
--- a/http/main.go
+++ /dev/null
@@ -1,71 +0,0 @@
-// The HTTP package handles serving up web pages from the page interface
-// This package assumes you'll be changing directory to where the
-// Website's static content, templates and includes are located
-package http
-
-import (
- "fmt"
- "log"
- "net/http"
- "os"
- "path/filepath"
-
- "riedstra.dev/mitch/go-website/local"
- "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.NewPage(u)
-}
-
-// ReindexRedirectTo is the path that we'll redirect to when a call to rebuild
-// index is called
-var ReindexRedirectTo = "/fullIndex"
-
-// Logger can be overridden, errors and access logging are combined.
-var Logger = log.New(os.Stderr, "", log.LstdFlags)
-
-// GetHandler Returns a gorilla/mux Router which implements the http.Handler
-// interface, allowing you to pull this website into your other Go applications
-func GetHandler() *mux.Router {
- 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
-}
-
-// PageHandler is usually not called directly from external handlers, but the
-// option exists if you're building something custom.
-func PageHandler(w http.ResponseWriter, r *http.Request) {
- u := r.URL.Path
- if u == "/" {
- u = "/index"
- }
- u = filepath.Join(".", u)
-
- RenderForPath(w, r, u)
-}
-
-func RebuildIndexHandler(w http.ResponseWriter, r *http.Request) {
- if r.Method != "POST" {
- p := NewPage("index")
- _ = p.RebuildIndex()
- http.Redirect(w, r, ReindexRedirectTo, 302)
- }
-}
-
-// StaticHandler simply returns a HTTP handler that looks at the current
-// directory and exposes `static` via HTTP `/static`
-func StaticHandler() http.Handler {
- return http.StripPrefix("/static/", http.FileServer(http.Dir("static")))
-}
diff --git a/local/index.go b/page/index.go
index 7b821f6..a453335 100644
--- a/local/index.go
+++ b/page/index.go
@@ -1,37 +1,43 @@
-package local
+package page
import (
"fmt"
"os"
"path/filepath"
"strings"
+ "sync"
"time"
)
-var pageIndex map[string]PageList
+var index map[string]PageList
+var indexMu sync.RWMutex
// RebuildIndex can be called in order to rebuild the entire website
// index
func (p *Page) RebuildIndex() error {
- pageIndex = nil
+ indexMu.Lock()
+ index = nil
+ indexMu.Unlock()
_, err := p.Index()
return err
}
-// Index returns a map of all pages below the current Page's Path seperated
-// into their respective tags If a Page has multiple tags it will be listed
-// under each.
+// Index returns a map of all pages in the current directory seperated into
+// their respective tags If a Page has multiple tags it will be listed under
+// each.
+// Pages are located by their Suffix, default being ".md"
func (p *Page) Index() (map[string]PageList, error) {
- if pageIndex != nil {
- return pageIndex, nil
+ indexMu.RLock()
+ if index != nil && CacheIndex {
+ indexMu.RUnlock()
+ return index, nil
}
- fmt.Fprintln(os.Stderr, "Rebuilding index...")
+ indexMu.RUnlock()
+ Logger.Println("Rebuilding index...")
out := make(map[string]PageList)
- var pageErr error
-
- filepath.Walk(filepath.Dir(p.path),
+ filepath.Walk(filepath.Dir("."),
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
@@ -43,7 +49,6 @@ func (p *Page) Index() (map[string]PageList, error) {
err = p2.Read()
if err != nil {
- pageErr = err
fmt.Fprintln(os.Stderr, "Error encountered: ", err)
return err
}
@@ -61,7 +66,9 @@ func (p *Page) Index() (map[string]PageList, error) {
return nil
})
- pageIndex = out
+ indexMu.Lock()
+ index = out
+ indexMu.Unlock()
return out, nil
}
diff --git a/page/main.go b/page/main.go
deleted file mode 100644
index da7feec..0000000
--- a/page/main.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// The only purpose of this package is to define the Page interface
-// that is used by the `http` package
-package page
-
-import (
- "io"
-)
-
-type Page interface {
- Render(io.Writer) error
- RebuildIndex() error
- SetVars(map[string]interface{})
-}
diff --git a/local/page.go b/page/page.go
index 0ccaf2e..82f46f2 100644
--- a/local/page.go
+++ b/page/page.go
@@ -1,4 +1,4 @@
-// local implements the website backed by a local filesystem.
+// page implements the website backed by a local filesystem.
//
// Reading the base template off the disk, then any markdown files which are
// split into two sections by the DocumentSplit global variable. The first
@@ -11,7 +11,7 @@
// import (
// "fmt"
// "os"
-// site "riedstra.dev/mitch/go-website/local"
+// site "riedstra.dev/mitch/go-website/page"
// )
// // Where some/path.md exists
// p := site.NewPage("/some/path")
@@ -20,13 +20,14 @@
// if err != nil {
// fmt.Fprintln(os.Stderr, err)
// }
-package local
+package page
import (
"bufio"
"bytes"
"fmt"
"io"
+ "log"
"os"
"text/template"
@@ -57,6 +58,14 @@ type Page struct {
// .Global care must be taken when utilizing this functionality
var Global interface{}
+// CachePages determines whether or not the rendered page will be stored in
+// memory
+var CachePages = true
+
+// CacheIndex determines whether or not the index will be cached in memory
+// or rebuilt on each call
+var CacheIndex = true
+
// BaseTemplate can be adjusted to change the base template used in rendering
var BaseTemplate = "inc/base.html"
@@ -66,6 +75,9 @@ var Suffix = ".md"
// DocumentSplit is used to split the .md files into yaml and markdown
var DocumentSplit = "|---\n"
+// Default logger
+var Logger = log.New(os.Stderr, "", log.LstdFlags)
+
// NewPage returns a page struct with the path populated
func NewPage(pth string) *Page {
return &Page{path: pth}
diff --git a/local/pagelist.go b/page/pagelist.go
index ea76117..a5cf844 100644
--- a/local/pagelist.go
+++ b/page/pagelist.go
@@ -1,9 +1,11 @@
-package local
+package page
import (
"sort"
)
+// PageList is a slice of pages, providing a couple of methods to sort
+// by the date, or date reversed
type PageList []*Page
func (p PageList) SortDate() PageList {
diff --git a/http/render.go b/page/render.go
index b73ae76..4378675 100644
--- a/http/render.go
+++ b/page/render.go
@@ -1,4 +1,4 @@
-package http
+package page
import (
"net/http"
@@ -6,6 +6,8 @@ import (
"strings"
)
+// Render is a lower level option, allowing you to specify local
+// variables and the status code in which to return
func Render(w http.ResponseWriter, r *http.Request,
path string, vars map[string]interface{}, statusCode int) {
@@ -25,25 +27,38 @@ func Render(w http.ResponseWriter, r *http.Request,
err := p.Render(w)
if err != nil {
if strings.HasSuffix(err.Error(), "no such file or directory") {
- Logger.Printf("%s %s %d %s", r.RemoteAddr, r.Method, 404, u)
+ Logger.Printf("%s %s %d %s",
+ r.RemoteAddr,
+ r.Method,
+ http.StatusNotFound,
+ u)
p = NewPage("404")
- w.WriteHeader(404)
+ w.WriteHeader(http.StatusNotFound)
err := p.Render(w)
if err != nil {
- Logger.Printf("%s %s path: %s while trying 404: %s", r.RemoteAddr, r.Method, u, err)
- http.Error(w, "Internal server error", 500)
+ Logger.Printf("%s %s path: %s while trying 404: %s",
+ r.RemoteAddr,
+ r.Method,
+ u,
+ err)
+ http.Error(w, "Internal server error",
+ http.StatusInternalServerError)
return
}
return
} else {
- Logger.Printf("%s %s path: %s encountered: %s", r.RemoteAddr, r.Method, u, err)
- http.Error(w, "Internal server error", 500)
+ Logger.Printf("%s %s path: %s encountered: %s",
+ r.RemoteAddr,
+ r.Method,
+ u,
+ err)
+ http.Error(w, "Internal server error",
+ http.StatusInternalServerError)
return
}
}
Logger.Printf("%s %s %d %s", r.RemoteAddr, r.Method, statusCode, u)
-
}
// RenderWithVars allows you to specify a specific page and whether or not
@@ -52,7 +67,7 @@ func Render(w http.ResponseWriter, r *http.Request,
func RenderWithVars(w http.ResponseWriter, r *http.Request,
path string, vars map[string]interface{}) {
- Render(w, r, path, vars, 200)
+ Render(w, r, path, vars, http.StatusOK)
}
// RenderForPath takes the path to a page and finish up the rendering
diff --git a/local/time.go b/page/time.go
index 27efc88..958dc38 100644
--- a/local/time.go
+++ b/page/time.go
@@ -1,4 +1,4 @@
-package local
+package page
import (
"gopkg.in/yaml.v3"