go command - cmd/go - pkg.dev

文章推薦指數: 80 %
投票人數:10人

go get example.com/mod@none. See https://golang.org/ref/mod#go-get for details. The 'go install' command may be used to build and install packages. WhyGo GetStarted Packages Blog Details Validgo.modfile TheGomodulesystemwasintroducedinGo1.11andistheofficialdependencymanagement solutionforGo. Redistributablelicense Redistributablelicensesplaceminimalrestrictionsonhowsoftwarecanbeused, modified,andredistributed. Taggedversion Moduleswithtaggedversionsgiveimportersmorepredictablebuilds. Stableversion Whenaprojectreachesmajorversionv1itisconsideredstable. Learnmore Repository cs.opensource.google/go/go Jumpto... Documentation Overview SourceFiles Directories Documentation Documentation ¶ Renderedfor linux/amd64 windows/amd64 darwin/amd64 js/wasm Overview¶ Startabugreport Compilepackagesanddependencies Removeobjectfilesandcachedfiles Showdocumentationforpackageorsymbol PrintGoenvironmentinformation UpdatepackagestousenewAPIs Gofmt(reformat)packagesources GenerateGofilesbyprocessingsource Adddependenciestocurrentmoduleandinstallthem Compileandinstallpackagesanddependencies Listpackagesormodules Modulemaintenance Downloadmodulestolocalcache Editgo.modfromtoolsorscripts Printmodulerequirementgraph Initializenewmoduleincurrentdirectory Addmissingandremoveunusedmodules Makevendoredcopyofdependencies Verifydependencieshaveexpectedcontent Explainwhypackagesormodulesareneeded CompileandrunGoprogram Testpackages Runspecifiedgotool PrintGoversion Reportlikelymistakesinpackages Buildconstraints Buildmodes CallingbetweenGoandC Buildandtestcaching Environmentvariables Filetypes Thego.modfile GOPATHenvironmentvariable GOPATHandModules InternalDirectories VendorDirectories LegacyGOPATHgoget Moduleproxyprotocol Importpathsyntax Relativeimportpaths Remoteimportpaths Importpathchecking Modules,moduleversions,andmore Moduleauthenticationusinggo.sum Packagelistsandpatterns Configurationfordownloadingnon-publiccode Testingflags Testingfunctions ControllingversioncontrolwithGOVCS GoisatoolformanagingGosourcecode. Usage: go[arguments] Thecommandsare: bugstartabugreport buildcompilepackagesanddependencies cleanremoveobjectfilesandcachedfiles docshowdocumentationforpackageorsymbol envprintGoenvironmentinformation fixupdatepackagestousenewAPIs fmtgofmt(reformat)packagesources generategenerateGofilesbyprocessingsource getadddependenciestocurrentmoduleandinstallthem installcompileandinstallpackagesanddependencies listlistpackagesormodules modmodulemaintenance runcompileandrunGoprogram testtestpackages toolrunspecifiedgotool versionprintGoversion vetreportlikelymistakesinpackages Use"gohelp"formoreinformationaboutacommand. Additionalhelptopics: buildconstraintbuildconstraints buildmodebuildmodes ccallingbetweenGoandC cachebuildandtestcaching environmentenvironmentvariables filetypefiletypes go.modthego.modfile gopathGOPATHenvironmentvariable gopath-getlegacyGOPATHgoget goproxymoduleproxyprotocol importpathimportpathsyntax modulesmodules,moduleversions,andmore module-getmodule-awaregoget module-authmoduleauthenticationusinggo.sum packagespackagelistsandpatterns privateconfigurationfordownloadingnon-publiccode testflagtestingflags testfunctestingfunctions vcscontrollingversioncontrolwithGOVCS Use"gohelp"formoreinformationaboutthattopic. Startabugreport¶Usage: gobug Bugopensthedefaultbrowserandstartsanewbugreport. Thereportincludesusefulsysteminformation. Compilepackagesanddependencies¶Usage: gobuild[-ooutput][buildflags][packages] Buildcompilesthepackagesnamedbytheimportpaths, alongwiththeirdependencies,butitdoesnotinstalltheresults. Iftheargumentstobuildarealistof.gofilesfromasingledirectory, buildtreatsthemasalistofsourcefilesspecifyingasinglepackage. Whencompilingpackages,buildignoresfilesthatendin'_test.go'. Whencompilingasinglemainpackage,buildwrites theresultingexecutabletoanoutputfilenamedafter thefirstsourcefile('gobuilded.gorx.go'writes'ed'or'ed.exe') orthesourcecodedirectory('gobuildunix/sam'writes'sam'or'sam.exe'). The'.exe'suffixisaddedwhenwritingaWindowsexecutable. Whencompilingmultiplepackagesorasinglenon-mainpackage, buildcompilesthepackagesbutdiscardstheresultingobject, servingonlyasacheckthatthepackagescanbebuilt. The-oflagforcesbuildtowritetheresultingexecutableorobject tothenamedoutputfileordirectory,insteadofthedefaultbehaviordescribed inthelasttwoparagraphs.Ifthenamedoutputisanexistingdirectoryor endswithaslashorbackslash,thenanyresultingexecutables willbewrittentothatdirectory. The-iflaginstallsthepackagesthataredependenciesofthetarget. The-iflagisdeprecated.Compiledpackagesarecachedautomatically. Thebuildflagsaresharedbythebuild,clean,get,install,list,run, andtestcommands: -a forcerebuildingofpackagesthatarealreadyup-to-date. -n printthecommandsbutdonotrunthem. -pn thenumberofprograms,suchasbuildcommandsor testbinaries,thatcanberuninparallel. ThedefaultisGOMAXPROCS,normallythenumberofCPUsavailable. -race enabledataracedetection. Supportedonlyonlinux/amd64,freebsd/amd64,darwin/amd64,windows/amd64, linux/ppc64leandlinux/arm64(onlyfor48-bitVMA). -msan enableinteroperationwithmemorysanitizer. Supportedonlyonlinux/amd64,linux/arm64 andonlywithClang/LLVMasthehostCcompiler. Onlinux/arm64,piebuildmodewillbeused. -v printthenamesofpackagesastheyarecompiled. -work printthenameofthetemporaryworkdirectoryand donotdeleteitwhenexiting. -x printthecommands. -asmflags'[pattern=]arglist' argumentstopassoneachgotoolasminvocation. -buildmodemode buildmodetouse.See'gohelpbuildmode'formore. -compilername nameofcompilertouse,asinruntime.Compiler(gccgoorgc). -gccgoflags'[pattern=]arglist' argumentstopassoneachgccgocompiler/linkerinvocation. -gcflags'[pattern=]arglist' argumentstopassoneachgotoolcompileinvocation. -installsuffixsuffix asuffixtouseinthenameofthepackageinstallationdirectory, inordertokeepoutputseparatefromdefaultbuilds. Ifusingthe-raceflag,theinstallsuffixisautomaticallysettorace or,ifsetexplicitly,has_raceappendedtoit.Likewiseforthe-msan flag.Usinga-buildmodeoptionthatrequiresnon-defaultcompileflags hasasimilareffect. -ldflags'[pattern=]arglist' argumentstopassoneachgotoollinkinvocation. -linkshared buildcodethatwillbelinkedagainstsharedlibrariespreviously createdwith-buildmode=shared. -modmode moduledownloadmodetouse:readonly,vendor,ormod. Bydefault,ifavendordirectoryispresentandthegoversioningo.mod is1.14orhigher,thegocommandactsasif-mod=vendorwereset. Otherwise,thegocommandactsasif-mod=readonlywereset. Seehttps://golang.org/ref/mod#build-commandsfordetails. -modcacherw leavenewly-createddirectoriesinthemodulecacheread-write insteadofmakingthemread-only. -modfilefile inmoduleawaremode,read(andpossiblywrite)analternatego.mod fileinsteadoftheoneinthemodulerootdirectory.Afilenamed "go.mod"muststillbepresentinordertodeterminethemoduleroot directory,butitisnotaccessed.When-modfileisspecified,an alternatego.sumfileisalsoused:itspathisderivedfromthe -modfileflagbytrimmingthe".mod"extensionandappending".sum". -overlayfile readaJSONconfigfilethatprovidesanoverlayforbuildoperations. ThefileisaJSONstructwithasinglefield,named'Replace',that mapseachdiskfilepath(astring)toitsbackingfilepath,sothat abuildwillrunasifthediskfilepathexistswiththecontents givenbythebackingfilepaths,orasifthediskfilepathdoesnot existifitsbackingfilepathisempty.Supportforthe-overlayflag hassomelimitations:importantly,cgofilesincludedfromoutsidethe includepathmustbeinthesamedirectoryastheGopackagetheyare includedfrom,andoverlayswillnotappearwhenbinariesandtestsare runthroughgorunandgotestrespectively. -pkgdirdir installandloadallpackagesfromdirinsteadoftheusuallocations. Forexample,whenbuildingwithanon-standardconfiguration, use-pkgdirtokeepgeneratedpackagesinaseparatelocation. -tagstag,list acomma-separatedlistofbuildtagstoconsidersatisfiedduringthe build.Formoreinformationaboutbuildtags,seethedescriptionof buildconstraintsinthedocumentationforthego/buildpackage. (EarlierversionsofGousedaspace-separatedlist,andthatform isdeprecatedbutstillrecognized.) -trimpath removeallfilesystempathsfromtheresultingexecutable. Insteadofabsolutefilesystempaths,therecordedfilenames willbeginwitheither"go"(forthestandardlibrary), oramodulepath@version(whenusingmodules), oraplainimportpath(whenusingGOPATH). -toolexec'cmdargs' aprogramtousetoinvoketoolchainprogramslikevetandasm. Forexample,insteadofrunningasm,thegocommandwillrun 'cmdargs/path/to/asm'. TheTOOLEXEC_IMPORTPATHenvironmentvariablewillbeset, matching'golist-f{{.ImportPath}}'forthepackagebeingbuilt. The-asmflags,-gccgoflags,-gcflags,and-ldflagsflagsaccepta space-separatedlistofargumentstopasstoanunderlyingtool duringthebuild.Toembedspacesinanelementinthelist,surround itwitheithersingleordoublequotes.Theargumentlistmaybe precededbyapackagepatternandanequalsign,whichrestricts theuseofthatargumentlisttothebuildingofpackagesmatching thatpattern(see'gohelppackages'foradescriptionofpackage patterns).Withoutapattern,theargumentlistappliesonlytothe packagesnamedonthecommandline.Theflagsmayberepeated withdifferentpatternsinordertospecifydifferentargumentsfor differentsetsofpackages.Ifapackagematchespatternsgivenin multipleflags,thelatestmatchonthecommandlinewins. Forexample,'gobuild-gcflags=-Sfmt'printsthedisassembly onlyforpackagefmt,while'gobuild-gcflags=all=-Sfmt' printsthedisassemblyforfmtandallitsdependencies. Formoreaboutspecifyingpackages,see'gohelppackages'. Formoreaboutwherepackagesandbinariesareinstalled, run'gohelpgopath'. FormoreaboutcallingbetweenGoandC/C++,run'gohelpc'. Note:Buildadherestocertainconventionssuchasthosedescribed by'gohelpgopath'.Notallprojectscanfollowtheseconventions, however.Installationsthathavetheirownconventionsorthatuse aseparatesoftwarebuildsystemmaychoosetouselower-level invocationssuchas'gotoolcompile'and'gotoollink'toavoid someoftheoverheadsanddesigndecisionsofthebuildtool. Seealso:goinstall,goget,goclean. Removeobjectfilesandcachedfiles¶Usage: goclean[cleanflags][buildflags][packages] Cleanremovesobjectfilesfrompackagesourcedirectories. Thegocommandbuildsmostobjectsinatemporarydirectory, sogocleanismainlyconcernedwithobjectfilesleftbyother toolsorbymanualinvocationsofgobuild. Ifapackageargumentisgivenorthe-ior-rflagisset, cleanremovesthefollowingfilesfromeachofthe sourcedirectoriescorrespondingtotheimportpaths: _obj/oldobjectdirectory,leftfromMakefiles _test/oldtestdirectory,leftfromMakefiles _testmain.gooldgotestfile,leftfromMakefiles test.outoldtestlog,leftfromMakefiles build.outoldtestlog,leftfromMakefiles *.[568ao]objectfiles,leftfromMakefiles DIR(.exe)fromgobuild DIR.test(.exe)fromgotest-c MAINFILE(.exe)fromgobuildMAINFILE.go *.sofromSWIG Inthelist,DIRrepresentsthefinalpathelementofthe directory,andMAINFILEisthebasenameofanyGosource fileinthedirectorythatisnotincludedwhenbuilding thepackage. The-iflagcausescleantoremovethecorrespondinginstalled archiveorbinary(what'goinstall'wouldcreate). The-nflagcausescleantoprinttheremovecommandsitwouldexecute, butnotrunthem. The-rflagcausescleantobeappliedrecursivelytoallthe dependenciesofthepackagesnamedbytheimportpaths. The-xflagcausescleantoprintremovecommandsasitexecutesthem. The-cacheflagcausescleantoremovetheentiregobuildcache. The-testcacheflagcausescleantoexpirealltestresultsinthe gobuildcache. The-modcacheflagcausescleantoremovetheentiremodule downloadcache,includingunpackedsourcecodeofversioned dependencies. Formoreaboutbuildflags,see'gohelpbuild'. Formoreaboutspecifyingpackages,see'gohelppackages'. Showdocumentationforpackageorsymbol¶Usage: godoc[docflags][package|[package.]symbol[.methodOrField]] Docprintsthedocumentationcommentsassociatedwiththeitemidentifiedbyits arguments(apackage,const,func,type,var,method,orstructfield) followedbyaone-linesummaryofeachofthefirst-levelitems"under" thatitem(package-leveldeclarationsforapackage,methodsforatype, etc.). Docacceptszero,one,ortwoarguments. Givennoarguments,thatis,whenrunas godoc itprintsthepackagedocumentationforthepackageinthecurrentdirectory. Ifthepackageisacommand(packagemain),theexportedsymbolsofthepackage areelidedfromthepresentationunlessthe-cmdflagisprovided. Whenrunwithoneargument,theargumentistreatedasaGo-syntax-like representationoftheitemtobedocumented.Whattheargumentselectsdepends onwhatisinstalledinGOROOTandGOPATH,aswellastheformoftheargument, whichisschematicallyoneofthese: godoc godoc[.] godoc[.][.] godoc[.][.] Thefirstiteminthislistmatchedbytheargumentistheonewhosedocumentation isprinted.(Seetheexamplesbelow.)However,iftheargumentstartswithacapital letteritisassumedtoidentifyasymbolormethodinthecurrentdirectory. Forpackages,theorderofscanningisdeterminedlexicallyinbreadth-firstorder. Thatis,thepackagepresentedistheonethatmatchesthesearchandisnearest therootandlexicallyfirstatitslevelofthehierarchy.TheGOROOTtreeis alwaysscannedinitsentiretybeforeGOPATH. Ifthereisnopackagespecifiedormatched,thepackageinthecurrent directoryisselected,so"godocFoo"showsthedocumentationforsymbolFooin thecurrentpackage. Thepackagepathmustbeeitheraqualifiedpathorapropersuffixofa path.Thegotool'susualpackagemechanismdoesnotapply:packagepath elementslike.and...arenotimplementedbygodoc. Whenrunwithtwoarguments,thefirstmustbeafullpackagepath(notjusta suffix),andthesecondisasymbol,orsymbolwithmethodorstructfield. Thisissimilartothesyntaxacceptedbygodoc: godoc[.] Inallforms,whenmatchingsymbols,lower-caselettersintheargumentmatch eithercasebutupper-caselettersmatchexactly.Thismeansthattheremaybe multiplematchesofalower-caseargumentinapackageifdifferentsymbolshave differentcases.Ifthisoccurs,documentationforallmatchesisprinted. Examples: godoc Showdocumentationforcurrentpackage. godocFoo ShowdocumentationforFoointhecurrentpackage. (Foostartswithacapitallettersoitcannotmatch apackagepath.) godocencoding/json Showdocumentationfortheencoding/jsonpackage. godocjson Shorthandforencoding/json. godocjson.Number(orgodocjson.number) Showdocumentationandmethodsummaryforjson.Number. godocjson.Number.Int64(orgodocjson.number.int64) Showdocumentationforjson.Number'sInt64method. godoccmd/doc Showpackagedocsforthedoccommand. godoc-cmdcmd/doc Showpackagedocsandexportedsymbolswithinthedoccommand. godoctemplate.new Showdocumentationforhtml/template'sNewfunction. (html/templateislexicallybeforetext/template) godoctext/template.new#Oneargument Showdocumentationfortext/template'sNewfunction. godoctext/templatenew#Twoarguments Showdocumentationfortext/template'sNewfunction. Atleastinthecurrenttree,theseinvocationsallprintthe documentationforjson.Decoder'sDecodemethod: godocjson.Decoder.Decode godocjson.decoder.decode godocjson.decode cdgo/src/encoding/json;godocdecode Flags: -all Showallthedocumentationforthepackage. -c Respectcasewhenmatchingsymbols. -cmd Treatacommand(packagemain)likearegularpackage. Otherwisepackagemain'sexportedsymbolsarehidden whenshowingthepackage'stop-leveldocumentation. -short One-linerepresentationforeachsymbol. -src Showthefullsourcecodeforthesymbol.Thiswill displaythefullGosourceofitsdeclarationand definition,suchasafunctiondefinition(including thebody),typedeclarationorenclosingconst block.Theoutputmaythereforeincludeunexported details. -u Showdocumentationforunexportedaswellasexported symbols,methods,andfields. PrintGoenvironmentinformation¶Usage: goenv[-json][-u][-w][var...] EnvprintsGoenvironmentinformation. Bydefaultenvprintsinformationasashellscript (onWindows,abatchfile).Ifoneormorevariable namesisgivenasarguments,envprintsthevalueof eachnamedvariableonitsownline. The-jsonflagprintstheenvironmentinJSONformat insteadofasashellscript. The-uflagrequiresoneormoreargumentsandunsets thedefaultsettingforthenamedenvironmentvariables, ifonehasbeensetwith'goenv-w'. The-wflagrequiresoneormoreargumentsofthe formNAME=VALUEandchangesthedefaultsettings ofthenamedenvironmentvariablestothegivenvalues. Formoreaboutenvironmentvariables,see'gohelpenvironment'. UpdatepackagestousenewAPIs¶Usage: gofix[packages] FixrunstheGofixcommandonthepackagesnamedbytheimportpaths. Formoreaboutfix,see'godoccmd/fix'. Formoreaboutspecifyingpackages,see'gohelppackages'. Torunfixwithspecificoptions,run'gotoolfix'. Seealso:gofmt,govet. Gofmt(reformat)packagesources¶Usage: gofmt[-n][-x][packages] Fmtrunsthecommand'gofmt-l-w'onthepackagesnamed bytheimportpaths.Itprintsthenamesofthefilesthataremodified. Formoreaboutgofmt,see'godoccmd/gofmt'. Formoreaboutspecifyingpackages,see'gohelppackages'. The-nflagprintscommandsthatwouldbeexecuted. The-xflagprintscommandsastheyareexecuted. The-modflag'svaluesetswhichmoduledownloadmode touse:readonlyorvendor.See'gohelpmodules'formore. Torungofmtwithspecificoptions,rungofmtitself. Seealso:gofix,govet. GenerateGofilesbyprocessingsource¶Usage: gogenerate[-runregexp][-n][-v][-x][buildflags][file.go...|packages] Generaterunscommandsdescribedbydirectiveswithinexisting files.Thosecommandscanrunanyprocessbuttheintentisto createorupdateGosourcefiles. Gogenerateisneverrunautomaticallybygobuild,goget,gotest, andsoon.Itmustberunexplicitly. Gogeneratescansthefilefordirectives,whicharelinesof theform, //go:generatecommandargument... (note:noleadingspacesandnospacein"//go")wherecommand isthegeneratortoberun,correspondingtoanexecutablefile thatcanberunlocally.Itmusteitherbeintheshellpath (gofmt),afullyqualifiedpath(/usr/you/bin/mytool),ora commandalias,describedbelow. Notethatgogeneratedoesnotparsethefile,solinesthatlook likedirectivesincommentsormultilinestringswillbetreated asdirectives. Theargumentstothedirectivearespace-separatedtokensor double-quotedstringspassedtothegeneratorasindividual argumentswhenitisrun. QuotedstringsuseGosyntaxandareevaluatedbeforeexecution;a quotedstringappearsasasingleargumenttothegenerator. Toconveytohumansandmachinetoolsthatcodeisgenerated, generatedsourceshouldhavealinethatmatchesthefollowing regularexpression(inGosyntax): ^//Codegenerated.*DONOTEDIT\.$ Thislinemustappearbeforethefirstnon-comment,non-blank textinthefile. Gogeneratesetsseveralvariableswhenitrunsthegenerator: $GOARCH Theexecutionarchitecture(arm,amd64,etc.) $GOOS Theexecutionoperatingsystem(linux,windows,etc.) $GOFILE Thebasenameofthefile. $GOLINE Thelinenumberofthedirectiveinthesourcefile. $GOPACKAGE Thenameofthepackageofthefilecontainingthedirective. $DOLLAR Adollarsign. Otherthanvariablesubstitutionandquoted-stringevaluation,no specialprocessingsuchas"globbing"isperformedonthecommand line. Asalaststepbeforerunningthecommand,anyinvocationsofany environmentvariableswithalphanumericnames,suchas$GOFILEor $HOME,areexpandedthroughoutthecommandline.Thesyntaxfor variableexpansionis$NAMEonalloperatingsystems.Duetothe orderofevaluation,variablesareexpandedeveninsidequoted strings.IfthevariableNAMEisnotset,$NAMEexpandstothe emptystring. Adirectiveoftheform, //go:generate-commandxxxargs... specifies,fortheremainderofthissourcefileonly,thatthe stringxxxrepresentsthecommandidentifiedbythearguments.This canbeusedtocreatealiasesortohandlemultiwordgenerators. Forexample, //go:generate-commandfoogotoolfoo specifiesthatthecommand"foo"representsthegenerator "gotoolfoo". Generateprocessespackagesintheordergivenonthecommandline, oneatatime.Ifthecommandlinelists.gofilesfromasingledirectory, theyaretreatedasasinglepackage.Withinapackage,generateprocessesthe sourcefilesinapackageinfilenameorder,oneatatime.Within asourcefile,generaterunsgeneratorsintheordertheyappear inthefile,oneatatime.Thegogeneratetoolalsosetsthebuild tag"generate"sothatfilesmaybeexaminedbygogeneratebutignored duringbuild. Forpackageswithinvalidcode,generateprocessesonlysourcefileswitha validpackageclause. Ifanygeneratorreturnsanerrorexitstatus,"gogenerate"skips allfurtherprocessingforthatpackage. Thegeneratorisruninthepackage'ssourcedirectory. Gogenerateacceptsonespecificflag: -run="" ifnon-empty,specifiesaregularexpressiontoselect directiveswhosefulloriginalsourcetext(excluding anytrailingspacesandfinalnewline)matchesthe expression. Italsoacceptsthestandardbuildflagsincluding-v,-n,and-x. The-vflagprintsthenamesofpackagesandfilesastheyare processed. The-nflagprintscommandsthatwouldbeexecuted. The-xflagprintscommandsastheyareexecuted. Formoreaboutbuildflags,see'gohelpbuild'. Formoreaboutspecifyingpackages,see'gohelppackages'. Adddependenciestocurrentmoduleandinstallthem¶Usage: goget[-d][-t][-u][-v][buildflags][packages] Getresolvesitscommand-lineargumentstopackagesatspecificmoduleversions, updatesgo.modtorequirethoseversions,downloadssourcecodeintothe modulecache,thenbuildsandinstallsthenamedpackages. Toaddadependencyforapackageorupgradeittoitslatestversion: gogetexample.com/pkg Toupgradeordowngradeapackagetoaspecificversion: gogetexample.com/[email protected] Toremoveadependencyonamoduleanddowngrademodulesthatrequireit: gogetexample.com/mod@none Seehttps://golang.org/ref/mod#go-getfordetails. The'goinstall'commandmaybeusedtobuildandinstallpackages.Whena versionisspecified,'goinstall'runsinmodule-awaremodeandignores thego.modfileinthecurrentdirectory.Forexample: goinstallexample.com/[email protected] goinstallexample.com/pkg@latest See'gohelpinstall'orhttps://golang.org/ref/mod#go-installfordetails. Inadditiontobuildflags(listedin'gohelpbuild')'goget'acceptsthe followingflags. The-tflaginstructsgettoconsidermodulesneededtobuildtestsof packagesspecifiedonthecommandline. The-uflaginstructsgettoupdatemodulesprovidingdependencies ofpackagesnamedonthecommandlinetousenewerminororpatch releaseswhenavailable. The-u=patchflag(not-upatch)alsoinstructsgettoupdatedependencies, butchangesthedefaulttoselectpatchreleases. Whenthe-tand-uflagsareusedtogether,getwillupdate testdependenciesaswell. The-dflaginstructsgetnottobuildorinstallpackages.getwillonly updatego.modanddownloadsourcecodeneededtobuildpackages. Buildingandinstallingpackageswithgetisdeprecated.Inafuturerelease, the-dflagwillbeenabledbydefault,and'goget'willbeonlybeusedto adjustdependenciesofthecurrentmodule.Toinstallapackageusing dependenciesfromthecurrentmodule,use'goinstall'.Toinstallapackage ignoringthecurrentmodule,use'goinstall'withan@versionsuffixlike "@latest"aftereachargument. Formoreaboutmodules,seehttps://golang.org/ref/mod. Formoreaboutspecifyingpackages,see'gohelppackages'. Thistextdescribesthebehaviorofgetusingmodulestomanagesource codeanddependencies.IfinsteadthegocommandisrunninginGOPATH mode,thedetailsofget'sflagsandeffectschange,asdoes'gohelpget'. See'gohelpgopath-get'. Seealso:gobuild,goinstall,goclean,gomod. Compileandinstallpackagesanddependencies¶Usage: goinstall[buildflags][packages] Installcompilesandinstallsthepackagesnamedbytheimportpaths. ExecutablesareinstalledinthedirectorynamedbytheGOBINenvironment variable,whichdefaultsto$GOPATH/binor$HOME/go/biniftheGOPATH environmentvariableisnotset.Executablesin$GOROOT areinstalledin$GOROOT/binor$GOTOOLDIRinsteadof$GOBIN. Iftheargumentshaveversionsuffixes(like@[email protected]),"goinstall" buildspackagesinmodule-awaremode,ignoringthego.modfileinthecurrent directoryoranyparentdirectory,ifthereisone.Thisisusefulfor installingexecutableswithoutaffectingthedependenciesofthemainmodule. Toeliminateambiguityaboutwhichmoduleversionsareusedinthebuild,the argumentsmustsatisfythefollowingconstraints: -Argumentsmustbepackagepathsorpackagepatterns(with"..."wildcards). Theymustnotbestandardpackages(likefmt),meta-patterns(std,cmd, all),orrelativeorabsolutefilepaths. -Allargumentsmusthavethesameversionsuffix.Differentqueriesarenot allowed,eveniftheyrefertothesameversion. -Allargumentsmustrefertopackagesinthesamemoduleatthesameversion. -Nomoduleisconsideredthe"main"module.Ifthemodulecontaining packagesnamedonthecommandlinehasago.modfile,itmustnotcontain directives(replaceandexclude)thatwouldcauseittobeinterpreted differentlythanifitwerethemainmodule.Themodulemustnotrequire ahigherversionofitself. -Packagepathargumentsmustrefertomainpackages.Patternarguments willonlymatchmainpackages. Iftheargumentsdon'thaveversionsuffixes,"goinstall"mayrunin module-awaremodeorGOPATHmode,dependingontheGO111MODULEenvironment variableandthepresenceofago.modfile.See'gohelpmodules'fordetails. Ifmodule-awaremodeisenabled,"goinstall"runsinthecontextofthemain module. Whenmodule-awaremodeisdisabled,otherpackagesareinstalledinthe directory$GOPATH/pkg/$GOOS_$GOARCH.Whenmodule-awaremodeisenabled, otherpackagesarebuiltandcachedbutnotinstalled. The-iflaginstallsthedependenciesofthenamedpackagesaswell. The-iflagisdeprecated.Compiledpackagesarecachedautomatically. Formoreaboutthebuildflags,see'gohelpbuild'. Formoreaboutspecifyingpackages,see'gohelppackages'. Seealso:gobuild,goget,goclean. Listpackagesormodules¶Usage: golist[-fformat][-json][-m][listflags][buildflags][packages] Listliststhenamedpackages,oneperline. Themostcommonly-usedflagsare-fand-json,whichcontroltheform oftheoutputprintedforeachpackage.Otherlistflags,documentedbelow, controlmorespecificdetails. Thedefaultoutputshowsthepackageimportpath: bytes encoding/json github.com/gorilla/mux golang.org/x/net/html The-fflagspecifiesanalternateformatforthelist,usingthe syntaxofpackagetemplate.Thedefaultoutputisequivalent to-f'{{.ImportPath}}'.Thestructbeingpassedtothetemplateis: typePackagestruct{ Dirstring//directorycontainingpackagesources ImportPathstring//importpathofpackageindir ImportCommentstring//pathinimportcommentonpackagestatement Namestring//packagename Docstring//packagedocumentationstring Targetstring//installpath Shlibstring//thesharedlibrarythatcontainsthispackage(onlysetwhen-linkshared) Gorootbool//isthispackageintheGoroot? Standardbool//isthispackagepartofthestandardGolibrary? Stalebool//would'goinstall'doanythingforthispackage? StaleReasonstring//explanationforStale==true Rootstring//GorootorGopathdircontainingthispackage ConflictDirstring//thisdirectoryshadowsDirin$GOPATH BinaryOnlybool//binary-onlypackage(nolongersupported) ForTeststring//packageisonlyforuseinnamedtest Exportstring//filecontainingexportdata(whenusing-export) BuildIDstring//buildIDofthecompiledpackage(whenusing-export) Module*Module//infoaboutpackage'scontainingmodule,ifany(canbenil) Match[]string//command-linepatternsmatchingthispackage DepOnlybool//packageisonlyadependency,notexplicitlylisted //Sourcefiles GoFiles[]string//.gosourcefiles(excludingCgoFiles,TestGoFiles,XTestGoFiles) CgoFiles[]string//.gosourcefilesthatimport"C" CompiledGoFiles[]string//.gofilespresentedtocompiler(whenusing-compiled) IgnoredGoFiles[]string//.gosourcefilesignoredduetobuildconstraints IgnoredOtherFiles[]string//non-.gosourcefilesignoredduetobuildconstraints CFiles[]string//.csourcefiles CXXFiles[]string//.cc,.cxxand.cppsourcefiles MFiles[]string//.msourcefiles HFiles[]string//.h,.hh,.hppand.hxxsourcefiles FFiles[]string//.f,.F,.forand.f90Fortransourcefiles SFiles[]string//.ssourcefiles SwigFiles[]string//.swigfiles SwigCXXFiles[]string//.swigcxxfiles SysoFiles[]string//.sysoobjectfilestoaddtoarchive TestGoFiles[]string//_test.gofilesinpackage XTestGoFiles[]string//_test.gofilesoutsidepackage //Embeddedfiles EmbedPatterns[]string////go:embedpatterns EmbedFiles[]string//filesmatchedbyEmbedPatterns TestEmbedPatterns[]string////go:embedpatternsinTestGoFiles TestEmbedFiles[]string//filesmatchedbyTestEmbedPatterns XTestEmbedPatterns[]string////go:embedpatternsinXTestGoFiles XTestEmbedFiles[]string//filesmatchedbyXTestEmbedPatterns //Cgodirectives CgoCFLAGS[]string//cgo:flagsforCcompiler CgoCPPFLAGS[]string//cgo:flagsforCpreprocessor CgoCXXFLAGS[]string//cgo:flagsforC++compiler CgoFFLAGS[]string//cgo:flagsforFortrancompiler CgoLDFLAGS[]string//cgo:flagsforlinker CgoPkgConfig[]string//cgo:pkg-confignames //Dependencyinformation Imports[]string//importpathsusedbythispackage ImportMapmap[string]string//mapfromsourceimporttoImportPath(identityentriesomitted) Deps[]string//all(recursively)importeddependencies TestImports[]string//importsfromTestGoFiles XTestImports[]string//importsfromXTestGoFiles //Errorinformation Incompletebool//thispackageoradependencyhasanerror Error*PackageError//errorloadingpackage DepsErrors[]*PackageError//errorsloadingdependencies } PackagesstoredinvendordirectoriesreportanImportPaththatincludesthe pathtothevendordirectory(forexample,"d/vendor/p"insteadof"p"), sothattheImportPathuniquelyidentifiesagivencopyofapackage. TheImports,Deps,TestImports,andXTestImportslistsalsocontainthese expandedimportpaths.Seegolang.org/s/go15vendorformoreaboutvendoring. Theerrorinformation,ifany,is typePackageErrorstruct{ ImportStack[]string//shortestpathfrompackagenamedoncommandlinetothisone Posstring//positionoferror(ifpresent,file:line:col) Errstring//theerroritself } ThemoduleinformationisaModulestruct,definedinthediscussion oflist-mbelow. Thetemplatefunction"join"callsstrings.Join. Thetemplatefunction"context"returnsthebuildcontext,definedas: typeContextstruct{ GOARCHstring//targetarchitecture GOOSstring//targetoperatingsystem GOROOTstring//Goroot GOPATHstring//Gopath CgoEnabledbool//whethercgocanbeused UseAllFilesbool//usefilesregardlessof+buildlines,filenames Compilerstring//compilertoassumewhencomputingtargetpaths BuildTags[]string//buildconstraintstomatchin+buildlines ToolTags[]string//toolchain-specificbuildconstraints ReleaseTags[]string//releasesthecurrentreleaseiscompatiblewith InstallSuffixstring//suffixtouseinthenameoftheinstalldir } Formoreinformationaboutthemeaningofthesefieldsseethedocumentation forthego/buildpackage'sContexttype. The-jsonflagcausesthepackagedatatobeprintedinJSONformat insteadofusingthetemplateformat. The-compiledflagcauseslisttosetCompiledGoFilestotheGosource filespresentedtothecompiler.Typicallythismeansthatitrepeats thefileslistedinGoFilesandthenalsoaddstheGocodegenerated byprocessingCgoFilesandSwigFiles.TheImportslistcontainsthe unionofallimportsfrombothGoFilesandCompiledGoFiles. The-depsflagcauseslisttoiterateovernotjustthenamedpackages butalsoalltheirdependencies.Itvisitstheminadepth-firstpost-order traversal,sothatapackageislistedonlyafterallitsdependencies. PackagesnotexplicitlylistedonthecommandlinewillhavetheDepOnly fieldsettotrue. The-eflagchangesthehandlingoferroneouspackages,thosethat cannotbefoundoraremalformed.Bydefault,thelistcommand printsanerrortostandarderrorforeacherroneouspackageand omitsthepackagesfromconsiderationduringtheusualprinting. Withthe-eflag,thelistcommandneverprintserrorstostandard errorandinsteadprocessestheerroneouspackageswiththeusual printing.Erroneouspackageswillhaveanon-emptyImportPathand anon-nilErrorfield;otherinformationmayormaynotbemissing (zeroed). The-exportflagcauseslisttosettheExportfieldtothenameofa filecontainingup-to-dateexportinformationforthegivenpackage. The-findflagcauseslisttoidentifythenamedpackagesbutnot resolvetheirdependencies:theImportsandDepslistswillbeempty. The-testflagcauseslisttoreportnotonlythenamedpackages butalsotheirtestbinaries(forpackageswithtests),toconveyto sourcecodeanalysistoolsexactlyhowtestbinariesareconstructed. Thereportedimportpathforatestbinaryistheimportpathof thepackagefollowedbya".test"suffix,asin"math/rand.test". Whenbuildingatest,itissometimesnecessarytorebuildcertain dependenciesspeciallyforthattest(mostcommonlythetested packageitself).Thereportedimportpathofapackagerecompiled foraparticulartestbinaryisfollowedbyaspaceandthenameof thetestbinaryinbrackets,asin"math/rand[math/rand.test]" or"regexp[sort.test]".TheForTestfieldisalsosettothename ofthepackagebeingtested("math/rand"or"sort"intheprevious examples). TheDir,Target,Shlib,Root,ConflictDir,andExportfilepaths areallabsolutepaths. Bydefault,thelistsGoFiles,CgoFiles,andsoonholdnamesoffilesinDir (thatis,pathsrelativetoDir,notabsolutepaths). Thegeneratedfilesaddedwhenusingthe-compiledand-testflags areabsolutepathsreferringtocachedcopiesofgeneratedGosourcefiles. AlthoughtheyareGosourcefiles,thepathsmaynotendin".go". The-mflagcauseslisttolistmodulesinsteadofpackages. Whenlistingmodules,the-fflagstillspecifiesaformattemplate appliedtoaGostruct,butnowaModulestruct: typeModulestruct{ Pathstring//modulepath Versionstring//moduleversion Versions[]string//availablemoduleversions(with-versions) Replace*Module//replacedbythismodule Time*time.Time//timeversionwascreated Update*Module//availableupdate,ifany(with-u) Mainbool//isthisthemainmodule? Indirectbool//isthismoduleonlyanindirectdependencyofmainmodule? Dirstring//directoryholdingfilesforthismodule,ifany GoModstring//pathtogo.modfileusedwhenloadingthismodule,ifany GoVersionstring//goversionusedinmodule Retractedstring//retractioninformation,ifany(with-retractedor-u) Error*ModuleError//errorloadingmodule } typeModuleErrorstruct{ Errstring//theerroritself } ThefileGoModreferstomaybeoutsidethemoduledirectoryifthe moduleisinthemodulecacheorifthe-modfileflagisused. Thedefaultoutputistoprintthemodulepathandthen informationabouttheversionandreplacementifany. Forexample,'golist-mall'mightprint: my/main/module golang.org/x/textv0.3.0=>/tmp/text rsc.io/pdfv0.1.1 TheModulestructhasaStringmethodthatformatsthis lineofoutput,sothatthedefaultformatisequivalent to-f'{{.String}}'. Notethatwhenamodulehasbeenreplaced,itsReplacefield describesthereplacementmodule,anditsDirfieldissetto thereplacement'ssourcecode,ifpresent.(Thatis,ifReplace isnon-nil,thenDirissettoReplace.Dir,withnoaccessto thereplacedsourcecode.) The-uflagaddsinformationaboutavailableupgrades. Whenthelatestversionofagivenmoduleisnewerthan thecurrentone,list-usetstheModule'sUpdatefield toinformationaboutthenewermodule.list-uwillalsoset themodule'sRetractedfieldifthecurrentversionisretracted. TheModule'sStringmethodindicatesanavailableupgradeby formattingthenewerversioninbracketsafterthecurrentversion. Ifaversionisretracted,thestring"(retracted)"willfollowit. Forexample,'golist-m-uall'mightprint: my/main/module golang.org/x/textv0.3.0[v0.4.0]=>/tmp/text rsc.io/pdfv0.1.1(retracted)[v0.1.2] (Fortools,'golist-m-u-jsonall'maybemoreconvenienttoparse.) The-versionsflagcauseslisttosettheModule'sVersionsfield toalistofallknownversionsofthatmodule,orderedaccording tosemanticversioning,earliesttolatest.Theflagalsochanges thedefaultoutputformattodisplaythemodulepathfollowedbythe space-separatedversionlist. The-retractedflagcauseslisttoreportinformationaboutretracted moduleversions.When-retractedisusedwith-for-json,theRetracted fieldwillbesettoastringexplainingwhytheversionwasretracted. Thestringistakenfromcommentsontheretractdirectiveinthe module'sgo.modfile.When-retractedisusedwith-versions,retracted versionsarelistedtogetherwithunretractedversions.The-retracted flagmaybeusedwithorwithout-m. Theargumentstolist-mareinterpretedasalistofmodules,notpackages. Themainmoduleisthemodulecontainingthecurrentdirectory. Theactivemodulesarethemainmoduleanditsdependencies. Withnoarguments,list-mshowsthemainmodule. Witharguments,list-mshowsthemodulesspecifiedbythearguments. Anyoftheactivemodulescanbespecifiedbyitsmodulepath. Thespecialpattern"all"specifiesalltheactivemodules,firstthemain moduleandthendependenciessortedbymodulepath. Apatterncontaining"..."specifiestheactivemoduleswhose modulepathsmatchthepattern. Aqueryoftheformpath@versionspecifiestheresultofthatquery, whichisnotlimitedtoactivemodules. See'gohelpmodules'formoreaboutmodulequeries. Thetemplatefunction"module"takesasinglestringargument thatmustbeamodulepathorqueryandreturnsthespecified moduleasaModulestruct.Ifanerroroccurs,theresultwill beaModulestructwithanon-nilErrorfield. Formoreaboutbuildflags,see'gohelpbuild'. Formoreaboutspecifyingpackages,see'gohelppackages'. Formoreaboutmodules,seehttps://golang.org/ref/mod. Modulemaintenance¶Gomodprovidesaccesstooperationsonmodules. Notethatsupportformodulesisbuiltintoallthegocommands, notjust'gomod'.Forexample,day-to-dayadding,removing,upgrading, anddowngradingofdependenciesshouldbedoneusing'goget'. See'gohelpmodules'foranoverviewofmodulefunctionality. Usage: gomod[arguments] Thecommandsare: downloaddownloadmodulestolocalcache editeditgo.modfromtoolsorscripts graphprintmodulerequirementgraph initinitializenewmoduleincurrentdirectory tidyaddmissingandremoveunusedmodules vendormakevendoredcopyofdependencies verifyverifydependencieshaveexpectedcontent whyexplainwhypackagesormodulesareneeded Use"gohelpmod"formoreinformationaboutacommand. Downloadmodulestolocalcache¶Usage: gomoddownload[-x][-json][modules] Downloaddownloadsthenamedmodules,whichcanbemodulepatternsselecting dependenciesofthemainmoduleormodulequeriesoftheformpath@version. Withnoarguments,downloadappliestoalldependenciesofthemainmodule (equivalentto'gomoddownloadall'). Thegocommandwillautomaticallydownloadmodulesasneededduringordinary execution.The"gomoddownload"commandisusefulmainlyforpre-filling thelocalcacheortocomputetheanswersforaGomoduleproxy. Bydefault,downloadwritesnothingtostandardoutput.Itmayprintprogress messagesanderrorstostandarderror. The-jsonflagcausesdownloadtoprintasequenceofJSONobjects tostandardoutput,describingeachdownloadedmodule(orfailure), correspondingtothisGostruct: typeModulestruct{ Pathstring//modulepath Versionstring//moduleversion Errorstring//errorloadingmodule Infostring//absolutepathtocached.infofile GoModstring//absolutepathtocached.modfile Zipstring//absolutepathtocached.zipfile Dirstring//absolutepathtocachedsourcerootdirectory Sumstring//checksumforpath,version(asingo.sum) GoModSumstring//checksumforgo.mod(asingo.sum) } The-xflagcausesdownloadtoprintthecommandsdownloadexecutes. Seehttps://golang.org/ref/mod#go-mod-downloadformoreabout'gomoddownload'. Seehttps://golang.org/ref/mod#version-queriesformoreaboutversionqueries. Editgo.modfromtoolsorscripts¶Usage: gomodedit[editingflags][-fmt|-print|-json][go.mod] Editprovidesacommand-lineinterfaceforeditinggo.mod, foruseprimarilybytoolsorscripts.Itreadsonlygo.mod; itdoesnotlookupinformationaboutthemodulesinvolved. Bydefault,editreadsandwritesthego.modfileofthemainmodule, butadifferenttargetfilecanbespecifiedaftertheeditingflags. Theeditingflagsspecifyasequenceofeditingoperations. The-fmtflagreformatsthego.modfilewithoutmakingotherchanges. Thisreformattingisalsoimpliedbyanyothermodificationsthatuseor rewritethego.modfile.Theonlytimethisflagisneededisifnoother flagsarespecified,asin'gomodedit-fmt'. The-moduleflagchangesthemodule'spath(thego.modfile'smoduleline). The-require=path@versionand-droprequire=pathflags addanddroparequirementonthegivenmodulepathandversion. Notethat-requireoverridesanyexistingrequirementsonpath. Theseflagsaremainlyfortoolsthatunderstandthemodulegraph. Usersshouldprefer'gogetpath@version'or'gogetpath@none', whichmakeothergo.modadjustmentsasneededtosatisfy constraintsimposedbyothermodules. The-exclude=path@versionand-dropexclude=path@versionflags addanddropanexclusionforthegivenmodulepathandversion. Notethat-exclude=path@versionisano-opifthatexclusionalreadyexists. The-replace=old[@v]=new[@v]flagaddsareplacementofthegiven modulepathandversionpair.Ifthe@vinold@visomitted,a replacementwithoutaversionontheleftsideisadded,whichapplies toallversionsoftheoldmodulepath.Ifthe@vinnew@visomitted, thenewpathshouldbealocalmodulerootdirectory,notamodule path.Notethat-replaceoverridesanyredundantreplacementsforold[@v], soomitting@vwilldropexistingreplacementsforspecificversions. The-dropreplace=old[@v]flagdropsareplacementofthegiven modulepathandversionpair.Ifthe@visomitted,areplacementwithout aversionontheleftsideisdropped. The-retract=versionand-dropretract=versionflagsaddanddropa retractiononthegivenversion.Theversionmaybeasingleversion like"v1.2.3"oraclosedintervallike"[v1.1.0,v1.1.9]".Notethat -retract=versionisano-opifthatretractionalreadyexists. The-require,-droprequire,-exclude,-dropexclude,-replace, -dropreplace,-retract,and-dropretracteditingflagsmayberepeated, andthechangesareappliedintheordergiven. The-go=versionflagsetstheexpectedGolanguageversion. The-printflagprintsthefinalgo.modinitstextformatinsteadof writingitbacktogo.mod. The-jsonflagprintsthefinalgo.modfileinJSONformatinsteadof writingitbacktogo.mod.TheJSONoutputcorrespondstotheseGotypes: typeModulestruct{ Pathstring Versionstring } typeGoModstruct{ ModuleModPath Gostring Require[]Require Exclude[]Module Replace[]Replace Retract[]Retract } typeModPathstruct{ Pathstring Deprecatedstring } typeRequirestruct{ Pathstring Versionstring Indirectbool } typeReplacestruct{ OldModule NewModule } typeRetractstruct{ Lowstring Highstring Rationalestring } Retractentriesrepresentingasingleversion(notaninterval)willhave the"Low"and"High"fieldssettothesamevalue. Notethatthisonlydescribesthego.modfileitself,notothermodules referredtoindirectly.Forthefullsetofmodulesavailabletoabuild, use'golist-m-jsonall'. Seehttps://golang.org/ref/mod#go-mod-editformoreabout'gomodedit'. Printmodulerequirementgraph¶Usage: gomodgraph[-go=version] Graphprintsthemodulerequirementgraph(withreplacementsapplied) intextform.Eachlineintheoutputhastwospace-separatedfields:amodule andoneofitsrequirements.Eachmoduleisidentifiedasastringoftheform path@version,exceptforthemainmodule,whichhasno@versionsuffix. The-goflagcausesgraphtoreportthemodulegraphasloadedbythe givenGoversion,insteadoftheversionindicatedbythe'go'directive inthego.modfile. Seehttps://golang.org/ref/mod#go-mod-graphformoreabout'gomodgraph'. Initializenewmoduleincurrentdirectory¶Usage: gomodinit[module-path] Initinitializesandwritesanewgo.modfileinthecurrentdirectory,in effectcreatinganewmodulerootedatthecurrentdirectory.Thego.modfile mustnotalreadyexist. Initacceptsoneoptionalargument,themodulepathforthenewmodule.Ifthe modulepathargumentisomitted,initwillattempttoinferthemodulepath usingimportcommentsin.gofiles,vendoringtoolconfigurationfiles(like Gopkg.lock),andthecurrentdirectory(ifinGOPATH). Ifaconfigurationfileforavendoringtoolispresent,initwillattemptto importmodulerequirementsfromit. Seehttps://golang.org/ref/mod#go-mod-initformoreabout'gomodinit'. Addmissingandremoveunusedmodules¶Usage: gomodtidy[-e][-v][-go=version][-compat=version] Tidymakessurego.modmatchesthesourcecodeinthemodule. Itaddsanymissingmodulesnecessarytobuildthecurrentmodule's packagesanddependencies,anditremovesunusedmodulesthat don'tprovideanyrelevantpackages.Italsoaddsanymissingentries togo.sumandremovesanyunnecessaryones. The-vflagcausestidytoprintinformationaboutremovedmodules tostandarderror. The-eflagcausestidytoattempttoproceeddespiteerrors encounteredwhileloadingpackages. The-goflagcausestidytoupdatethe'go'directiveinthego.mod filetothegivenversion,whichmaychangewhichmoduledependencies areretainedasexplicitrequirementsinthego.modfile. (Goversions1.17andhigherretainmorerequirementsinorderto supportlazymoduleloading.) The-compatflagpreservesanyadditionalchecksumsneededforthe 'go'commandfromtheindicatedmajorGoreleasetosuccessfullyload themodulegraph,andcausestidytoerroroutifthatversionofthe 'go'commandwouldloadanyimportedpackagefromadifferentmodule version.Bydefault,tidyactsasifthe-compatflagweresettothe versionpriortotheoneindicatedbythe'go'directiveinthego.mod file. Seehttps://golang.org/ref/mod#go-mod-tidyformoreabout'gomodtidy'. Makevendoredcopyofdependencies¶Usage: gomodvendor[-e][-v] Vendorresetsthemainmodule'svendordirectorytoincludeallpackages neededtobuildandtestallthemainmodule'spackages. Itdoesnotincludetestcodeforvendoredpackages. The-vflagcausesvendortoprintthenamesofvendored modulesandpackagestostandarderror. The-eflagcausesvendortoattempttoproceeddespiteerrors encounteredwhileloadingpackages. Seehttps://golang.org/ref/mod#go-mod-vendorformoreabout'gomodvendor'. Verifydependencieshaveexpectedcontent¶Usage: gomodverify Verifychecksthatthedependenciesofthecurrentmodule, whicharestoredinalocaldownloadedsourcecache,havenotbeen modifiedsincebeingdownloaded.Ifallthemodulesareunmodified, verifyprints"allmodulesverified."Otherwiseitreportswhich moduleshavebeenchangedandcauses'gomod'toexitwitha non-zerostatus. Seehttps://golang.org/ref/mod#go-mod-verifyformoreabout'gomodverify'. Explainwhypackagesormodulesareneeded¶Usage: gomodwhy[-m][-vendor]packages... Whyshowsashortestpathintheimportgraphfromthemainmoduleto eachofthelistedpackages.Ifthe-mflagisgiven,whytreatsthe argumentsasalistofmodulesandfindsapathtoanypackageineach ofthemodules. Bydefault,whyqueriesthegraphofpackagesmatchedby"golistall", whichincludestestsforreachablepackages.The-vendorflagcauseswhy toexcludetestsofdependencies. Theoutputisasequenceofstanzas,oneforeachpackageormodule nameonthecommandline,separatedbyblanklines.Eachstanzabegins withacommentline"#package"or"#module"givingthetarget packageormodule.Subsequentlinesgiveapaththroughtheimport graph,onepackageperline.Ifthepackageormoduleisnot referencedfromthemainmodule,thestanzawilldisplayasingle parenthesizednoteindicatingthatfact. Forexample: $gomodwhygolang.org/x/text/languagegolang.org/x/text/encoding #golang.org/x/text/language rsc.io/quote rsc.io/sampler golang.org/x/text/language #golang.org/x/text/encoding (mainmoduledoesnotneedpackagegolang.org/x/text/encoding) $ Seehttps://golang.org/ref/mod#go-mod-whyformoreabout'gomodwhy'. CompileandrunGoprogram¶Usage: gorun[buildflags][-execxprog]package[arguments...] RuncompilesandrunsthenamedmainGopackage. Typicallythepackageisspecifiedasalistof.gosourcefilesfromasingle directory,butitmayalsobeanimportpath,filesystempath,orpattern matchingasingleknownpackage,asin'gorun.'or'gorunmy/cmd'. Ifthepackageargumenthasaversionsuffix(like@[email protected]), "gorun"buildstheprograminmodule-awaremode,ignoringthego.modfilein thecurrentdirectoryoranyparentdirectory,ifthereisone.Thisisuseful forrunningprogramswithoutaffectingthedependenciesofthemainmodule. Ifthepackageargumentdoesn'thaveaversionsuffix,"gorun"mayrunin module-awaremodeorGOPATHmode,dependingontheGO111MODULEenvironment variableandthepresenceofago.modfile.See'gohelpmodules'fordetails. Ifmodule-awaremodeisenabled,"gorun"runsinthecontextofthemain module. Bydefault,'gorun'runsthecompiledbinarydirectly:'a.outarguments...'. Ifthe-execflagisgiven,'gorun'invokesthebinaryusingxprog: 'xproga.outarguments...'. Ifthe-execflagisnotgiven,GOOSorGOARCHisdifferentfromthesystem default,andaprogramnamedgo_$GOOS_$GOARCH_execcanbefound onthecurrentsearchpath,'gorun'invokesthebinaryusingthatprogram, forexample'go_js_wasm_execa.outarguments...'.Thisallowsexecutionof cross-compiledprogramswhenasimulatororotherexecutionmethodis available. TheexitstatusofRunisnottheexitstatusofthecompiledbinary. Formoreaboutbuildflags,see'gohelpbuild'. Formoreaboutspecifyingpackages,see'gohelppackages'. Seealso:gobuild. Testpackages¶Usage: gotest[build/testflags][packages][build/testflags&testbinaryflags] 'Gotest'automatestestingthepackagesnamedbytheimportpaths. Itprintsasummaryofthetestresultsintheformat: okarchive/tar0.011s FAILarchive/zip0.022s okcompress/gzip0.033s ... followedbydetailedoutputforeachfailedpackage. 'Gotest'recompileseachpackagealongwithanyfileswithnamesmatching thefilepattern"*_test.go". Theseadditionalfilescancontaintestfunctions,benchmarkfunctions,and examplefunctions.See'gohelptestfunc'formore. Eachlistedpackagecausestheexecutionofaseparatetestbinary. Fileswhosenamesbeginwith"_"(including"_test.go")or"."areignored. Testfilesthatdeclareapackagewiththesuffix"_test"willbecompiledasa separatepackage,andthenlinkedandrunwiththemaintestbinary. Thegotoolwillignoreadirectorynamed"testdata",makingitavailable toholdancillarydataneededbythetests. Aspartofbuildingatestbinary,gotestrunsgovetonthepackage anditstestsourcefilestoidentifysignificantproblems.Ifgovet findsanyproblems,gotestreportsthoseanddoesnotrunthetest binary.Onlyahigh-confidencesubsetofthedefaultgovetchecksare used.Thatsubsetis:'atomic','bool','buildtags','errorsas', 'ifaceassert','nilfunc','printf',and'stringintconv'.Youcansee thedocumentationfortheseandothervettestsvia"godoccmd/vet". Todisabletherunningofgovet,usethe-vet=offflag. Alltestoutputandsummarylinesareprintedtothegocommand's standardoutput,evenifthetestprintedthemtoitsownstandard error.(Thegocommand'sstandarderrorisreservedforprinting errorsbuildingthetests.) Gotestrunsintwodifferentmodes: Thefirst,calledlocaldirectorymode,occurswhengotestis invokedwithnopackagearguments(forexample,'gotest'or'go test-v').Inthismode,gotestcompilesthepackagesourcesand testsfoundinthecurrentdirectoryandthenrunstheresulting testbinary.Inthismode,caching(discussedbelow)isdisabled. Afterthepackagetestfinishes,gotestprintsasummaryline showingtheteststatus('ok'or'FAIL'),packagename,andelapsed time. Thesecond,calledpackagelistmode,occurswhengotestisinvoked withexplicitpackagearguments(forexample'gotestmath','go test./...',andeven'gotest.').Inthismode,gotestcompiles andtestseachofthepackageslistedonthecommandline.Ifa packagetestpasses,gotestprintsonlythefinal'ok'summary line.Ifapackagetestfails,gotestprintsthefulltestoutput. Ifinvokedwiththe-benchor-vflag,gotestprintsthefull outputevenforpassingpackagetests,inordertodisplaythe requestedbenchmarkresultsorverboselogging.Afterthepackage testsforallofthelistedpackagesfinish,andtheiroutputis printed,gotestprintsafinal'FAIL'statusifanypackagetest hasfailed. Inpackagelistmodeonly,gotestcachessuccessfulpackagetest resultstoavoidunnecessaryrepeatedrunningoftests.Whenthe resultofatestcanberecoveredfromthecache,gotestwill redisplaythepreviousoutputinsteadofrunningthetestbinary again.Whenthishappens,gotestprints'(cached)'inplaceofthe elapsedtimeinthesummaryline. Theruleforamatchinthecacheisthattheruninvolvesthesame testbinaryandtheflagsonthecommandlinecomeentirelyfroma restrictedsetof'cacheable'testflags,definedas-benchtime,-cpu, -list,-parallel,-run,-short,and-v.Ifarunofgotesthasanytest ornon-testflagsoutsidethisset,theresultisnotcached.To disabletestcaching,useanytestflagorargumentotherthanthe cacheableflags.Theidiomaticwaytodisabletestcachingexplicitly istouse-count=1.Teststhatopenfileswithinthepackage'ssource root(usually$GOPATH)orthatconsultenvironmentvariablesonly matchfuturerunsinwhichthefilesandenvironmentvariablesareunchanged. Acachedtestresultistreatedasexecutinginnotimeatall, soasuccessfulpackagetestresultwillbecachedandreused regardlessof-timeoutsetting. Inadditiontothebuildflags,theflagshandledby'gotest'itselfare: -args Passtheremainderofthecommandline(everythingafter-args) tothetestbinary,uninterpretedandunchanged. Becausethisflagconsumestheremainderofthecommandline, thepackagelist(ifpresent)mustappearbeforethisflag. -c Compilethetestbinarytopkg.testbutdonotrunit (wherepkgisthelastelementofthepackage'simportpath). Thefilenamecanbechangedwiththe-oflag. -execxprog Runthetestbinaryusingxprog.Thebehavioristhesameas in'gorun'.See'gohelprun'fordetails. -i Installpackagesthataredependenciesofthetest. Donotrunthetest. The-iflagisdeprecated.Compiledpackagesarecachedautomatically. -json ConverttestoutputtoJSONsuitableforautomatedprocessing. See'godoctest2json'fortheencodingdetails. -ofile Compilethetestbinarytothenamedfile. Theteststillruns(unless-cor-iisspecified). Thetestbinaryalsoacceptsflagsthatcontrolexecutionofthetest;these flagsarealsoaccessibleby'gotest'.See'gohelptestflag'fordetails. Formoreaboutbuildflags,see'gohelpbuild'. Formoreaboutspecifyingpackages,see'gohelppackages'. Seealso:gobuild,govet. Runspecifiedgotool¶Usage: gotool[-n]command[args...] Toolrunsthegotoolcommandidentifiedbythearguments. Withnoargumentsitprintsthelistofknowntools. The-nflagcausestooltoprintthecommandthatwouldbe executedbutnotexecuteit. Formoreabouteachtoolcommand,see'godoccmd/'. PrintGoversion¶Usage: goversion[-m][-v][file...] VersionprintsthebuildinformationforGoexecutables. GoversionreportstheGoversionusedtobuildeachofthenamed executablefiles. Ifnofilesarenamedonthecommandline,goversionprintsitsown versioninformation. Ifadirectoryisnamed,goversionwalksthatdirectory,recursively, lookingforrecognizedGobinariesandreportingtheirversions. Bydefault,goversiondoesnotreportunrecognizedfilesfound duringadirectoryscan.The-vflagcausesittoreportunrecognizedfiles. The-mflagcausesgoversiontoprinteachexecutable'sembedded moduleversioninformation,whenavailable.Intheoutput,themodule informationconsistsofmultiplelinesfollowingtheversionline,each indentedbyaleadingtabcharacter. Seealso:godocruntime/debug.BuildInfo. Reportlikelymistakesinpackages¶Usage: govet[-n][-x][-vettoolprog][buildflags][vetflags][packages] VetrunstheGovetcommandonthepackagesnamedbytheimportpaths. Formoreaboutvetanditsflags,see'godoccmd/vet'. Formoreaboutspecifyingpackages,see'gohelppackages'. Foralistofcheckersandtheirflags,see'gotoolvethelp'. Fordetailsofaspecificcheckersuchas'printf',see'gotoolvethelpprintf'. The-nflagprintscommandsthatwouldbeexecuted. The-xflagprintscommandsastheyareexecuted. The-vettool=progflagselectsadifferentanalysistoolwithalternative oradditionalchecks. Forexample,the'shadow'analyzercanbebuiltandrunusingthesecommands: goinstallgolang.org/x/tools/go/analysis/passes/shadow/cmd/shadow govet-vettool=$(whichshadow) Thebuildflagssupportedbygovetarethosethatcontrolpackageresolution andexecution,suchas-n,-x,-v,-tags,and-toolexec. Formoreabouttheseflags,see'gohelpbuild'. Seealso:gofmt,gofix. Buildconstraints¶Abuildconstraint,alsoknownasabuildtag,isalinecommentthatbegins //go:build thatliststheconditionsunderwhichafileshouldbeincludedinthepackage. Constraintsmayappearinanykindofsourcefile(notjustGo),but theymustappearnearthetopofthefile,preceded onlybyblanklinesandotherlinecomments.TheserulesmeanthatinGo filesabuildconstraintmustappearbeforethepackageclause. Todistinguishbuildconstraintsfrompackagedocumentation, abuildconstraintshouldbefollowedbyablankline. Abuildconstraintisevaluatedasanexpressioncontainingoptions combinedby||,&&,and!operatorsandparentheses.Operatorshave thesamemeaningasinGo. Forexample,thefollowingbuildconstraintconstrainsafileto buildwhenthe"linux"and"386"constraintsaresatisfied,orwhen "darwin"issatisfiedand"cgo"isnot: //go:build(linux&&386)||(darwin&&!cgo) Itisanerrorforafiletohavemorethanone//go:buildline. Duringaparticularbuild,thefollowingwordsaresatisfied: -thetargetoperatingsystem,asspelledbyruntime.GOOS,setwiththe GOOSenvironmentvariable. -thetargetarchitecture,asspelledbyruntime.GOARCH,setwiththe GOARCHenvironmentvariable. -thecompilerbeingused,either"gc"or"gccgo" -"cgo",ifthecgocommandissupported(seeCGO_ENABLEDin 'gohelpenvironment'). -atermforeachGomajorrelease,throughthecurrentversion: "go1.1"fromGoversion1.1onward,"go1.12"fromGo1.12,andsoon. -anyadditionaltagsgivenbythe-tagsflag(see'gohelpbuild'). Therearenoseparatebuildtagsforbetaorminorreleases. Ifafile'sname,afterstrippingtheextensionandapossible_testsuffix, matchesanyofthefollowingpatterns: *_GOOS *_GOARCH *_GOOS_GOARCH (example:source_windows_amd64.go)whereGOOSandGOARCHrepresent anyknownoperatingsystemandarchitecturevaluesrespectively,then thefileisconsideredtohaveanimplicitbuildconstraintrequiring thoseterms(inadditiontoanyexplicitconstraintsinthefile). UsingGOOS=androidmatchesbuildtagsandfilesasforGOOS=linux inadditiontoandroidtagsandfiles. UsingGOOS=illumosmatchesbuildtagsandfilesasforGOOS=solaris inadditiontoillumostagsandfiles. UsingGOOS=iosmatchesbuildtagsandfilesasforGOOS=darwin inadditiontoiostagsandfiles. Tokeepafilefrombeingconsideredforthebuild: //go:buildignore (anyotherunsatisfiedwordwillworkaswell,but"ignore"isconventional.) Tobuildafileonlywhenusingcgo,andonlyonLinuxandOSX: //go:buildcgo&&(linux||darwin) Suchafileisusuallypairedwithanotherfileimplementingthe defaultfunctionalityforothersystems,whichinthiscasewould carrytheconstraint: //go:build!(cgo&&(linux||darwin)) Namingafiledns_windows.gowillcauseittobeincludedonlywhen buildingthepackageforWindows;similarly,math_386.swillbeincluded onlywhenbuildingthepackagefor32-bitx86. Goversions1.16andearlierusedadifferentsyntaxforbuildconstraints, witha"//+build"prefix.Thegofmtcommandwilladdanequivalent//go:build constraintwhenencounteringtheoldersyntax. Buildmodes¶The'gobuild'and'goinstall'commandstakea-buildmodeargumentwhich indicateswhichkindofobjectfileistobebuilt.Currentlysupportedvalues are: -buildmode=archive Buildthelistednon-mainpackagesinto.afiles.Packagesnamed mainareignored. -buildmode=c-archive Buildthelistedmainpackage,plusallpackagesitimports, intoaCarchivefile.Theonlycallablesymbolswillbethose functionsexportedusingacgo//exportcomment.Requires exactlyonemainpackagetobelisted. -buildmode=c-shared Buildthelistedmainpackage,plusallpackagesitimports, intoaCsharedlibrary.Theonlycallablesymbolswill bethosefunctionsexportedusingacgo//exportcomment. Requiresexactlyonemainpackagetobelisted. -buildmode=default Listedmainpackagesarebuiltintoexecutablesandlisted non-mainpackagesarebuiltinto.afiles(thedefault behavior). -buildmode=shared Combineallthelistednon-mainpackagesintoasingleshared librarythatwillbeusedwhenbuildingwiththe-linkshared option.Packagesnamedmainareignored. -buildmode=exe Buildthelistedmainpackagesandeverythingtheyimportinto executables.Packagesnotnamedmainareignored. -buildmode=pie Buildthelistedmainpackagesandeverythingtheyimportinto positionindependentexecutables(PIE).Packagesnotnamed mainareignored. -buildmode=plugin Buildthelistedmainpackages,plusallpackagesthatthey import,intoaGoplugin.Packagesnotnamedmainareignored. OnAIX,whenlinkingaCprogramthatusesaGoarchivebuiltwith -buildmode=c-archive,youmustpass-Wl,-bnoobjreordertotheCcompiler. CallingbetweenGoandC¶TherearetwodifferentwaystocallbetweenGoandC/C++code. Thefirstisthecgotool,whichispartoftheGodistribution.For informationonhowtouseitseethecgodocumentation(godoccmd/cgo). ThesecondistheSWIGprogram,whichisageneraltoolfor interfacingbetweenlanguages.ForinformationonSWIGsee http://swig.org/.Whenrunninggobuild,anyfilewitha.swig extensionwillbepassedtoSWIG.Anyfilewitha.swigcxxextension willbepassedtoSWIGwiththe-c++option. WheneithercgoorSWIGisused,gobuildwillpassany.c,.m,.s,.S or.sxfilestotheCcompiler,andany.cc,.cpp,.cxxfilestotheC++ compiler.TheCCorCXXenvironmentvariablesmaybesettodetermine theCorC++compiler,respectively,touse. Buildandtestcaching¶Thegocommandcachesbuildoutputsforreuseinfuturebuilds. Thedefaultlocationforcachedataisasubdirectorynamedgo-build inthestandardusercachedirectoryforthecurrentoperatingsystem. SettingtheGOCACHEenvironmentvariableoverridesthisdefault, andrunning'goenvGOCACHE'printsthecurrentcachedirectory. Thegocommandperiodicallydeletescacheddatathathasnotbeen usedrecently.Running'goclean-cache'deletesallcacheddata. ThebuildcachecorrectlyaccountsforchangestoGosourcefiles, compilers,compileroptions,andsoon:cleaningthecacheexplicitly shouldnotbenecessaryintypicaluse.However,thebuildcache doesnotdetectchangestoClibrariesimportedwithcgo. IfyouhavemadechangestotheClibrariesonyoursystem,you willneedtocleanthecacheexplicitlyorelseusethe-abuildflag (see'gohelpbuild')toforcerebuildingofpackagesthat dependontheupdatedClibraries. Thegocommandalsocachessuccessfulpackagetestresults. See'gohelptest'fordetails.Running'goclean-testcache'removes allcachedtestresults(butnotcachedbuildresults). TheGODEBUGenvironmentvariablecanenableprintingofdebugging informationaboutthestateofthecache: GODEBUG=gocacheverify=1causesthegocommandtobypassthe useofanycacheentriesandinsteadrebuildeverythingandcheck thattheresultsmatchexistingcacheentries. GODEBUG=gocachehash=1causesthegocommandtoprinttheinputs forallofthecontenthashesitusestoconstructcachelookupkeys. Theoutputisvoluminousbutcanbeusefulfordebuggingthecache. GODEBUG=gocachetest=1causesthegocommandtoprintdetailsofits decisionsaboutwhethertoreuseacachedtestresult. Environmentvariables¶Thegocommandandthetoolsitinvokesconsultenvironmentvariables forconfiguration.Ifanenvironmentvariableisunset,thegocommand usesasensibledefaultsetting.Toseetheeffectivesettingofthe variable,run'goenv'.Tochangethedefaultsetting, run'goenv-w='.Defaultschangedusing'goenv-w' arerecordedinaGoenvironmentconfigurationfilestoredinthe per-userconfigurationdirectory,asreportedbyos.UserConfigDir. Thelocationoftheconfigurationfilecanbechangedbysetting theenvironmentvariableGOENV,and'goenvGOENV'printsthe effectivelocation,but'goenv-w'cannotchangethedefaultlocation. See'gohelpenv'fordetails. General-purposeenvironmentvariables: GO111MODULE Controlswhetherthegocommandrunsinmodule-awaremodeorGOPATHmode. Maybe"off","on",or"auto". Seehttps://golang.org/ref/mod#mod-commands. GCCGO Thegccgocommandtorunfor'gobuild-compiler=gccgo'. GOARCH Thearchitecture,orprocessor,forwhichtocompilecode. Examplesareamd64,386,arm,ppc64. GOBIN Thedirectorywhere'goinstall'willinstallacommand. GOCACHE Thedirectorywherethegocommandwillstorecached informationforreuseinfuturebuilds. GOMODCACHE Thedirectorywherethegocommandwillstoredownloadedmodules. GODEBUG Enablevariousdebuggingfacilities.See'godocruntime' fordetails. GOENV ThelocationoftheGoenvironmentconfigurationfile. Cannotbesetusing'goenv-w'. GOFLAGS Aspace-separatedlistof-flag=valuesettingstoapply togocommandsbydefault,whenthegivenflagisknownby thecurrentcommand.Eachentrymustbeastandaloneflag. Becausetheentriesarespace-separated,flagvaluesmust notcontainspaces.Flagslistedonthecommandline areappliedafterthislistandthereforeoverrideit. GOINSECURE Comma-separatedlistofglobpatterns(inthesyntaxofGo'spath.Match) ofmodulepathprefixesthatshouldalwaysbefetchedinaninsecure manner.Onlyappliestodependenciesthatarebeingfetcheddirectly. GOINSECUREdoesnotdisablechecksumdatabasevalidation.GOPRIVATEor GONOSUMDBmaybeusedtoachievethat. GOOS Theoperatingsystemforwhichtocompilecode. Examplesarelinux,darwin,windows,netbsd. GOPATH Formoredetailssee:'gohelpgopath'. GOPROXY URLofGomoduleproxy.Seehttps://golang.org/ref/mod#environment-variables andhttps://golang.org/ref/mod#module-proxyfordetails. GOPRIVATE,GONOPROXY,GONOSUMDB Comma-separatedlistofglobpatterns(inthesyntaxofGo'spath.Match) ofmodulepathprefixesthatshouldalwaysbefetcheddirectly orthatshouldnotbecomparedagainstthechecksumdatabase. Seehttps://golang.org/ref/mod#private-modules. GOROOT Therootofthegotree. GOSUMDB Thenameofchecksumdatabasetouseandoptionallyitspublickeyand URL.Seehttps://golang.org/ref/mod#authenticating. GOTMPDIR Thedirectorywherethegocommandwillwrite temporarysourcefiles,packages,andbinaries. GOVCS Listsversioncontrolcommandsthatmaybeusedwithmatchingservers. See'gohelpvcs'. Environmentvariablesforusewithcgo: AR Thecommandtousetomanipulatelibraryarchiveswhen buildingwiththegccgocompiler. Thedefaultis'ar'. CC ThecommandtousetocompileCcode. CGO_ENABLED Whetherthecgocommandissupported.Either0or1. CGO_CFLAGS Flagsthatcgowillpasstothecompilerwhencompiling Ccode. CGO_CFLAGS_ALLOW Aregularexpressionspecifyingadditionalflagstoallow toappearin#cgoCFLAGSsourcecodedirectives. DoesnotapplytotheCGO_CFLAGSenvironmentvariable. CGO_CFLAGS_DISALLOW Aregularexpressionspecifyingflagsthatmustbedisallowed fromappearingin#cgoCFLAGSsourcecodedirectives. DoesnotapplytotheCGO_CFLAGSenvironmentvariable. CGO_CPPFLAGS,CGO_CPPFLAGS_ALLOW,CGO_CPPFLAGS_DISALLOW LikeCGO_CFLAGS,CGO_CFLAGS_ALLOW,andCGO_CFLAGS_DISALLOW, butfortheCpreprocessor. CGO_CXXFLAGS,CGO_CXXFLAGS_ALLOW,CGO_CXXFLAGS_DISALLOW LikeCGO_CFLAGS,CGO_CFLAGS_ALLOW,andCGO_CFLAGS_DISALLOW, butfortheC++compiler. CGO_FFLAGS,CGO_FFLAGS_ALLOW,CGO_FFLAGS_DISALLOW LikeCGO_CFLAGS,CGO_CFLAGS_ALLOW,andCGO_CFLAGS_DISALLOW, butfortheFortrancompiler. CGO_LDFLAGS,CGO_LDFLAGS_ALLOW,CGO_LDFLAGS_DISALLOW LikeCGO_CFLAGS,CGO_CFLAGS_ALLOW,andCGO_CFLAGS_DISALLOW, butforthelinker. CXX ThecommandtousetocompileC++code. FC ThecommandtousetocompileFortrancode. PKG_CONFIG Pathtopkg-configtool. Architecture-specificenvironmentvariables: GOARM ForGOARCH=arm,theARMarchitectureforwhichtocompile. Validvaluesare5,6,7. GO386 ForGOARCH=386,howtoimplementfloatingpointinstructions. Validvaluesaresse2(default),softfloat. GOMIPS ForGOARCH=mips{,le},whethertousefloatingpointinstructions. Validvaluesarehardfloat(default),softfloat. GOMIPS64 ForGOARCH=mips64{,le},whethertousefloatingpointinstructions. Validvaluesarehardfloat(default),softfloat. GOPPC64 ForGOARCH=ppc64{,le},thetargetISA(InstructionSetArchitecture). Validvaluesarepower8(default),power9. GOWASM ForGOARCH=wasm,comma-separatedlistofexperimentalWebAssemblyfeaturestouse. Validvaluesaresatconv,signext. Special-purposeenvironmentvariables: GCCGOTOOLDIR Ifset,wheretofindgccgotools,suchascgo. Thedefaultisbasedonhowgccgowasconfigured. GOEXPERIMENT Comma-separatedlistoftoolchainexperimentstoenableordisable. Thelistofavailableexperimentsmaychangearbitrarilyovertime. Seesrc/internal/goexperiment/flags.goforcurrentlyvalidvalues. Warning:Thisvariableisprovidedforthedevelopmentandtesting oftheGotoolchainitself.Usebeyondthatpurposeisunsupported. GOROOT_FINAL TherootoftheinstalledGotree,whenitis installedinalocationotherthanwhereitisbuilt. FilenamesinstacktracesarerewrittenfromGOROOTto GOROOT_FINAL. GO_EXTLINK_ENABLED Whetherthelinkershoulduseexternallinkingmode whenusing-linkmode=autowithcodethatusescgo. Setto0todisableexternallinkingmode,1toenableit. GIT_ALLOW_PROTOCOL DefinedbyGit.Acolon-separatedlistofschemesthatareallowed tobeusedwithgitfetch/clone.Ifset,anyschemenotexplicitly mentionedwillbeconsideredinsecureby'goget'. BecausethevariableisdefinedbyGit,thedefaultvaluecannot besetusing'goenv-w'. Additionalinformationavailablefrom'goenv'butnotreadfromtheenvironment: GOEXE Theexecutablefilenamesuffix(".exe"onWindows,""onothersystems). GOGCCFLAGS Aspace-separatedlistofargumentssuppliedtotheCCcommand. GOHOSTARCH Thearchitecture(GOARCH)oftheGotoolchainbinaries. GOHOSTOS Theoperatingsystem(GOOS)oftheGotoolchainbinaries. GOMOD Theabsolutepathtothego.modofthemainmodule. Ifmodule-awaremodeisenabled,butthereisnogo.mod,GOMODwillbe os.DevNull("/dev/null"onUnix-likesystems,"NUL"onWindows). Ifmodule-awaremodeisdisabled,GOMODwillbetheemptystring. GOTOOLDIR Thedirectorywherethegotools(compile,cover,doc,etc...)areinstalled. GOVERSION TheversionoftheinstalledGotree,asreportedbyruntime.Version. Filetypes¶Thegocommandexaminesthecontentsofarestrictedsetoffiles ineachdirectory.Itidentifieswhichfilestoexaminebasedon theextensionofthefilename.Theseextensionsare: .go Gosourcefiles. .c,.h Csourcefiles. IfthepackageusescgoorSWIG,thesewillbecompiledwiththe OS-nativecompiler(typicallygcc);otherwisetheywill triggeranerror. .cc,.cpp,.cxx,.hh,.hpp,.hxx C++sourcefiles.OnlyusefulwithcgoorSWIG,andalways compiledwiththeOS-nativecompiler. .m Objective-Csourcefiles.Onlyusefulwithcgo,andalways compiledwiththeOS-nativecompiler. .s,.S,.sx Assemblersourcefiles. IfthepackageusescgoorSWIG,thesewillbeassembledwiththe OS-nativeassembler(typicallygcc(sic));otherwisethey willbeassembledwiththeGoassembler. .swig,.swigcxx SWIGdefinitionfiles. .syso Systemobjectfiles. Filesofeachofthesetypesexcept.sysomaycontainbuild constraints,butthegocommandstopsscanningforbuildconstraints atthefirstiteminthefilethatisnotablanklineor//-style linecomment.Seethego/buildpackagedocumentationfor moredetails. Thego.modfile¶Amoduleversionisdefinedbyatreeofsourcefiles,withago.mod fileinitsroot.Whenthegocommandisrun,itlooksinthecurrent directoryandthensuccessiveparentdirectoriestofindthego.mod markingtherootofthemain(current)module. Thego.modfileformatisdescribedindetailat https://golang.org/ref/mod#go-mod-file. Tocreateanewgo.modfile,use'gomodinit'.Fordetailssee 'gohelpmodinit'orhttps://golang.org/ref/mod#go-mod-init. Toaddmissingmodulerequirementsorremoveunneededrequirements, use'gomodtidy'.Fordetails,see'gohelpmodtidy'or https://golang.org/ref/mod#go-mod-tidy. Toadd,upgrade,downgrade,orremoveaspecificmodulerequirement,use 'goget'.Fordetails,see'gohelpmodule-get'or https://golang.org/ref/mod#go-get. Tomakeotherchangesortoparsego.modasJSONforusebyothertools, use'gomodedit'.See'gohelpmodedit'or https://golang.org/ref/mod#go-mod-edit. GOPATHenvironmentvariable¶TheGopathisusedtoresolveimportstatements. Itisimplementedbyanddocumentedinthego/buildpackage. TheGOPATHenvironmentvariablelistsplacestolookforGocode. OnUnix,thevalueisacolon-separatedstring. OnWindows,thevalueisasemicolon-separatedstring. OnPlan9,thevalueisalist. Iftheenvironmentvariableisunset,GOPATHdefaults toasubdirectorynamed"go"intheuser'shomedirectory ($HOME/goonUnix,%USERPROFILE%\goonWindows), unlessthatdirectoryholdsaGodistribution. Run"goenvGOPATH"toseethecurrentGOPATH. Seehttps://golang.org/wiki/SettingGOPATHtosetacustomGOPATH. EachdirectorylistedinGOPATHmusthaveaprescribedstructure: Thesrcdirectoryholdssourcecode.Thepathbelowsrc determinestheimportpathorexecutablename. Thepkgdirectoryholdsinstalledpackageobjects. AsintheGotree,eachtargetoperatingsystemand architecturepairhasitsownsubdirectoryofpkg (pkg/GOOS_GOARCH). IfDIRisadirectorylistedintheGOPATH,apackagewith sourceinDIR/src/foo/barcanbeimportedas"foo/bar"and hasitscompiledforminstalledto"DIR/pkg/GOOS_GOARCH/foo/bar.a". Thebindirectoryholdscompiledcommands. Eachcommandisnamedforitssourcedirectory,butonly thefinalelement,nottheentirepath.Thatis,the commandwithsourceinDIR/src/foo/quuxisinstalledinto DIR/bin/quux,notDIR/bin/foo/quux.The"foo/"prefixisstripped sothatyoucanaddDIR/bintoyourPATHtogetatthe installedcommands.IftheGOBINenvironmentvariableis set,commandsareinstalledtothedirectoryitnamesinstead ofDIR/bin.GOBINmustbeanabsolutepath. Here'sanexampledirectorylayout: GOPATH=/home/user/go /home/user/go/ src/ foo/ bar/(gocodeinpackagebar) x.go quux/(gocodeinpackagemain) y.go bin/ quux(installedcommand) pkg/ linux_amd64/ foo/ bar.a(installedpackageobject) GosearcheseachdirectorylistedinGOPATHtofindsourcecode, butnewpackagesarealwaysdownloadedintothefirstdirectory inthelist. Seehttps://golang.org/doc/code.htmlforanexample. GOPATHandModules¶Whenusingmodules,GOPATHisnolongerusedforresolvingimports. However,itisstillusedtostoredownloadedsourcecode(inGOPATH/pkg/mod) andcompiledcommands(inGOPATH/bin). InternalDirectories¶Codeinorbelowadirectorynamed"internal"isimportableonly bycodeinthedirectorytreerootedattheparentof"internal". Here'sanextendedversionofthedirectorylayoutabove: /home/user/go/ src/ crash/ bang/(gocodeinpackagebang) b.go foo/(gocodeinpackagefoo) f.go bar/(gocodeinpackagebar) x.go internal/ baz/(gocodeinpackagebaz) z.go quux/(gocodeinpackagemain) y.go Thecodeinz.goisimportedas"foo/internal/baz",butthat importstatementcanonlyappearinsourcefilesinthesubtree rootedatfoo.Thesourcefilesfoo/f.go,foo/bar/x.go,and foo/quux/y.gocanallimport"foo/internal/baz",butthesourcefile crash/bang/b.gocannot. Seehttps://golang.org/s/go14internalfordetails. VendorDirectories¶Go1.6includessupportforusinglocalcopiesofexternaldependencies tosatisfyimportsofthosedependencies,oftenreferredtoasvendoring. Codebelowadirectorynamed"vendor"isimportableonly bycodeinthedirectorytreerootedattheparentof"vendor", andonlyusinganimportpaththatomitstheprefixuptoand includingthevendorelement. Here'stheexamplefromtheprevioussection, butwiththe"internal"directoryrenamedto"vendor" andanewfoo/vendor/crash/bangdirectoryadded: /home/user/go/ src/ crash/ bang/(gocodeinpackagebang) b.go foo/(gocodeinpackagefoo) f.go bar/(gocodeinpackagebar) x.go vendor/ crash/ bang/(gocodeinpackagebang) b.go baz/(gocodeinpackagebaz) z.go quux/(gocodeinpackagemain) y.go Thesamevisibilityrulesapplyasforinternal,butthecode inz.goisimportedas"baz",notas"foo/vendor/baz". Codeinvendordirectoriesdeeperinthesourcetreeshadows codeinhigherdirectories.Withinthesubtreerootedatfoo,animport of"crash/bang"resolvesto"foo/vendor/crash/bang",notthe top-level"crash/bang". Codeinvendordirectoriesisnotsubjecttoimportpath checking(see'gohelpimportpath'). When'goget'checksoutorupdatesagitrepository,itnowalso updatessubmodules. Vendordirectoriesdonotaffecttheplacementofnewrepositories beingcheckedoutforthefirsttimeby'goget':thosearealways placedinthemainGOPATH,neverinavendorsubtree. Seehttps://golang.org/s/go15vendorfordetails. LegacyGOPATHgoget¶The'goget'commandchangesbehaviordependingonwhetherthe gocommandisrunninginmodule-awaremodeorlegacyGOPATHmode. Thishelptext,accessibleas'gohelpgopath-get'eveninmodule-awaremode, describes'goget'asitoperatesinlegacyGOPATHmode. Usage:goget[-d][-f][-t][-u][-v][-fix][buildflags][packages] Getdownloadsthepackagesnamedbytheimportpaths,alongwiththeir dependencies.Ittheninstallsthenamedpackages,like'goinstall'. The-dflaginstructsgettostopafterdownloadingthepackages;thatis, itinstructsgetnottoinstallthepackages. The-fflag,validonlywhen-uisset,forcesget-unottoverifythat eachpackagehasbeencheckedoutfromthesourcecontrolrepository impliedbyitsimportpath.Thiscanbeusefulifthesourceisalocalfork oftheoriginal. The-fixflaginstructsgettorunthefixtoolonthedownloadedpackages beforeresolvingdependenciesorbuildingthecode. The-tflaginstructsgettoalsodownloadthepackagesrequiredtobuild thetestsforthespecifiedpackages. The-uflaginstructsgettousethenetworktoupdatethenamedpackages andtheirdependencies.Bydefault,getusesthenetworktocheckout missingpackagesbutdoesnotuseittolookforupdatestoexistingpackages. The-vflagenablesverboseprogressanddebugoutput. Getalsoacceptsbuildflagstocontroltheinstallation.See'gohelpbuild'. Whencheckingoutanewpackage,getcreatesthetargetdirectory GOPATH/src/.IftheGOPATHcontainsmultipleentries, getusesthefirstone.Formoredetailssee:'gohelpgopath'. Whencheckingoutorupdatingapackage,getlooksforabranchortag thatmatchesthelocallyinstalledversionofGo.Themostimportant ruleisthatifthelocalinstallationisrunningversion"go1",get searchesforabranchortagnamed"go1".Ifnosuchversionexists itretrievesthedefaultbranchofthepackage. WhengogetchecksoutorupdatesaGitrepository, italsoupdatesanygitsubmodulesreferencedbytherepository. Getneverchecksoutorupdatescodestoredinvendordirectories. Formoreaboutspecifyingpackages,see'gohelppackages'. Formoreabouthow'goget'findssourcecodeto download,see'gohelpimportpath'. ThistextdescribesthebehaviorofgetwhenusingGOPATH tomanagesourcecodeanddependencies. Ifinsteadthegocommandisrunninginmodule-awaremode, thedetailsofget'sflagsandeffectschange,asdoes'gohelpget'. See'gohelpmodules'and'gohelpmodule-get'. Seealso:gobuild,goinstall,goclean. Moduleproxyprotocol¶AGomoduleproxyisanywebserverthatcanrespondtoGETrequestsfor URLsofaspecifiedform.Therequestshavenoqueryparameters,soeven asiteservingfromafixedfilesystem(includingafile:///URL) canbeamoduleproxy. FordetailsontheGOPROXYprotocol,see https://golang.org/ref/mod#goproxy-protocol. Importpathsyntax¶Animportpath(see'gohelppackages')denotesapackagestoredinthelocal filesystem.Ingeneral,animportpathdenoteseitherastandardpackage(such as"unicode/utf8")orapackagefoundinoneoftheworkspaces(Formore detailssee:'gohelpgopath'). Relativeimportpaths¶Animportpathbeginningwith./or../iscalledarelativepath. Thetoolchainsupportsrelativeimportpathsasashortcutintwoways. First,arelativepathcanbeusedasashorthandonthecommandline. Ifyouareworkinginthedirectorycontainingthecodeimportedas "unicode"andwanttorunthetestsfor"unicode/utf8",youcantype "gotest./utf8"insteadofneedingtospecifythefullpath. Similarly,inthereversesituation,"gotest.."willtest"unicode"from the"unicode/utf8"directory.Relativepatternsarealsoallowed,like "gotest./..."totestallsubdirectories.See'gohelppackages'fordetails onthepatternsyntax. Second,ifyouarecompilingaGoprogramnotinaworkspace, youcanusearelativepathinanimportstatementinthatprogram torefertonearbycodealsonotinaworkspace. Thismakesiteasytoexperimentwithsmallmultipackageprograms outsideoftheusualworkspaces,butsuchprogramscannotbe installedwith"goinstall"(thereisnoworkspaceinwhichtoinstallthem), sotheyarerebuiltfromscratcheachtimetheyarebuilt. Toavoidambiguity,Goprogramscannotuserelativeimportpaths withinaworkspace. Remoteimportpaths¶Certainimportpathsalso describehowtoobtainthesourcecodeforthepackageusing arevisioncontrolsystem. Afewcommoncodehostingsiteshavespecialsyntax: Bitbucket(Git,Mercurial) import"bitbucket.org/user/project" import"bitbucket.org/user/project/sub/directory" GitHub(Git) import"github.com/user/project" import"github.com/user/project/sub/directory" Launchpad(Bazaar) import"launchpad.net/project" import"launchpad.net/project/series" import"launchpad.net/project/series/sub/directory" import"launchpad.net/~user/project/branch" import"launchpad.net/~user/project/branch/sub/directory" IBMDevOpsServices(Git) import"hub.jazz.net/git/user/project" import"hub.jazz.net/git/user/project/sub/directory" Forcodehostedonotherservers,importpathsmayeitherbequalified withtheversioncontroltype,orthegotoolcandynamicallyfetch theimportpathoverhttps/httpanddiscoverwherethecoderesides fromatagintheHTML. Todeclarethecodelocation,animportpathoftheform repository.vcs/path specifiesthegivenrepository,withorwithoutthe.vcssuffix, usingthenamedversioncontrolsystem,andthenthepathinside thatrepository.Thesupportedversioncontrolsystemsare: Bazaar.bzr Fossil.fossil Git.git Mercurial.hg Subversion.svn Forexample, import"example.org/user/foo.hg" denotestherootdirectoryoftheMercurialrepositoryat example.org/user/fooorfoo.hg,and import"example.org/repo.git/foo/bar" denotesthefoo/bardirectoryoftheGitrepositoryat example.org/repoorrepo.git. Whenaversioncontrolsystemsupportsmultipleprotocols, eachistriedinturnwhendownloading.Forexample,aGit downloadtrieshttps://,thengit+ssh://. Bydefault,downloadsarerestrictedtoknownsecureprotocols (e.g.https,ssh).TooverridethissettingforGitdownloads,the GIT_ALLOW_PROTOCOLenvironmentvariablecanbeset(Formoredetailssee: 'gohelpenvironment'). Iftheimportpathisnotaknowncodehostingsiteandalsolacksa versioncontrolqualifier,thegotoolattemptstofetchtheimport overhttps/httpandlooksforataginthedocument'sHTML . Themetataghastheform: Theimport-prefixistheimportpathcorrespondingtotherepository root.Itmustbeaprefixoranexactmatchofthepackagebeing fetchedwith"goget".Ifit'snotanexactmatch,anotherhttp requestismadeattheprefixtoverifythetagsmatch. Themetatagshouldappearasearlyinthefileaspossible. Inparticular,itshouldappearbeforeanyrawJavaScriptorCSS, toavoidconfusingthegocommand'srestrictedparser. Thevcsisoneof"bzr","fossil","git","hg","svn". Therepo-rootistherootoftheversioncontrolsystem containingaschemeandnotcontaininga.vcsqualifier. Forexample, import"example.org/pkg/foo" willresultinthefollowingrequests: https://example.org/pkg/foo?go-get=1(preferred) http://example.org/pkg/foo?go-get=1(fallback,onlywithuseofcorrectlysetGOINSECURE) Ifthatpagecontainsthemetatag thegotoolwillverifythathttps://example.org/?go-get=1containsthe samemetatagandthengitclonehttps://code.org/r/p/exprojinto GOPATH/src/example.org. WhenusingGOPATH,downloadedpackagesarewrittentothefirstdirectory listedintheGOPATHenvironmentvariable. (See'gohelpgopath-get'and'gohelpgopath'.) Whenusingmodules,downloadedpackagesarestoredinthemodulecache. Seehttps://golang.org/ref/mod#module-cache. Whenusingmodules,anadditionalvariantofthego-importmetatagis recognizedandispreferredoverthoselistingversioncontrolsystems. Thatvariantuses"mod"asthevcsinthecontentvalue,asin: Thistagmeanstofetchmoduleswithpathsbeginningwithexample.org fromthemoduleproxyavailableattheURLhttps://code.org/moduleproxy. Seehttps://golang.org/ref/mod#goproxy-protocolfordetailsaboutthe proxyprotocol. Importpathchecking¶Whenthecustomimportpathfeaturedescribedaboveredirectstoa knowncodehostingsite,eachoftheresultingpackageshastwopossible importpaths,usingthecustomdomainortheknownhostingsite. Apackagestatementissaidtohavean"importcomment"ifitisimmediately followed(beforethenextnewline)byacommentofoneofthesetwoforms: packagemath//import"path" packagemath/*import"path"*/ Thegocommandwillrefusetoinstallapackagewithanimportcomment unlessitisbeingreferredtobythatimportpath.Inthisway,importcomments letpackageauthorsmakesurethecustomimportpathisusedandnota directpathtotheunderlyingcodehostingsite. Importpathcheckingisdisabledforcodefoundwithinvendortrees. Thismakesitpossibletocopycodeintoalternatelocationsinvendortrees withoutneedingtoupdateimportcomments. Importpathcheckingisalsodisabledwhenusingmodules. Importpathcommentsareobsoletedbythego.modfile'smodulestatement. Seehttps://golang.org/s/go14customimportfordetails. Modules,moduleversions,andmore¶ModulesarehowGomanagesdependencies. Amoduleisacollectionofpackagesthatarereleased,versioned,and distributedtogether.Modulesmaybedownloadeddirectlyfromversioncontrol repositoriesorfrommoduleproxyservers. Foraseriesoftutorialsonmodules,see https://golang.org/doc/tutorial/create-module. Foradetailedreferenceonmodules,seehttps://golang.org/ref/mod. Bydefault,thegocommandmaydownloadmodulesfromhttps://proxy.golang.org. Itmayauthenticatemodulesusingthechecksumdatabaseat https://sum.golang.org.BothservicesareoperatedbytheGoteamatGoogle. Theprivacypoliciesfortheseservicesareavailableat https://proxy.golang.org/privacyandhttps://sum.golang.org/privacy, respectively. Thegocommand'sdownloadbehaviormaybeconfiguredusingGOPROXY,GOSUMDB, GOPRIVATE,andotherenvironmentvariables.See'gohelpenvironment' andhttps://golang.org/ref/mod#private-module-privacyformoreinformation. Moduleauthenticationusinggo.sum¶Whenthegocommanddownloadsamodulezipfileorgo.modfileintothe modulecache,itcomputesacryptographichashandcomparesitwithaknown valuetoverifythefilehasn'tchangedsinceitwasfirstdownloaded.Known hashesarestoredinafileinthemodulerootdirectorynamedgo.sum.Hashes mayalsobedownloadedfromthechecksumdatabasedependingonthevaluesof GOSUMDB,GOPRIVATE,andGONOSUMDB. Fordetails,seehttps://golang.org/ref/mod#authenticating. Packagelistsandpatterns¶Manycommandsapplytoasetofpackages: goaction[packages] Usually,[packages]isalistofimportpaths. Animportpaththatisarootedpathorthatbeginswith a.or..elementisinterpretedasafilesystempathand denotesthepackageinthatdirectory. Otherwise,theimportpathPdenotesthepackagefoundin thedirectoryDIR/src/PforsomeDIRlistedintheGOPATH environmentvariable(Formoredetailssee:'gohelpgopath'). Ifnoimportpathsaregiven,theactionappliestothe packageinthecurrentdirectory. Therearefourreservednamesforpathsthatshouldnotbeused forpackagestobebuiltwiththegotool: -"main"denotesthetop-levelpackageinastand-aloneexecutable. -"all"expandstoallpackagesfoundinalltheGOPATH trees.Forexample,'golistall'listsallthepackagesonthelocal system.Whenusingmodules,"all"expandstoallpackagesin themainmoduleandtheirdependencies,includingdependencies neededbytestsofanyofthose. -"std"islikeallbutexpandstojustthepackagesinthestandard Golibrary. -"cmd"expandstotheGorepository'scommandsandtheir internallibraries. Importpathsbeginningwith"cmd/"onlymatchsourcecodein theGorepository. Animportpathisapatternifitincludesoneormore"..."wildcards, eachofwhichcanmatchanystring,includingtheemptystringand stringscontainingslashes.Suchapatternexpandstoallpackage directoriesfoundintheGOPATHtreeswithnamesmatchingthe patterns. Tomakecommonpatternsmoreconvenient,therearetwospecialcases. First,/...attheendofthepatterncanmatchanemptystring, sothatnet/...matchesbothnetandpackagesinitssubdirectories,likenet/http. Second,anyslash-separatedpatternelementcontainingawildcardnever participatesinamatchofthe"vendor"elementinthepathofavendored package,sothat./...doesnotmatchpackagesinsubdirectoriesof ./vendoror./mycode/vendor,but./vendor/...and./mycode/vendor/...do. Note,however,thatadirectorynamedvendorthatitselfcontainscode isnotavendoredpackage:cmd/vendorwouldbeacommandnamedvendor, andthepatterncmd/...matchesit. Seegolang.org/s/go15vendorformoreaboutvendoring. Animportpathcanalsonameapackagetobedownloadedfrom aremoterepository.Run'gohelpimportpath'fordetails. Everypackageinaprogrammusthaveauniqueimportpath. Byconvention,thisisarrangedbystartingeachpathwitha uniqueprefixthatbelongstoyou.Forexample,pathsused internallyatGoogleallbeginwith'google',andpaths denotingremoterepositoriesbeginwiththepathtothecode, suchas'github.com/user/repo'. Packagesinaprogramneednothaveuniquepackagenames, buttherearetworeservedpackagenameswithspecialmeaning. Thenamemainindicatesacommand,notalibrary. Commandsarebuiltintobinariesandcannotbeimported. Thenamedocumentationindicatesdocumentationfor anon-Goprograminthedirectory.Filesinpackagedocumentation areignoredbythegocommand. Asaspecialcase,ifthepackagelistisalistof.gofilesfroma singledirectory,thecommandisappliedtoasinglesynthesized packagemadeupofexactlythosefiles,ignoringanybuildconstraints inthosefilesandignoringanyotherfilesinthedirectory. Directoryandfilenamesthatbeginwith"."or"_"areignored bythegotool,asaredirectoriesnamed"testdata". Configurationfordownloadingnon-publiccode¶ThegocommanddefaultstodownloadingmodulesfromthepublicGomodule mirroratproxy.golang.org.Italsodefaultstovalidatingdownloadedmodules, regardlessofsource,againstthepublicGochecksumdatabaseatsum.golang.org. Thesedefaultsworkwellforpubliclyavailablesourcecode. TheGOPRIVATEenvironmentvariablecontrolswhichmodulesthegocommand considerstobeprivate(notavailablepublicly)andshouldthereforenotuse theproxyorchecksumdatabase.Thevariableisacomma-separatedlistof globpatterns(inthesyntaxofGo'spath.Match)ofmodulepathprefixes. Forexample, GOPRIVATE=*.corp.example.com,rsc.io/private causesthegocommandtotreatasprivateanymodulewithapathprefix matchingeitherpattern,includinggit.corp.example.com/xyzzy,rsc.io/private, andrsc.io/private/quux. Forfine-grainedcontrolovermoduledownloadandvalidation,theGONOPROXY andGONOSUMDBenvironmentvariablesacceptthesamekindofgloblist andoverrideGOPRIVATEforthespecificdecisionofwhethertousetheproxy andchecksumdatabase,respectively. Forexample,ifacompanyranamoduleproxyservingprivatemodules, userswouldconfiguregousing: GOPRIVATE=*.corp.example.com GOPROXY=proxy.example.com GONOPROXY=none TheGOPRIVATEvariableisalsousedtodefinethe"public"and"private" patternsfortheGOVCSvariable;see'gohelpvcs'.Forthatusage, GOPRIVATEapplieseveninGOPATHmode.Inthatcase,itmatchesimportpaths insteadofmodulepaths. The'goenv-w'command(see'gohelpenv')canbeusedtosetthesevariables forfuturegocommandinvocations. Formoredetails,seehttps://golang.org/ref/mod#private-modules. Testingflags¶The'gotest'commandtakesbothflagsthatapplyto'gotest'itself andflagsthatapplytotheresultingtestbinary. Severaloftheflagscontrolprofilingandwriteanexecutionprofile suitablefor"gotoolpprof";run"gotoolpprof-h"formore information.The--alloc_space,--alloc_objects,and--show_bytes optionsofpprofcontrolhowtheinformationispresented. Thefollowingflagsarerecognizedbythe'gotest'commandand controltheexecutionofanytest: -benchregexp Runonlythosebenchmarksmatchingaregularexpression. Bydefault,nobenchmarksarerun. Torunallbenchmarks,use'-bench.'or'-bench=.'. Theregularexpressionissplitbyunbracketedslash(/) charactersintoasequenceofregularexpressions,andeach partofabenchmark'sidentifiermustmatchthecorresponding elementinthesequence,ifany.Possibleparentsofmatches arerunwithb.N=1toidentifysub-benchmarks.Forexample, given-bench=X/Y,top-levelbenchmarksmatchingXarerun withb.N=1tofindanysub-benchmarksmatchingY,whichare thenruninfull. -benchtimet Runenoughiterationsofeachbenchmarktotaket,specified asatime.Duration(forexample,-benchtime1h30s). Thedefaultis1second(1s). ThespecialsyntaxNxmeanstorunthebenchmarkNtimes (forexample,-benchtime100x). -countn Runeachtestandbenchmarkntimes(default1). If-cpuisset,runntimesforeachGOMAXPROCSvalue. Examplesarealwaysrunonce. -cover Enablecoverageanalysis. Notethatbecausecoverageworksbyannotatingthesource codebeforecompilation,compilationandtestfailureswith coverageenabledmayreportlinenumbersthatdon'tcorrespond totheoriginalsources. -covermodeset,count,atomic Setthemodeforcoverageanalysisforthepackage[s] beingtested.Thedefaultis"set"unless-raceisenabled, inwhichcaseitis"atomic". Thevalues: set:bool:doesthisstatementrun? count:int:howmanytimesdoesthisstatementrun? atomic:int:count,butcorrectinmultithreadedtests; significantlymoreexpensive. Sets-cover. -coverpkgpattern1,pattern2,pattern3 Applycoverageanalysisineachtesttopackagesmatchingthepatterns. Thedefaultisforeachtesttoanalyzeonlythepackagebeingtested. See'gohelppackages'foradescriptionofpackagepatterns. Sets-cover. -cpu1,2,4 SpecifyalistofGOMAXPROCSvaluesforwhichthetestsor benchmarksshouldbeexecuted.Thedefaultisthecurrentvalue ofGOMAXPROCS. -failfast Donotstartnewtestsafterthefirsttestfailure. -listregexp Listtests,benchmarks,orexamplesmatchingtheregularexpression. Notests,benchmarksorexampleswillberun.Thiswillonly listtop-leveltests.Nosubtestorsubbenchmarkswillbeshown. -paralleln Allowparallelexecutionoftestfunctionsthatcallt.Parallel. Thevalueofthisflagisthemaximumnumberofteststorun simultaneously;bydefault,itissettothevalueofGOMAXPROCS. Notethat-parallelonlyapplieswithinasingletestbinary. The'gotest'commandmayruntestsfordifferentpackages inparallelaswell,accordingtothesettingofthe-pflag (see'gohelpbuild'). -runregexp Runonlythosetestsandexamplesmatchingtheregularexpression. Fortests,theregularexpressionissplitbyunbracketedslash(/) charactersintoasequenceofregularexpressions,andeachpart ofatest'sidentifiermustmatchthecorrespondingelementin thesequence,ifany.Notethatpossibleparentsofmatchesare runtoo,sothat-run=X/Ymatchesandrunsandreportstheresult ofalltestsmatchingX,eventhosewithoutsub-testsmatchingY, becauseitmustrunthemtolookforthosesub-tests. -short Telllong-runningteststoshortentheirruntime. Itisoffbydefaultbutsetduringall.bashsothatinstalling theGotreecanrunasanitycheckbutnotspendtimerunning exhaustivetests. -shuffleoff,on,N Randomizetheexecutionorderoftestsandbenchmarks. Itisoffbydefault.If-shuffleissettoon,thenitwillseed therandomizerusingthesystemclock.If-shuffleissettoan integerN,thenNwillbeusedastheseedvalue.Inbothcases, theseedwillbereportedforreproducibility. -timeoutd Ifatestbinaryrunslongerthandurationd,panic. Ifdis0,thetimeoutisdisabled. Thedefaultis10minutes(10m). -v Verboseoutput:logalltestsastheyarerun.Alsoprintall textfromLogandLogfcallsevenifthetestsucceeds. -vetlist Configuretheinvocationof"govet"during"gotest" tousethecomma-separatedlistofvetchecks. Iflistisempty,"gotest"runs"govet"withacuratedlistof checksbelievedtobealwaysworthaddressing. Iflistis"off","gotest"doesnotrun"govet"atall. Thefollowingflagsarealsorecognizedby'gotest'andcanbeusedto profilethetestsduringexecution: -benchmem Printmemoryallocationstatisticsforbenchmarks. -blockprofileblock.out Writeagoroutineblockingprofiletothespecifiedfile whenalltestsarecomplete. Writestestbinaryas-cwould. -blockprofileraten Controlthedetailprovidedingoroutineblockingprofilesby callingruntime.SetBlockProfileRatewithn. See'godocruntime.SetBlockProfileRate'. Theprofileraimstosample,onaverage,oneblockingeventevery nnanosecondstheprogramspendsblocked.Bydefault, if-test.blockprofileissetwithoutthisflag,allblockingevents arerecorded,equivalentto-test.blockprofilerate=1. -coverprofilecover.out Writeacoverageprofiletothefileafteralltestshavepassed. Sets-cover. -cpuprofilecpu.out WriteaCPUprofiletothespecifiedfilebeforeexiting. Writestestbinaryas-cwould. -memprofilemem.out Writeanallocationprofiletothefileafteralltestshavepassed. Writestestbinaryas-cwould. -memprofileraten Enablemoreprecise(andexpensive)memoryallocationprofilesby settingruntime.MemProfileRate.See'godocruntime.MemProfileRate'. Toprofileallmemoryallocations,use-test.memprofilerate=1. -mutexprofilemutex.out Writeamutexcontentionprofiletothespecifiedfile whenalltestsarecomplete. Writestestbinaryas-cwould. -mutexprofilefractionn Sample1innstacktracesofgoroutinesholdinga contendedmutex. -outputdirdirectory Placeoutputfilesfromprofilinginthespecifieddirectory, bydefaultthedirectoryinwhich"gotest"isrunning. -tracetrace.out Writeanexecutiontracetothespecifiedfilebeforeexiting. Eachoftheseflagsisalsorecognizedwithanoptional'test.'prefix, asin-test.v.Wheninvokingthegeneratedtestbinary(theresultof 'gotest-c')directly,however,theprefixismandatory. The'gotest'commandrewritesorremovesrecognizedflags, asappropriate,bothbeforeandaftertheoptionalpackagelist, beforeinvokingthetestbinary. Forinstance,thecommand gotest-v-myflagtestdata-cpuprofile=prof.out-x willcompilethetestbinaryandthenrunitas pkg.test-test.v-myflagtestdata-test.cpuprofile=prof.out (The-xflagisremovedbecauseitappliesonlytothegocommand's execution,nottothetestitself.) Thetestflagsthatgenerateprofiles(otherthanforcoverage)also leavethetestbinaryinpkg.testforusewhenanalyzingtheprofiles. When'gotest'runsatestbinary,itdoessofromwithinthe correspondingpackage'ssourcecodedirectory.Dependingonthetest, itmaybenecessarytodothesamewheninvokingageneratedtest binarydirectly. Thecommand-linepackagelist,ifpresent,mustappearbeforeany flagnotknowntothegotestcommand.Continuingtheexampleabove, thepackagelistwouldhavetoappearbefore-myflag,butcouldappear oneithersideof-v. When'gotest'runsinpackagelistmode,'gotest'cachessuccessful packagetestresultstoavoidunnecessaryrepeatedrunningoftests.To disabletestcaching,useanytestflagorargumentotherthanthe cacheableflags.Theidiomaticwaytodisabletestcachingexplicitly istouse-count=1. Tokeepanargumentforatestbinaryfrombeinginterpretedasa knownflagorapackagename,use-args(see'gohelptest')which passestheremainderofthecommandlinethroughtothetestbinary uninterpretedandunaltered. Forinstance,thecommand gotest-v-args-x-v willcompilethetestbinaryandthenrunitas pkg.test-test.v-x-v Similarly, gotest-argsmath willcompilethetestbinaryandthenrunitas pkg.testmath Inthefirstexample,the-xandthesecond-varepassedthroughtothe testbinaryunchangedandwithnoeffectonthegocommanditself. Inthesecondexample,theargumentmathispassedthroughtothetest binary,insteadofbeinginterpretedasthepackagelist. Testingfunctions¶The'gotest'commandexpectstofindtest,benchmark,andexamplefunctions inthe"*_test.go"filescorrespondingtothepackageundertest. AtestfunctionisonenamedTestXxx(whereXxxdoesnotstartwitha lowercaseletter)andshouldhavethesignature, funcTestXxx(t*testing.T){...} AbenchmarkfunctionisonenamedBenchmarkXxxandshouldhavethesignature, funcBenchmarkXxx(b*testing.B){...} Anexamplefunctionissimilartoatestfunctionbut,insteadofusing *testing.Ttoreportsuccessorfailure,printsoutputtoos.Stdout. Ifthelastcommentinthefunctionstartswith"Output:"thentheoutput iscomparedexactlyagainstthecomment(seeexamplesbelow).Ifthelast commentbeginswith"Unorderedoutput:"thentheoutputiscomparedtothe comment,howevertheorderofthelinesisignored.Anexamplewithnosuch commentiscompiledbutnotexecuted.Anexamplewithnotextafter "Output:"iscompiled,executed,andexpectedtoproducenooutput. GodocdisplaysthebodyofExampleXxxtodemonstratetheuse ofthefunction,constant,orvariableXxx.AnexampleofamethodMwith receivertypeTor*TisnamedExampleT_M.Theremaybemultipleexamples foragivenfunction,constant,orvariable,distinguishedbyatrailing_xxx, wherexxxisasuffixnotbeginningwithanuppercaseletter. Hereisanexampleofanexample: funcExamplePrintln(){ Println("Theoutputof\nthisexample.") //Output:Theoutputof //thisexample. } Hereisanotherexamplewheretheorderingoftheoutputisignored: funcExamplePerm(){ for_,value:=rangePerm(4){ fmt.Println(value) } //Unorderedoutput:4 //2 //1 //3 //0 } Theentiretestfileispresentedastheexamplewhenitcontainsasingle examplefunction,atleastoneotherfunction,type,variable,orconstant declaration,andnotestorbenchmarkfunctions. Seethedocumentationofthetestingpackageformoreinformation. ControllingversioncontrolwithGOVCS¶The'goget'commandcanrunversioncontrolcommandslikegit todownloadimportedcode.Thisfunctionalityiscriticaltothedecentralized Gopackageecosystem,inwhichcodecanbeimportedfromanyserver, butitisalsoapotentialsecurityproblem,ifamaliciousserverfindsa waytocausetheinvokedversioncontrolcommandtorununintendedcode. Tobalancethefunctionalityandsecurityconcerns,the'goget'command bydefaultwillonlyusegitandhgtodownloadcodefrompublicservers. Butitwilluseanyknownversioncontrolsystem(bzr,fossil,git,hg,svn) todownloadcodefromprivateservers,definedasthosehostingpackages matchingtheGOPRIVATEvariable(see'gohelpprivate').Therationalebehind allowingonlyGitandMercurialisthatthesetwosystemshavehadthemost attentiontoissuesofbeingrunasclientsofuntrustedservers.Incontrast, Bazaar,Fossil,andSubversionhaveprimarilybeenusedintrusted, authenticatedenvironmentsandarenotaswellscrutinizedasattacksurfaces. Theversioncontrolcommandrestrictionsonlyapplywhenusingdirectversion controlaccesstodownloadcode.Whendownloadingmodulesfromaproxy, 'goget'usestheproxyprotocolinstead,whichisalwayspermitted. Bydefault,the'goget'commandusestheGomodulemirror(proxy.golang.org) forpublicpackagesandonlyfallsbacktoversioncontrolforprivate packagesorwhenthemirrorrefusestoserveapublicpackage(typicallyfor legalreasons).Therefore,clientscanstillaccesspubliccodeservedfrom Bazaar,Fossil,orSubversionrepositoriesbydefault,becausethosedownloads usetheGomodulemirror,whichtakesonthesecurityriskofrunningthe versioncontrolcommandsusingacustomsandbox. TheGOVCSvariablecanbeusedtochangetheallowedversioncontrolsystems forspecificpackages(identifiedbyamoduleorimportpath). TheGOVCSvariableapplieswhenbuildingpackageinbothmodule-awaremode andGOPATHmode.Whenusingmodules,thepatternsmatchagainstthemodulepath. WhenusingGOPATH,thepatternsmatchagainsttheimportpathcorrespondingto therootoftheversioncontrolrepository. ThegeneralformoftheGOVCSsettingisacomma-separatedlistof pattern:vcslistrules.Thepatternisaglobpatternthatmustmatch oneormoreleadingelementsofthemoduleorimportpath.Thevcslist isapipe-separatedlistofallowedversioncontrolcommands,or"all" toallowuseofanyknowncommand,or"off"todisallowallcommands. Notethatifamodulematchesapatternwithvcslist"off",itmaystillbe downloadediftheoriginserverusesthe"mod"scheme,whichinstructsthe gocommandtodownloadthemoduleusingtheGOPROXYprotocol. Theearliestmatchingpatterninthelistapplies,eveniflaterpatterns mightalsomatch. Forexample,consider: GOVCS=github.com:git,evil.com:off,*:git|hg Withthissetting,codewithamoduleorimportpathbeginningwith github.com/canonlyusegit;pathsonevil.comcannotuseanyversion controlcommand,andallotherpaths(*matcheseverything)canuse onlygitorhg. Thespecialpatterns"public"and"private"matchpublicandprivate moduleorimportpaths.ApathisprivateifitmatchestheGOPRIVATE variable;otherwiseitispublic. IfnorulesintheGOVCSvariablematchaparticularmoduleorimportpath, the'goget'commandappliesitsdefaultrule,whichcannowbesummarized inGOVCSnotationas'public:git|hg,private:all'. Toallowunfettereduseofanyversioncontrolsystemforanypackage,use: GOVCS=*:all Todisablealluseofversioncontrol,use: GOVCS=*:off The'goenv-w'command(see'gohelpenv')canbeusedtosettheGOVCS variableforfuturegocommandinvocations. SourceFiles ¶ Viewall alldocs.go go11.go main.go Directories ¶ Expandall Path Synopsis internal auth Packageauthprovidesaccesstouser-providedauthenticationcredentials. Packageauthprovidesaccesstouser-providedauthenticationcredentials. base Packagebasedefinessharedbasicpiecesofthegocommand,inparticularloggingandtheCommandstructure. Packagebasedefinessharedbasicpiecesofthegocommand,inparticularloggingandtheCommandstructure. bug Packagebugimplementsthe“gobug”command. Packagebugimplementsthe“gobug”command. cache Packagecacheimplementsabuildartifactcache. Packagecacheimplementsabuildartifactcache. cfg Packagecfgholdsconfigurationsharedbymultiplepartsofthegocommand. Packagecfgholdsconfigurationsharedbymultiplepartsofthegocommand. clean Packagecleanimplementsthe“goclean”command. Packagecleanimplementsthe“goclean”command. cmdflag Packagecmdflaghandlesflagprocessingcommontoseveralgotools. Packagecmdflaghandlesflagprocessingcommontoseveralgotools. doc Packagedocimplementsthe“godoc”command. Packagedocimplementsthe“godoc”command. envcmd Packageenvcmdimplementsthe“goenv”command. Packageenvcmdimplementsthe“goenv”command. fix Packagefiximplementsthe“gofix”command. Packagefiximplementsthe“gofix”command. fmtcmd Packagefmtcmdimplementsthe“gofmt”command. Packagefmtcmdimplementsthe“gofmt”command. fsys Packagefsysisanabstractionforreadingfilesthatallowsforvirtualoverlaysontopofthefilesondisk. Packagefsysisanabstractionforreadingfilesthatallowsforvirtualoverlaysontopofthefilesondisk. generate Packagegenerateimplementsthe“gogenerate”command. Packagegenerateimplementsthe“gogenerate”command. get Packagegetimplementsthe“goget”command. Packagegetimplementsthe“goget”command. help Packagehelpimplementsthe“gohelp”command. Packagehelpimplementsthe“gohelp”command. imports list Packagelistimplementsthe“golist”command. Packagelistimplementsthe“golist”command. load Packageloadloadspackages. Packageloadloadspackages. lockedfile Packagelockedfilecreatesandmanipulatesfileswhosecontentsshouldonlychangeatomically. Packagelockedfilecreatesandmanipulatesfileswhosecontentsshouldonlychangeatomically. lockedfile/internal/filelock Packagefilelockprovidesaplatform-independentAPIforadvisoryfilelocking. Packagefilelockprovidesaplatform-independentAPIforadvisoryfilelocking. modcmd Packagemodcmdimplementsthe“gomod”command. Packagemodcmdimplementsthe“gomod”command. modconv modfetch modfetch/codehost Packagecodehostdefinestheinterfaceimplementedbyacodehostingsource,alongwithsupportcodeforusebyimplementations. Packagecodehostdefinestheinterfaceimplementedbyacodehostingsource,alongwithsupportcodeforusebyimplementations. modget Packagemodgetimplementsthemodule-aware“goget”command. Packagemodgetimplementsthemodule-aware“goget”command. modinfo modload mvs PackagemvsimplementsMinimalVersionSelection. PackagemvsimplementsMinimalVersionSelection. par Packageparimplementsparallelexecutionhelpers. Packageparimplementsparallelexecutionhelpers. robustio PackagerobustiowrapsI/OfunctionsthatarepronetofailureonWindows,transparentlyretryingerrorsuptoanarbitrarytimeout. PackagerobustiowrapsI/OfunctionsthatarepronetofailureonWindows,transparentlyretryingerrorsuptoanarbitrarytimeout. run Packagerunimplementsthe“gorun”command. Packagerunimplementsthe“gorun”command. search str Packagestrprovidesstringmanipulationutilities. Packagestrprovidesstringmanipulationutilities. test tool Packagetoolimplementsthe“gotool”command. Packagetoolimplementsthe“gotool”command. trace txtar Packagetxtarimplementsatrivialtext-basedfilearchiveformat. Packagetxtarimplementsatrivialtext-basedfilearchiveformat. vcs version Packageversionimplementsthe“goversion”command. Packageversionimplementsthe“goversion”command. vet Packagevetimplementsthe“govet”command. Packagevetimplementsthe“govet”command. web PackagewebdefinesminimalhelperroutinesforaccessingHTTP/HTTPSresourceswithoutrequiringexternaldependenciesonthenetpackage. PackagewebdefinesminimalhelperroutinesforaccessingHTTP/HTTPSresourceswithoutrequiringexternaldependenciesonthenetpackage. work Jumpto Close Keyboardshortcuts ?:Thismenu /:Searchsite forF:Jumpto yorY :CanonicalURL Close



請為這篇文章評分?