在 Mac OS 上,我正在尝试构建以下文件以在 Linux 计算机上运行。
package main
import (
"context"
"database/sql"
_ "github.com/godror/godror"
)
func main() {
dsn := "user/password@host:port/sid"
// Open a connection to the Oracle database
db, err := sql.Open("godror", dsn)
if err != nil {
panic(err.Error())
}
defer db.Close()
// Test the database connection
ctx := context.Background()
err = db.PingContext(ctx)
if err != nil {
panic(err.Error())
}
query := "SELECT * FROM table"
rows, err := db.QueryContext(ctx, query)
if err != nil {
panic(err.Error())
}
defer rows.Close()
if err := rows.Err(); err != nil {
panic(err.Error())
}
}
我使用以下命令来构建:
env GOOS=linux GOARCH=amd64 go build db.go
错误:
# github.com/godror/godror
../../../../pkg/mod/github.com/godror/[email protected]/orahlp.go:530:19: undefined: VersionInfo
../../../../pkg/mod/github.com/godror/[email protected]/orahlp.go:531:19: undefined: VersionInfo
../../../../pkg/mod/github.com/godror/[email protected]/orahlp.go:532:10: undefined: StartupMode
../../../../pkg/mod/github.com/godror/[email protected]/orahlp.go:533:11: undefined: ShutdownMode
../../../../pkg/mod/github.com/godror/[email protected]/orahlp.go:535:31: undefined: Event
../../../../pkg/mod/github.com/godror/[email protected]/orahlp.go:535:42: undefined: SubscriptionOption
../../../../pkg/mod/github.com/godror/[email protected]/orahlp.go:535:64: undefined: Subscription
../../../../pkg/mod/github.com/godror/[email protected]/orahlp.go:536:31: undefined: ObjectType
../../../../pkg/mod/github.com/godror/[email protected]/orahlp.go:537:59: undefined: Data
../../../../pkg/mod/github.com/godror/[email protected]/orahlp.go:538:28: undefined: DirectLob
../../../../pkg/mod/github.com/godror/[email protected]/orahlp.go:538:28: too many errors
我能够针对 Mac OS 进行构建,但针对 Linux 进行构建时遇到问题。你能帮我解决这些错误吗?
此交叉编译错误是由于
github.com/godror/godror
包使用了 CGO 造成的。要编译应用程序,您需要有效的 gcc 安装和 CGO_ENABLED=1,如软件包的 readme 中所述。
您可以尝试使用 docker 编译 linux/amd64。
示例:
DOCKER_DEFAULT_PLATFORM=linux/amd64 docker run --rm -v "$PWD":/app -w /app golang:1.21 go build -v db.go
这将在 Docker 容器中构建应用程序并将可执行文件保存在当前目录中。