Best Gauge code snippet using main.getGOOS
make.go
Source:make.go  
...68	bytes, err := cmd.Output()69	return strings.TrimSpace(fmt.Sprintf("%s", bytes)), err70}71func signExecutable(exeFilePath string, certFilePath string, certFilePwd string) {72	if getGOOS() == windows {73		if certFilePath != "" && certFilePwd != "" {74			log.Printf("Signing: %s", exeFilePath)75			runProcess("signtool", "sign", "/f", certFilePath, "/p", certFilePwd, exeFilePath)76		} else {77			log.Printf("No certificate file passed. Executable won't be signed.")78		}79	}80}81var buildMetadata string82func getBuildVersion() string {83	if buildMetadata != "" {84		return fmt.Sprintf("%s.%s", version.CurrentGaugeVersion.String(), buildMetadata)85	}86	return version.CurrentGaugeVersion.String()87}88func compileGauge() {89	executablePath := getGaugeExecutablePath(gauge)90	runProcess("go", "build", "-ldflags", "-X github.com/getgauge/gauge/version.BuildMetadata="+buildMetadata, "-o", executablePath)91	compileGaugeScreenshot()92}93func compileGaugeScreenshot() {94	getGaugeScreenshot()95	executablePath := getGaugeExecutablePath(gaugeScreenshot)96	runProcess("go", "build", "-o", executablePath, gaugeScreenshotLocation)97}98func getGaugeScreenshot() {99	runProcess("go", "get", "-u", "-d", gaugeScreenshotLocation)100}101func runTests(coverage bool) {102	if coverage {103		runProcess("go", "test", "-covermode=count", "-coverprofile=count.out")104		if coverage {105			runProcess("go", "tool", "cover", "-html=count.out")106		}107	} else {108		runProcess("go", "test", "./...", "-v")109	}110}111// key will be the source file and value will be the target112func installFiles(files map[string]string, installDir string) {113	for src, dst := range files {114		base := filepath.Base(src)115		installDst := filepath.Join(installDir, dst)116		log.Printf("Install %s -> %s\n", src, installDst)117		stat, err := os.Stat(src)118		if err != nil {119			panic(err)120		}121		if stat.IsDir() {122			_, err = common.MirrorDir(src, installDst)123		} else {124			err = common.MirrorFile(src, filepath.Join(installDst, base))125		}126		if err != nil {127			panic(err)128		}129	}130}131func copyGaugeConfigFiles(installPath string) {132	files := make(map[string]string)133	files[filepath.Join("skel", "example.spec")] = filepath.Join(config, "skel")134	files[filepath.Join("skel", "default.properties")] = filepath.Join(config, "skel", "env")135	files[filepath.Join("skel", "gauge.properties")] = config136	files[filepath.Join("notice.md")] = config137	files = addInstallScripts(files)138	installFiles(files, installPath)139}140func copyGaugeBinaries(installPath string) {141	files := make(map[string]string)142	files[getGaugeExecutablePath(gauge)] = bin143	files[getGaugeExecutablePath(gaugeScreenshot)] = bin144	installFiles(files, installPath)145}146func addInstallScripts(files map[string]string) map[string]string {147	if (getGOOS() == darwin || getGOOS() == linux) && (*distro) {148		files[filepath.Join("build", "install", installShellScript)] = ""149	} else if getGOOS() == windows {150		files[filepath.Join("build", "install", "windows", "plugin-install.bat")] = ""151		files[filepath.Join("build", "install", "windows", "backup_properties_file.bat")] = ""152		files[filepath.Join("build", "install", "windows", "set_timestamp.bat")] = ""153	}154	return files155}156func setEnv(envVariables map[string]string) {157	for k, v := range envVariables {158		os.Setenv(k, v)159	}160}161var test = flag.Bool("test", false, "Run the test cases")162var coverage = flag.Bool("coverage", false, "Run the test cases and show the coverage")163var install = flag.Bool("install", false, "Install to the specified prefix")164var nightly = flag.Bool("nightly", false, "Add nightly build information")165var gaugeInstallPrefix = flag.String("prefix", "", "Specifies the prefix where gauge files will be installed")166var allPlatforms = flag.Bool("all-platforms", false, "Compiles for all platforms windows, linux, darwin both x86 and x86_64")167var targetLinux = flag.Bool("target-linux", false, "Compiles for linux only, both x86 and x86_64")168var binDir = flag.String("bin-dir", "", "Specifies OS_PLATFORM specific binaries to install when cross compiling")169var distro = flag.Bool("distro", false, "Create gauge distributable")170var skipWindowsDistro = flag.Bool("skip-windows", false, "Skips creation of windows distributable on unix machines while cross platform compilation")171var certFile = flag.String("certFile", "", "Should be passed for signing the windows installer along with the password (certFilePwd)")172var certFilePwd = flag.String("certFilePwd", "", "Password for certificate that will be used to sign the windows installer")173// Defines all the compile targets174// Each target name is the directory name175var (176	platformEnvs = []map[string]string{177		map[string]string{GOARCH: X86, GOOS: darwin, CGO_ENABLED: "0"},178		map[string]string{GOARCH: X86_64, GOOS: darwin, CGO_ENABLED: "0"},179		map[string]string{GOARCH: X86, GOOS: linux, CGO_ENABLED: "0"},180		map[string]string{GOARCH: X86_64, GOOS: linux, CGO_ENABLED: "0"},181		map[string]string{GOARCH: X86, GOOS: windows, CC: "i586-mingw32-gcc", CGO_ENABLED: "1"},182		map[string]string{GOARCH: X86_64, GOOS: windows, CC: "x86_64-w64-mingw32-gcc", CGO_ENABLED: "1"},183	}184	osDistroMap = map[string]distroFunc{windows: createWindowsDistro, linux: createLinuxPackage, darwin: createDarwinPackage}185)186func main() {187	flag.Parse()188	if *nightly {189		buildMetadata = fmt.Sprintf("nightly-%s", time.Now().Format(nightlyDatelayout))190	} else if isatty.IsTerminal(os.Stdout.Fd()) {191		buildMetadata = fmt.Sprintf("%s%s", buildMetadata, revParseHead())192	}193	fmt.Println("Build: " + buildMetadata)194	if *test {195		runTests(*coverage)196	} else if *install {197		installGauge()198	} else if *distro {199		createGaugeDistributables(*allPlatforms)200	} else {201		if *allPlatforms {202			crossCompileGauge()203		} else {204			compileGauge()205		}206	}207}208func revParseHead() string {209	cmd := exec.Command("git", "rev-parse", "--short", "HEAD")210	var hash bytes.Buffer211	cmd.Stdout = &hash212	err := cmd.Run()213	if err != nil {214		log.Fatal(err)215	}216	cmd = exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")217	var branch bytes.Buffer218	cmd.Stdout = &branch219	err = cmd.Run()220	if err != nil {221		log.Fatal(err)222	}223	return fmt.Sprintf("%s-%s", strings.TrimSpace(hash.String()), strings.TrimSpace(branch.String()))224}225func filteredPlatforms() []map[string]string {226	filteredPlatformEnvs := platformEnvs[:0]227	for _, x := range platformEnvs {228		if *targetLinux {229			if x[GOOS] == linux {230				filteredPlatformEnvs = append(filteredPlatformEnvs, x)231			}232		} else {233			filteredPlatformEnvs = append(filteredPlatformEnvs, x)234		}235	}236	return filteredPlatformEnvs237}238func crossCompileGauge() {239	for _, platformEnv := range filteredPlatforms() {240		setEnv(platformEnv)241		log.Printf("Compiling for platform => OS:%s ARCH:%s \n", platformEnv[GOOS], platformEnv[GOARCH])242		compileGauge()243	}244}245func installGauge() {246	updateGaugeInstallPrefix()247	copyGaugeBinaries(deployDir)248	if _, err := common.MirrorDir(filepath.Join(deployDir, bin), filepath.Join(*gaugeInstallPrefix, bin)); err != nil {249		panic(fmt.Sprintf("Could not install gauge : %s", err))250	}251	updateConfigDir()252	copyGaugeConfigFiles(deployDir)253	if _, err := common.MirrorDir(filepath.Join(deployDir, config), gaugeConfigDir); err != nil {254		panic(fmt.Sprintf("Could not copy gauge configuration files: %s", err))255	}256}257func createGaugeDistributables(forAllPlatforms bool) {258	if forAllPlatforms {259		for _, platformEnv := range filteredPlatforms() {260			setEnv(platformEnv)261			log.Printf("Creating distro for platform => OS:%s ARCH:%s \n", platformEnv[GOOS], platformEnv[GOARCH])262			createDistro()263		}264	} else {265		createDistro()266	}267}268type distroFunc func()269func createDistro() {270	osDistroMap[getGOOS()]()271}272func createWindowsDistro() {273	if !*skipWindowsDistro {274		createWindowsInstaller()275	}276}277func createWindowsInstaller() {278	pName := packageName()279	distroDir, err := filepath.Abs(filepath.Join(deploy, pName))280	installerFileName := filepath.Join(filepath.Dir(distroDir), pName)281	if err != nil {282		panic(err)283	}284	copyGaugeBinaries(distroDir)285	copyGaugeConfigFiles(distroDir)286	runProcess("makensis.exe",287		fmt.Sprintf("/DPRODUCT_VERSION=%s", getBuildVersion()),288		fmt.Sprintf("/DGAUGE_DISTRIBUTABLES_DIR=%s", distroDir),289		fmt.Sprintf("/DOUTPUT_FILE_NAME=%s.exe", installerFileName),290		filepath.Join("build", "install", "windows", "gauge-install.nsi"))291	createZipFromUtil(deploy, pName, pName)292	os.RemoveAll(distroDir)293	signExecutable(installerFileName+".exe", *certFile, *certFilePwd)294}295func createDarwinPackage() {296	distroDir := filepath.Join(deploy, gauge)297	copyGaugeBinaries(distroDir)298	copyGaugeConfigFiles(distroDir)299	createZipFromUtil(deploy, gauge, packageName())300	runProcess(packagesBuild, "-v", darwinPackageProject)301	runProcess("mv", filepath.Join(deploy, gauge+pkg), filepath.Join(deploy, fmt.Sprintf("%s-%s-%s.%s%s", gauge, getBuildVersion(), getGOOS(), getPackageArchSuffix(), pkg)))302	os.RemoveAll(distroDir)303}304func createLinuxPackage() {305	distroDir := filepath.Join(deploy, packageName())306	copyGaugeBinaries(distroDir)307	copyGaugeConfigFiles(distroDir)308	createZipFromUtil(deploy, packageName(), packageName())309	os.RemoveAll(distroDir)310}311func packageName() string {312	return fmt.Sprintf("%s-%s-%s.%s", gauge, getBuildVersion(), getGOOS(), getPackageArchSuffix())313}314func removeUnwatedFiles(dir, currentOS string) error {315	fileList := []string{316		".DS_STORE",317		".localized",318		"$RECYCLE.BIN",319	}320	if currentOS == "windows" {321		fileList = append(fileList, []string{322			"backup_properties_file.bat",323			"plugin-install.bat",324			"set_timestamp.bat",325			"desktop.ini",326			"Thumbs.db",327		}...)328	}329	for _, f := range fileList {330		err := os.RemoveAll(filepath.Join(dir, f))331		if err != nil && !os.IsNotExist(err) {332			return err333		}334	}335	return nil336}337func createZipFromUtil(dir, zipDir, pkgName string) {338	wd, err := os.Getwd()339	if err != nil {340		panic(err)341	}342	absdir, err := filepath.Abs(dir)343	if err != nil {344		panic(err)345	}346	currentOS := getGOOS()347	windowsZipScript := filepath.Join(wd, "build", "create_windows_zipfile.ps1")348	err = removeUnwatedFiles(filepath.Join(dir, zipDir), currentOS)349	if err != nil {350		panic(fmt.Sprintf("Failed to cleanup unwanted file(s): %s", err))351	}352	err = os.Chdir(filepath.Join(dir, zipDir))353	if err != nil {354		panic(fmt.Sprintf("Failed to change directory: %s", err))355	}356	zipcmd := "zip"357	zipargs := []string{"-r", filepath.Join("..", pkgName+".zip"), "."}358	if currentOS == "windows" {359		zipcmd = "powershell.exe"360		zipargs = []string{"-noprofile", "-executionpolicy", "bypass", "-file", windowsZipScript, filepath.Join(absdir, zipDir), filepath.Join(absdir, pkgName+".zip")}361	}362	output, err := runCommand(zipcmd, zipargs...)363	fmt.Println(output)364	if err != nil {365		panic(fmt.Sprintf("Failed to zip: %s", err))366	}367	os.Chdir(wd)368}369func updateConfigDir() {370	if os.Getenv(GAUGE_ROOT) != "" {371		gaugeConfigDir = os.Getenv(GAUGE_ROOT)372	} else {373		if runtime.GOOS == "windows" {374			appdata := os.Getenv("APPDATA")375			gaugeConfigDir = filepath.Join(appdata, gauge, config)376		} else {377			home := os.Getenv("HOME")378			gaugeConfigDir = filepath.Join(home, dotgauge, config)379		}380	}381}382func updateGaugeInstallPrefix() {383	if *gaugeInstallPrefix == "" {384		if runtime.GOOS == "windows" {385			*gaugeInstallPrefix = os.Getenv("PROGRAMFILES")386			if *gaugeInstallPrefix == "" {387				panic(fmt.Errorf("Failed to find programfiles"))388			}389			*gaugeInstallPrefix = filepath.Join(*gaugeInstallPrefix, gauge)390		} else {391			*gaugeInstallPrefix = "/usr/local"392		}393	}394}395func getGaugeExecutablePath(file string) string {396	return filepath.Join(getBinDir(), getExecutableName(file))397}398func getBinDir() string {399	if *binDir != "" {400		return *binDir401	}402	return filepath.Join(bin, fmt.Sprintf("%s_%s", getGOOS(), getGOARCH()))403}404func getExecutableName(file string) string {405	if getGOOS() == windows {406		return file + ".exe"407	}408	return file409}410func getGOARCH() string {411	goArch := os.Getenv(GOARCH)412	if goArch == "" {413		goArch = runtime.GOARCH414	}415	return goArch416}417func getGOOS() string {418	goOS := os.Getenv(GOOS)419	if goOS == "" {420		goOS = runtime.GOOS421	}422	return goOS423}424func getPackageArchSuffix() string {425	if strings.HasSuffix(*binDir, "386") {426		return "x86"427	}428	if strings.HasSuffix(*binDir, "amd64") {429		return "x86_64"430	}431	if arch := getGOARCH(); arch == X86 {...monitor.go
Source:monitor.go  
1package main2import (3	"encoding/json"4	"expvar"5	"fmt"6	"github.com/gin-gonic/gin"7	"net/http"8	"runtime"9	"time"10)11func init() {12	//è¿äºé½æ¯æèªå®ä¹çåéï¼åå¸å°expvarä¸ï¼æ¯æ¬¡è¯·æ±æ¥å£ï¼expvarä¼èªå¨å»è·åè¿äºåéï¼å¹¶è¿åç»æ13	expvar.Publish("è¿è¡æ¶é´", expvar.Func(calculateUptime))14	expvar.Publish("version", expvar.Func(currentGoVersion))15	expvar.Publish("cores", expvar.Func(getNumCPUs))16	expvar.Publish("os", expvar.Func(getGoOS))17	expvar.Publish("cgo", expvar.Func(getNumCgoCall))18	expvar.Publish("goroutine", expvar.Func(getNumGoroutins))19	expvar.Publish("gcpause", expvar.Func(getLastGCPauseTime))20}21// å¼å§æ¶é´,å
å
¨å±åéåinit22var start = time.Now()23// calculateUptime 计ç®è¿è¡æ¶é´24func calculateUptime() interface{} {25	return time.Since(start).String()26}27// currentGoVersion å½å Golang çæ¬28func currentGoVersion() interface{} {29	return runtime.Version()30}31// getNumCPUs è·å CPU æ ¸å¿æ°é32func getNumCPUs() interface{} {33	return runtime.NumCPU()34}35// getGoOS å½åç³»ç»ç±»å36func getGoOS() interface{} {37	return runtime.GOOS38}39// getNumGoroutins å½å goroutine æ°é40func getNumGoroutins() interface{} {41	return runtime.NumGoroutine()42}43// getNumCgoCall CGo è°ç¨æ¬¡æ°44func getNumCgoCall() interface{} {45	return runtime.NumCgoCall()46}47var lastPause uint3248// getLastGCPauseTime è·å䏿¬¡ GC çæåæ¶é´49func getLastGCPauseTime() interface{} {50	var gcPause uint6451	ms := new(runtime.MemStats)52	statString := expvar.Get("memstats").String()53	if statString != "" {54		json.Unmarshal([]byte(statString), ms)55		if lastPause == 0 || lastPause != ms.NumGC {56			gcPause = ms.PauseNs[(ms.NumGC+255)%256]57			lastPause = ms.NumGC58		}59	}60	return gcPause61}62// GetCurrentRunningStats è¿åå½åè¿è¡ä¿¡æ¯63func GetCurrentRunningStats(c *gin.Context) {64	c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")65	first := true66	report := func(key string, value interface{}) {67		if !first {68			fmt.Fprintf(c.Writer, ",\n")69		}70		first = false71		if str, ok := value.(string); ok {72			fmt.Fprintf(c.Writer, "%q: %q", key, str)73		} else {74			fmt.Fprintf(c.Writer, "%q: %v", key, value)75		}76	}77	fmt.Fprintf(c.Writer, "{\n")78	expvar.Do(func(kv expvar.KeyValue) {79		report(kv.Key, kv.Value)80	})81	fmt.Fprintf(c.Writer, "\n}\n")82	c.String(http.StatusOK, "")83}...getGOOS
Using AI Code Generation
1import (2func main() {3	fmt.Println(getGOOS())4}5import (6func main() {7	fmt.Println(getGOOS())8}9import (10func main() {11	fmt.Println(getGOOS())12}13import (14func main() {15	fmt.Println(getGOOS())16}17import (18func main() {19	fmt.Println(getGOOS())20}21import (22func main() {23	fmt.Println(getGOOS())24}25import (26func main() {27	fmt.Println(getGOOS())28}29import (30func main() {31	fmt.Println(getGOOS())32}33import (34func main() {35	fmt.Println(getGOOS())36}37import (38func main() {39	fmt.Println(getGOOS())40}41import (42func main() {43	fmt.Println(getGOOS())44}45import (46func main() {47	fmt.Println(getGOOS())48}49import (50func main() {51	fmt.Println(getGOOS())52}getGOOS
Using AI Code Generation
1import (2func main() {3	fmt.Println(runtime.GOOS)4}5import (6func main() {7	fmt.Println(runtime.GOOS)8}9import (10func main() {11	fmt.Println(runtime.GOOS)12}13import (14func main() {15	fmt.Println(runtime.GOOS)16}17import (18func main() {19	fmt.Println(runtime.GOOS)20}21import (22func main() {23	fmt.Println(runtime.GOOS)24}25import (26func main() {27	fmt.Println(runtime.GOOS)28}29import (30func main() {31	fmt.Println(runtime.GOOS)32}33import (34func main() {35	fmt.Println(runtime.GOOS)36}37import (38func main() {39	fmt.Println(runtime.GOOS)40}41import (42func main() {43	fmt.Println(runtime.GOOS)44}45import (46func main() {47	fmt.Println(runtime.GOOS)48}getGOOS
Using AI Code Generation
1import (2func main() {3    fmt.Println("GOOS:", runtime.GOOS)4    fmt.Println("GOARCH:", runtime.GOARCH)5    fmt.Println("GOARM:", runtime.GOARM)6    fmt.Println("GOMIPS:", runtime.GOMIPS)7    fmt.Println("GO386:", runtime.GO386)8}getGOOS
Using AI Code Generation
1import (2func main() {3    fmt.Println("Hello World")4    fmt.Println("The GOOS is: ", os.GetGOOS())5}6func Getenv(key string) string7func Getpid() int8func Getppid() int9func Getwd() (dir string, err error)10func Hostname() (name string, err error)11func IsExist(err error) bool12func IsNotExist(err error) bool13func IsPathSeparator(c uint8) bool14func IsPermission(err error) bool15func Mkdir(name string, perm FileMode) error16func MkdirAll(path string, perm FileMode) error17func Remove(name string) error18func RemoveAll(path string) string19func Rename(oldpath, newpath string) error20func TempDir() string21func Truncate(name string, size int64) error22func UserCacheDir() (string, error)23func UserConfigDir() (string, error)24func UserHomeDir() (string, error)25func UserLookup(name string) (*User, error)26func UserLookupId(uid string) (*User, error)27func UserCurrent() (*User, error)28func UserGroup() (*User, error)29func UserGroups() ([]string, error)30func UserHomeDir() (string, error)31func UserLookup(name string) (*User, error)32func UserLookupId(uid string) (*User, error)33func UserCurrent() (*User, error)34func UserGroup() (*User, error)35func UserGroups() ([]string, error)36func UserHomeDir() (string, error)37func UserLookup(name string) (*User, error)38func UserLookupId(uid string) (*User, error)39func UserCurrent() (*User, error)40func UserGroup() (*User, error)41func UserGroups() ([]string, error)42func UserHomeDir() (string, error)43func UserLookup(name string) (*User, error)44func UserLookupId(uid string) (*User, error)Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
