Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible from Go app to detect if CGo enabled?

Tags:

go

cgo

My Go app can work with MySQL, Postgres, and SQLite. At the first start, it asks what DB should be used.

SQLite works only with CGo. Depending on whether it is enabled or not, SQLite should be displayed in a list of supported databases.

Is it possible form Go app to detect if CGo enabled?

like image 706
FiftiN Avatar asked Jan 24 '23 14:01

FiftiN


1 Answers

Use build constraints to detect CGO. Add these two files to the package:

cgotrue.go:

// +build cgo

package yourPackageNameHere

const cgoEnabled = true

cgofalse.go:

// +build !cgo

package yourPackageNameHere

const cgoEnabled = false

Only one of the files is compiled. Examine the cgoEnabled const to determine of CGO is enabled.

Another option is to add the following to a file that's always compiled:

var drivers []string{ "MySQL", "Postgres"}

and this to a CGO only file:

// +build cgo

package yourPackageNameHere

func init() {
      drivers = append(drivers, "SQLite")
}
like image 83
Twyla Avatar answered Feb 11 '23 18:02

Twyla