60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
// Notes implements a data structure for reasoning about and rendering
|
|
// markdown notes
|
|
package notes
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"html/template"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"gitea.gwairfelin.com/max/gonotes/internal/conf"
|
|
"github.com/yuin/goldmark"
|
|
"github.com/yuin/goldmark/extension"
|
|
)
|
|
|
|
// Note is the central data structure. It can be Saved, Rendered and Loaded
|
|
// using the Save, Render and LoadNote functions.
|
|
type Note struct {
|
|
Title string
|
|
BodyRendered template.HTML
|
|
Body []byte
|
|
}
|
|
|
|
func fmtPath(path string) string {
|
|
return fmt.Sprintf("%s.%s", path, conf.Conf.Extension)
|
|
}
|
|
|
|
// Save a note to a path derived from the title
|
|
func (n *Note) Save() error {
|
|
filename := filepath.Join(conf.Conf.NotesDir, fmtPath(n.Title))
|
|
return os.WriteFile(filename, n.Body, 0600)
|
|
}
|
|
|
|
// Render the markdown content of the note to HTML
|
|
func (n *Note) Render() {
|
|
var buf bytes.Buffer
|
|
md := goldmark.New(
|
|
goldmark.WithExtensions(
|
|
extension.TaskList,
|
|
),
|
|
)
|
|
err := md.Convert(n.Body, &buf)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
n.BodyRendered = template.HTML(buf.String())
|
|
}
|
|
|
|
// Load a note from the disk. The path is derived from the title
|
|
func LoadNote(title string) (*Note, error) {
|
|
filename := filepath.Join(conf.Conf.NotesDir, fmtPath(title))
|
|
body, err := os.ReadFile(filename)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Note{Title: title, Body: body}, nil
|
|
}
|