Bun Starter Kit
Bun starter kit
open in new window consists of:
- bunrouter
open in new window is an exremely fast and flexible HTTP router. - bun
open in new window - Hooks to decouple and initialize the app.
- CLI to run migrations.
- example
open in new window package that shows how to load fixtures and test handlers.
You can also check bun-realworld-app
open in new window which is a JSON API built with Bun starter kit.
App structure
The starter kit has the following structure:
1. ├─ bunapp
2. │ └─ app.go
3. │ └─ config.go
4. │ └─ router.go
5. │ └─ start.go
6. │ └─ hook.go
7. │ └─ embed
8. │ └─ config
9. │ └─ dev.yaml
10. │ └─ test.yaml
11. ├─ cmd
12. │ └─ bun
13. │ └─ main.go
14. │ └─ migrations
15. │ └─ main.go
16. │ └─ 20210505110026_init.go
17. ├─ example
18. │ └─ init.go
19. │ └─ example_handler.go
20. │ └─ example_handler_test.go
21. ├─ .gitignore
22. └─ go.mod
The main entrypoints are:
bunapp/app.gocontainsAppstruct that maintains the app state. For example,App.DB()creates*bun.DB.bunapp/config.gocontains theConfigstruct to parse YAML configuration, for example,bunapp/embed/config/dev.yaml.cmd/bun/migrationscontains database migrations.example/init.gois the package entry point.
You should keep HTTP handlers and DB models in the same package, but split the app into logically isolated packages. Each package should have init.go file with the module initialization logic.
Starting the app
The kit provides convenience methods to start/stop the app:
1. func main() {
2. ctx, app, err := bunapp.Start(ctx, "service_name", "environment_name")
3. if err != nil {
4. panic(err)
5. }
6. defer app.Stop()
7. }
It also provides hooks to execute custom code on the app start/stop. You usually add hooks from the init function in your module’s init.go file.
1. func init() {
2. bunapp.OnStart("hook.name", func(ctx context.Context, app *bunapp.App) error {
3. app.Router().GET("/endpoint", handler)
5. app.OnStop("hook.name", func(ctx context.Context, app *bunapp.App) error {
6. log.Println("stopping...")
7. })
9. return nil
10. })
11. }
Migrations
The kit also provides a CLI to manage migrations:
1. go run cmd/bun/main.go
3. NAME:
4. bun db - manage database migrations
6. USAGE:
7. bun db [global options] command [command options] [arguments...]
9. COMMANDS:
10. init create migration tables
11. migrate migrate database
12. rollback rollback the last migration group
13. unlock unlock migrations
14. create_go create a Go migration
15. create_sql create a SQL migration
16. help, h Shows a list of commands or help for one command
18. GLOBAL OPTIONS:
19. --help, -h show help (default: false)
