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)
  4. app.OnStop("hook.name", func(ctx context.Context, app *bunapp.App) error {
  5. log.Println("stopping...")
  6. })
  7. return nil
  8. })
  9. }

Migrations

The kit also provides a CLI to manage migrations:

  1. go run cmd/bun/main.go
  2. NAME:
  3. bun db - manage database migrations
  4. USAGE:
  5. bun db [global options] command [command options] [arguments...]
  6. COMMANDS:
  7. init create migration tables
  8. migrate migrate database
  9. rollback rollback the last migration group
  10. unlock unlock migrations
  11. create_go create a Go migration
  12. create_sql create a SQL migration
  13. help, h Shows a list of commands or help for one command
  14. GLOBAL OPTIONS:
  15. --help, -h show help (default: false)