Skip to content

[Question] Since main.go is generated, where should initialization logic be performed? i.e. setting up a database #146

Answered by matthewmueller
donovanrost asked this question in Q&A
Discussion options

You must be logged in to vote

Hey @donovanrost! The automatic dependency injection should help you with initializing your dependencies (like a database) on boot. The nice thing about this is that you will (soon) be able to do this with other entrypoints like tests so there's much less initialization boilerplate.

I wrote an example in this comment that I think is relevant here.

Create an env/env.go file:

package env

import "github.com/caarlos0/env"

// Load the environment
func Load() (*Env, error) {
  var e Env
  if err := env.Parse(&env); err != nil {
    return err
  }
  return &e, nil
}


type Env struct {
  DatabaseURL string `env:DATABASE_URL`
}

Then in a db/db.go file:

package db

import "app.com/env"
import "g…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@matthewmueller
Comment options

Answer selected by matthewmueller
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #145 on June 20, 2022 23:12.