An alternative to Pastebin or GitHub Gists, built in Go
Snippetbox is a simple web application that lets you store and share snippets of text or code. It's designed as a practical project to learn and demonstrate idiomatic Go web development, including best practices for project structure, secure session management, database interaction, and HTML templating.
- Create, view, and share code/text snippets.
- List latest public snippets.
- Expiry time for each snippet.
- Simple, clean web interface.
- Secure session management using cookies.
- MySQL database backend.
- Templated HTML views.
- Static asset embedding using Go's
embed
package.
snippetbox/
├── cmd/
│ └── web/ # Main web server application
├── internal/
│ └── models/ # Database models (Snippet, User, etc.)
├── ui/
│ ├── html/ # HTML templates
│ ├── static/ # Static assets (CSS, JS, images)
│ └── efs.go # Asset embedding
├── go.mod
├── go.sum
└── .gitignore
- cmd/web/: Entry point with
main.go
configuring the server, routes, and dependencies. - internal/models/: Contains data access logic for snippets and users.
- ui/html/: HTML templates for rendering pages.
- ui/static/: CSS, JavaScript, and images for the frontend.
- ui/efs.go: Uses Go's
embed
to package templates and static files into the binary.
- Go 1.18 or newer
- MySQL database
git clone https://github.com/hawkaii/snippetbox.git
cd snippetbox
go mod tidy
- Create a MySQL database and user.
- Use the following schema to create the
snippets
table:
CREATE TABLE snippets (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
created DATETIME NOT NULL,
expires DATETIME NOT NULL
);
- Update the
dsn
(data source name) incmd/web/main.go
or run with the correct DB credentials:-dsn "user:password@/snippetbox?parseTime=true"
go run ./cmd/web
By default, the app runs on https://localhost:4000
Note: TLS certificates (cert.pem
and key.pem
) are required for HTTPS. You can generate self-signed certs for local development.
Open your browser at https://localhost:4000