tilde.town/genblog.go

118 lines
1.9 KiB
Go
Raw Normal View History

2021-08-06 03:18:46 +00:00
package main
2021-08-06 07:31:25 +00:00
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"text/template"
)
const statsPath = "/home/vilmibm/bin/townstats"
// TODO const statsPath = "/town/bin/stats"
type newsEntry struct {
Title string `json:"title"` // Title of entry
Pubdate string `json:"pubdate"` // Human readable date
Content string `json:"content"` // HTML of entry
}
type tildeData struct {
News []newsEntry `json:"news"` // Collection of town news entries
}
func _main() error {
data, err := stats()
if err != nil {
return err
}
hypertextDocument := getHeader()
for _, entry := range data.News {
entryHTML, err := renderEntry(entry)
if err != nil {
return err
}
hypertextDocument += entryHTML
}
hypertextDocument += getFooter()
fmt.Println(hypertextDocument)
return nil
}
func renderEntry(entry newsEntry) (string, error) {
t, err := template.New("news").Parse(`
<h2>{{.Title}}</h2>
<em>{{.Pubdate}}</em>
{{.Content}}
`)
if err != nil {
return "", err
}
out := bytes.Buffer{}
err = t.Execute(&out, entry)
if err != nil {
return "", err
}
return out.String(), nil
}
func getHeader() string {
return `
<!DOCTYPE html>
<html>
<head>
<title>web log of tilde town</title>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>a web log for tilde town or at least what passes for one</h1>
`
}
func getFooter() string {
return `
</body>
</html>
`
}
func stats() (*tildeData, error) {
sout := bytes.Buffer{}
cmd := exec.Command(statsPath)
cmd.Stdout = &sout
err := cmd.Run()
if err != nil {
return nil, err
}
data := tildeData{}
err = json.Unmarshal(sout.Bytes(), &data)
if err != nil {
return nil, err
}
return &data, nil
}
2021-08-06 03:18:46 +00:00
func main() {
2021-08-06 07:31:25 +00:00
err := _main()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
os.Exit(1)
}
2021-08-06 03:18:46 +00:00
}