From e7ea2445b2178a975bc41a063755f1d038a22c33 Mon Sep 17 00:00:00 2001 From: gfanton <8671905+gfanton@users.noreply.github.com> Date: Wed, 3 Jun 2026 19:08:14 +0200 Subject: [PATCH 1/7] feat(gnoweb): add Accept-header markdown negotiation helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- gno.land/pkg/gnoweb/negotiate.go | 45 +++++++++++++++++++++++++++ gno.land/pkg/gnoweb/negotiate_test.go | 40 ++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 gno.land/pkg/gnoweb/negotiate.go create mode 100644 gno.land/pkg/gnoweb/negotiate_test.go diff --git a/gno.land/pkg/gnoweb/negotiate.go b/gno.land/pkg/gnoweb/negotiate.go new file mode 100644 index 00000000000..469f8c41334 --- /dev/null +++ b/gno.land/pkg/gnoweb/negotiate.go @@ -0,0 +1,45 @@ +package gnoweb + +import ( + "strconv" + "strings" +) + +// negotiatesMarkdown reports whether the client explicitly accepts markdown. +// +// It returns true only when "text/markdown" (or the alias "text/x-markdown") +// is named explicitly in the Accept header with a non-zero q-value. It never +// matches the "*/*" or "text/*" wildcards, so browsers — which always accept +// "*/*" — continue to receive HTML. +func negotiatesMarkdown(accept string) bool { + for _, part := range strings.Split(accept, ",") { + mediaType, params, _ := strings.Cut(strings.TrimSpace(part), ";") + mediaType = strings.ToLower(strings.TrimSpace(mediaType)) + if mediaType != "text/markdown" && mediaType != "text/x-markdown" { + continue + } + if markdownQualityIsZero(params) { + continue + } + return true + } + return false +} + +// markdownQualityIsZero reports whether the media-range parameters contain an +// explicit q-value of zero (an explicit refusal). An absent or unparseable +// q-value is treated as acceptable. +func markdownQualityIsZero(params string) bool { + for _, p := range strings.Split(params, ";") { + key, value, ok := strings.Cut(p, "=") + if !ok || strings.ToLower(strings.TrimSpace(key)) != "q" { + continue + } + q, err := strconv.ParseFloat(strings.TrimSpace(value), 64) + if err != nil { + return false // unparseable q -> treat as acceptable + } + return q <= 0 + } + return false +} diff --git a/gno.land/pkg/gnoweb/negotiate_test.go b/gno.land/pkg/gnoweb/negotiate_test.go new file mode 100644 index 00000000000..c0809f31eb3 --- /dev/null +++ b/gno.land/pkg/gnoweb/negotiate_test.go @@ -0,0 +1,40 @@ +package gnoweb + +import "testing" + +func TestNegotiatesMarkdown(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + accept string + want bool + }{ + {"empty", "", false}, + {"plain markdown", "text/markdown", true}, + {"x-markdown alias", "text/x-markdown", true}, + {"case insensitive", "TEXT/Markdown", true}, + {"markdown with charset param", "text/markdown; charset=utf-8", true}, + {"markdown q half", "text/markdown;q=0.5", true}, + {"markdown q one", "text/markdown;q=1.0", true}, + {"markdown q zero", "text/markdown;q=0", false}, + {"markdown q zero point zero", "text/markdown;q=0.0", false}, + {"markdown negative q", "text/markdown;q=-1", false}, + {"html then markdown", "text/html, text/markdown", true}, + {"browser accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", false}, + {"wildcard only", "*/*", false}, + {"text wildcard", "text/*", false}, + {"json", "application/json", false}, + {"surrounding spaces", " text/markdown ", true}, + {"markdown present with non-zero q among others", "text/html;q=0.9, text/markdown;q=0.8", true}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + if got := negotiatesMarkdown(tc.accept); got != tc.want { + t.Errorf("negotiatesMarkdown(%q) = %v, want %v", tc.accept, got, tc.want) + } + }) + } +} From a78ae9aa23b4ca5178d89f0deded40989631bda2 Mon Sep 17 00:00:00 2001 From: gfanton <8671905+gfanton@users.noreply.github.com> Date: Wed, 3 Jun 2026 19:13:42 +0200 Subject: [PATCH 2/7] feat(gnoweb): add MarkdownView for raw text/markdown responses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .../pkg/gnoweb/components/view_markdown.go | 19 +++++++++++++ .../gnoweb/components/view_markdown_test.go | 27 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 gno.land/pkg/gnoweb/components/view_markdown.go create mode 100644 gno.land/pkg/gnoweb/components/view_markdown_test.go diff --git a/gno.land/pkg/gnoweb/components/view_markdown.go b/gno.land/pkg/gnoweb/components/view_markdown.go new file mode 100644 index 00000000000..9f273d33bf1 --- /dev/null +++ b/gno.land/pkg/gnoweb/components/view_markdown.go @@ -0,0 +1,19 @@ +package components + +import ( + "bytes" +) + +// MarkdownViewType marks a View whose content is raw markdown, to be served +// verbatim as text/markdown without the HTML page layout. +const MarkdownViewType ViewType = "markdown-view" + +// MarkdownView returns a View that renders the given content as-is. The handler +// layer recognizes this view type and serves it with a text/markdown +// Content-Type, bypassing IndexLayout. +func MarkdownView(content []byte) *View { + return &View{ + Type: MarkdownViewType, + Component: NewReaderComponent(bytes.NewReader(content)), + } +} diff --git a/gno.land/pkg/gnoweb/components/view_markdown_test.go b/gno.land/pkg/gnoweb/components/view_markdown_test.go new file mode 100644 index 00000000000..81268a50861 --- /dev/null +++ b/gno.land/pkg/gnoweb/components/view_markdown_test.go @@ -0,0 +1,27 @@ +package components_test + +import ( + "bytes" + "testing" + + "github.com/gnolang/gno/gno.land/pkg/gnoweb/components" +) + +func TestMarkdownView(t *testing.T) { + t.Parallel() + + content := []byte("# Title\n\nbody text\n") + v := components.MarkdownView(content) + + if v.Type != components.MarkdownViewType { + t.Fatalf("Type = %q, want %q", v.Type, components.MarkdownViewType) + } + + var buf bytes.Buffer + if err := v.Render(&buf); err != nil { + t.Fatalf("Render returned error: %v", err) + } + if buf.String() != string(content) { + t.Fatalf("Render wrote %q, want verbatim %q", buf.String(), string(content)) + } +} From 22b6e20f9d802003d1e8ad1198e03710f4f0653a Mon Sep 17 00:00:00 2001 From: gfanton <8671905+gfanton@users.noreply.github.com> Date: Wed, 3 Jun 2026 19:20:45 +0200 Subject: [PATCH 3/7] feat(gnoweb): serve realm and static-md pages as text/markdown on Accept MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- gno.land/pkg/gnoweb/handler_http.go | 43 ++++++-- gno.land/pkg/gnoweb/handler_http_test.go | 129 +++++++++++++++++++++++ 2 files changed, 163 insertions(+), 9 deletions(-) diff --git a/gno.land/pkg/gnoweb/handler_http.go b/gno.land/pkg/gnoweb/handler_http.go index 79ffbbb308e..c7004fed122 100644 --- a/gno.land/pkg/gnoweb/handler_http.go +++ b/gno.land/pkg/gnoweb/handler_http.go @@ -101,6 +101,8 @@ func (h *HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: w.Header().Add("Content-Type", "text/html; charset=utf-8") + // The same URL can return HTML or markdown depending on Accept. + w.Header().Set("Vary", "Accept") h.Get(w, r) case http.MethodPost: h.Post(w, r) @@ -176,8 +178,22 @@ func (h *HTTPHandler) Get(w http.ResponseWriter, r *http.Request) { indexData.Mode = components.ViewModeRealm } - var status int - status, indexData.BodyView = h.prepareIndexBodyView(r, &indexData) + wantMarkdown := negotiatesMarkdown(r.Header.Get("Accept")) + + status, bodyView := h.prepareIndexBodyView(r, &indexData, wantMarkdown) + + // The realm and static-markdown paths return a markdown view; serve its + // raw source verbatim with a text/markdown Content-Type, bypassing the layout. + if bodyView.Type == components.MarkdownViewType { + w.Header().Set("Content-Type", "text/markdown; charset=utf-8") + w.WriteHeader(status) + if err := bodyView.Render(w); err != nil { + h.Logger.Error("failed to render markdown view", "error", err) + } + return + } + + indexData.BodyView = bodyView // Render the final page with the rendered body w.WriteHeader(status) @@ -239,7 +255,7 @@ func (h *HTTPHandler) Post(w http.ResponseWriter, r *http.Request) { } // prepareIndexBodyView prepares the data and main view for the index page. -func (h *HTTPHandler) prepareIndexBodyView(r *http.Request, indexData *components.IndexData) (int, *components.View) { +func (h *HTTPHandler) prepareIndexBodyView(r *http.Request, indexData *components.IndexData, wantMarkdown bool) (int, *components.View) { ctx := r.Context() aliasTarget, aliasExists := h.Aliases[r.URL.Path] @@ -267,9 +283,9 @@ func (h *HTTPHandler) prepareIndexBodyView(r *http.Request, indexData *component switch { case aliasExists && aliasTarget.Kind == StaticMarkdown: indexData.HeaderData.Static = true - return h.GetMarkdownView(gnourl, aliasTarget.Value) + return h.GetMarkdownView(gnourl, aliasTarget.Value, wantMarkdown) case gnourl.IsRealm(), gnourl.IsPure(), gnourl.IsUser(): - return h.GetPackageView(ctx, gnourl, indexData) + return h.GetPackageView(ctx, gnourl, indexData, wantMarkdown) default: h.Logger.Debug("invalid path: path is neither a pure package or a realm") return http.StatusBadRequest, components.StatusErrorComponent("invalid path") @@ -277,7 +293,11 @@ func (h *HTTPHandler) prepareIndexBodyView(r *http.Request, indexData *component } // GetMarkdownView handles rendering of markdown files. -func (h *HTTPHandler) GetMarkdownView(gnourl *weburl.GnoURL, mdContent string) (int, *components.View) { +func (h *HTTPHandler) GetMarkdownView(gnourl *weburl.GnoURL, mdContent string, wantMarkdown bool) (int, *components.View) { + if wantMarkdown { + return http.StatusOK, components.MarkdownView([]byte(mdContent)) + } + var content bytes.Buffer // Use Goldmark for Markdown parsing @@ -298,7 +318,7 @@ func (h *HTTPHandler) GetMarkdownView(gnourl *weburl.GnoURL, mdContent string) ( } // GetPackageView handles package pages, including help, source, directory, and user views. -func (h *HTTPHandler) GetPackageView(ctx context.Context, gnourl *weburl.GnoURL, indexData *components.IndexData) (int, *components.View) { +func (h *HTTPHandler) GetPackageView(ctx context.Context, gnourl *weburl.GnoURL, indexData *components.IndexData, wantMarkdown bool) (int, *components.View) { // Handle Help page if gnourl.WebQuery.Has("help") { return h.GetHelpView(ctx, gnourl) @@ -320,11 +340,11 @@ func (h *HTTPHandler) GetPackageView(ctx context.Context, gnourl *weburl.GnoURL, } // Ultimately get realm view - return h.GetRealmView(ctx, gnourl, indexData) + return h.GetRealmView(ctx, gnourl, indexData, wantMarkdown) } // GetRealmView renders a realm page or returns an error/status if not available. -func (h *HTTPHandler) GetRealmView(ctx context.Context, gnourl *weburl.GnoURL, indexData *components.IndexData) (int, *components.View) { +func (h *HTTPHandler) GetRealmView(ctx context.Context, gnourl *weburl.GnoURL, indexData *components.IndexData, wantMarkdown bool) (int, *components.View) { // First fecth the realm raw, err := h.Client.Realm(ctx, gnourl.Path, gnourl.EncodeArgs()) switch { @@ -340,6 +360,11 @@ func (h *HTTPHandler) GetRealmView(ctx context.Context, gnourl *weburl.GnoURL, i return GetClientErrorStatusPage(gnourl, err) } + // Serve raw markdown verbatim, skipping the goldmark HTML render. + if wantMarkdown { + return http.StatusOK, components.MarkdownView(raw) + } + var content bytes.Buffer meta, err := h.Renderer.RenderRealm(&content, gnourl, raw, RealmRenderContext{ ChainId: h.Static.ChainId, diff --git a/gno.land/pkg/gnoweb/handler_http_test.go b/gno.land/pkg/gnoweb/handler_http_test.go index a53c5d0f569..82653c639cb 100644 --- a/gno.land/pkg/gnoweb/handler_http_test.go +++ b/gno.land/pkg/gnoweb/handler_http_test.go @@ -1399,6 +1399,135 @@ func TestGetHelpView_BackslashEscapingIssueFixed(t *testing.T) { require.Contains(t, body, "`_`") } +// TestHTTPHandler_MarkdownNegotiation verifies that an explicit Accept: +// text/markdown yields the raw realm markdown (no HTML layout), while other +// Accept values fall back to HTML. Vary: Accept is always present. +func TestHTTPHandler_MarkdownNegotiation(t *testing.T) { + t.Parallel() + + mockPackage := &gnoweb.MockPackage{ + Domain: "example.com", + Path: "/r/mock/path", + Files: map[string]string{ + "render.gno": `package main; func Render(path string) string { return "hello" }`, + }, + Functions: []*doc.JSONFunc{ + {Name: "Render", Params: []*doc.JSONField{{Name: "path", Type: "string"}}, Results: []*doc.JSONField{{Name: "", Type: "string"}}}, + }, + } + config := newTestHandlerConfig(t, gnoweb.NewMockClient(mockPackage)) + + cases := []struct { + name string + accept string + wantCT string + markdown bool // true => raw markdown body (no HTML layout) + }{ + {"explicit markdown", "text/markdown", "text/markdown; charset=utf-8", true}, + {"x-markdown alias", "text/x-markdown", "text/markdown; charset=utf-8", true}, + {"markdown with charset", "text/markdown; charset=utf-8", "text/markdown; charset=utf-8", true}, + {"browser accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "text/html; charset=utf-8", false}, + {"wildcard only", "*/*", "text/html; charset=utf-8", false}, + {"markdown refused q0", "text/markdown;q=0", "text/html; charset=utf-8", false}, + {"no accept header", "", "text/html; charset=utf-8", false}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + logger := slog.New(slog.NewTextHandler(&testingLogger{t}, &slog.HandlerOptions{})) + handler, err := gnoweb.NewHTTPHandler(logger, config) + require.NoError(t, err) + + req, err := http.NewRequest(http.MethodGet, "/r/mock/path", nil) + require.NoError(t, err) + if tc.accept != "" { + req.Header.Set("Accept", tc.accept) + } + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + require.Equal(t, http.StatusOK, rr.Code) + assert.Equal(t, tc.wantCT, rr.Header().Get("Content-Type")) + assert.Contains(t, rr.Header().Values("Vary"), "Accept") + + body := rr.Body.String() + if tc.markdown { + assert.NotContains(t, body, "") + assert.Contains(t, body, "[example.com]/r/mock/path") // from MockClient.Realm + } else { + assert.Contains(t, body, "") + } + }) + } +} + +// TestHTTPHandler_MarkdownNegotiation_StaticAlias verifies a StaticMarkdown +// alias is served verbatim under Accept: text/markdown. +func TestHTTPHandler_MarkdownNegotiation_StaticAlias(t *testing.T) { + t.Parallel() + + const md = "# About\n\nStatic markdown content.\n" + config := &gnoweb.HTTPHandlerConfig{ + ClientAdapter: gnoweb.NewMockClient(), + Renderer: &rawRenderer{}, + Aliases: map[string]gnoweb.AliasTarget{ + "/about": {Value: md, Kind: gnoweb.StaticMarkdown}, + }, + } + + logger := slog.New(slog.NewTextHandler(&testingLogger{t}, &slog.HandlerOptions{})) + handler, err := gnoweb.NewHTTPHandler(logger, config) + require.NoError(t, err) + + req, err := http.NewRequest(http.MethodGet, "/about", nil) + require.NoError(t, err) + req.Header.Set("Accept", "text/markdown") + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + require.Equal(t, http.StatusOK, rr.Code) + assert.Equal(t, "text/markdown; charset=utf-8", rr.Header().Get("Content-Type")) + assert.Equal(t, md, rr.Body.String()) +} + +// TestHTTPHandler_MarkdownNegotiation_NoRenderFallsBackToHTML verifies that a +// realm without a Render() function falls back to the HTML directory view even +// when markdown is requested. This guards the ordering invariant: the markdown +// short-circuit sits AFTER the fetch error-switch, not before it. +func TestHTTPHandler_MarkdownNegotiation_NoRenderFallsBackToHTML(t *testing.T) { + t.Parallel() + + mockPackage := &gnoweb.MockPackage{ + Domain: "example.com", + Path: "/r/norender/path", + Files: map[string]string{ + "a.gno": `package main; func init() {}`, + "gno.mod": `module example.com/r/norender/path`, + }, + Functions: []*doc.JSONFunc{}, // no Render + } + config := newTestHandlerConfig(t, gnoweb.NewMockClient(mockPackage)) + + logger := slog.New(slog.NewTextHandler(&testingLogger{t}, &slog.HandlerOptions{})) + handler, err := gnoweb.NewHTTPHandler(logger, config) + require.NoError(t, err) + + req, err := http.NewRequest(http.MethodGet, "/r/norender/path", nil) + require.NoError(t, err) + req.Header.Set("Accept", "text/markdown") + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + // Fell back to the HTML directory view, NOT markdown. + assert.Equal(t, "text/html; charset=utf-8", rr.Header().Get("Content-Type")) + assert.Contains(t, rr.Body.String(), "") +} + func TestHTTPHandler_ThemeCookie(t *testing.T) { t.Parallel() From 5e04188afbbbc9e1384d43301bb97c5791ab9086 Mon Sep 17 00:00:00 2001 From: gfanton <8671905+gfanton@users.noreply.github.com> Date: Wed, 3 Jun 2026 19:36:52 +0200 Subject: [PATCH 4/7] refactor(gnoweb): parse Accept with stdlib mime.ParseMediaType MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the hand-rolled media-type/q-value splitting with mime.ParseMediaType, removing the markdownQualityIsZero helper. Behavior is unchanged and covered by TestNegotiatesMarkdown. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- gno.land/pkg/gnoweb/negotiate.go | 37 +++++++++++--------------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/gno.land/pkg/gnoweb/negotiate.go b/gno.land/pkg/gnoweb/negotiate.go index 469f8c41334..ef9cb644d21 100644 --- a/gno.land/pkg/gnoweb/negotiate.go +++ b/gno.land/pkg/gnoweb/negotiate.go @@ -1,6 +1,7 @@ package gnoweb import ( + "mime" "strconv" "strings" ) @@ -8,38 +9,24 @@ import ( // negotiatesMarkdown reports whether the client explicitly accepts markdown. // // It returns true only when "text/markdown" (or the alias "text/x-markdown") -// is named explicitly in the Accept header with a non-zero q-value. It never -// matches the "*/*" or "text/*" wildcards, so browsers — which always accept -// "*/*" — continue to receive HTML. +// is named explicitly in the Accept header and not refused with an explicit +// q=0. It never matches the "*/*" or "text/*" wildcards, so browsers — which +// always accept "*/*" — continue to receive HTML. func negotiatesMarkdown(accept string) bool { for _, part := range strings.Split(accept, ",") { - mediaType, params, _ := strings.Cut(strings.TrimSpace(part), ";") - mediaType = strings.ToLower(strings.TrimSpace(mediaType)) - if mediaType != "text/markdown" && mediaType != "text/x-markdown" { - continue - } - if markdownQualityIsZero(params) { + mediaType, params, err := mime.ParseMediaType(strings.TrimSpace(part)) + if err != nil { continue } - return true - } - return false -} - -// markdownQualityIsZero reports whether the media-range parameters contain an -// explicit q-value of zero (an explicit refusal). An absent or unparseable -// q-value is treated as acceptable. -func markdownQualityIsZero(params string) bool { - for _, p := range strings.Split(params, ";") { - key, value, ok := strings.Cut(p, "=") - if !ok || strings.ToLower(strings.TrimSpace(key)) != "q" { + if mediaType != "text/markdown" && mediaType != "text/x-markdown" { continue } - q, err := strconv.ParseFloat(strings.TrimSpace(value), 64) - if err != nil { - return false // unparseable q -> treat as acceptable + if q, ok := params["q"]; ok { + if v, err := strconv.ParseFloat(q, 64); err == nil && v <= 0 { + continue + } } - return q <= 0 + return true } return false } From 9938c09653cb2a9977c2104b8a7b3ba057f0798e Mon Sep 17 00:00:00 2001 From: gfanton <8671905+gfanton@users.noreply.github.com> Date: Thu, 4 Jun 2026 10:30:38 +0200 Subject: [PATCH 5/7] test(gnoweb): lock in Claude Code WebFetch Accept string MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WebFetch sends "Accept: text/markdown, text/html, */*" (verified via httpbin.org/headers), so an agent fetch gets markdown automatically with no manual header. Pin the exact string as a regression case. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- gno.land/pkg/gnoweb/negotiate_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/gno.land/pkg/gnoweb/negotiate_test.go b/gno.land/pkg/gnoweb/negotiate_test.go index c0809f31eb3..a75032c3ac8 100644 --- a/gno.land/pkg/gnoweb/negotiate_test.go +++ b/gno.land/pkg/gnoweb/negotiate_test.go @@ -22,6 +22,7 @@ func TestNegotiatesMarkdown(t *testing.T) { {"markdown negative q", "text/markdown;q=-1", false}, {"html then markdown", "text/html, text/markdown", true}, {"browser accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", false}, + {"claude-code webfetch accept", "text/markdown, text/html, */*", true}, {"wildcard only", "*/*", false}, {"text wildcard", "text/*", false}, {"json", "application/json", false}, From a8dbdfa87ba639e564f5b035a67db93b803393de Mon Sep 17 00:00:00 2001 From: gfanton <8671905+gfanton@users.noreply.github.com> Date: Thu, 4 Jun 2026 17:05:45 +0200 Subject: [PATCH 6/7] chore(gnoweb): address review nits (single import, malformed-q test) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- gno.land/pkg/gnoweb/components/view_markdown.go | 4 +--- gno.land/pkg/gnoweb/negotiate_test.go | 1 + 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/gno.land/pkg/gnoweb/components/view_markdown.go b/gno.land/pkg/gnoweb/components/view_markdown.go index 9f273d33bf1..d98ad8b8494 100644 --- a/gno.land/pkg/gnoweb/components/view_markdown.go +++ b/gno.land/pkg/gnoweb/components/view_markdown.go @@ -1,8 +1,6 @@ package components -import ( - "bytes" -) +import "bytes" // MarkdownViewType marks a View whose content is raw markdown, to be served // verbatim as text/markdown without the HTML page layout. diff --git a/gno.land/pkg/gnoweb/negotiate_test.go b/gno.land/pkg/gnoweb/negotiate_test.go index a75032c3ac8..a5797f1fb9c 100644 --- a/gno.land/pkg/gnoweb/negotiate_test.go +++ b/gno.land/pkg/gnoweb/negotiate_test.go @@ -20,6 +20,7 @@ func TestNegotiatesMarkdown(t *testing.T) { {"markdown q zero", "text/markdown;q=0", false}, {"markdown q zero point zero", "text/markdown;q=0.0", false}, {"markdown negative q", "text/markdown;q=-1", false}, + {"markdown malformed q", "text/markdown;q=abc", true}, {"html then markdown", "text/html, text/markdown", true}, {"browser accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", false}, {"claude-code webfetch accept", "text/markdown, text/html, */*", true}, From 589d1970d2a3ff34144a4308b99493ef952955b0 Mon Sep 17 00:00:00 2001 From: gfanton <8671905+gfanton@users.noreply.github.com> Date: Mon, 8 Jun 2026 16:10:18 +0200 Subject: [PATCH 7/7] refactor(gnoweb): replace wantMarkdown flag on leaf views with GetMarkdownRealmView MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Split the realm render path into GetRealmView (HTML) and GetMarkdownRealmView, sharing a fetchRealm helper for the fetch and error fallbacks. The wantMarkdown bool remains only as a dispatch selector in prepareIndexBodyView/GetPackageView. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- gno.land/pkg/gnoweb/handler_http.go | 56 +++++++++++++++++++---------- 1 file changed, 38 insertions(+), 18 deletions(-) diff --git a/gno.land/pkg/gnoweb/handler_http.go b/gno.land/pkg/gnoweb/handler_http.go index c7004fed122..7cb6ebb072a 100644 --- a/gno.land/pkg/gnoweb/handler_http.go +++ b/gno.land/pkg/gnoweb/handler_http.go @@ -100,7 +100,7 @@ func (h *HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: - w.Header().Add("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Content-Type", "text/html; charset=utf-8") // The same URL can return HTML or markdown depending on Accept. w.Header().Set("Vary", "Accept") h.Get(w, r) @@ -282,8 +282,11 @@ func (h *HTTPHandler) prepareIndexBodyView(r *http.Request, indexData *component switch { case aliasExists && aliasTarget.Kind == StaticMarkdown: + if wantMarkdown { + return http.StatusOK, components.MarkdownView([]byte(aliasTarget.Value)) + } indexData.HeaderData.Static = true - return h.GetMarkdownView(gnourl, aliasTarget.Value, wantMarkdown) + return h.GetMarkdownView(gnourl, aliasTarget.Value) case gnourl.IsRealm(), gnourl.IsPure(), gnourl.IsUser(): return h.GetPackageView(ctx, gnourl, indexData, wantMarkdown) default: @@ -293,11 +296,7 @@ func (h *HTTPHandler) prepareIndexBodyView(r *http.Request, indexData *component } // GetMarkdownView handles rendering of markdown files. -func (h *HTTPHandler) GetMarkdownView(gnourl *weburl.GnoURL, mdContent string, wantMarkdown bool) (int, *components.View) { - if wantMarkdown { - return http.StatusOK, components.MarkdownView([]byte(mdContent)) - } - +func (h *HTTPHandler) GetMarkdownView(gnourl *weburl.GnoURL, mdContent string) (int, *components.View) { var content bytes.Buffer // Use Goldmark for Markdown parsing @@ -340,29 +339,40 @@ func (h *HTTPHandler) GetPackageView(ctx context.Context, gnourl *weburl.GnoURL, } // Ultimately get realm view - return h.GetRealmView(ctx, gnourl, indexData, wantMarkdown) + if wantMarkdown { + return h.GetMarkdownRealmView(ctx, gnourl, indexData) + } + return h.GetRealmView(ctx, gnourl, indexData) } -// GetRealmView renders a realm page or returns an error/status if not available. -func (h *HTTPHandler) GetRealmView(ctx context.Context, gnourl *weburl.GnoURL, indexData *components.IndexData, wantMarkdown bool) (int, *components.View) { - // First fecth the realm +// fetchRealm fetches a realm's raw Render() output. On success it returns the +// bytes with ok=true and the status/fallback unset. When the realm cannot be +// rendered it returns ok=false with the HTML fallback view and status to send as-is. +func (h *HTTPHandler) fetchRealm(ctx context.Context, gnourl *weburl.GnoURL, indexData *components.IndexData) ([]byte, int, *components.View, bool) { raw, err := h.Client.Realm(ctx, gnourl.Path, gnourl.EncodeArgs()) switch { - case err == nil: // ok + case err == nil: + return raw, 0, nil, true case errors.Is(err, ErrClientRenderNotDeclared): // No Render() declared: fall back to directory view (which will show README.md if present) - return h.GetDirectoryView(ctx, gnourl, indexData) + status, view := h.GetDirectoryView(ctx, gnourl, indexData) + return nil, status, view, false case errors.Is(err, ErrClientPackageNotFound): // No realm exists here, try to display underlying paths - return h.GetPathsListView(ctx, gnourl, indexData) + status, view := h.GetPathsListView(ctx, gnourl, indexData) + return nil, status, view, false default: h.Logger.Error("unable to fetch realm", "error", err, "path", gnourl.EncodeURL()) - return GetClientErrorStatusPage(gnourl, err) + status, view := GetClientErrorStatusPage(gnourl, err) + return nil, status, view, false } +} - // Serve raw markdown verbatim, skipping the goldmark HTML render. - if wantMarkdown { - return http.StatusOK, components.MarkdownView(raw) +// GetRealmView renders a realm page as HTML, or returns an error/status if not available. +func (h *HTTPHandler) GetRealmView(ctx context.Context, gnourl *weburl.GnoURL, indexData *components.IndexData) (int, *components.View) { + raw, status, fallback, ok := h.fetchRealm(ctx, gnourl, indexData) + if !ok { + return status, fallback } var content bytes.Buffer @@ -386,6 +396,16 @@ func (h *HTTPHandler) GetRealmView(ctx context.Context, gnourl *weburl.GnoURL, i }) } +// GetMarkdownRealmView serves a realm's raw Render() output as text/markdown. It +// falls back to the directory, paths-list, or error view when the realm cannot be fetched. +func (h *HTTPHandler) GetMarkdownRealmView(ctx context.Context, gnourl *weburl.GnoURL, indexData *components.IndexData) (int, *components.View) { + raw, status, fallback, ok := h.fetchRealm(ctx, gnourl, indexData) + if !ok { + return status, fallback + } + return http.StatusOK, components.MarkdownView(raw) +} + // buildContributions returns the sorted list of contributions (packages and realms) for a user. func (h *HTTPHandler) buildContributions(ctx context.Context, username string) ([]components.UserContribution, int, error) { prefix := "@" + username