webhouse.appwebhouse.appdocs

Læs @webhouse/cms-indhold fra Go — Hugo-temaer, Gin-handlers og standard bibliotek fil I/O.

Opsætning

mit-projekt/
  cms.config.ts
  content/          # JSON-dokumenter
  public/uploads/
  main.go
  templates/

Reader-pakke

Opret internal/webhouse/webhouse.go:

go
package webhouse

import (
    "encoding/json"
    "os"
    "path/filepath"
    "sort"
    "strings"
)

type Document struct {
    ID               string                 `json:"id"`
    Slug             string                 `json:"slug"`
    Status           string                 `json:"status"`
    Locale           string                 `json:"locale,omitempty"`
    TranslationGroup string                 `json:"translationGroup,omitempty"`
    Data             map[string]interface{} `json:"data"`
}

type Client struct {
    ContentDir string
}

func New(contentDir string) *Client {
    return &Client{ContentDir: contentDir}
}

func (c *Client) Collection(name, locale string) ([]Document, error) {
    dir := filepath.Join(c.ContentDir, name)
    entries, err := os.ReadDir(dir)
    if err != nil {
        return nil, err
    }

    var docs []Document
    for _, e := range entries {
        if !strings.HasSuffix(e.Name(), ".json") {
            continue
        }
        raw, err := os.ReadFile(filepath.Join(dir, e.Name()))
        if err != nil {
            continue
        }
        var d Document
        if err := json.Unmarshal(raw, &d); err != nil {
            continue
        }
        if d.Status != "published" {
            continue
        }
        if locale != "" && d.Locale != locale {
            continue
        }
        docs = append(docs, d)
    }

    sort.Slice(docs, func(i, j int) bool {
        di, _ := docs[i].Data["date"].(string)
        dj, _ := docs[j].Data["date"].(string)
        return di > dj
    })
    return docs, nil
}

func (c *Client) Document(collection, slug string) (*Document, error) {
    path := filepath.Join(c.ContentDir, collection, slug+".json")
    raw, err := os.ReadFile(path)
    if err != nil {
        return nil, err
    }
    var d Document
    if err := json.Unmarshal(raw, &d); err != nil {
        return nil, err
    }
    if d.Status != "published" {
        return nil, nil
    }
    return &d, nil
}

Gin-handler

go
package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
    "mitprojekt/internal/webhouse"
)

func main() {
    wh := webhouse.New("content")
    r := gin.Default()
    r.LoadHTMLGlob("templates/*")
    r.Static("/uploads", "./public/uploads")

    r.GET("/", func(c *gin.Context) {
        posts, _ := wh.Collection("posts", "da")
        c.HTML(http.StatusOK, "home.html", gin.H{"Posts": posts})
    })

    r.GET("/blog/:slug", func(c *gin.Context) {
        post, _ := wh.Document("posts", c.Param("slug"))
        if post == nil {
            c.AbortWithStatus(404)
            return
        }
        c.HTML(http.StatusOK, "post.html", gin.H{"Post": post})
    })

    r.Run(":8080")
}

Skabelon

html
<!-- templates/post.html -->
<article>
  <h1>{{ index .Post.Data "title" }}</h1>
  <time>{{ index .Post.Data "date" }}</time>
  <div class="prose">
    {{ index .Post.Data "content" | markdown }}
  </div>
</article>

Hugo-integration

Hugo bruger sit eget content-system, men du kan skrive et lille script der konverterer @webhouse/cms JSON til Hugo's front matter + markdown format ved build-tid.

Caching

Brug en sync.Map eller in-memory cache med TTL:

go
var cache sync.Map

func (c *Client) CollectionCached(name, locale string) ([]Document, error) {
    key := name + ":" + locale
    if v, ok := cache.Load(key); ok {
        return v.([]Document), nil
    }
    docs, err := c.Collection(name, locale)
    if err != nil {
        return nil, err
    }
    cache.Store(key, docs)
    return docs, nil
}

Næste skridt

Tags:FrameworksFilesystem Adapter
Forrige
Forbrug fra Rails (Ruby)
Næste
Forbrug fra C# / .NET
JSON API →Edit on GitHub →