Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 39 ยท Projects and Practice

Project: A Blog with Server-Rendered Pages

Build a blog with Gin and html/template: layouts, post list and detail pages, a create form with validation and flash messages, CSRF protection and a runnable stand-in.

The first two projects were JSON APIs. This one is a classic server-rendered website: a blog with a post list, a post page, and a form to write new posts, all as HTML produced on the server. It exercises templates, forms, validation errors shown next to the fields, the Post/Redirect/Get pattern, flash messages and CSRF protection.

Gin is not available in the in-page runner, so the Gin code is read-only. The runnable stand-in uses html/template and net/http with the same templates, form handling and redirects, so you see real HTML and real status codes.

Pages and routes

Route What it does
GET / List of published posts, newest first
GET /posts/:slug One post
GET /admin/posts/new Empty form (login required)
POST /admin/posts Validate, save, redirect to the new post

Public pages are safe to cache (no per-user content). The admin pages use a session cookie from Passwords and Sessions and must never be cached by shared caches.

Template files

A shared layout (see Layouts, Partials and Template Inheritance) plus one template per page:

TEXT
templates/
  layout.tmpl         # <html>, nav, flash message, {{ block "content" . }}
  index.tmpl          # list of posts
  post.tmpl           # one post
  form.tmpl           # new post form with errors
static/css/site.css

Because Gin's LoadHTMLGlob loads all files into one namespace, pages that define the same block name overwrite each other. The reliable fix is to build one template set per page and register them with a custom renderer, as explained in the layouts lesson. Gin's multitemplate extension package automates this.

Handlers

Go
func (h *Blog) Index(c *gin.Context) {
	var posts []model.Post
	h.db.Where("published = ?", true).Order("created_at DESC").Limit(20).Find(&posts)
	c.HTML(http.StatusOK, "index.tmpl", gin.H{"Posts": posts, "Flash": flash.Pop(c)})
}

func (h *Blog) Show(c *gin.Context) {
	var post model.Post
	if err := h.db.Where("slug = ? AND published = ?", c.Param("slug"), true).First(&post).Error; err != nil {
		c.HTML(http.StatusNotFound, "404.tmpl", nil)
		return
	}
	c.HTML(http.StatusOK, "post.tmpl", gin.H{"Post": post})
}

type postForm struct {
	Title string `form:"title" binding:"required,min=3,max=120"`
	Body  string `form:"body"  binding:"required,min=20"`
}

func (h *Blog) Create(c *gin.Context) {
	var form postForm
	if err := c.ShouldBind(&form); err != nil {
		// Re-render the form with a 422 and the user's input preserved
		c.HTML(http.StatusUnprocessableEntity, "form.tmpl", gin.H{
			"Form": form, "Errors": fieldErrors(err),
		})
		return
	}
	post := model.Post{Title: form.Title, Body: form.Body, Slug: slugify(form.Title), Published: true}
	if err := h.db.Create(&post).Error; err != nil {
		c.HTML(http.StatusInternalServerError, "500.tmpl", nil)
		return
	}
	flash.Set(c, "Post published.")
	c.Redirect(http.StatusSeeOther, "/posts/"+post.Slug) // 303: Post/Redirect/Get
}

Three patterns to notice:

  • Redisplay on error. The form comes back with status 422 and the user's input and per-field messages, so nobody retypes a long post.
  • Post/Redirect/Get. After a successful POST, redirect (303) to a GET page. If the user presses refresh, the browser repeats the harmless GET instead of re-submitting the form and creating a duplicate post.
  • Flash messages. "Post published." must survive exactly one redirect. Store it in the session (or a short-lived cookie) and remove it when displayed.

Slugs

A slug turns a title into a URL segment. It should be lowercase, ASCII, dash-separated, and unique. On a clash, append a number.

Go Generate unique slugs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Non-ASCII titles lose their letters in this simple version; real projects transliterate them or fall back to the ID. The database needs a unique index on the slug, as in the URL shortener project, because two writers can race.

A runnable blog

This stand-in renders HTML pages, validates the form, redisplays errors, and does Post/Redirect/Get with a one-time flash message. A tiny cookie-less flash is kept in memory to keep the example short; a real app stores it in the session.

Go Blog pages, form errors and redirect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In the "bad submit" output, the input value appears HTML-escaped (&lt;b&gt;short&lt;/b&gt;) and the messages sit next to their fields. After the good submit the server answers 303 with a Location header, and the flash appears once on the next page and not on the one after that.

CSRF and security

Browser forms that change data need CSRF protection: a hidden token in the form that must match one stored in the session (see CORS, CSRF and Security Headers and the gin-contrib/csrf middleware). Also remember:

  • Escape output: only html/template, never string concatenation. If posts allow Markdown, convert it and sanitize the HTML (for example with bluemonday) before marking it template.HTML.
  • Hash passwords with bcrypt or argon2 and rotate the session ID at login.
  • Send the security headers from the earlier lesson, and serve static/ through r.Static with cache headers (Static Files and Embedding Assets).
  • Limit title and body sizes (and request body size) on the server, not just in the form.

Extensions

  1. Pagination on the home page with ?page=2 links.
  2. Edit and delete posts with PUT/DELETE via a method-override hidden field.
  3. Comments with moderation, using a has many relationship.
  4. An RSS feed at /feed.xml using c.XML (Responses: JSON, XML and HTML).
  5. Embed templates and CSS with go:embed and ship one binary through the Docker image.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why redirect with 303 after a successful form POST?

    Post/Redirect/Get prevents duplicate submissions when the user refreshes.
  2. 2. Which status fits a form that failed validation and is shown again?

    422 (or 400) tells caches and clients the submission was rejected; keeping input avoids retyping.
  3. 3. How long should a flash message live?

    It is stored for the redirect and removed as soon as it is displayed.
  4. 4. Where must Markdown-generated HTML be sanitized?

    template.HTML tells the engine the content is already safe, so you must make it safe first.

Summary

  • A server-rendered Gin site is a layout plus per-page templates, handlers that build view data and forms bound with ShouldBind.
  • Redisplay forms with errors and preserved input; use Post/Redirect/Get and one-time flash messages.
  • Slugs need normalization and a unique index; escape all output and sanitize any HTML you mark safe.
  • Protect state-changing forms with CSRF tokens and sessions.

Next: Gin Practice: Exercises and Interview Questions