Bun Starter Kit

Bun starter kitStarter kit - 图1open in new window consists of:

You can also check bun-realworld-appStarter kit - 图5open 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.go contains App struct that maintains the app state. For example, App.DB() creates *bun.DB.
  • bunapp/config.go contains the Config struct to parse YAML configuration, for example, bunapp/embed/config/dev.yaml.
  • cmd/bun/migrations contains database migrations.
  • example/init.go is 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)