From 09141314d8d786dbab61c74fe4eab09c56acfd5d Mon Sep 17 00:00:00 2001 From: maddalax Date: Fri, 27 Sep 2024 21:41:32 -0500 Subject: [PATCH] add github stars example --- htmgo-site/md/docs/5_performance/1_caching.md | 18 +++++++++++++++++- htmgo-site/partials/navbar.go | 8 ++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/htmgo-site/md/docs/5_performance/1_caching.md b/htmgo-site/md/docs/5_performance/1_caching.md index b793e30..7165a5b 100644 --- a/htmgo-site/md/docs/5_performance/1_caching.md +++ b/htmgo-site/md/docs/5_performance/1_caching.md @@ -43,9 +43,25 @@ func IndexPage(ctx *h.RequestContext) *h.Page { ) } ``` + +**Real Example:** +I want to make a navbar that renders how many github stars my repository has. I don't want to make a request to the GitHub API everytime someone visits my page, so I will cache the component for 15 minutes. +```go +var CachedGithubStars = h.CachedT(time.Minute*15, func(t *h.RequestContext) *h.Element { + return GithubStars(t) +}) + +func GithubStars(ctx *h.RequestContext) *h.Element { + stars := http.Get("https://api.github.com/repos/maddalax/htmgo/stargazers") + return h.Div( + h.Text(stars), + ) +} +``` + **Note:** We are using CachedT because the component takes one argument, the RequestContext. If the component takes more arguments, use CachedT2, CachedT3, etc. **Important**: 1. The cached value is stored globally in memory, so it is shared across all requests. Do not store request-specific data in a cached component. Only cache components that you are OK with all users seeing the same data. -2. Ensure the declaration of the cached component is **outside the function** that uses it. This is to prevent the component from being redeclared on each request. \ No newline at end of file +2. Ensure the declaration of the cached component is **outside the function** that uses it. This is to prevent the component from being redeclared on each request. diff --git a/htmgo-site/partials/navbar.go b/htmgo-site/partials/navbar.go index ea9a396..9191c85 100644 --- a/htmgo-site/partials/navbar.go +++ b/htmgo-site/partials/navbar.go @@ -17,10 +17,6 @@ var navItems = []NavItem{ {Name: "Examples", Url: "/examples"}, } -var CachedStar = h.CachedT(time.Minute*15, func(t *h.RequestContext) *h.Element { - return Star(t) -}) - func ToggleNavbar(ctx *h.RequestContext) *h.Partial { return h.SwapManyPartial( ctx, @@ -28,6 +24,10 @@ func ToggleNavbar(ctx *h.RequestContext) *h.Partial { ) } +var CachedStar = h.CachedT(time.Minute*15, func(t *h.RequestContext) *h.Element { + return Star(t) +}) + func Star(ctx *h.RequestContext) *h.Element { type Repo struct {