4

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
FiftiN
  • 740
  • 1
  • 7
  • 27

1 Answers1

6

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")
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Twyla
  • 84
  • 1