godoc: convert Markdown files to HTML during serving
For golang.org today, Markdown is converted to HTML during
the static file embedding, but that precludes using Markdown with
"live serving".
Moving the code here lets godoc itself do the conversion and
therefore works with live serving. It is also more consistent with
re-executing templates during serving for Template:true files.
When a file is .md but also has Template: true, templates apply
first, so that templates can generate Markdown.
This is reversed from what x/website was doing (Markdown before templates)
but that decision was mostly forced by doing it during static
embedding and not necessarily the right one.
There's no reason to force switching to raw HTML just because
you want to use a template.
(A template can of course still generate HTML.)
Change-Id: I7db6d54b43e45803e965df7a1ab2f26293285cfd
Reviewed-on: https://go-review.googlesource.com/c/tools/+/251343
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
diff --git a/godoc/server.go b/godoc/server.go
index 8724291..8c9b1b9 100644
--- a/godoc/server.go
+++ b/godoc/server.go
@@ -695,7 +695,15 @@
func (p *Presentation) ServeHTMLDoc(w http.ResponseWriter, r *http.Request, abspath, relpath string) {
// get HTML body contents
+ isMarkdown := false
src, err := vfs.ReadFile(p.Corpus.fs, abspath)
+ if err != nil && strings.HasSuffix(abspath, ".html") {
+ if md, errMD := vfs.ReadFile(p.Corpus.fs, strings.TrimSuffix(abspath, ".html")+".md"); errMD == nil {
+ src = md
+ isMarkdown = true
+ err = nil
+ }
+ }
if err != nil {
log.Printf("ReadFile: %s", err)
p.ServeError(w, r, relpath, err)
@@ -738,6 +746,18 @@
src = buf.Bytes()
}
+ // Apply markdown as indicated.
+ // (Note template applies before Markdown.)
+ if isMarkdown {
+ html, err := renderMarkdown(src)
+ if err != nil {
+ log.Printf("executing markdown %s: %v", relpath, err)
+ p.ServeError(w, r, relpath, err)
+ return
+ }
+ src = html
+ }
+
// if it's the language spec, add tags to EBNF productions
if strings.HasSuffix(abspath, "go_spec.html") {
var buf bytes.Buffer
@@ -797,7 +817,8 @@
if redirect(w, r) {
return
}
- if index := pathpkg.Join(abspath, "index.html"); util.IsTextFile(p.Corpus.fs, index) {
+ index := pathpkg.Join(abspath, "index.html")
+ if util.IsTextFile(p.Corpus.fs, index) || util.IsTextFile(p.Corpus.fs, pathpkg.Join(abspath, "index.md")) {
p.ServeHTMLDoc(w, r, index, index)
return
}