Write new entries in the same file #3

This commit is contained in:
Peter Stuifzand 2019-12-22 12:57:14 +01:00
parent 4f8b167e7d
commit a11318072f
3 changed files with 84 additions and 27 deletions

67
main.go
View File

@ -1,12 +1,16 @@
package main
import (
"bytes"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"regexp"
"time"
"github.com/jinzhu/now"
@ -16,12 +20,31 @@ import (
"p83.nl/go/ekster/pkg/jf2"
)
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
}
func main() {
u, err := url.Parse(os.Args[1])
if err != nil {
log.Fatal(err)
}
filename := os.Args[2]
re, err := regexp.Compile(`<span class="next-entry"></span>`)
if err != nil {
log.Fatal(err)
}
f, err := openAndCreate(filename)
data, err := ioutil.ReadAll(f)
if err != nil {
log.Fatal(err)
}
f.Close()
var buf bytes.Buffer
items, err := getEntriesForFeed(u)
if err != nil {
log.Fatal(err)
@ -29,19 +52,53 @@ func main() {
items = filterEntriesAfter(items, now.With(time.Now()).Monday())
err = outputEntries(items)
err = outputEntries(items, &buf)
if err != nil {
log.Fatal(err)
}
output := re.ReplaceAll(data, buf.Bytes())
err = ioutil.WriteFile(filename, output, 0666)
if err != nil {
log.Fatal(err)
}
}
func outputEntries(items []microsub.Item) error {
func openAndCreate(filename string) (io.ReadCloser, error) {
f, err := os.Open(filename)
if err != nil && !os.IsExist(err) {
t, err := template.ParseFiles("templates/full.html")
if err != nil {
return nil, err
}
f, err = os.Create(filename)
if err != nil {
return nil, err
}
err = t.Execute(f, nil)
if err != nil {
return nil, err
}
err = f.Close()
if err != nil {
return nil, err
}
f, err = os.Open(filename)
if err != nil {
return nil, err
}
} else if err != nil {
return nil, err
}
return f, nil
}
func outputEntries(items []microsub.Item, w io.Writer) error {
t, err := template.ParseFiles("templates/weekly.html")
if err != nil {
return err
log.Fatal(err)
}
err = t.Execute(os.Stdout, items)
err = t.Execute(w, items)
if err != nil {
return err
}

11
templates/full.html Normal file
View File

@ -0,0 +1,11 @@
<html lang="en">
<head>
<title>Weekly summaries</title>
</head>
<body>
<div class="h-feed">
<h1 class="p-name">Weekly</h1>
<span class="next-entry"></span>
</div>
</body>
</html>

View File

@ -1,13 +1,6 @@
<html lang="en">
<head>
<title>Weekly summaries</title>
</head>
<body>
<div class="h-feed">
<h1 class="p-name">Weekly</h1>
<span class="next-entry"></span>
<div class="h-entry">
{{ range . }}
<div class="h-entry">
<h2 class="p-name">{{ .Name }}</h2>
{{ if .Content }}
{{ if .Content.HTML }}
@ -16,10 +9,6 @@
<div class="p-content">{{ .Content.Text }}</div>
{{ end }}
{{ end }}
<time datetime="{{ .Published }}">{{ .Published }}</time>
</div>
{{ end }}
</div>
</body>
</html>