diff --git a/examples/html.go b/examples/html.go index bb99c56..bbef5f1 100644 --- a/examples/html.go +++ b/examples/html.go @@ -7,76 +7,77 @@ package main import ( "fmt" "html" - "strings" + "io" + "os" "git.sr.ht/~adnano/go-gemini" ) func main() { - text := gemini.Text{ - gemini.LineHeading1("Hello, world!"), - gemini.LineText("This is a gemini text document."), + hw := HTMLWriter{ + out: os.Stdout, } - - html := textToHTML(text) - fmt.Print(html) + gemini.ParseLines(os.Stdin, hw.Handle) + hw.Finish() } -// textToHTML returns the Gemini text response as HTML. -func textToHTML(text gemini.Text) string { - var b strings.Builder - var pre bool - var list bool - for _, l := range text { - if _, ok := l.(gemini.LineListItem); ok { - if !list { - list = true - fmt.Fprint(&b, "
\n")
- } else {
- fmt.Fprint(&b, "\n")
- }
- case gemini.LinePreformattedText:
- fmt.Fprintf(&b, "%s\n", html.EscapeString(string(l)))
- case gemini.LineHeading1:
- fmt.Fprintf(&b, "%s\n", html.EscapeString(string(l))) - case gemini.LineText: - if l == "" { - fmt.Fprint(&b, "
%s
\n", html.EscapeString(string(l))) - } + } else if h.list { + h.list = false + fmt.Fprint(h.out, "\n") + } + switch line := line.(type) { + case gemini.LineLink: + url := html.EscapeString(line.URL) + name := html.EscapeString(line.Name) + if name == "" { + name = url + } + fmt.Fprintf(h.out, "\n", url, name) + case gemini.LinePreformattingToggle: + h.pre = !h.pre + if h.pre { + fmt.Fprint(h.out, "\n")
+ } else {
+ fmt.Fprint(h.out, "\n")
+ }
+ case gemini.LinePreformattedText:
+ fmt.Fprintf(h.out, "%s\n", html.EscapeString(string(line)))
+ case gemini.LineHeading1:
+ fmt.Fprintf(h.out, "%s\n", html.EscapeString(string(line))) + case gemini.LineText: + if line == "" { + fmt.Fprint(h.out, "
%s
\n", html.EscapeString(string(line))) } } - if pre { - fmt.Fprint(&b, "\n") +} + +func (h *HTMLWriter) Finish() { + if h.pre { + fmt.Fprint(h.out, "\n") } - if list { - fmt.Fprint(&b, "\n") + if h.list { + fmt.Fprint(h.out, "\n") } - return b.String() }