aboutsummaryrefslogtreecommitdiff
path: root/cmd/server
diff options
context:
space:
mode:
Diffstat (limited to 'cmd/server')
-rw-r--r--cmd/server/feed.go216
-rw-r--r--cmd/server/handlers.go13
-rw-r--r--cmd/server/main.go42
3 files changed, 266 insertions, 5 deletions
diff --git a/cmd/server/feed.go b/cmd/server/feed.go
new file mode 100644
index 0000000..2d4a75b
--- /dev/null
+++ b/cmd/server/feed.go
@@ -0,0 +1,216 @@
+package main
+
+import (
+ "bytes"
+ "encoding/xml"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/gorilla/mux"
+ "riedstra.dev/mitch/go-website/page"
+)
+
+type Author struct {
+ Name string `xml:"name"` // Required
+ Uri string `xml:"uri,omitempty"`
+ Email string `xml:"email,omitempty"`
+}
+
+type Link struct {
+ Href string `xml:"href,attr,omitempty"`
+ Rel string `xml:"rel,attr,omitempty"`
+ Type string `xml:"type,attr,omitempty"`
+ Title string `xml:"Title,attr,omitempty"`
+ Length string `xml:"Length,attr,omitempty"`
+}
+
+type Content struct {
+ Type string `xml:"type,attr"`
+ Data string `xml:",chardata"`
+}
+
+type Entry struct {
+ // Spec requires this, autogenerated from Title and updated if otherwise
+ // left empty
+ Id string `xml:"id"`
+
+ Title string `xml:"title"` // Required
+ Updated *time.Time `xml:"updated"` // Required
+ Author *Author `xml:"author,omitempty"`
+ Published *time.Time `xml:"published,omitempty"`
+ Links []Link `xml:"link,omitempty"`
+ Content *Content `xml:"content,omitempty"`
+}
+
+func (i Entry) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
+ type Alias Entry
+
+ errs := []string{}
+ if i.Title == "" {
+ errs = append(errs, "Title Cannot be empty")
+ }
+ if i.Updated == nil {
+ errs = append(errs, "Updated cannot be nil")
+ }
+
+ if len(errs) > 0 {
+ return errors.New(strings.Join(errs, ","))
+ }
+
+ if i.Id == "" {
+ i.Id = fmt.Sprintf("%s::%d", i.Title, i.Updated.Unix())
+ }
+
+ i2 := (*Alias)(&i)
+
+ return e.EncodeElement(i2, start)
+}
+
+type Atom struct {
+ Ns string `xml:"xmlns,attr"`
+ Title string `xml:"title"` // Required
+ Id string `xml:"id"` // Required
+ Author Author `xml:"author,omitempty"` // Required
+ Updated *time.Time `xml:"updated"` // Required
+ Published *time.Time `xml:"published,omitempty"`
+ Subtitle string `xml:"subtitle,omitempty"`
+ Entries []Entry `xml:"entry"`
+}
+
+func (a Atom) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
+ type Alias Atom
+
+ a.Ns = "http://www.w3.org/2005/Atom"
+ errs := []string{}
+ if a.Id == "" {
+ errs = append(errs, "ID Cannot be empty")
+ }
+ if a.Author.Name == "" {
+ errs = append(errs, "Author Name cannot be empty")
+ }
+ if a.Updated == nil {
+ errs = append(errs, "Updated cannot be empty")
+ }
+
+ if len(errs) > 0 {
+ return errors.New(strings.Join(errs, ","))
+ }
+
+ start.Name = xml.Name{Local: "feed"}
+
+ a2 := (*Alias)(&a)
+
+ return e.EncodeElement(a2, start)
+}
+
+// FeedHandler takes care of pulling from the index all of the relevant posts
+// and dumping them into an Atom feed.
+//
+// Relevant query parameters are:
+//
+// "content" if unset, or set to false content is omitted from the feed
+// "limit=n" stop at "n" and return the feed
+//
+func (a *App) FeedHandler(w http.ResponseWriter, r *http.Request) {
+ vars := mux.Vars(r)
+ var addContent bool
+ var limit int
+
+ if _, ok := r.URL.Query()["content"]; ok {
+ if r.URL.Query().Get("content") != "false" {
+ addContent = true
+ }
+ }
+
+ if l := r.URL.Query().Get("limit"); l != "" {
+ i, err := strconv.Atoi(l)
+ if err == nil {
+ limit = i
+ }
+ }
+
+ tag, ok := vars["tag"]
+ if !ok {
+ http.Error(w, "Tag not found or supplied", http.StatusNotFound)
+ return
+ }
+
+ p := page.NewPage("index")
+ index, err := p.Index()
+ if err != nil {
+ log.Println(err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ pages, ok := index[tag]
+ if !ok {
+ http.Error(w, "Invalid tag", http.StatusNotFound)
+ return
+ }
+
+ pages, dateless := pages.RemoveDateless()
+ for _, p := range dateless {
+ log.Printf("Warning, page %s has no Date field. Skipping inclusion on feed", p)
+ }
+ pages.SortDate()
+
+ feed := &Atom{
+ Author: a.Author,
+ Title: a.Title,
+ Id: a.FeedId,
+ Updated: &a.Updated.Time,
+ Subtitle: a.Description,
+ }
+
+ entries := []Entry{}
+
+ for n, p := range pages {
+ if limit != 0 && n >= limit {
+ break
+ }
+
+ content := &bytes.Buffer{}
+ err := p.Render(content)
+ if err != nil {
+ log.Println(err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ entry := Entry{
+ Title: p.Title,
+ Updated: &p.Date.Time,
+ Links: []Link{Link{Href: strings.Join([]string{a.SiteURL, p.Path()}, "/")}},
+ }
+
+ if addContent {
+ entry.Content = &Content{Type: "html", Data: content.String()}
+ }
+
+ entries = append(entries, entry)
+
+ }
+
+ feed.Entries = entries
+
+ w.Header().Add("Content-type", "application/xml")
+ w.Write([]byte(xml.Header))
+
+ enc := xml.NewEncoder(w)
+ enc.Indent("", " ")
+
+ err = enc.Encode(feed)
+ if err != nil {
+ log.Println(err)
+ // Headers probably already sent, but we'll try anyway
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ }
+
+ return
+}
diff --git a/cmd/server/handlers.go b/cmd/server/handlers.go
index 60e0a35..5ea89cd 100644
--- a/cmd/server/handlers.go
+++ b/cmd/server/handlers.go
@@ -1,6 +1,7 @@
package main
import (
+ "fmt"
"net/http"
"path/filepath"
@@ -8,9 +9,20 @@ import (
"riedstra.dev/mitch/go-website/page"
)
+var FeedPrefixDefault = ".feeds"
+
type App struct {
ReIndexPath string
StaticDirectory string
+
+ // Related to the Atom feed
+ Title string
+ Description string // aka, "subtitle"
+ Author Author
+ SiteURL string
+ FeedId string
+ Updated page.PageTime
+ FeedPrefix string
}
func (a *App) PageHandler(w http.ResponseWriter, r *http.Request) {
@@ -48,6 +60,7 @@ func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rtr := mux.NewRouter()
rtr.HandleFunc(a.ReIndexPath, a.RebuildIndexHandler)
rtr.PathPrefix("/static/").Handler(a.StaticHandler())
+ rtr.PathPrefix(fmt.Sprintf("/%s/{tag}", a.FeedPrefix)).HandlerFunc(a.FeedHandler)
rtr.PathPrefix("/").HandlerFunc(a.PageHandler)
rtr.ServeHTTP(w, r)
}
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 9ec96da..4b2c1ad 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -3,6 +3,7 @@ package main
import (
"flag"
"fmt"
+ "gopkg.in/yaml.v3"
"log"
"net/http"
"os"
@@ -18,13 +19,28 @@ func VersionPrint() {
os.Exit(0)
}
+func loadConf(fn string) (*App, error) {
+ fh, err := os.Open(fn)
+ if err != nil {
+ return nil, err
+ }
+ dec := yaml.NewDecoder(fh)
+
+ app := &App{}
+ err = dec.Decode(app)
+ return app, err
+}
+
func main() {
fl := flag.NewFlagSet("Website", flag.ExitOnError)
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(&page.TimeFormat, "T", page.TimeFormat, "Print the version then exit")
- indexPath := fl.String("i", "/reIndex",
+ confFn := fl.String("c", "conf.yml", "Location for the config file")
+ verbose := fl.Bool("V", false, "Be more verbose ( dump config, etc ) ")
+ fl.StringVar(&page.TimeFormat, "T", page.TimeFormat, "Set the page time format, be careful with this")
+ defaultIndexPath := "/reIndex"
+ indexPath := fl.String("i", defaultIndexPath,
"Path in which, when called will rebuild the index and clear the cache")
_ = fl.Parse(os.Args[1:])
@@ -36,9 +52,25 @@ func main() {
log.Fatal(err)
}
- app := &App{
- ReIndexPath: *indexPath,
- StaticDirectory: "static",
+ app, err := loadConf(*confFn)
+ if err != nil {
+ log.Println(err)
+ app = &App{}
+ }
+
+ if app.ReIndexPath == "" || *indexPath != defaultIndexPath {
+ app.ReIndexPath = *indexPath
+ }
+ if app.StaticDirectory == "" {
+ app.StaticDirectory = "static"
+ }
+ if app.FeedPrefix == "" {
+ app.FeedPrefix = FeedPrefixDefault
+ }
+
+ if *verbose {
+ b, _ := yaml.Marshal(app)
+ os.Stderr.Write(b)
}
srv := &http.Server{