导入特定的包。

huangapple go评论77阅读模式
英文:

Import specific package

问题

我正在尝试解决一个依赖问题:假设我想让我的 main.go 代码与数据库完全解耦,我创建了两个包:dummy 和 postgres。

/app/
-- main.go

/dummy/
-- dummy.go

/postgres/
-- postgres.go

一切都正常工作,我只需要在 main.go 中选择要导入的包,以获取不同的行为... 但是在构建 main.go 时是否有一种选择的方法?

如果有更符合惯例的方法来实现这一点,我当然非常感兴趣!

英文:

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 !

答案1

得分: 0

你可以通过使用构建标签(build tags)来利用Go的条件构建,并针对main.go进行编译。

参考这篇文章(https://dave.cheney.net/2014/09/28/using-build-to-switch-between-debug-and-release),并付诸实践。

例如:

目录结构

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

示例实现:

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()
}

现在让我们构建并针对dummy标签进行目标编译,你也可以用同样的方式为postgres标签进行操作。

go build --tags="dummy"

# 运行程序
./build-tags

My name is dummy package
英文:

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

huangapple
  • 本文由 发表于 2017年6月25日 01:04:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/44738878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定