[Golang] Code snippets - Semver comparison

To make the project backward-compatible, a common util function for comparing the semantic version is indispensable. Here is a Golang solution implemented by leveraging go-semver package. package utils import "github.com/coreos/go-semver/semver" // CompareSemanticVersion compares two string written in semver format // return 0 indicates that the first version equals to the second version // return 1 indicates that the first version is greater than the second version // return -1 indicates that the first version is less than the second version func CompareSemanticVersion(current, last string) int { if current == last { return 0 } currentVersion := semver.New(current) lastVersion := semver.New(last) if currentVersion.LessThan(*lastVersion) { return -1 } return 1 } The unit test: ...

[Golang] Write a simple CLI program

I will show a simple example in this post. Let’s say the program called cli-example. package main import ( "flag" "fmt" "os" ) func main() { command := os.Args[1] os.Args = append(os.Args[:1], os.Args[2:]...) switch command { case "version": fmt.Println("1.1.1") } } The 1st argument will always be the binary name, so the command starts from the 2nd argument. If your app also needs the subcommand, then extract it from the 3rd argument, like docker image ls. ...

DigitalOcean Referral Badge
Sign up to get $200, 60-day account credit !