blog

package
v0.16.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PageTypeWriting  = "writing"
	PageTypeAbout    = "about"
	PageTypeCustom   = "custom"
	PageTypeTags     = "tags"
	PageTypeArchives = "archives"
)

Page types

Variables

This section is empty.

Functions

func CanonicalSlug

func CanonicalSlug(slug string) string

CanonicalSlug is the one stored form of a slug: escaped exactly once, however many times the input already was. Posts are looked up by it, so a URL that carries extra layers still finds its post.

func GithubAuthorizeURL

func GithubAuthorizeURL(origin, clientID, state string) string

GithubAuthorizeURL builds the URL that starts GitHub's OAuth flow.

redirect_uri carries no query of its own. GitHub matches it against the callback registered for the app, so a constant value is the one most likely to match; where the visitor was heading rides in the session instead, which also keeps it out of a URL that gets logged and passed to a third party.

state ties the authorize request to the browser that made it: GithubCallback will not exchange a code unless it comes back unchanged (#637).

func GithubLoginURL

func GithubLoginURL(next string) string

GithubLoginURL is where the login page's GitHub button points: /login/github, carrying where the visitor was heading so GithubLogin can put it in the session.

The themes each assembled this with a nested template conditional, which is the sort of thing moving the authorize URL into Go was meant to stop. A template prints this value instead, so the URL's shape stays the server's business and adding to it later touches no theme.

func IsSelfHost

func IsSelfHost(refHost string, siteHosts ...string) bool

IsSelfHost reports whether refHost (from a Referer header) refers to this site, i.e. it matches one of the given site hosts after normalization. IP literals and localhost are always treated as self: an operator visiting their own server by IP is far more likely than an external site linking from a bare IP.

func RequestOrigin

func RequestOrigin(c *gin.Context) string

RequestOrigin is the scheme and host the client actually used, without a trailing slash. Unlike SiteURL it ignores the site_url setting: GitHub matches an OAuth redirect_uri against the callback registered for the app, so the origin has to be the one the visitor is on — which is what the login page used to send when it built the URL from window.location.

func SafeNext

func SafeNext(raw string) string

SafeNext reduces a requested post-login destination to a same-site path: it must start with a single "/" (so no "//host" or "/\host" scheme-relative URLs and no absolute URLs). Anything else becomes "/".

func UnescapeSlug

func UnescapeSlug(slug string) string

UnescapeSlug undoes every layer of URL escaping on a slug, so one that has been escaped more than once (%253A) comes back as plain text (:).

Types

type Backlink struct {
	SourcePostID uint `gorm:"primaryKey;index"`
	TargetPostID uint `gorm:"primaryKey;index"`
}

Backlink tracks which posts link to other posts internally

type Blog

type Blog struct {
	Version    string
	PageFilter PageFilter // optional filter set by plugin system
	// contains filtered or unexported fields
}

Blog API handles non-admin functions of the blog like listing posts, tags comments, etc.

func New

func New(db *gorm.DB, auth auth.IAuth, version string) Blog

New constructs a Blog API

func (*Blog) CommentToken

func (b *Blog) CommentToken(postID uint) string

CommentToken mints a comment-form token for postID issued now.

func (*Blog) CommentTokenAt

func (b *Blog) CommentTokenAt(postID uint, issued time.Time) string

CommentTokenAt mints a comment-form token for postID issued at the given time.

func (*Blog) CommentsRequireLogin

func (b *Blog) CommentsRequireLogin() bool

CommentsRequireLogin reports the comments_require_login setting. Login is required unless the setting exists and is explicitly "false", so a missing row (or a settings table that hasn't been seeded) fails closed.

func (b *Blog) ComputeBacklinks(post *Post)

ComputeBacklinks parses a post's content for internal links and upserts backlink records.

func (*Blog) CountComments

func (b *Blog) CountComments() int64

CountComments returns the number of comments across all posts.

func (*Blog) CountPages

func (b *Blog) CountPages() int64

CountPages returns the number of pages, enabled or not.

func (*Blog) CountPosts

func (b *Blog) CountPosts() (published, drafts int64)

CountPosts returns how many posts are published and how many are drafts.

func (*Blog) DynamicPage

func (b *Blog) DynamicPage(c *gin.Context, page *Page, subPath string)

DynamicPage renders the appropriate template for a page based on its PageType. subPath is the request path after the page's slug; it is only ever non-empty for plugin-owned pages (see NoRoute) and is passed through to the plugin.

func (b *Blog) GetBacklinks(postID uint) []Post

GetBacklinks returns posts that link TO the given post.

func (*Blog) GetComments

func (b *Blog) GetComments(offset, limit int) ([]Comment, int64)

GetComments returns a page of comments across all posts, newest first, along with the total number of comments.

func (b *Blog) GetExternalBacklinks(postID uint) []ExternalBacklink

GetExternalBacklinks returns external referers for a given post.

func (*Blog) GetLatest

func (b *Blog) GetLatest() Post

func (*Blog) GetNavPages

func (b *Blog) GetNavPages() []Page

GetNavPages returns enabled pages that should show in the navigation, ordered by nav_order. Pages owned by disabled plugins are filtered out.

func (b *Blog) GetOutboundLinks(postID uint) []Post

GetOutboundLinks returns posts that the given post links TO.

func (*Blog) GetPageBySlug

func (b *Blog) GetPageBySlug(slug string) (*Page, error)

GetPageBySlug returns a page by its slug. Returns error if not found or disabled.

func (*Blog) GetPost

func (b *Blog) GetPost(c *gin.Context)

GetPost returns a post with yyyy/mm/dd/slug

func (*Blog) GetPostObject

func (b *Blog) GetPostObject(c *gin.Context) (*Post, error)

func (*Blog) GetPostTypeBySlug

func (b *Blog) GetPostTypeBySlug(slug string) (*PostType, error)

GetPostTypeBySlug returns a post type by its slug

func (*Blog) GetPostTypes

func (b *Blog) GetPostTypes() []PostType

GetPostTypes returns all post types

func (*Blog) GetPosts

func (b *Blog) GetPosts(drafts bool) []Post

Generic Functions (not JSON or HTML)

func (*Blog) GetPostsByIDs

func (b *Blog) GetPostsByIDs(ids []uint) map[uint]Post

GetPostsByIDs returns a map of post ID to Post for the given IDs

func (*Blog) GetPostsByType

func (b *Blog) GetPostsByType(postTypeID uint, drafts bool) []Post

GetPostsByType returns posts filtered by post type

func (*Blog) GetRecentComments

func (b *Blog) GetRecentComments(limit int) []Comment

GetRecentComments returns the most recent comments across all posts

func (*Blog) GetRecentPosts

func (b *Blog) GetRecentPosts(n int) []Post

GetRecentPosts returns the newest n posts, drafts included, for the admin dashboard.

func (*Blog) GetSettings

func (b *Blog) GetSettings() map[string]Setting

func (*Blog) GithubLogin

func (b *Blog) GithubLogin(c *gin.Context)

GithubLogin serves /login/github: it starts the OAuth flow rather than having each theme assemble the authorize URL in an inline script, where the escaping was wrong and had to be fixed in every theme separately (#631).

The state it mints, and where the visitor was heading, are kept in the session for GithubCallback to check when GitHub returns (#637).

func (*Blog) Home

func (b *Blog) Home(c *gin.Context)

Home returns html of the home page using the template if people want to have different stuff show on the home page they probably need to modify this function

func (*Blog) IsDbNil

func (b *Blog) IsDbNil() bool

func (*Blog) ListPosts

func (b *Blog) ListPosts(c *gin.Context)

ListPosts lists all blog posts

func (*Blog) Login

func (b *Blog) Login(c *gin.Context)

Login to the blog

func (*Blog) Logout

func (b *Blog) Logout(c *gin.Context)

func (*Blog) NoRoute

func (b *Blog) NoRoute(c *gin.Context)

NoRoute returns a custom 404 page

func (*Blog) Post

func (b *Blog) Post(c *gin.Context)

Post is the page for all individual posts

func (*Blog) PostTypeListing

func (b *Blog) PostTypeListing(c *gin.Context, pt *PostType)

PostTypeListing renders the listing page for a post type

func (*Blog) RSS

func (b *Blog) RSS(c *gin.Context)

RSS serves /rss.xml: an RSS 2.0 feed of the newest published posts, with absolute links under SiteURL and each post rendered to HTML on the server.

func (*Blog) Render

func (b *Blog) Render(c *gin.Context, code int, templateName string, data gin.H)

Render wraps c.HTML with plugin data injection. If a plugin registry is available on the Gin context, it enriches the template data with plugin_head_html, plugin_footer_html, and plugins data. Render executes templateName with data, after adding what the shared <head> needs on every page — site_url (resolved, see SiteURL) and canonical_url (site_url plus canonical_path, a post's permalink, or the request path without its query) — and the enabled plugins' template data. A handler that has already set a key keeps it.

func (*Blog) RequireAdminPage

func (b *Blog) RequireAdminPage(c *gin.Context) bool

Logout of the blog RequireAdminPage guards an admin *page* — one a browser navigates to, as opposed to the JSON API, which answers 401 so the admin scripts can show the error. It reports whether the handler may continue; when it does not, the response is already written:

  • nobody signed in: a redirect to the login page, told where to return to (login carries "next" through the GitHub round trip and the email code form alike);
  • signed in but not an admin: 403 and a page saying so. Sending them to a login they have already completed would be a loop.

func (*Blog) RobotsTxt

func (b *Blog) RobotsTxt(c *gin.Context)

RobotsTxt serves /robots.txt: crawlers may index everything but the admin, the wizard, the JSON API, sign-in and search result pages, and are pointed at the sitemap.

func (*Blog) Search

func (b *Blog) Search(c *gin.Context)

Search handles the search page. "results" is the one list a theme renders (through the shared _search_results partial): matching posts first, then whatever enabled plugins contribute (plugin.Searcher). "posts", "plugin_results" and "result_count" remain for themes that still render the list themselves.

func (*Blog) SearchPosts

func (b *Blog) SearchPosts(query string) []Post

func (*Blog) SettingValue

func (b *Blog) SettingValue(key, def string) string

SettingValue returns one site setting, or def when the database is not ready, the setting is missing, or it is empty.

func (*Blog) SiteURL

func (b *Blog) SiteURL(c *gin.Context) string

SiteURL is the site's public origin without a trailing slash: the site_url setting, or — when it is unset — the requesting scheme and host, honouring X-Forwarded-Proto from a reverse proxy.

func (*Blog) Sitemap

func (b *Blog) Sitemap(c *gin.Context)

Sitemap serves /sitemap.xml: the home page, post type listings, every enabled page (nav or not), published posts, and whatever URLs enabled plugins list for the pages under their slugs. Tag pages are left out: they only re-list posts that are already here. Every loc is under SiteURL and appears once. lastmod is the date the content last changed — for the home page or a listing, that of its newest post — and is left out when that is not known, never filled in with the time of the request.

func (*Blog) SubmitComment

func (b *Blog) SubmitComment(c *gin.Context)

SubmitComment handles POST /comments form submissions

func (*Blog) Tag

func (b *Blog) Tag(c *gin.Context)

Tag lists all posts with a given tag

func (*Blog) TrackReferer

func (b *Blog) TrackReferer(c *gin.Context, postID uint)

TrackReferer records external referers for a post.

func (*Blog) UpdateDb

func (b *Blog) UpdateDb(db *gorm.DB)

type Comment

type Comment struct {
	ID        uint      `gorm:"primaryKey" json:"id"`
	CreatedAt time.Time `json:"created_at"`
	PostID    uint      `json:"post_id" gorm:"index;not null"`
	Name      string    `json:"name"`
	Email     string    `json:"email"`
	Content   string    `sql:"type:text;" json:"content"`
	IPAddress string    `json:"-"`
	// UserID is the BlogUser who posted the comment while logged in; nil for
	// comments left anonymously (before login was required, or with the
	// comments_require_login setting off).
	UserID *int `json:"user_id" gorm:"index"`
}

Comment represents a user comment on a blog post

func (Comment) HTML

func (c Comment) HTML() template.HTML

HTML is the comment rendered to HTML on the server. Commenters are anonymous, so the result is sanitised: ordinary formatting survives, raw HTML, scripts and javascript: URLs do not.

type ExternalBacklink struct {
	ID        uint      `gorm:"primaryKey"`
	PostID    uint      `gorm:"uniqueIndex:idx_post_referer" json:"post_id"`
	Referer   string    `gorm:"uniqueIndex:idx_post_referer,length:255;type:text" json:"referer"` // length: see Page.Slug
	FirstSeen time.Time `json:"first_seen"`
	LastSeen  time.Time `json:"last_seen"`
	HitCount  int       `json:"hit_count"`
}

ExternalBacklink tracks external sites linking to blog posts via HTTP Referer

type Page

type Page struct {
	ID         uint       `gorm:"primaryKey" json:"id"`
	CreatedAt  time.Time  `json:"created_at"`
	UpdatedAt  time.Time  `json:"updated_at"`
	DeletedAt  *time.Time `sql:"index" json:"deleted_at,omitempty"`
	Title      string     `json:"title"`
	Slug       string     `gorm:"uniqueIndex:,length:191" json:"slug"` // length: MySQL cannot index a text column without one; other databases ignore it
	Content    string     `sql:"type:text;" json:"content"`
	HeroURL    string     `json:"hero_url"`
	HeroType   string     `json:"hero_type"` // "image" or "video"
	PageType   string     `json:"page_type"` // "writing", "about", "custom", "tags", "archives", or plugin-defined (e.g. "research")
	ShowInNav  bool       `json:"show_in_nav"`
	NavOrder   int        `json:"nav_order"`
	Enabled    bool       `json:"enabled"`
	ScholarID  string     `json:"scholar_id,omitempty"` // deprecated: use scholar plugin settings instead
	PostTypeID *uint      `json:"post_type_id,omitempty"`
}

Page represents a configurable site page (nav items, content pages, etc.)

func (Page) HTML

func (p Page) HTML() template.HTML

HTML is the page's content rendered to HTML on the server, with the same policy as a post: its author is an admin.

func (Page) HasHero

func (p Page) HasHero() bool

HasHero returns true if a hero URL is configured

func (Page) IsVideo

func (p Page) IsVideo() bool

IsVideo returns true if the hero media is a video

func (p Page) PagePermalink() string

PagePermalink returns the URL path for this page

type PageFilter

type PageFilter func(page Page) bool

PageFilter is a function that decides whether a page should be shown. Used to filter out pages owned by disabled plugins.

func PluginPageFilter

func PluginPageFilter(reg interface {
	HasPageType(string) bool
	IsPageTypeEnabled(string) bool
}) PageFilter

PluginPageFilter hides pages whose type belongs to a disabled plugin or to no plugin at all (e.g. a plugin that was uninstalled or moved to the directory); such pages come back as soon as a plugin claims the type.

type Post

type Post struct {
	ID         uint      `gorm:"primaryKey"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time
	DeletedAt  *time.Time `sql:"index"`
	Title      string     `json:"title"`
	Slug       string     `json:"slug"`
	Content    string     `sql:"type:text;" json:"content"`
	Tags       []Tag      `gorm:"many2many:post_tags" json:"tags"`
	Draft      bool       `json:"draft"`
	PostTypeID uint       `json:"post_type_id"`
	PostType   PostType   `json:"post_type" gorm:"foreignKey:PostTypeID"`
}

Post defines blog posts

func (p Post) Adminlink() string
func (p Post) ExternalLinks() []string

ExternalLinks extracts external URLs from the post's markdown content

func (Post) ExtractImages

func (p Post) ExtractImages() []string

func (Post) HTML

func (p Post) HTML() template.HTML

HTML is the post's content rendered to HTML on the server: what the page, the feed and the editor preview all show.

func (Post) HTMLPreview

func (p Post) HTMLPreview(length int) template.HTML

HTMLPreview strips markdown syntax but preserves links as HTML hyperlinks

func (Post) ImageURLs

func (p Post) ImageURLs(site string) []string

ImageURLs is ExtractImages with every relative URL made absolute under site (the resolved site_url), for Open Graph and structured data.

func (p Post) Permalink() string

Permalink returns the link to the post relative to root

func (Post) PlainTextPreview

func (p Post) PlainTextPreview(length int) string

PlainTextPreview strips markdown syntax and returns clean plain text for previews

func (Post) PreviewContent

func (p Post) PreviewContent(length int) string

PreviewContent gets a shortened version of the content for showing a preview https://stackoverflow.com/questions/23466497/how-to-truncate-a-string-in-a-golang-template

type PostRevision

type PostRevision struct {
	ID         uint      `gorm:"primaryKey" json:"id"`
	CreatedAt  time.Time `json:"created_at"`
	PostID     uint      `json:"post_id" gorm:"index;not null"`
	Title      string    `json:"title"`
	Slug       string    `json:"slug"`
	Content    string    `gorm:"type:text" json:"content"`
	Draft      bool      `json:"draft"`
	PostTypeID uint      `json:"post_type_id"`
}

PostRevision stores a snapshot of a post's content before each edit, allowing users to view previous versions and roll back to them.

type PostType

type PostType struct {
	ID          uint       `gorm:"primaryKey" json:"id"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
	DeletedAt   *time.Time `sql:"index" json:"deleted_at,omitempty"`
	Name        string     `json:"name"`
	Slug        string     `gorm:"uniqueIndex:,length:191" json:"slug"` // length: see Page.Slug
	Description string     `sql:"type:text;" json:"description"`
}

PostType defines different kinds of content (e.g. Posts, Notes, Links)

func (pt PostType) Permalink() string

Permalink returns the URL path for this post type's listing page

type SearchHit

type SearchHit struct {
	Title   string
	URL     string
	Summary string
	Kind    string // short label shown next to the result, e.g. "Plugin"
}

SearchHit is one hit a plugin contributes to the search page (see plugin.Searcher; plugin.SearchResult is an alias of this type). Summary is plain text; it is escaped when it becomes a SearchResult.

type SearchResult

type SearchResult struct {
	Title   string
	URL     string
	Summary template.HTML
	Kind    string
	Date    time.Time
	Tags    []Tag
}

SearchResult is one entry on the search page — a post or a plugin hit — as the shared _search_results partial renders it. Date and Tags are set for posts only; Kind is "" for posts.

type Setting

type Setting struct {
	Key  string `gorm:"primaryKey" json:"key"`
	Type string `json:"type"` // indicates whether it's a file, string, number, etc - mostly for the front-end of the
	// admin panel to know how to render the input field
	Value string `json:"value"`
}

type SitemapURL

type SitemapURL struct {
	Loc     string
	LastMod time.Time
}

SitemapURL is one entry a plugin adds to the sitemap (see plugin.Sitemapper): a site-relative path and, when known, its last change.

type Tag

type Tag struct {
	Name  string `gorm:"primaryKey" json:"name"`
	Posts []Post `gorm:"many2many:post_tags"`
}

Tag is used to collect Posts with similar topics

func (t Tag) Permalink() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL