1 回答
TA贡献1856条经验 获得超11个赞
您可以使用-ldflags传递配置的 min golang 构建并在 init() 时间检查运行时是否与指定版本匹配。
package main
import "runtime"
// go run -ldflags "-X main.minGoVersion=go1.5.1" main.go
// from http://stackoverflow.com/questions/18409373/how-to-compare-two-version-number-strings-in-golang
func VersionOrdinal(version string) string {
// ISO/IEC 14651:2011
const maxByte = 1<<8 - 1
vo := make([]byte, 0, len(version)+8)
j := -1
for i := 0; i < len(version); i++ {
b := version[i]
if '0' > b || b > '9' {
vo = append(vo, b)
j = -1
continue
}
if j == -1 {
vo = append(vo, 0x00)
j = len(vo) - 1
}
if vo[j] == 1 && vo[j+1] == '0' {
vo[j+1] = b
continue
}
if vo[j]+1 > maxByte {
panic("VersionOrdinal: invalid version")
}
vo = append(vo, b)
vo[j]++
}
return string(vo)
}
var minGoVersion string
func init() {
if minGoVersion == "" {
panic("please pass -ldflags \"-X main.minGoVersion=<version string> flag\"")
}
current := VersionOrdinal(runtime.Version())
desired := VersionOrdinal(minGoVersion)
if current < desired {
panic("unsupported golang runtime " + current + " < " + desired)
}
}
func main() {
}
- 1 回答
- 0 关注
- 153 浏览
添加回答
举报