Static site generators are powerful tools that simplify the creation of lightweight, fast, and scalable websites. Whether you're building blogs, documentation, or small business sites, they transform content written in Markdown into efficient, static HTML files.
In this guide, we’ll create a Static Site Generator (SSG) in Go, a programming language renowned for its performance, simplicity, and concurrency. We’ll build a CLI tool that takes Markdown files as input, processes them using a predefined HTML template, and outputs beautiful, static HTML pages.
Why Build This?
A static site generator can serve several practical purposes:
- Documentation Sites: Generate fast-loading sites for technical documentation.
- Blogs: Write your content in Markdown and deploy it effortlessly.
- Prototyping: Quickly spin up static sites for small projects or showcases.
Why use Go for this project?
- Speed: Go compiles to native machine code, making tools like this blazingly fast.
- Concurrency: Go makes it easy to process multiple files simultaneously.
- Simplicity: Go’s syntax is minimal, and building CLI tools is straightforward.
I had a great fun time building this project :)
Project Setup
Before diving into the code, let’s outline the structure of the project:
static-site-generator/ ├── cmd/ │ └── ssg/ │ └── main.go # Entry point ├── internal/ │ ├── generator/ │ │ └── html.go # HTML generation logic │ ├── parser/ │ │ ├── frontmatter.go # YAML frontmatter parsing │ │ └── markdown.go # Markdown processing │ └── watcher/ │ └── watcher.go # File change detection ├── templates/ │ └── default.html # HTML template ├── content/ # Markdown files └── output/
If you want to build from scratch, run this command to initialize a Go module for the project
go mod init
Key Features:
Convert Markdown to HTML ?
YAML frontmatter for metadata parsing
HTML templates for customizable output
Real-time file change detection with a watcher ?
Building the Project
1. Clone the Repository
Before starting, clone the repository to your local machine:
git clone https://github.com/Tabintel/static-site-generator.git cd static-site-generator
Tabintel
/
static-site-generator
Static Site Generator
A fast and simple static site generator written in Go.
This will give you all the starter files and project structure needed to build and run the SSG.
2. Markdown Parser
The Markdown parser handles converting .md files into HTML content. It also enables extended features like automatic heading IDs.
internal/parser/markdown.go
static-site-generator/ ├── cmd/ │ └── ssg/ │ └── main.go # Entry point ├── internal/ │ ├── generator/ │ │ └── html.go # HTML generation logic │ ├── parser/ │ │ ├── frontmatter.go # YAML frontmatter parsing │ │ └── markdown.go # Markdown processing │ └── watcher/ │ └── watcher.go # File change detection ├── templates/ │ └── default.html # HTML template ├── content/ # Markdown files └── output/
?Converts Markdown content into HTML format with extended feature support.
3. Frontmatter Parser
The frontmatter parser extracts metadata like title, date, tags, and description from Markdown files.
internal/parser/frontmatter.go
go mod init
? Extracts and returns metadata along with the content of the Markdown file.
4. HTML Generator
The HTML generator uses Go’s html/template package to create static HTML pages based on a template.
internal/generator/html.go
git clone https://github.com/Tabintel/static-site-generator.git cd static-site-generator
? Generates HTML files from templates and parsed Markdown content.
5. File Watcher
Our watcher monitors the content/ directory for changes and triggers rebuilds automatically.
This is built using https://github.com/fsnotify/fsnotify
internal/watcher/watcher.go
package parser import ( "github.com/gomarkdown/markdown" "github.com/gomarkdown/markdown/parser" ) type MarkdownContent struct { Content string Title string Date string Tags []string HTMLOutput string } func ParseMarkdown(content []byte) *MarkdownContent { extensions := parser.CommonExtensions | parser.AutoHeadingIDs parser := parser.NewWithExtensions(extensions) html := markdown.ToHTML(content, parser, nil) return &MarkdownContent{ Content: string(content), HTMLOutput: string(html), } }
? Detects file changes and automates the regeneration of static files.
6. Main Application
The entry point ties all components together and provides CLI options for customization.
cmd/ssg/main.go
package parser import ( "bytes" "gopkg.in/yaml.v2" ) type Frontmatter struct { Title string `yaml:"title"` Date string `yaml:"date"` Tags []string `yaml:"tags"` Description string `yaml:"description"` } func ParseFrontmatter(content []byte) (*Frontmatter, []byte, error) { parts := bytes.Split(content, []byte("---")) if len(parts) < 3 { return nil, content, nil } var meta Frontmatter err := yaml.Unmarshal(parts[1], &meta) if err != nil { return nil, content, err } return &meta, bytes.Join(parts[2:], []byte("---")), nil }
Usage
Before you run the app, create a markdown file using .md and save it in the content directory
Then run the generator:
package generator import ( "html/template" "os" "path/filepath" ) type Generator struct { TemplateDir string OutputDir string } func NewGenerator(templateDir, outputDir string) *Generator { return &Generator{ TemplateDir: templateDir, OutputDir: outputDir, } } func (g *Generator) Generate(data interface{}, outputFile string) error { if err := os.MkdirAll(g.OutputDir, 0755); err != nil { return err } tmpl, err := template.ParseFiles(filepath.Join(g.TemplateDir, "default.html")) if err != nil { return err } out, err := os.Create(filepath.Join(g.OutputDir, outputFile)) if err != nil { return err } defer out.Close() return tmpl.Execute(out, data) }
It converts the markdown file to an HTML file and saves it in the output directory
As you can see, it adds formatting to make it visually appealing :)
Watch for Changes
Enable the watcher:
package watcher import ( "fmt" "github.com/fsnotify/fsnotify" "log" "os" "path/filepath" ) type ProcessFn func() error func Watch(dir string, process ProcessFn) error { watcher, err := fsnotify.NewWatcher() if err != nil { return err } defer watcher.Close() done := make(chan bool) go func() { for { select { case event, ok := <-watcher.Events: if !ok { return } if event.Op&fsnotify.Write == fsnotify.Write { fmt.Printf("Modified file: %s\n", event.Name) if err := process(); err != nil { log.Printf("Error processing: %v\n", err) } } case err, ok := <-watcher.Errors: if !ok { return } log.Printf("Error: %v\n", err) } } }() err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { return watcher.Add(path) } return nil }) if err != nil { return err } <-done return nil }
And that's It!
This SSG converts markdown to clean HTML, watches for changes, and keeps your content organized. Drop a comment if you build something with it - I'd love to see what you create!
Found this helpful? You can buy me a coffee to support more Go tutorials! ?
Happy coding! ?
Tabintel
/
static-site-generator
Static Site Generator
A fast and simple static site generator written in Go.
The above is the detailed content of How to Create a Static Site Generator with Go. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go compiles the program into a standalone binary by default, the main reason is static linking. 1. Simpler deployment: no additional installation of dependency libraries, can be run directly across Linux distributions; 2. Larger binary size: Including all dependencies causes file size to increase, but can be optimized through building flags or compression tools; 3. Higher predictability and security: avoid risks brought about by changes in external library versions and enhance stability; 4. Limited operation flexibility: cannot hot update of shared libraries, and recompile and deployment are required to fix dependency vulnerabilities. These features make Go suitable for CLI tools, microservices and other scenarios, but trade-offs are needed in environments where storage is restricted or relies on centralized management.

