导入特定包装

I'm trying to solve a dependency problem : let's say I want to keep the code in my main.go totally decoupled from my database, I created 2 packages for that : dummy & postgres.

/app/
-- main.go

/dummy/
-- dummy.go

/postgres/
-- postgres.go

Everything is working fine, I just have to select in my main.go which package I would like to import to get a behavior or another... but is there a way to choose that when building main.go ?

If there's a more idiomatic way to achieve this, I'm of course very interested !

You can utilize the Go conditional build via build tags and target your compilation of main.go.

Refer this article and put your thoughts into action.

For Example:

Directory structure

build-tags
├── build-tags
├── dummy
│   └── dummy.go
├── main_dummy.go
├── main_postgres.go
└── postgres
    └── postgres.go

Sample implementation:

dummy/dummy.go

package dummy

import "fmt"

func PrintName() {
    fmt.Println("My name is dummy package")
}

postgres/postgres.go

package postgres

import "fmt"

func PrintName() {
    fmt.Println("My name is postgres package")
}

main_dummy.go

// +build dummy

package main

import "build-tags/dummy"

func main() {
    dummy.PrintName()
}

postgres.go

// +build postgres

package main

import "build-tags/postgres"

func main() {
    postgres.PrintName()
}

Now let's build targeting dummy tag, same way you can do for postgres tag.

go build --tags="dummy"

# run the program
./build-tags

My name is dummy package