Goensuresmemorysafetywithoutmanualmanagementthroughautomaticgarbagecollection,nopointerarithmetic,safeconcurrency,andruntimechecks.First,Go’sgarbagecollectorautomaticallyreclaimsunusedmemory,preventingleaksanddanglingpointers.Second,itdisallowspointe

To create a buffer channel in Go, just specify the capacity parameters in the make function. The buffer channel allows the sending operation to temporarily store data when there is no receiver, as long as the specified capacity is not exceeded. For example, ch:=make(chanint,10) creates a buffer channel that can store up to 10 integer values; unlike unbuffered channels, data will not be blocked immediately when sending, but the data will be temporarily stored in the buffer until it is taken away by the receiver; when using it, please note: 1. The capacity setting should be reasonable to avoid memory waste or frequent blocking; 2. The buffer needs to prevent memory problems from being accumulated indefinitely in the buffer; 3. The signal can be passed by the chanstruct{} type to save resources; common scenarios include controlling the number of concurrency, producer-consumer models and differentiation

Go is ideal for system programming because it combines the performance of compiled languages ??such as C with the ease of use and security of modern languages. 1. In terms of file and directory operations, Go's os package supports creation, deletion, renaming and checking whether files and directories exist. Use os.ReadFile to read the entire file in one line of code, which is suitable for writing backup scripts or log processing tools; 2. In terms of process management, the exec.Command function of the os/exec package can execute external commands, capture output, set environment variables, redirect input and output flows, and control process life cycles, which are suitable for automation tools and deployment scripts; 3. In terms of network and concurrency, the net package supports TCP/UDP programming, DNS query and original sets.

In Go language, calling a structure method requires first defining the structure and the method that binds the receiver, and accessing it using a point number. After defining the structure Rectangle, the method can be declared through the value receiver or the pointer receiver; 1. Use the value receiver such as func(rRectangle)Area()int and directly call it through rect.Area(); 2. If you need to modify the structure, use the pointer receiver such as func(r*Rectangle)SetWidth(...), and Go will automatically handle the conversion of pointers and values; 3. When embedding the structure, the method of embedded structure will be improved, and it can be called directly through the outer structure; 4. Go does not need to force use getter/setter,

In Go, an interface is a type that defines behavior without specifying implementation. An interface consists of method signatures, and any type that implements these methods automatically satisfy the interface. For example, if you define a Speaker interface that contains the Speak() method, all types that implement the method can be considered Speaker. Interfaces are suitable for writing common functions, abstract implementation details, and using mock objects in testing. Defining an interface uses the interface keyword and lists method signatures, without explicitly declaring the type to implement the interface. Common use cases include logs, formatting, abstractions of different databases or services, and notification systems. For example, both Dog and Robot types can implement Speak methods and pass them to the same Anno

In Go language, string operations are mainly implemented through strings package and built-in functions. 1.strings.Contains() is used to determine whether a string contains a substring and returns a Boolean value; 2.strings.Index() can find the location where the substring appears for the first time, and if it does not exist, it returns -1; 3.strings.ReplaceAll() can replace all matching substrings, and can also control the number of replacements through strings.Replace(); 4.len() function is used to obtain the length of the bytes of the string, but when processing Unicode, you need to pay attention to the difference between characters and bytes. These functions are often used in scenarios such as data filtering, text parsing, and string processing.

TointegrateGolangserviceswithexistingPythoninfrastructure,useRESTAPIsorgRPCforinter-servicecommunication,allowingGoandPythonappstointeractseamlesslythroughstandardizedprotocols.1.UseRESTAPIs(viaframeworkslikeGininGoandFlaskinPython)orgRPC(withProtoco
