CoolFace
Datasetpublic

enigmare/v2-crawler

sourceHugging Faceupdated 28d agoView on Hugging Face
1likes904downloads
go_dev.jsonl54 linesDownload Raw Back to documentation
1{"id":"doc-managing_connections_the_go_programming_language-a72d8169","source":"documentation","title":"Managing connections - The Go Programming Language","url":"https://go.dev/doc/database/manage-connections","text":"Managing connections For the vast majority of programs, you needn’t adjust the sql.DB connection pool defaults. But for some advanced programs, you might need to tune the connection pool parameters or work with connections explicitly. This topic explains how. The sql.DB database handle is safe for concurrent use by multiple goroutines (meaning the handle is what other languages might call “thread-safe”). Some other database access libraries are based on connections that can only be used for one operation at a time. To bridge that gap, each sql.DB manages a pool of active connections to the underlying database, creating new ones as needed for parallelism in your Go program. The connection pool is suitable for most data access needs. When you call an sql.DB Query or Exec method, the sql.DB implementation retrieves an available connection from the pool or, if needed, creates one. The package returns the connection to the pool when it’s no longer needed. This supports a high level of parallelism for database access. Setting connection pool properties You can set properties that guide how the sql package manages a connection pool. To get statistics about the effects of these properties, use DB.Stats. Setting the maximum number of open connections DB.SetMaxOpenConns imposes a limit on the number of open connections. Past this limit, new database operations will wait for an existing operation to finish, at which time sql.DB will create another connection. By default, sql.DB creates a new connection any time all the existing connections are in use when a connection is needed. Keep in mind that setting a limit makes database usage similar to acquiring a lock or semaphore, with the result that your application can deadlock waiting for a new database connection. Setting the maximum number of idle connections DB.SetMaxIdleConns changes the limit on the maximum number of idle connections sql.DB maintains. When an SQL operation finishes on a given database connection, it is not typically shut down application may need one again soon, and keeping the open connection around avoids having to reconnect to the database for the next operation. By default an sql.DB keeps two idle connections at any given moment. Raising the limit can avoid frequent reconnects in programs with significant parallelism. Setting the maximum amount a time a connection can be idle DB.SetConnMaxIdleTime sets the maximum length of time a connection can be idle before it is closed. This causes the sql.DB to close connections that have been idle for longer than the given duration. By default, when an idle connection is added to the connection pool, it remains there until it is needed again. When using DB.SetMaxIdleConns to increase the number of allowed idle connections during bursts of parallel activity, also using DB.SetConnMaxIdleTime can arrange to release those connections later when the system is quiet. Setting the maximum lifetime of connections Using DB.SetConnMaxLifetime sets the maximum length of time a connection can be held open before it is closed. By default, a connection can be used and reused for an arbitrarily long amount of time, subject to the limits described above. In some systems, such as those using a load-balanced database server, it can be helpful to ensure that the application never uses a particular connection for too long without reconnecting. Using dedicated connections The database/sql package includes functions you can use when a database may assign implicit meaning to a sequence of operations executed on a particular connection. The most common example is transactions, which typically start with a BEGIN command, end with a COMMIT or ROLLBACK command, and include all the commands issued on the connection between those commands in the overall transaction. For this use case, use the sql package’s transaction support. See Executing transactions. For other use cases where a sequence of individual operations must all execute on the same connection, the sql package provides dedicated connections. DB.Conn obtains a dedicated connection, an sql.Conn. The sql.Conn has methods BeginTx, ExecContext, PingContext, PrepareContext, QueryContext, and QueryRowContext that behave like the equivalent methods on DB but only use the dedicated connection. When finished with the dedicated connection, your code must release it using Conn.Close.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.365Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":0,"totalLines":5,"estimatedTokens":1131}}2{"id":"doc-go_doc_comments_the_go_programming_language-144773fd","source":"documentation","title":"Go Doc Comments - The Go Programming Language","url":"https://go.dev/doc/comment","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n// Package path implements utility routines for manipulating slash-separated\n// paths.\n//\n// The path package should only be used for paths separated by forward\n// slashes, such as the paths in URLs. This package does not deal with\n// Windows paths with drive letters or backslashes; to manipulate\n// operating system paths, use the [path/filepath] package.\npackage path\n```\n\nExample:\n```text\n/*\nGofmt formats Go programs.\nIt uses tabs for indentation and blanks for alignment.\nAlignment assumes that an editor is using a fixed-width font.\n\nWithout an explicit path, it processes the standard input. Given a file,\nit operates on that file; given a directory, it operates on all .go files in\nthat directory, recursively. (Files starting with a period are ignored.)\nBy default, gofmt prints the reformatted sources to standard output.\n\nUsage:\n\n    gofmt [flags] [path ...]\n\nThe flags are:\n\n    -d\n        Do not print reformatted sources to standard output.\n        If a file's formatting is different than gofmt's, print diffs\n        to standard output.\n    -w\n        Do not print reformatted sources to standard output.\n        If a file's formatting is different from gofmt's, overwrite it\n        with gofmt's version. If an error occurred during overwriting,\n        the original file is restored from an automatic backup.\n\nWhen gofmt reads from standard input, it accepts either a full Go program\nor a program fragment. A program fragment must be a syntactically\nvalid declaration list, statement list, or expression. When formatting\nsuch a fragment, gofmt preserves leading indentation as well as leading\nand trailing spaces, so that individual sections of a Go program can be\nformatted by piping them through gofmt.\n*/\npackage main\n```\n\nExample:\n```text\n$ go doc gofmt\nGofmt formats Go programs. It uses tabs for indentation and blanks for\nalignment. Alignment assumes that an editor is using a fixed-width font.\n\nWithout an explicit path, it processes the standard input. Given a file, it\noperates on that file; given a directory, it operates on all .go files in that\ndirectory, recursively. (Files starting with a period are ignored.) By default,\ngofmt prints the reformatted sources to standard output.\n\nUsage:\n\n    gofmt [flags] [path ...]\n\nThe flags are:\n\n    -d\n        Do not print reformatted sources to standard output.\n        If a file's formatting is different than gofmt's, print diffs\n        to standard output.\n...\n```\n\nExample:\n```text\npackage zip\n\n// A Reader serves content from a ZIP archive.\ntype Reader struct {\n    ...\n}\n```\n\nExample:\n```text\npackage regexp\n\n// Regexp is the representation of a compiled regular expression.\n// A Regexp is safe for concurrent use by multiple goroutines,\n// except for configuration methods, such as Longest.\ntype Regexp struct {\n    ...\n}\n```\n\nExample:\n```text\npackage bytes\n\n// A Buffer is a variable-sized buffer of bytes with Read and Write methods.\n// The zero value for Buffer is an empty buffer ready to use.\ntype Buffer struct {\n    ...\n}\n```\n\nExample:\n```text\npackage io\n\n// A LimitedReader reads from R but limits the amount of\n// data returned to just N bytes. Each call to Read\n// updates N to reflect the new amount remaining.\n// Read returns EOF when N <= 0.\ntype LimitedReader struct {\n    R   Reader // underlying reader\n    N   int64  // max bytes remaining\n}\n```\n\nExample:\n```text\npackage comment\n\n// A Printer is a doc comment printer.\n// The fields in the struct can be filled in before calling\n// any of the printing methods\n// in order to customize the details of the printing process.\ntype Printer struct {\n    // HeadingLevel is the nesting level used for\n    // HTML and Markdown headings.\n    // If HeadingLevel is zero, it defaults to level 3,\n    // meaning to use <h3> and ###.\n    HeadingLevel int\n    ...\n}\n```\n\nExample:\n```text\n$ go doc -all regexp | grep pairs\npairs within the input string: result[2*n:2*n+2] identifies the indexes\n    FindReaderSubmatchIndex returns a slice holding the index pairs identifying\n    FindStringSubmatchIndex returns a slice holding the index pairs identifying\n    FindSubmatchIndex returns a slice holding the index pairs identifying the\n$\n```\n\nExample:\n```text\npackage strconv\n\n// Quote returns a double-quoted Go string literal representing s.\n// The returned string uses Go escape sequences (\\t, \\n, \\xFF, \\u0100)\n// for control characters and non-printable characters as defined by IsPrint.\nfunc Quote(s string) string {\n    ...\n}\n```\n\nExample:\n```text\npackage os\n\n// Exit causes the current program to exit with the given status code.\n// Conventionally, code zero indicates success, non-zero an error.\n// The program terminates immediately; deferred functions are not run.\n//\n// For portability, the status code should be in the range [0, 125].\nfunc Exit(code int) {\n    ...\n}\n```\n\nExample:\n```text\npackage strings\n\n// HasPrefix reports whether the string s begins with prefix.\nfunc HasPrefix(s, prefix string) bool\n```\n\nExample:\n```text\npackage io\n\n// Copy copies from src to dst until either EOF is reached\n// on src or an error occurs. It returns the total number of bytes\n// written and the first error encountered while copying, if any.\n//\n// A successful Copy returns err == nil, not err == EOF.\n// Because Copy is defined to read from src until EOF, it does\n// not treat an EOF from Read as an error to be reported.\nfunc Copy(dst Writer, src Reader) (n int64, err error) {\n    ...\n}\n```\n\nExample:\n```text\n$ go doc bytes.Buffer\npackage bytes // import \"bytes\"\n\ntype Buffer struct {\n    // Has unexported fields.\n}\n    A Buffer is a variable-sized buffer of bytes with Read and Write methods.\n    The zero value for Buffer is an empty buffer ready to use.\n\nfunc NewBuffer(buf []byte) *Buffer\nfunc NewBufferString(s string) *Buffer\nfunc (b *Buffer) Bytes() []byte\nfunc (b *Buffer) Cap() int\nfunc (b *Buffer) Grow(n int)\nfunc (b *Buffer) Len() int\nfunc (b *Buffer) Next(n int) []byte\nfunc (b *Buffer) Read(p []byte) (n int, err error)\nfunc (b *Buffer) ReadByte() (byte, error)\n...\n```\n\nExample:\n```text\npackage sql\n\n// Close returns the connection to the connection pool.\n// All operations after a Close will return with ErrConnDone.\n// Close is safe to call concurrently with other operations and will\n// block until all other operations finish. It may be useful to first\n// cancel any used context and then call Close directly after.\nfunc (c *Conn) Close() error {\n    ...\n}\n```\n\nExample:\n```text\npackage math\n\n// Sqrt returns the square root of x.\n//\n// Special cases are:\n//\n//  Sqrt(+Inf) = +Inf\n//  Sqrt(±0) = ±0\n//  Sqrt(x < 0) = NaN\n//  Sqrt(NaN) = NaN\nfunc Sqrt(x float64) float64 {\n    ...\n}\n```\n\nExample:\n```text\npackage sort\n\n// Sort sorts data in ascending order as determined by the Less method.\n// It makes one call to data.Len to determine n and O(n*log(n)) calls to\n// data.Less and data.Swap. The sort is not guaranteed to be stable.\nfunc Sort(data Interface) {\n    ...\n}\n```\n\nExample:\n```text\npackage scanner // import \"text/scanner\"\n\n// The result of Scan is one of these tokens or a Unicode character.\nconst (\n    EOF = -(iota + 1)\n    Ident\n    Int\n    Float\n    Char\n    ...\n)\n```\n\nExample:\n```text\npackage unicode // import \"unicode\"\n\nconst (\n    MaxRune         = '\\U0010FFFF' // maximum valid Unicode code point.\n    ReplacementChar = '\\uFFFD'     // represents invalid code points.\n    MaxASCII        = '\\u007F'     // maximum ASCII value.\n    MaxLatin1       = '\\u00FF'     // maximum Latin-1 value.\n)\n```\n\nExample:\n```text\npackage unicode\n\n// Version is the Unicode edition from which the tables are derived.\nconst Version = \"13.0.0\"\n```\n\nExample:\n```text\npackage syntax\n\n// An Op is a single regular expression operator.\ntype Op uint8\n\nconst (\n    OpNoMatch        Op = 1 + iota // matches no strings\n    OpEmptyMatch                   // matches empty string\n    OpLiteral                      // matches Runes sequence\n    OpCharClass                    // matches Runes interpreted as range pair list\n    OpAnyCharNotNL                 // matches any character except newline\n    ...\n)\n```\n\nExample:\n```text\npackage fs\n\n// Generic file system errors.\n// Errors returned by file systems can be tested against these errors\n// using errors.Is.\nvar (\n    ErrInvalid    = errInvalid()    // \"invalid argument\"\n    ErrPermission = errPermission() // \"permission denied\"\n    ErrExist      = errExist()      // \"file already exists\"\n    ErrNotExist   = errNotExist()   // \"file does not exist\"\n    ErrClosed     = errClosed()     // \"file already closed\"\n)\n```\n\nExample:\n```text\npackage unicode\n\n// Scripts is the set of Unicode script tables.\nvar Scripts = map[string]*RangeTable{\n    \"Adlam\":                  Adlam,\n    \"Ahom\":                   Ahom,\n    \"Anatolian_Hieroglyphs\":  Anatolian_Hieroglyphs,\n    \"Arabic\":                 Arabic,\n    \"Armenian\":               Armenian,\n    ...\n}\n```\n\nExample:\n```text\n// TODO(user1): refactor to use standard library context\n// BUG(user2): not cleaned up\nvar ctx context.Context\n```\n\nExample:\n```text\n// Package rc4 implements the RC4 stream cipher.\n//\n// Deprecated: RC4 is cryptographically broken and should not be used\n// except for compatibility with legacy systems.\n//\n// This package is frozen and no new functionality will be added.\npackage rc4\n\n// Reset zeros the key data and makes the Cipher unusable.\n//\n// Deprecated: Reset can't guarantee that the key will be entirely removed from\n// the process's memory.\nfunc (c *Cipher) Reset()\n```\n\nExample:\n```text\n// Package strconv implements conversions to and from string representations\n// of basic data types.\n//\n// # Numeric Conversions\n//\n// The most common numeric conversions are [Atoi] (string to int) and [Itoa] (int to string).\n...\npackage strconv\n```\n\nExample:\n```text\n// #This is not a heading, because there is no space.\n//\n// # This is not a heading,\n// # because it is multiple lines.\n//\n// # This is not a heading,\n// because it is also multiple lines.\n//\n// The next paragraph is not a heading, because there is no additional text:\n//\n// #\n//\n// In the middle of a span of non-blank lines,\n// # this is not a heading either.\n//\n//     # This is not a heading, because it is indented.\n```\n\nExample:\n```text\n// Package json implements encoding and decoding of JSON as defined in\n// [RFC 7159]. The mapping between JSON and Go values is described\n// in the documentation for the Marshal and Unmarshal functions.\n//\n// For an introduction to this package, see the article\n// “[JSON and Go].”\n//\n// [RFC 7159]: https://tools.ietf.org/html/rfc7159\n// [JSON and Go]: https://golang.org/doc/articles/json_and_go.html\npackage json\n```\n\nExample:\n```text\npackage bytes\n\n// ReadFrom reads data from r until EOF and appends it to the buffer, growing\n// the buffer as needed. The return value n is the number of bytes read. Any\n// error except [io.EOF] encountered during the read is also returned. If the\n// buffer becomes too large, ReadFrom will panic with [ErrTooLarge].\nfunc (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {\n    ...\n}\n```\n\nExample:\n```text\npackage url\n\n// PublicSuffixList provides the public suffix of a domain. For example:\n//   - the public suffix of \"example.com\" is \"com\",\n//   - the public suffix of \"foo1.foo2.foo3.co.uk\" is \"co.uk\", and\n//   - the public suffix of \"bar.pvt.k12.ma.us\" is \"pvt.k12.ma.us\".\n//\n// Implementations of PublicSuffixList must be safe for concurrent use by\n// multiple goroutines.\n//\n// An implementation that always returns \"\" is valid and may be useful for\n// testing but it is not secure: it means that the HTTP server for foo.com can\n// set a cookie for bar.com.\n//\n// A public suffix list implementation is in the package\n// golang.org/x/net/publicsuffix.\ntype PublicSuffixList interface {\n    ...\n}\n```\n\nExample:\n```text\npackage path\n\n// Clean returns the shortest path name equivalent to path\n// by purely lexical processing. It applies the following rules\n// iteratively until no further processing can be done:\n//\n//  1. Replace multiple slashes with a single slash.\n//  2. Eliminate each . path name element (the current directory).\n//  3. Eliminate each inner .. path name element (the parent directory)\n//     along with the non-.. element that precedes it.\n//  4. Eliminate .. elements that begin a rooted path:\n//     that is, replace \"/..\" by \"/\" at the beginning of a path.\n//\n// The returned path ends in a slash only if it is the root \"/\".\n//\n// If the result of this process is an empty string, Clean\n// returns the string \".\".\n//\n// See also Rob Pike, “[Lexical File Names in Plan 9].”\n//\n// [Lexical File Names in Plan 9]: https://9p.io/sys/doc/lexnames.html\nfunc Clean(path string) string {\n    ...\n}\n```\n\nExample:\n```text\npackage sort\n\n// Search uses binary search...\n//\n// As a more whimsical example, this program guesses your number:\n//\n//  func GuessingGame() {\n//      var s string\n//      fmt.Printf(\"Pick an integer from 0 to 100.\\n\")\n//      answer := sort.Search(100, func(i int) bool {\n//          fmt.Printf(\"Is your number <= %d? \", i)\n//          fmt.Scanf(\"%s\", &s)\n//          return s != \"\" && s[0] == 'y'\n//      })\n//      fmt.Printf(\"Your number is %d.\\n\", answer)\n//  }\nfunc Search(n int, f func(int) bool) int {\n    ...\n}\n```\n\nExample:\n```text\npackage path\n\n// Match reports whether name matches the shell pattern.\n// The pattern syntax is:\n//\n//  pattern:\n//      { term }\n//  term:\n//      '*'         matches any sequence of non-/ characters\n//      '?'         matches any single non-/ character\n//      '[' [ '^' ] { character-range } ']'\n//                  character class (must be non-empty)\n//      c           matches character c (c != '*', '?', '\\\\', '[')\n//      '\\\\' c      matches character c\n//\n//  character-range:\n//      c           matches character c (c != '\\\\', '-', ']')\n//      '\\\\' c      matches character c\n//      lo '-' hi   matches character c for lo <= c <= hi\n//\n// Match requires pattern to match all of name, not just a substring.\n// The only possible returned error is [ErrBadPattern], when pattern\n// is malformed.\nfunc Match(pattern, name string) (matched bool, err error) {\n    ...\n}\n```\n\nExample:\n```text\npackage regexp\n\n// An Op is a single regular expression operator.\n//\n//go:generate stringer -type Op -trimprefix Op\ntype Op uint8\n```\n\nExample:\n```text\npackage http\n\n// cancelTimerBody is an io.ReadCloser that wraps rc with two features:\n// 1) On Read error or close, the stop func is called.\n// 2) On Read failure, if reqDidTimeout is true, the error is wrapped and\n//    marked as net.Error that hit its timeout.\ntype cancelTimerBody struct {\n    ...\n}\n```\n\nExample:\n```text\ncancelTimerBody is an io.ReadCloser that wraps rc with two features:\n1) On Read error or close, the stop func is called. 2) On Read failure,\nif reqDidTimeout is true, the error is wrapped and\n\n    marked as net.Error that hit its timeout.\n```\n\nExample:\n```text\npackage smtp\n\n// localhostCert is a PEM-encoded TLS cert generated from src/crypto/tls:\n//\n// go run generate_cert.go --rsa-bits 1024 --host 127.0.0.1,::1,example.com \\\n//     --ca --start-date \"Jan 1 00:00:00 1970\" --duration=1000000h\nvar localhostCert = []byte(`...`)\n```\n\nExample:\n```text\nlocalhostCert is a PEM-encoded TLS cert generated from src/crypto/tls:\n\ngo run generate_cert.go --rsa-bits 1024 --host 127.0.0.1,::1,example.com \\\n\n    --ca --start-date \"Jan 1 00:00:00 1970\" --duration=1000000h\n```\n\nExample:\n```text\n// On the wire, the JSON will look something like this:\n// {\n//  \"kind\":\"MyAPIObject\",\n//  \"apiVersion\":\"v1\",\n//  \"myPlugin\": {\n//      \"kind\":\"PluginA\",\n//      \"aOption\":\"foo\",\n//  },\n// }\n```\n\nExample:\n```text\nOn the wire, the JSON will look something like this: {\n\n    \"kind\":\"MyAPIObject\",\n    \"apiVersion\":\"v1\",\n    \"myPlugin\": {\n        \"kind\":\"PluginA\",\n        \"aOption\":\"foo\",\n    },\n\n}\n```\n\nExample:\n```text\n// cancelTimerBody is an io.ReadCloser that wraps rc with two features:\n//  1. On Read error or close, the stop func is called.\n//  2. On Read failure, if reqDidTimeout is true, the error is wrapped and\n//     marked as net.Error that hit its timeout.\n\n// localhostCert is a PEM-encoded TLS cert generated from src/crypto/tls:\n//\n//  go run generate_cert.go --rsa-bits 1024 --host 127.0.0.1,::1,example.com \\\n//      --ca --start-date \"Jan 1 00:00:00 1970\" --duration=1000000h\n\n// On the wire, the JSON will look something like this:\n//\n//  {\n//      \"kind\":\"MyAPIObject\",\n//      \"apiVersion\":\"v1\",\n//      \"myPlugin\": {\n//          \"kind\":\"PluginA\",\n//          \"aOption\":\"foo\",\n//      },\n//  }\n```\n\nExample:\n```text\n// TODO Revisit this design. It may make sense to walk those nodes\n//      only once.\n\n// According to the document:\n// \"The alignment factor (in bytes) that is used to align the raw data of sections in\n//  the image file. The value should be a power of 2 between 512 and 64 K, inclusive.\"\n```\n\nExample:\n```text\n// Uses of this error model include:\n//\n//   - Partial errors. If a service needs to return partial errors to the\n// client,\n//     it may embed the `Status` in the normal response to indicate the\n// partial\n//     errors.\n//\n//   - Workflow errors. A typical workflow has multiple steps. Each step\n// may\n//     have a `Status` message for error reporting.\n```\n\nExample:\n```text\n// Here is a list:\n//\n//  - Item 1.\n//    * Subitem 1.\n//    * Subitem 2.\n//  - Item 2.\n//  - Item 3.\n```\n\nExample:\n```text\n// Here is a list:\n//\n//  - Item 1.\n//  - Subitem 1.\n//  - Subitem 2.\n//  - Item 2.\n//  - Item 3.\n```\n\nExample:\n```text\n// Here is a list:\n//\n//  1. Item 1.\n//\n//     - Subitem 1.\n//\n//     - Subitem 2.\n//\n//  2. Item 2.\n//\n//  3. Item 3.\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.367Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":46,"totalLines":703,"estimatedTokens":4435}}3{"id":"doc-developing_a_major_version_update_the_go_program-12a3805b","source":"documentation","title":"Developing a major version update - The Go Programming Language","url":"https://go.dev/doc/modules/major-version","text":"Developing a major version update You must update to a major version when changes you’re making in a potential new version can’t guarantee backward compatibility for the module’s users. For example, you’ll make this change if you change your module’s public API such that it breaks client code using previous versions of the module. release type – major, minor, patch, or pre-release – has a different meaning for a module’s users. Those users rely on these differences to understand the level of risk a release represents to their own code. In other words, when preparing a release, be sure that its version number accurately reflects the nature of the changes since the preceding release. For more on version numbers, see Module version numbering. See also For an overview of module development, see Developing and publishing modules. For an end-to-end view, see Module release and versioning workflow. Considerations for a major version update You should only update to a new major version when it’s absolutely necessary. A major version update represents significant churn for both you and your module’s users. When you’re considering a major version update, think about the clear with your users about what releasing the new major version means for your support of previous major versions. Are previous versions deprecated? Supported as they were before? Will you be maintaining previous versions, including with bug fixes? Be ready to take on the maintenance of two old and the new. For example, if you fix bugs in one, you’ll often be porting those fixes into the other. Remember that a new major version is a new module from a dependency management perspective. Your users will need to update to use a new module after you release, rather than simply upgrading. That’s because a new major version has a different module path from the preceding major version. For example, for a module whose module path is example.com/mymodule, a v2 version would have the module path example.com/mymodule/v2. When you’re developing a new major version, you must also update import paths wherever code imports packages from the new module. Your module’s users must also update their import paths if they want to upgrade to the new major version. Branching for a major release The most straightforward approach to handling source when preparing to develop a new major version is to branch the repository at the latest version of the previous major version. For example, in a command prompt you might change to your module’s root directory, then create a new v2 branch there. $ cd mymodule $ git checkout -b v2 Switched to a new branch \"v2\" Once you have the source branched, you’ll need to make the following changes to the source for your new the new version’s go.mod file, append new major version number to the module path, as in the following /mymodule New /mymodule/v2 In your Go code, update every imported package path where you import a package from the module, appending the major version number to the module path portion. Old import \"example.com/mymodule/package1\" New import \"example.com/mymodule/v2/package1\" For publishing steps, see Publishing a module.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ cd mymodule\n$ git checkout -b v2\nSwitched to a new branch \"v2\"\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.368Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":1,"totalLines":12,"estimatedTokens":846}}4{"id":"doc-avoiding_sql_injection_risk_the_go_programming_l-bb99a27b","source":"documentation","title":"Avoiding SQL injection risk - The Go Programming Language","url":"https://go.dev/doc/database/sql-injection","text":"Avoiding SQL injection risk You can avoid an SQL injection risk by providing SQL parameter values as sql package function arguments. Many functions in the sql package provide parameters for the SQL statement and for values to be used in that statement’s parameters (others provide a parameter for a prepared statement and parameters). Code in the following example uses the ? symbol as a placeholder for the id parameter, which is provided as a function argument: // Correct format for executing an SQL statement with parameters. rows, err := db.Query(\"SELECT * FROM user WHERE id = ?\", id) sql package functions that perform database operations create prepared statements from the arguments you supply. At run time, the sql package turns the SQL statement into a prepared statement and sends it along with the parameter, which is separate. placeholders vary depending on the DBMS and driver you’re using. For example, pq driver for Postgres accepts a placeholder form such as $1 instead of ?. You might be tempted to use a function from the fmt package to assemble the SQL statement as a string with parameters included – like this: // SECURITY RISK! rows, err := db.Query(fmt.Sprintf(\"SELECT * FROM user WHERE id = %s\", id)) This is not secure! When you do this, Go assembles the entire SQL statement, replacing the %s format verb with the parameter value, before sending the full statement to the DBMS. This poses an SQL injection risk because the code’s caller could send an unexpected SQL snippet as the id argument. That snippet could complete the SQL statement in unpredictable ways that are dangerous to your application. For example, by passing a certain %s value, you might end up with something like the following, which could return all user records in your * FROM user WHERE id = 1 OR 1=1;\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n// Correct format for executing an SQL statement with parameters.\nrows, err := db.Query(\"SELECT * FROM user WHERE id = ?\", id)\n```\n\nExample:\n```text\n// SECURITY RISK!\nrows, err := db.Query(fmt.Sprintf(\"SELECT * FROM user WHERE id = %s\", id))\n```\n\nExample:\n```text\nSELECT * FROM user WHERE id = 1 OR 1=1;\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.368Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":3,"totalLines":22,"estimatedTokens":567}}5{"id":"doc-developing_and_publishing_modules_the_go_program-192c54e9","source":"documentation","title":"Developing and publishing modules - The Go Programming Language","url":"https://go.dev/doc/modules/developing","text":"Developing and publishing modules You can collect related packages into modules, then publish the modules for other developers to use. This topic gives an overview of developing and publishing modules. To support developing, publishing, and using modules, you workflow through which you develop and publish modules, revising them with new versions over time. See Workflow for developing and publishing modules. Design practices that help a module’s users understand it and upgrade to new versions in a stable way. See Design and development. A decentralized system for publishing modules and retrieving their code. You make your module available for other developers to use from your own repository and publish with a version number. See Decentralized publishing. A package search engine and documentation browser (pkg.go.dev) at which developers can find your module. See Package discovery. A module version numbering convention to communicate expectations of stability and backward compatibility to developers using your module. See Versioning. Go tools that make it easier for other developers to manage dependencies, including getting your module’s source, upgrading, and so on. See Managing dependencies. See also If you’re interested simply in using packages developed by others, this isn’t the topic for you. Instead, see Managing dependencies. For a tutorial that includes a few module development basics, see a Go module. Workflow for developing and publishing modules When you want to publish your modules for others, you adopt a few conventions to make using those modules easier. The following high-level steps are described in more detail in Module release and versioning workflow. Design and code the packages that the module will include. Commit code to your repository using conventions that ensure it’s available to others via Go tools. Publish the module to make it discoverable by developers. Over time, revise the module with versions that use a version numbering convention that signals each version’s stability and backward compatibility. Design and development Your module will be easier for developers to find and use if the functions and packages in it form a coherent whole. When you’re designing a module’s public API, try to keep its functionality focused and discrete. Also, designing and developing your module with backward compatibility in mind helps its users upgrade while minimizing churn to their own code. You can use certain techniques in code to avoid releasing a version that breaks backward compatibility. For more about those techniques, see Keeping your modules compatible on the Go blog. Before you publish a module, you can reference it on the local file system using the replace directive. This makes it easier to write client code that calls functions in the module while the module is still in development. For more information, see “Coding against an unpublished module” in Module release and versioning workflow. Decentralized publishing In Go, you publish your module by tagging its code in your repository to make it available for other developers to use. You don’t need to push your module to a centralized service because Go tools can download your module directly from your repository (located using the module’s path, which is a URL with the scheme omitted) or from a proxy server. After importing your package in their code, developers use Go tools (including the go get command) to download your module’s code to compile with. To support this model, you follow conventions and best practices that make it possible for Go tools (on behalf of another developer) to retrieve your module’s source from your repository. For example, Go tools use the module’s module path you specify, along with the module version number you use to tag the module for release, to locate and download the module for its users. For more about source and publishing conventions and best practices, see Managing module source. For step-by-step instructions on publishing a module, see Publishing a module. Package discovery After you’ve published your module and someone has fetched it with Go tools, it will become visible on the Go package discovery site at pkg.go.dev. There, developers can search the site to find it and read its documentation. To begin using the module, a developer imports packages from the module, then runs the go get command to download its source code to compile with. For more about how developers find and use modules, see Managing dependencies. Versioning As you revise and improve your module over time, you assign version numbers (based on the semantic versioning model) designed to signal each version’s stability and backward compatibility. This helps developers using your module determine when the module is stable and whether an upgrade may include significant changes in behavior. You indicate a module’s version number by tagging the module’s source in the repository with the number. For more on developing major version updates, see Developing a major version update. For more about how you use the semantic versioning model for Go modules, see Module version numbering.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.369Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":0,"totalLines":5,"estimatedTokens":1321}}6{"id":"doc-organizing_a_go_module_the_go_programming_langua-278a1eaf","source":"documentation","title":"Organizing a Go module - The Go Programming Language","url":"https://go.dev/doc/modules/layout","text":"Organizing a Go module A common question developers new to Go have is “How do I organize my Go project?”, in terms of the layout of files and folders. The goal of this document is to provide some guidelines that will help answer this question. To make the most of this document, make sure you’re familiar with the basics of Go modules by reading the tutorial and managing module source. Go projects can include packages, command-line programs or a combination of the two. This guide is organized by project type. Basic package A basic Go package has all its code in the project’s root directory. The project consists of a single module, which consists of a single package. The package name matches the last path component of the module name. For a very simple package requiring a single Go file, the project structure / go.mod modname.go modname_test.go [throughout this document, file/package names are entirely arbitrary] Assuming this directory is uploaded to a GitHub repository at github.com/someuser/modname, the module line in the go.mod file should say module github.com/someuser/modname. The code in modname.go declares the package modname // ... package code here Users can then rely on this package by import-ing it in their Go code \"github.com/someuser/modname\" A Go package can be split into multiple files, all residing within the same directory, e.g.: project-root-directory/ go.mod modname.go modname_test.go auth.go auth_test.go hash.go hash_test.go All the files in the directory declare package modname. Basic command A basic executable program (or command-line tool) is structured according to its complexity and code size. The simplest program can consist of a single Go file where func main is defined. Larger programs can have their code split across multiple files, all declaring package / go.mod auth.go auth_test.go client.go main.go Here the main.go file contains func main, but this is just a convention. The “main” file can also be called modname.go (for an appropriate value of modname) or anything else. Assuming this directory is uploaded to a GitHub repository at github.com/someuser/modname, the module line in the go.mod file should github.com/someuser/modname And a user should be able to install it on their machine with: $ go install github.com/someuser/modname@latest Package or command with supporting packages Larger packages or commands may benefit from splitting off some functionality into supporting packages. Initially, it’s recommended placing such packages into a directory named internal; this prevents other modules from depending on packages we don’t necessarily want to expose and support for external uses. Since other projects cannot import code from our internal directory, we’re free to refactor its API and generally move things around without breaking external users. The project structure for a package is / internal/ auth/ auth.go auth_test.go hash/ hash.go hash_test.go go.mod modname.go modname_test.go The modname.go file declares package modname, auth.go declares package auth and so on. modname.go can import the auth package as \"github.com/someuser/modname/internal/auth\" The layout for a command with supporting packages in an internal directory is very similar, except that the file(s) in the root directory declare package main. Multiple packages A module can consist of multiple importable packages; each package has its own directory, and can be structured hierarchically. Here’s a sample project / go.mod modname.go modname_test.go auth/ auth.go auth_test.go token/ token.go token_test.go hash/ hash.go internal/ trace/ trace.go As a reminder, we assume that the module line in go.mod github.com/someuser/modname The modname package resides in the root directory, declares package modname and can be imported by users \"github.com/someuser/modname\" Sub-packages can be imported by users as \"github.com/someuser/modname/auth\" import \"github.com/someuser/modname/auth/token\" import \"github.com/someuser/modname/hash\" Package trace that resides in internal/trace cannot be imported outside this module. It’s recommended to keep packages in internal as much as possible. Multiple commands Multiple programs in the same repository will typically have separate / go.mod internal/ ... shared internal packages prog1/ main.go prog2/ main.go In each directory, the program’s Go files declare package main. A top-level internal directory can contain shared packages used by all commands in the repository. Users can install these programs as follows: $ go install github.com/someuser/modname/prog1@latest $ go install github.com/someuser/modname/prog2@latest A common convention is placing all commands in a repository into a cmd directory; while this isn’t strictly necessary in a repository that consists only of commands, it’s very useful in a mixed repository that has both commands and importable packages, as we will discuss next. Packages and commands in the same repository Sometimes a repository will provide both importable packages and installable commands with related functionality. Here’s a sample project structure for such a / go.mod modname.go modname_test.go auth/ auth.go auth_test.go internal/ ... internal packages cmd/ prog1/ main.go prog2/ main.go Assuming this module is called github.com/someuser/modname, users can now both import packages from \"github.com/someuser/modname\" import \"github.com/someuser/modname/auth\" And install programs from it: $ go install github.com/someuser/modname/cmd/prog1@latest $ go install github.com/someuser/modname/cmd/prog2@latest Server project Go is a common language choice for implementing servers. There is a very large variance in the structure of such projects, given the many aspects of server (REST? gRPC?), deployments, front-end files, containerization, scripts and so on. We will focus our guidance here on the parts of the project written in Go. Server projects typically won’t have packages for export, since a server is usually a self-contained binary (or a group of binaries). Therefore, it’s recommended to keep the Go packages implementing the server’s logic in the internal directory. Moreover, since the project is likely to have many other directories with non-Go files, it’s a good idea to keep all Go commands together in a cmd / go.mod internal/ auth/ ... metrics/ ... model/ ... cmd/ api-server/ main.go metrics-analyzer/ main.go ... ... the project's other directories with non-Go code In case the server repository grows packages that become useful for sharing with other projects, it’s best to split these off to separate modules.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\nproject-root-directory/\n  go.mod\n  modname.go\n  modname_test.go\n```\n\nExample:\n```text\npackage modname\n\n// ... package code here\n```\n\nExample:\n```text\nimport \"github.com/someuser/modname\"\n```\n\nExample:\n```text\nproject-root-directory/\n  go.mod\n  modname.go\n  modname_test.go\n  auth.go\n  auth_test.go\n  hash.go\n  hash_test.go\n```\n\nExample:\n```text\nproject-root-directory/\n  go.mod\n  auth.go\n  auth_test.go\n  client.go\n  main.go\n```\n\nExample:\n```text\nmodule github.com/someuser/modname\n```\n\nExample:\n```text\n$ go install github.com/someuser/modname@latest\n```\n\nExample:\n```text\nproject-root-directory/\n  internal/\n    auth/\n      auth.go\n      auth_test.go\n    hash/\n      hash.go\n      hash_test.go\n  go.mod\n  modname.go\n  modname_test.go\n```\n\nExample:\n```text\nimport \"github.com/someuser/modname/internal/auth\"\n```\n\nExample:\n```text\nproject-root-directory/\n  go.mod\n  modname.go\n  modname_test.go\n  auth/\n    auth.go\n    auth_test.go\n    token/\n      token.go\n      token_test.go\n  hash/\n    hash.go\n  internal/\n    trace/\n      trace.go\n```\n\nExample:\n```text\nimport \"github.com/someuser/modname/auth\"\nimport \"github.com/someuser/modname/auth/token\"\nimport \"github.com/someuser/modname/hash\"\n```\n\nExample:\n```text\nproject-root-directory/\n  go.mod\n  internal/\n    ... shared internal packages\n  prog1/\n    main.go\n  prog2/\n    main.go\n```\n\nExample:\n```text\n$ go install github.com/someuser/modname/prog1@latest\n$ go install github.com/someuser/modname/prog2@latest\n```\n\nExample:\n```text\nproject-root-directory/\n  go.mod\n  modname.go\n  modname_test.go\n  auth/\n    auth.go\n    auth_test.go\n  internal/\n    ... internal packages\n  cmd/\n    prog1/\n      main.go\n    prog2/\n      main.go\n```\n\nExample:\n```text\nimport \"github.com/someuser/modname\"\nimport \"github.com/someuser/modname/auth\"\n```\n\nExample:\n```text\n$ go install github.com/someuser/modname/cmd/prog1@latest\n$ go install github.com/someuser/modname/cmd/prog2@latest\n```\n\nExample:\n```text\nproject-root-directory/\n  go.mod\n  internal/\n    auth/\n      ...\n    metrics/\n      ...\n    model/\n      ...\n  cmd/\n    api-server/\n      main.go\n    metrics-analyzer/\n      main.go\n    ...\n  ... the project's other directories with non-Go code\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.370Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":17,"totalLines":171,"estimatedTokens":2231}}7{"id":"doc-module_release_and_versioning_workflow_the_go_pr-2582cc37","source":"documentation","title":"Module release and versioning workflow - The Go Programming Language","url":"https://go.dev/doc/modules/release-workflow","text":"Module release and versioning workflow When you develop modules for use by other developers, you can follow a workflow that helps ensure a reliable, consistent experience for developers using the module. This topic describes the high-level steps in that workflow. For an overview of module development, see Developing and publishing modules. See also If you’re merely wanting to use external packages in your code, be sure to see Managing dependencies. With each new version, you signal the changes to your module with its version number. For more, see Module version numbering. Common workflow steps The following sequence illustrates release and versioning workflow steps for an example new module. For more about each step, see the sections in this topic. Begin a module and organize its sources to make it easier for developers to use and for you to maintain. If you’re brand new to developing modules, check out a Go module. In Go’s decentralized module publishing system, how you organize your code matters. For more, see Managing module source. Set up to write local client code that calls functions in the unpublished module. Before you publish a module, it’s unavailable for the typical dependency management workflow using commands such as go get. A good way to test your module code at this stage is to try it while it is in a directory local to your calling code. See Coding against an unpublished module for more about local development. When the module’s code is ready for other developers to try it out, begin publishing v0 pre-releases such as alphas and betas. See Publishing pre-release versions for more. Release a v0 that’s not guaranteed to be stable, but which users can try out. For more, see Publishing the first (unstable) version. After your v0 version is published, you can (and should!) continue to release new versions of it. These new versions might include bug fixes (patch releases), additions to the module’s public API (minor releases), and even breaking changes. Because a v0 release makes no guarantees of stability or backward compatibility, you can make breaking changes in its versions. For more, see Publishing bug fixes and Publishing non-breaking API changes. When you’re getting a stable version ready for release, you publish pre-releases as alphas and betas. For more, see Publishing pre-release versions. Release a v1 as the first stable release. This is the first release that makes commitments about the module’s stability. For more, see Publishing the first stable version. In the v1 version, continue to fix bugs and, where necessary, make additions to the module’s public API. For more, see Publishing bug fixes and Publishing non-breaking API changes. When it can’t be avoided, publish breaking changes in a new major version. A major version update – such as from v1.x.x to v2.x.x – can be a very disruptive upgrade for your module’s users. It should be a last resort. For more, see Publishing breaking API changes. Coding against an unpublished module When you begin developing a module or a new version of a module, you won’t yet have published it. Before you publish a module, you won’t be able to use Go commands to add the module as a dependency. Instead, at first, when writing client code in a different module that calls functions in the unpublished module, you’ll need to reference a copy of the module on the local file system. You can reference a module locally from the client module’s go.mod file by using the replace directive in the client module’s go.mod file. For more information, see in Requiring module code in a local directory. Publishing pre-release versions You can publish pre-release versions to make a module available for others to try it out and give you feedback. A pre-release version includes no guarantee of stability. Pre-release version numbers are appended with a pre-release identifier. For more on version numbers, see Module version numbering. Here are two v1.2.3-alpha When making a pre-release available, keep in mind that developers using the pre-release will need to explicitly specify it by version with the go get command. That’s because, by default, the go command prefers release versions over pre-release versions when locating the module you’re asking for. So developers must get the pre-release by specifying it explicitly, as in the following get example.com/theirmodule@v1.2.3-alpha You publish a pre-release by tagging the module code in your repository, specifying the pre-release identifier in the tag. For more, see Publishing a module. Publishing the first (unstable) version As when you publish a pre-release version, you can publish release versions that don’t guarantee stability or backward compatibility, but give your users an opportunity to try out the module and give you feedback. Unstable releases are those whose version numbers are in the v0.x.x range. A v0 version makes no stability or backward compatibility guarantees. But it gives you a way to get feedback and refine your API before making stability commitments with v1 and later. For more see, Module version numbering. As with other published versions, you can increment the minor and patch parts of the v0 version number as you make changes toward releasing a stable v1 version. For example, after releasing a v.0.0.0, you might release a v0.0.1 with the first set of bug fixes. Here’s an example version You publish an unstable release by tagging the module code in your repository, specifying a v0 version number in the tag. For more, see Publishing a module. Publishing the first stable version Your first stable release will have a v1.x.x version number. The first stable release follows pre-release and v0 releases through which you got feedback, fixed bugs, and stabilized the module for users. With a v1 release, you’re making the following commitments to developers using your can upgrade to the major version’s subsequent minor and patch releases without breaking their own code. You won’t be making further changes to the module’s public API – including its function and method signatures – that break backward compatibility. You won’t be removing any exported types, which would break backward compatibility. Future changes to your API (such as adding a new field to a struct) will be backward compatible and will be included in a new minor release. Bug fixes (such as a security fix) will be included in a patch release or as part of a minor release. your first major version might be a v0 release, a v0 version does not signal stability or backward compatibility guarantees. As a result, when you increment from v0 to v1, you needn’t be mindful of breaking backward compatibility because the v0 release was not considered stable. For more about version numbers, see Module version numbering. Here’s an example of a stable version You publish a first stable release by tagging the module code in your repository, specifying a v1 version number in the tag. For more, see Publishing a module. Publishing bug fixes You can publish a release in which the changes are limited to bug fixes. This is known as a patch release. A patch release includes only minor changes. In particular, it includes no changes to the module’s public API. Developers of consuming code can upgrade to this version safely and without needing to change their code. patch release should try not to upgrade any of that module’s own transitive dependencies by more than a patch release. Otherwise, someone upgrading to the patch of your module could wind up accidentally pulling in a more invasive change to a transitive dependency that they use. A patch release increments the patch part of the module’s version number. For more see, Module version numbering. In the following example, v1.0.1 is a patch release. Old New You publish a patch release by tagging the module code in your repository, incrementing the patch version number in the tag. For more, see Publishing a module. Publishing non-breaking API changes You can make non-breaking changes to your module’s public API and publish those changes in a minor version release. This version changes the API, but not in a way that breaks calling code. This might include changes to a module’s own dependencies or the addition of new functions, methods, struct fields, or types. Even with the changes it includes, this kind of release guarantees backward compatibility and stability for existing code that calls the module’s functions. A minor release increments the minor part of the module’s version number. For more, see Module version numbering. In the following example, v1.1.0 is a minor release. Old New You publish a minor release by tagging the module code in your repository, incrementing the minor version number in the tag. For more, see Publishing a module. Publishing breaking API changes You can publish a version that breaks backward compatibility by publishing a major version release. A major version release doesn’t guarantee backward compatibility, typically because it includes changes to the module’s public API that would break code using the module’s previous versions. Given the disruptive effect a major version upgrade can have on code relying on the module, you should avoid a major version update if you can. For more about major version updates, see Developing a major version update. For strategies to avoid making breaking changes, see the blog post Keeping your modules compatible. Where publishing other kinds of versions requires essentially tagging the module code with the version number, publishing a major version update requires more steps. Before beginning development of the new major version, in your repository create a place for the new version’s source. One way to do this is to create a new branch in your repository that is specifically for the new major version and its subsequent minor and patch versions. For more, see Managing module source. In the module’s go.mod file, revise the module path to append the new major version number, as in the following /mymodule/v2 Given that the module path is the module’s identifier, this change effectively creates a new module. It also changes the package path, ensuring that developers won’t unintentionally import a version that breaks their code. Instead, those wanting to upgrade will explicitly replace occurrences of the old path with the new one. In your code, change any package paths where you’re importing packages in the module you’re updating, including packages in the module you’re updating. You need to do this because you changed your module path. As with any new release, you should publish pre-release versions to get feedback and bug reports before publishing an official release. Publish the new major version by tagging the module code in your repository, incrementing the major version number in the tag – such as from v1.5.2 to v2.0.0. For more, see Publishing a module.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\nv0.2.1-beta.1\nv1.2.3-alpha\n```\n\nExample:\n```text\ngo get example.com/theirmodule@v1.2.3-alpha\n```\n\nExample:\n```text\nv0.1.3\n```\n\nExample:\n```text\nv1.0.0\n```\n\nExample:\n```text\nexample.com/mymodule/v2\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.372Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":5,"totalLines":31,"estimatedTokens":2815}}8{"id":"doc-publishing_a_module_the_go_programming_language-5a48d124","source":"documentation","title":"Publishing a module - The Go Programming Language","url":"https://go.dev/doc/modules/publishing","text":"Publishing a module When you want to make a module available for other developers, you publish it so that it’s visible to Go tools. Once you’ve published the module, developers importing its packages will be able to resolve a dependency on the module by running commands such as go get. ’t change a tagged version of a module after publishing it. For developers using the module, Go tools authenticate a downloaded module against the first downloaded copy. If the two differ, Go tools will return a security error. Instead of changing the code for a previously published version, publish a new version. See also For an overview of module development, see Developing and publishing modules For a high-level module development workflow – which includes publishing – see Module release and versioning workflow. Publishing steps Use the following steps to publish a module. Open a command prompt and change to your module’s root directory in the local repository. Run go mod tidy, which removes any dependencies the module might have accumulated that are no longer necessary. $ go mod tidy Run go test ./... a final time to make sure everything is working. This runs the unit tests you’ve written to use the Go testing framework. $ go test ./... ok example.com/mymodule 0.015s Tag the project with a new version number using the git tag command. For the version number, use a number that signals to users the nature of changes in this release. For more, see Module version numbering. $ git commit -m \"mymodule: changes for v0.1.0\" $ git tag v0.1.0 Push the new tag to the origin repository. $ git push origin v0.1.0 Make the module available by running the go list command to prompt Go to update its index of modules with information about the module you’re publishing. Precede the command with a statement to set the GOPROXY environment variable to a Go proxy. This will ensure that your request reaches the proxy. $ GOPROXY=proxy.golang.org go list -m example.com/mymodule@v0.1.0 Developers interested in your module import a package from it and run the go get command just as they would with any other module. They can run the go get command for latest versions or they can specify a particular version, as in the following example: $ go get example.com/mymodule@v0.1.0\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ go mod tidy\n```\n\nExample:\n```text\n$ go test ./...\nok      example.com/mymodule       0.015s\n```\n\nExample:\n```text\n$ git commit -m \"mymodule: changes for v0.1.0\"\n$ git tag v0.1.0\n```\n\nExample:\n```text\n$ git push origin v0.1.0\n```\n\nExample:\n```text\n$ GOPROXY=proxy.golang.org go list -m example.com/mymodule@v0.1.0\n```\n\nExample:\n```text\n$ go get example.com/mymodule@v0.1.0\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.373Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":6,"totalLines":37,"estimatedTokens":701}}9{"id":"doc-module_version_numbering_the_go_programming_lang-53fcd69c","source":"documentation","title":"Module version numbering - The Go Programming Language","url":"https://go.dev/doc/modules/version-numbers","text":"Module version numbering A module’s developer uses each part of a module’s version number to signal the version’s stability and backward compatibility. For each new release, a module’s release version number specifically reflects the nature of the module’s changes since the preceding release. When you’re developing code that uses external modules, you can use the version numbers to understand an external module’s stability when you’re considering an upgrade. When you’re developing your own modules, your version numbers will signal your modules’ stability and backward compatibility to other developers. This topic describes what module version numbers mean. See also When you’re using external packages in your code, you can manage those dependencies with Go tools. For more, see Managing dependencies. If you’re developing modules for others to use, you apply a version number when you publish the module, tagging the module in its repository. For more, see Publishing a module. A released module is published with a version number in the semantic versioning model, as in the following following table describes how the parts of a version number signify a module’s stability and backward compatibility. Version stage Example Message to developers In development Automatic pseudo-version number v0.x.x Signals that the module is still in development and unstable. This release carries no backward compatibility or stability guarantees. Major version v1.x.x Signals backward-incompatible public API changes. This release carries no guarantee that it will be backward compatible with preceding major versions. Minor version vx.4.x Signals backward-compatible public API changes. This release guarantees backward compatibility and stability. Patch version vx.x.1 Signals changes that don't affect the module's public API or its dependencies. This release guarantees backward compatibility and stability. Pre-release version vx.x.x-beta.2 Signals that this is a pre-release milestone, such as an alpha or beta. This release carries no stability guarantees. In development Signals that the module is still in development and unstable. This release carries no backward compatibility or stability guarantees. The version number can take one of the following number v0.0.0-20170915032832-14c0d48ead0c v0 number v0.x.x Pseudo-version number When a module has not been tagged in its repository, Go tools will generate a pseudo-version number for use in the go.mod file of code that calls functions in the module. a best practice, always allow Go tools to generate the pseudo-version number rather than creating your own. Pseudo-versions are useful when a developer of code consuming the module’s functions needs to develop against a commit that hasn’t been tagged with a semantic version tag yet. A pseudo-version number has three parts separated by dashes, as shown in the following baseVersionPrefix-timestamp-revisionIdentifier Parts baseVersionPrefix (vX.0.0 or vX.Y.Z-0) is a value derived either from a semantic version tag that precedes the revision or from vX.0.0 if there is no such tag. timestamp (yymmddhhmmss) is the UTC time the revision was created. In Git, this is the commit time, not the author time. revisionIdentifier (abcdefabcdef) is a 12-character prefix of the commit hash, or in Subversion, a zero-padded revision number. v0 number A module published with a v0 number will have a formal semantic version number with a major, minor, and patch part, as well as an optional pre-release identifier. Though a v0 version can be used in production, it makes no stability or backward compatibility guarantees. In addition, versions v1 and later are allowed to break backward compatibility for code using the v0 versions. For this reason, a developer with code consuming functions in a v0 module is responsible for adapting to incompatible changes until v1 is released. Pre-release version Signals that this is a pre-release milestone, such as an alpha or beta. This release carries no stability guarantees. Example vx.x.x-beta.2 A module’s developer can use a pre-release identifier with any major.minor.patch combination by appending a hyphen and the pre-release identifier. Minor version Signals backward-compatible changes to the module’s public API. This release guarantees backward compatibility and stability. Example vx.4.x This version changes the module’s public API, but not in a way that breaks calling code. This might include changes to a module’s own dependencies or the addition of new functions, methods, struct fields, or types. In other words, this version might include enhancements through new functions that another developer might want to use. However, a developer using previous minor versions needn’t change their code otherwise. Patch version Signals changes that don’t affect the module’s public API or its dependencies. This release guarantees backward compatibility and stability. Example vx.x.1 An update that increments this number is only for minor changes such as bug fixes. Developers of consuming code can upgrade to this version safely without needing to change their code. Major version Signals backward-incompatible changes in a module’s public API. This release carries no guarantee that it will be backward compatible with preceding major versions. Example v1.x.x A v1 or above version number signals that the module is stable for use (with exceptions for its pre-release versions). Note that because a version 0 makes no stability or backward compatibility guarantees, a developer upgrading a module from v0 to v1 is responsible for adapting to changes that break backward compatibility. A module developer should increment this number past v1 only when necessary because the version upgrade represents significant disruption for developers whose code uses function in the upgraded module. This disruption includes backward-incompatible changes to the public API, as well as the need for developers using the module to update the package path wherever they import packages from the module. A major version update to a number higher than v1 will also have a new module path. That’s because the module path will have the major version number appended, as in the following example.com/mymodule/v2 v2.0.0 A major version update makes this a new module with a separate history from the module’s previous version. If you’re developing modules to publish for others, see “Publishing breaking API changes” in Module release and versioning workflow. For more on the module directive, see go.mod reference.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\nvx.x.x-beta.2\n```\n\nExample:\n```text\nvx.4.x\n```\n\nExample:\n```text\nvx.x.1\n```\n\nExample:\n```text\nmodule example.com/mymodule/v2 v2.0.0\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.374Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":4,"totalLines":25,"estimatedTokens":1711}}10{"id":"doc-debugging_go_code_with_gdb_the_go_programming_la-eeb1588f","source":"documentation","title":"Debugging Go Code with GDB - The Go Programming Language","url":"https://go.dev/doc/gdb","text":"Documentation Debugging Go Code with GDB Debugging Go Code with GDB The following instructions apply to the standard toolchain (the gc Go compiler and tools). Gccgo has native gdb support. Note that Delve is a better alternative to GDB when debugging Go programs built with the standard toolchain. It understands the Go runtime, data structures, and expressions better than GDB. Delve currently supports Linux, OSX, and Windows on amd64. For the most up-to-date list of supported platforms, please see the Delve documentation. GDB does not understand Go programs well. The stack management, threading, and runtime contain aspects that differ enough from the execution model GDB expects that they can confuse the debugger and cause incorrect results even when the program is compiled with gccgo. As a consequence, although GDB can be useful in some situations (e.g., debugging Cgo code, or debugging the runtime itself), it is not a reliable debugger for Go programs, particularly heavily concurrent ones. Moreover, it is not a priority for the Go project to address these issues, which are difficult. In short, the instructions below should be taken only as a guide to how to use GDB when it works, not as a guarantee of success. Besides this overview you might want to consult the GDB manual. Introduction When you compile and link your Go programs with the gc toolchain on Linux, macOS, FreeBSD or NetBSD, the resulting binaries contain DWARFv4 debugging information that recent versions (≥7.5) of the GDB debugger can use to inspect a live process or a core dump. Pass the '-w' flag to the linker to omit the debug information (for example, go build -ldflags=-w prog.go). The code generated by the gc compiler includes inlining of function invocations and registerization of variables. These optimizations can sometimes make debugging with gdb harder. If you find that you need to disable these optimizations, build your program using go build -gcflags=all=\"-N -l\". If you want to use gdb to inspect a core dump, you can trigger a dump on a program crash, on systems that permit it, by setting GOTRACEBACK=crash in the environment (see the runtime package documentation for more info). Common Operations Show file and line number for code, set breakpoints and disassemble: (gdb) list (gdb) list line (gdb) list file.go:line (gdb) break line (gdb) break file.go:line (gdb) disas Show backtraces and unwind stack frames: (gdb) bt (gdb) frame n Show the name, type and location on the stack frame of local variables, arguments and return values: (gdb) info locals (gdb) info args (gdb) p variable (gdb) whatis variable Show the name, type and location of global variables: (gdb) info variables regexp Go Extensions A recent extension mechanism to GDB allows it to load extension scripts for a given binary. The toolchain uses this to extend GDB with a handful of commands to inspect internals of the runtime code (such as goroutines) and to pretty print the built-in map, slice and channel types. Pretty printing a string, slice, map, channel or interface: (gdb) p var A $len() and $cap() function for strings, slices and maps: (gdb) p $len(var) A function to cast interfaces to their dynamic types: (gdb) p $dtype(var) (gdb) iface var Known can’t automatically find the dynamic type of an interface value if its long name differs from its short name (annoying when printing stacktraces, the pretty printer falls back to printing the short type name and a pointer). Inspecting goroutines: (gdb) info goroutines (gdb) goroutine n cmd (gdb) help goroutine For example: (gdb) goroutine 12 bt You can inspect all goroutines by passing all instead of a specific goroutine's ID. For example: (gdb) goroutine all bt If you'd like to see how this works, or want to extend it, take a look at src/runtime/runtime-gdb.py in the Go source distribution. It depends on some special magic types (hash<T,U>) and variables (runtime.m and runtime.g) that the linker (src/cmd/link/internal/ld/dwarf.go) ensures are described in the DWARF code. If you're interested in what the debugging information looks like, run objdump -W a.out and browse through the .debug_* sections. Known Issues String pretty printing only triggers for type string, not for types derived from it. Type information is missing for the C parts of the runtime library. GDB does not understand Go’s name qualifications and treats \"fmt.Print\" as an unstructured literal with a \".\" that needs to be quoted. It objects even more strongly to method names of the form pkg.(*MyType).Meth. As of Go 1.11, debug information is compressed by default. Older versions of gdb, such as the one available by default on MacOS, do not understand the compression. You can generate uncompressed debug information by using go build -ldflags=-compressdwarf=false. (For convenience you can put the -ldflags option in the GOFLAGS environment variable so that you don't have to specify it each time.) Tutorial In this tutorial we will inspect the binary of the regexp package's unit tests. To build the binary, change to $GOROOT/src/regexp and run go test -c. This should produce an executable file named regexp.test. Getting Started Launch GDB, debugging regexp.test: $ gdb regexp.test GNU gdb (GDB) 7.2-gg8 Copyright (C) 2010 Free Software Foundation, Inc. License GPLv 3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> Type \"show copying\" and \"show warranty\" for licensing/warranty details. This GDB was configured as \"x86_64-linux\". Reading symbols from /home/user/go/src/regexp/regexp.test... done. Loading Go Runtime support. (gdb) The message \"Loading Go Runtime support\" means that GDB loaded the extension from $GOROOT/src/runtime/runtime-gdb.py. To help GDB find the Go runtime sources and the accompanying support script, pass your $GOROOT with the '-d' flag: $ gdb regexp.test -d $GOROOT If for some reason GDB still can't find that directory or that script, you can load it by hand by telling gdb (assuming you have the go sources in ~/go/): (gdb) source ~/go/src/runtime/runtime-gdb.py Loading Go Runtime support. Inspecting the source Use the \"l\" or \"list\" command to inspect source code. (gdb) l List a specific part of the source parameterizing \"list\" with a function name (it must be qualified with its package name). (gdb) l main.main List a specific file and line number: (gdb) l regexp.go:1 (gdb) # Hit enter to repeat last command. Here, this lists next 10 lines. Naming Variable and function names must be qualified with the name of the packages they belong to. The Compile function from the regexp package is known to GDB as 'regexp.Compile'. Methods must be qualified with the name of their receiver types. For example, the *Regexp type’s String method is known as 'regexp.(*Regexp).String'. Variables that shadow other variables are magically suffixed with a number in the debug info. Variables referenced by closures will appear as pointers magically prefixed with '&'. Setting breakpoints Set a breakpoint at the TestFind function: (gdb) b 'regexp.TestFind' Breakpoint 1 at /home/user/go/src/regexp/find_test.go, line 148. Run the program: (gdb) run Starting program: /home/user/go/src/regexp/regexp.test Breakpoint 1, regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/regexp/find_test.go:148 148 func TestFind(t *testing.T) { Execution has paused at the breakpoint. See which goroutines are running, and what they're doing: (gdb) info goroutines 1 waiting runtime.gosched * 13 running runtime.goexit the one marked with the * is the current goroutine. Inspecting the stack Look at the stack trace for where we’ve paused the program: (gdb) bt # backtrace 0x7ffff7f9ef60, tests= []testing.InternalTest = {...}) at /home/user/go/src/testing/testing.go:201 0x7ffff7f9ef80, tests= []testing.InternalTest = {...}, benchmarks= []testing.InternalBenchmark = {...}) at /home/user/go/src/testing/testing.go:168 (gdb) p *t->ch $3 = struct hchan<*testing.T> That struct hchan<*testing.T> is the runtime-internal representation of a channel. It is currently empty, or gdb would have pretty-printed its contents. Stepping forward: (gdb) n # execute next line 149 for _, test := range findTests { (gdb) # enter is repeat 150 re := MustCompile(test.pat) (gdb) p test.pat $4 = \"\" (gdb) p re $5 = (struct regexp.Regexp *) 0xf84068d070 (gdb) p *re $6 = {expr = \"\", prog = 0xf840688b80, prefix = \"\", prefixBytes = []uint8, prefixComplete = true, prefixRune = 0, cond = 0 '\\000', numSubexp = 0, longest = false, mu = {state = 0, sema = 0}, machine = []*regexp.machine} (gdb) p *re->prog $7 = {Inst = []regexp/syntax.Inst = {{Op = 5 '\\005', Out = 0, Arg = 0, Rune = []int}, {Op = 6 '\\006', Out = 2, Arg = 0, Rune = []int}, {Op = 4 '\\004', Out = 0, Arg = 0, Rune = []int}}, Start = 1, NumCap = 2} We can step into the Stringfunction call with \"s\": (gdb) s regexp.(*Regexp).String (re=0xf84068d070, noname=void) at /home/user/go/src/regexp/regexp.go:97 97 func (re *Regexp) String() string { Get a stack trace to see where we are: (gdb) bt 100 101 // Compile parses a regular expression and returns, if successful, Pretty Printing GDB's pretty printing mechanism is triggered by regexp matches on type names. An example for slices: (gdb) p utf $22 = []uint8 = {0 '\\000', 0 '\\000', 0 '\\000', 0 '\\000'} Since slices, arrays and strings are not C pointers, GDB can't interpret the subscripting operation for you, but you can look inside the runtime representation to do that (tab completion helps here): (gdb) p slc $11 = []int = {0, 0} (gdb) p slc-><TAB> array slc len (gdb) p slc->array $12 = (int *) 0xf84057af00 (gdb) p slc->array[1] $13 = 0 The extension functions $len and $cap work on strings, arrays and slices: (gdb) p $len(utf) $23 = 4 (gdb) p $cap(utf) $24 = 4 Channels and maps are 'reference' types, which gdb shows as pointers to C++-like types hash<int,string>*. Dereferencing will trigger prettyprinting Interfaces are represented in the runtime as a pointer to a type descriptor and a pointer to a value. The Go GDB runtime extension decodes this and automatically triggers pretty printing for the runtime type. The extension function $dtype decodes the dynamic type for you (examples are taken from a breakpoint at regexp.go line 293.) (gdb) p i $4 = {str = \"cbb\"} (gdb) whatis i type = regexp.input (gdb) p $dtype(i) $26 = (struct regexp.inputBytes *) 0xf8400b4930 (gdb) iface i regexp.input: struct regexp.inputBytes *\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n(gdb) list\n(gdb) list line\n(gdb) list file.go:line\n(gdb) break line\n(gdb) break file.go:line\n(gdb) disas\n```\n\nExample:\n```text\n(gdb) bt\n(gdb) frame n\n```\n\nExample:\n```text\n(gdb) info locals\n(gdb) info args\n(gdb) p variable\n(gdb) whatis variable\n```\n\nExample:\n```text\n(gdb) info variables regexp\n```\n\nExample:\n```text\n(gdb) p var\n```\n\nExample:\n```text\n(gdb) p $len(var)\n```\n\nExample:\n```text\n(gdb) p $dtype(var)\n(gdb) iface var\n```\n\nExample:\n```text\n(gdb) info goroutines\n(gdb) goroutine n cmd\n(gdb) help goroutine\n```\n\nExample:\n```text\n(gdb) goroutine 12 bt\n```\n\nExample:\n```text\n(gdb) goroutine all bt\n```\n\nExample:\n```text\n$ gdb regexp.test\nGNU gdb (GDB) 7.2-gg8\nCopyright (C) 2010 Free Software Foundation, Inc.\nLicense GPLv  3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\nType \"show copying\" and \"show warranty\" for licensing/warranty details.\nThis GDB was configured as \"x86_64-linux\".\n\nReading symbols from  /home/user/go/src/regexp/regexp.test...\ndone.\nLoading Go Runtime support.\n(gdb)\n```\n\nExample:\n```text\n$ gdb regexp.test -d $GOROOT\n```\n\nExample:\n```text\n(gdb) source ~/go/src/runtime/runtime-gdb.py\nLoading Go Runtime support.\n```\n\nExample:\n```text\n(gdb) l\n```\n\nExample:\n```text\n(gdb) l main.main\n```\n\nExample:\n```text\n(gdb) l regexp.go:1\n(gdb) # Hit enter to repeat last command. Here, this lists next 10 lines.\n```\n\nExample:\n```text\n(gdb) b 'regexp.TestFind'\nBreakpoint 1 at 0x424908: file /home/user/go/src/regexp/find_test.go, line 148.\n```\n\nExample:\n```text\n(gdb) run\nStarting program: /home/user/go/src/regexp/regexp.test\n\nBreakpoint 1, regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/regexp/find_test.go:148\n148\tfunc TestFind(t *testing.T) {\n```\n\nExample:\n```text\n(gdb) info goroutines\n  1  waiting runtime.gosched\n* 13  running runtime.goexit\n```\n\nExample:\n```text\n(gdb) bt  # backtrace\n#0  regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/regexp/find_test.go:148\n#1  0x000000000042f60b in testing.tRunner (t=0xf8404a89c0, test=0x573720) at /home/user/go/src/testing/testing.go:156\n#2  0x000000000040df64 in runtime.initdone () at /home/user/go/src/runtime/proc.c:242\n#3  0x000000f8404a89c0 in ?? ()\n#4  0x0000000000573720 in ?? ()\n#5  0x0000000000000000 in ?? ()\n```\n\nExample:\n```text\n(gdb) goroutine 1 bt\n#0  0x000000000040facb in runtime.gosched () at /home/user/go/src/runtime/proc.c:873\n#1  0x00000000004031c9 in runtime.chanrecv (c=void, ep=void, selected=void, received=void)\n at  /home/user/go/src/runtime/chan.c:342\n#2  0x0000000000403299 in runtime.chanrecv1 (t=void, c=void) at/home/user/go/src/runtime/chan.c:423\n#3  0x000000000043075b in testing.RunTests (matchString={void (struct string, struct string, bool *, error *)}\n 0x7ffff7f9ef60, tests=  []testing.InternalTest = {...}) at /home/user/go/src/testing/testing.go:201\n#4  0x00000000004302b1 in testing.Main (matchString={void (struct string, struct string, bool *, error *)}\n 0x7ffff7f9ef80, tests= []testing.InternalTest = {...}, benchmarks= []testing.InternalBenchmark = {...})\nat /home/user/go/src/testing/testing.go:168\n#5  0x0000000000400dc1 in main.main () at /home/user/go/src/regexp/_testmain.go:98\n#6  0x00000000004022e7 in runtime.mainstart () at /home/user/go/src/runtime/amd64/asm.s:78\n#7  0x000000000040ea6f in runtime.initdone () at /home/user/go/src/runtime/proc.c:243\n#8  0x0000000000000000 in ?? ()\n```\n\nExample:\n```text\n(gdb) info frame\nStack level 0, frame at 0x7ffff7f9ff88:\n rip = 0x425530 in regexp.TestFind (/home/user/go/src/regexp/find_test.go:148);\n    saved rip 0x430233\n called by frame at 0x7ffff7f9ffa8\n source language minimal.\n Arglist at 0x7ffff7f9ff78, args: t=0xf840688b60\n Locals at 0x7ffff7f9ff78, Previous frame's sp is 0x7ffff7f9ff88\n Saved registers:\n  rip at 0x7ffff7f9ff80\n```\n\nExample:\n```text\n(gdb) info args\nt = 0xf840688b60\n```\n\nExample:\n```text\n(gdb) p re\n(gdb) p t\n$1 = (struct testing.T *) 0xf840688b60\n(gdb) p t\n$1 = (struct testing.T *) 0xf840688b60\n(gdb) p *t\n$2 = {errors = \"\", failed = false, ch = 0xf8406f5690}\n(gdb) p *t->ch\n$3 = struct hchan<*testing.T>\n```\n\nExample:\n```text\n(gdb) n  # execute next line\n149             for _, test := range findTests {\n(gdb)    # enter is repeat\n150                     re := MustCompile(test.pat)\n(gdb) p test.pat\n$4 = \"\"\n(gdb) p re\n$5 = (struct regexp.Regexp *) 0xf84068d070\n(gdb) p *re\n$6 = {expr = \"\", prog = 0xf840688b80, prefix = \"\", prefixBytes =  []uint8, prefixComplete = true,\n  prefixRune = 0, cond = 0 '\\000', numSubexp = 0, longest = false, mu = {state = 0, sema = 0},\n  machine =  []*regexp.machine}\n(gdb) p *re->prog\n$7 = {Inst =  []regexp/syntax.Inst = {{Op = 5 '\\005', Out = 0, Arg = 0, Rune =  []int}, {Op =\n    6 '\\006', Out = 2, Arg = 0, Rune =  []int}, {Op = 4 '\\004', Out = 0, Arg = 0, Rune =  []int}},\n  Start = 1, NumCap = 2}\n```\n\nExample:\n```text\n(gdb) s\nregexp.(*Regexp).String (re=0xf84068d070, noname=void) at /home/user/go/src/regexp/regexp.go:97\n97      func (re *Regexp) String() string {\n```\n\nExample:\n```text\n(gdb) bt\n#0  regexp.(*Regexp).String (re=0xf84068d070, noname=void)\n    at /home/user/go/src/regexp/regexp.go:97\n#1  0x0000000000425615 in regexp.TestFind (t=0xf840688b60)\n    at /home/user/go/src/regexp/find_test.go:151\n#2  0x0000000000430233 in testing.tRunner (t=0xf840688b60, test=0x5747b8)\n    at /home/user/go/src/testing/testing.go:156\n#3  0x000000000040ea6f in runtime.initdone () at /home/user/go/src/runtime/proc.c:243\n....\n```\n\nExample:\n```text\n(gdb) l\n92              mu      sync.Mutex\n93              machine []*machine\n94      }\n95\n96      // String returns the source text used to compile the regular expression.\n97      func (re *Regexp) String() string {\n98              return re.expr\n99      }\n100\n101     // Compile parses a regular expression and returns, if successful,\n```\n\nExample:\n```text\n(gdb) p utf\n$22 =  []uint8 = {0 '\\000', 0 '\\000', 0 '\\000', 0 '\\000'}\n```\n\nExample:\n```text\n(gdb) p slc\n$11 =  []int = {0, 0}\n(gdb) p slc-><TAB>\narray  slc    len\n(gdb) p slc->array\n$12 = (int *) 0xf84057af00\n(gdb) p slc->array[1]\n$13 = 0\n```\n\nExample:\n```text\n(gdb) p $len(utf)\n$23 = 4\n(gdb) p $cap(utf)\n$24 = 4\n```\n\nExample:\n```text\n(gdb) p i\n$4 = {str = \"cbb\"}\n(gdb) whatis i\ntype = regexp.input\n(gdb) p $dtype(i)\n$26 = (struct regexp.inputBytes *) 0xf8400b4930\n(gdb) iface i\nregexp.input: struct regexp.inputBytes *\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.376Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":32,"totalLines":286,"estimatedTokens":4210}}11{"id":"doc-about_the_go_command_the_go_programming_language-dc900eaf","source":"documentation","title":"About the go command - The Go Programming Language","url":"https://go.dev/doc/articles/go_command.html","text":"About the go command The Go distribution includes a command, named \"go\", that automates the downloading, building, installation, and testing of Go packages and commands. This document talks about why we wrote a new command, what it is, what it's not, and how to use it. Motivation You might have seen early Go talks in which Rob Pike jokes that the idea for Go arose while waiting for a large Google server to compile. That really was the motivation for build a language that worked well for building the large software that Google writes and runs. It was clear from the start that such a language must provide a way to express dependencies between code libraries clearly, hence the package grouping and the explicit import blocks. It was also clear from the start that you might want arbitrary syntax for describing the code being imported; this is why import paths are string literals. An explicit goal for Go from the beginning was to be able to build Go code using only the information found in the source itself, not needing to write a makefile or one of the many modern replacements for makefiles. If Go needed a configuration file to explain how to build your program, then Go would have failed. At first, there was no Go compiler, and the initial development focused on building one and then building libraries for it. For expedience, we postponed the automation of building Go code by using make and writing makefiles. When compiling a single package involved multiple invocations of the Go compiler, we even used a program to write the makefiles for us. You can find it if you dig through the repository history. The purpose of the new go command is our return to this ideal, that Go programs should compile without configuration or additional effort on the part of the developer beyond writing the necessary import statements. Configuration versus convention The way to achieve the simplicity of a configuration-free system is to establish conventions. The system works only to the extent that those conventions are followed. When we first launched Go, many people published packages that had to be installed in certain places, under certain names, using certain build tools, in order to be used. That's 's the way it works in most other languages. Over the last few years we consistently reminded people about the goinstall command (now replaced by go get) and its , that the import path is derived in a known way from the URL of the source code; second, that the place to store the sources in the local file system is derived in a known way from the import path; third, that each directory in a source tree corresponds to a single package; and fourth, that the package is built using only information in the source code. Today, the vast majority of packages follow these conventions. The Go ecosystem is simpler and more powerful as a result. We received many requests to allow a makefile in a package directory to provide just a little extra configuration beyond what's in the source code. But that would have introduced new rules. Because we did not accede to such requests, we were able to write the go command and eliminate our use of make or any other build system. It is important to understand that the go command is not a general build tool. It cannot be configured and it does not attempt to build anything but Go packages. These are important simplifying simplify not only the implementation but also, more important, the use of the tool itself. Go's conventions The go command requires that code adheres to a few key, well-established conventions. First, the import path is derived in a known way from the URL of the source code. For Bitbucket, GitHub, Google Code, and Launchpad, the root directory of the repository is identified by the repository's main URL, without the https:// prefix. Subdirectories are named by adding to that path. For example, the source code of the Google logging package glog is obtained by running git clone https://github.com/golang/glog and thus the import path of the glog package is \"github.com/golang/glog\". These paths are on the long side, but in exchange we get an automatically managed name space for import paths and the ability for a tool like the go command to look at an unfamiliar import path and deduce where to obtain the source code. Second, the place to store sources in the local file system is derived in a known way from the import path, specifically $GOPATH/src/<import-path>. If unset, $GOPATH defaults to a subdirectory named go in the user's home directory. If $GOPATH is set to a list of paths, the go command tries <dir>/src/<import-path> for each of the directories in that list. Each of those trees contains, by convention, a top-level directory named \"bin\", for holding compiled executables, and a top-level directory named \"pkg\", for holding compiled packages that can be imported, and the \"src\" directory, for holding package source files. Imposing this structure lets us keep each of these directory trees compiled form and the sources are always near each other. These naming conventions also let us work in the reverse direction, from a directory name to its import path. This mapping is important for many of the go command's subcommands, as we'll see below. Third, each directory in a source tree corresponds to a single package. By restricting a directory to a single package, we don't have to create hybrid import paths that specify first the directory and then the package within that directory. Also, most file management tools and UIs work on directories as fundamental units. Tying the fundamental Go unit—the package—to file system structure means that file system tools become Go package tools. Copying, moving, or deleting a package corresponds to copying, moving, or deleting a directory. Fourth, each package is built using only the information present in the source files. This makes it much more likely that the tool will be able to adapt to changing build environments and conditions. For example, if we allowed extra configuration such as compiler flags or command line recipes, then that configuration would need to be updated each time the build tools changed; it would also be inherently tied to the use of a specific toolchain. Getting started with the go command Finally, a quick tour of how to use the go command. As mentioned above, the default $GOPATH on Unix is $HOME/go. We'll store our programs there. To use a different location, you can set $GOPATH; see How to Write Go Code for details. We first add some source code. Suppose we want to use the indexing library from the codesearch project along with a left-leaning red-black tree. We can install both with the \"go get\" subcommand: $ go get github.com/google/codesearch/index $ go get github.com/petar/GoLLRB/llrb $ Both of these projects are now downloaded and installed into $HOME/go, which contains the two directories src/github.com/google/codesearch/index/ and src/github.com/petar/GoLLRB/llrb/, along with the compiled packages (in pkg/) for those libraries and their dependencies. Because we used version control systems (Mercurial and Git) to check out the sources, the source tree also contains the other files in the corresponding repositories, such as related packages. The \"go list\" subcommand lists the import paths corresponding to its arguments, and the pattern \"./...\" means start in the current directory (\"./\") and find all packages below that directory (\"...\"): $ cd $HOME/go/src $ go list ./... github.com/google/codesearch/cmd/cgrep github.com/google/codesearch/cmd/cindex github.com/google/codesearch/cmd/csearch github.com/google/codesearch/index github.com/google/codesearch/regexp github.com/google/codesearch/sparse github.com/petar/GoLLRB/example github.com/petar/GoLLRB/llrb $ We can also test those packages: $ go test ./... ? github.com/google/codesearch/cmd/cgrep [no test files] ? github.com/google/codesearch/cmd/cindex [no test files] ? github.com/google/codesearch/cmd/csearch [no test files] ok github.com/google/codesearch/index 0.203s ok github.com/google/codesearch/regexp 0.017s ? github.com/google/codesearch/sparse [no test files] ? github.com/petar/GoLLRB/example [no test files] ok github.com/petar/GoLLRB/llrb 0.231s $ If a go subcommand is invoked with no paths listed, it operates on the current directory: $ cd github.com/google/codesearch/regexp $ go list github.com/google/codesearch/regexp $ go test -v === RUN TestNstateEnc --- (0.00s) === RUN TestMatch --- (0.00s) === RUN TestGrep --- (0.00s) PASS ok github.com/google/codesearch/regexp 0.018s $ go install $ That \"go install\" subcommand installs the latest copy of the package into the pkg directory. Because the go command can analyze the dependency graph, \"go install\" also installs any packages that this package imports but that are out of date, recursively. Notice that \"go install\" was able to determine the name of the import path for the package in the current directory, because of the convention for directory naming. It would be a little more convenient if we could pick the name of the directory where we kept source code, and we probably wouldn't pick such a long name, but that ability would require additional configuration and complexity in the tool. Typing an extra directory name or two is a small price to pay for the increased simplicity and power. Limitations As mentioned above, the go command is not a general-purpose build tool. In particular, it does not have any facility for generating Go source files during a build, although it does provide go generate, which can automate the creation of Go files before the build. For more advanced build setups, you may need to write a makefile (or a configuration file for the build tool of your choice) to run whatever tool creates the Go files and then check those generated source files into your repository. This is more work for you, the package author, but it is significantly less work for your users, who can use \"go get\" without needing to obtain and build any additional tools. More information For more information, read How to Write Go Code and see the go command documentation.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\ngit clone https://github.com/golang/glog\n```\n\nExample:\n```text\n$ go get github.com/google/codesearch/index\n$ go get github.com/petar/GoLLRB/llrb\n$\n```\n\nExample:\n```text\n$ cd $HOME/go/src\n$ go list ./...\ngithub.com/google/codesearch/cmd/cgrep\ngithub.com/google/codesearch/cmd/cindex\ngithub.com/google/codesearch/cmd/csearch\ngithub.com/google/codesearch/index\ngithub.com/google/codesearch/regexp\ngithub.com/google/codesearch/sparse\ngithub.com/petar/GoLLRB/example\ngithub.com/petar/GoLLRB/llrb\n$\n```\n\nExample:\n```text\n$ go test ./...\n?   \tgithub.com/google/codesearch/cmd/cgrep\t[no test files]\n?   \tgithub.com/google/codesearch/cmd/cindex\t[no test files]\n?   \tgithub.com/google/codesearch/cmd/csearch\t[no test files]\nok  \tgithub.com/google/codesearch/index\t0.203s\nok  \tgithub.com/google/codesearch/regexp\t0.017s\n?   \tgithub.com/google/codesearch/sparse\t[no test files]\n?       github.com/petar/GoLLRB/example          [no test files]\nok      github.com/petar/GoLLRB/llrb             0.231s\n$\n```\n\nExample:\n```text\n$ cd github.com/google/codesearch/regexp\n$ go list\ngithub.com/google/codesearch/regexp\n$ go test -v\n=== RUN   TestNstateEnc\n--- PASS: TestNstateEnc (0.00s)\n=== RUN   TestMatch\n--- PASS: TestMatch (0.00s)\n=== RUN   TestGrep\n--- PASS: TestGrep (0.00s)\nPASS\nok  \tgithub.com/google/codesearch/regexp\t0.018s\n$ go install\n$\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.381Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":5,"totalLines":64,"estimatedTokens":2905}}12{"id":"doc-codewalk_share_memory_by_communicating_the_go_pr-9be0ae70","source":"documentation","title":"Codewalk: Share Memory By Communicating - The Go Programming Language","url":"https://go.dev/doc/codewalk/sharemem","text":"Memory By Communicating doc/codewalk/urlpoll.go code on left • right code width 70% filepaths shown • hidden Introduction Go's approach to concurrency differs from the traditional use of threads and shared memory. Philosophically, it can be 't communicate by sharing memory; share memory by communicating. Channels allow you to pass references to data structures between goroutines. If you consider this as passing around ownership of the data (the ability to read and write it), they become a powerful and expressive synchronization mechanism. In this codewalk we will look at a simple program that polls a list of URLs, checking their HTTP response codes and periodically printing their state. doc/codewalk/urlpoll.go State type The State type represents the state of a URL. The Pollers send State values to the StateMonitor, which maintains a map of the current state of each URL. doc/codewalk/urlpoll.go:26,30 Resource type A Resource represents the state of a URL to be URL itself and the number of errors encountered since the last successful poll. When the program starts, it allocates one Resource for each URL. The main goroutine and the Poller goroutines send the Resources to each other on channels. doc/codewalk/urlpoll.go:60,64 Poller function Each Poller receives Resource pointers from an input channel. In this program, the convention is that sending a Resource pointer on a channel passes ownership of the underlying data from the sender to the receiver. Because of this convention, we know that no two goroutines will access this Resource at the same time. This means we don't have to worry about locking to prevent concurrent access to these data structures. The Poller processes the Resource by calling its Poll method. It sends a State value to the status channel, to inform the StateMonitor of the result of the Poll. Finally, it sends the Resource pointer to the out channel. This can be interpreted as the Poller saying \"I'm done with this Resource\" and returning ownership of it to the main goroutine. Several goroutines run Pollers, processing Resources in parallel. doc/codewalk/urlpoll.go:86,92 The Poll method The Poll method (of the Resource type) performs an HTTP HEAD request for the Resource's URL and returns the HTTP response's status code. If an error occurs, Poll logs the message to standard error and returns the error string instead. doc/codewalk/urlpoll.go:66,77 main function The main function starts the Poller and StateMonitor goroutines and then loops passing completed Resources back to the pending channel after appropriate delays. doc/codewalk/urlpoll.go:94,116 Creating channels First, main makes two channels of *Resource, pending and complete. Inside main, a new goroutine sends one Resource per URL to pending and the main goroutine receives completed Resources from complete. The pending and complete channels are passed to each of the Poller goroutines, within which they are known as in and out. doc/codewalk/urlpoll.go:95,96 Initializing StateMonitor StateMonitor will initialize and launch a goroutine that stores the state of each Resource. We will look at this function in detail later. For now, the important thing to note is that it returns a channel of State, which is saved as status and passed to the Poller goroutines. doc/codewalk/urlpoll.go:98,99 Launching Poller goroutines Now that it has the necessary channels, main launches a number of Poller goroutines, passing the channels as arguments. The channels provide the means of communication between the main, Poller, and StateMonitor goroutines. doc/codewalk/urlpoll.go:101,104 Send Resources to pending To add the initial work to the system, main starts a new goroutine that allocates and sends one Resource per URL to pending. The new goroutine is necessary because unbuffered channel sends and receives are synchronous. That means these channel sends will block until the Pollers are ready to read from pending. Were these sends performed in the main goroutine with fewer Pollers than channel sends, the program would reach a deadlock situation, because main would not yet be receiving from complete. Exercise for the this part of the program to read a list of URLs from a file. (You may want to move this goroutine into its own named function.) doc/codewalk/urlpoll.go:106,111 Main Event Loop When a Poller is done with a Resource, it sends it on the complete channel. This loop receives those Resource pointers from complete. For each received Resource, it starts a new goroutine calling the Resource's Sleep method. Using a new goroutine for each ensures that the sleeps can happen in parallel. Note that any single Resource pointer may only be sent on either pending or complete at any one time. This ensures that a Resource is either being handled by a Poller goroutine or sleeping, but never both simultaneously. In this way, we share our Resource data by communicating. doc/codewalk/urlpoll.go:113,115 The Sleep method Sleep calls time.Sleep to pause before sending the Resource to done. The pause will either be of a fixed length (pollInterval) plus an additional delay proportional to the number of sequential errors (r.errCount). This is an example of a typical Go function intended to run inside a goroutine takes a channel, upon which it sends its return value (or other indication of completed state). doc/codewalk/urlpoll.go:79,84 StateMonitor The StateMonitor receives State values on a channel and periodically outputs the state of all Resources being polled by the program. doc/codewalk/urlpoll.go:32,50 The updates channel The variable updates is a channel of State, on which the Poller goroutines send State values. This channel is returned by the function. doc/codewalk/urlpoll.go:36 The urlStatus map The variable urlStatus is a map of URLs to their most recent status. doc/codewalk/urlpoll.go:37 The Ticker object A time.Ticker is an object that repeatedly sends a value on a channel at a specified interval. In this case, ticker triggers the printing of the current state to standard output every updateInterval nanoseconds. doc/codewalk/urlpoll.go:38 The StateMonitor goroutine StateMonitor will loop forever, selecting on two and update. The select statement blocks until one of its communications is ready to proceed. When StateMonitor receives a tick from ticker.C, it calls logState to print the current state. When it receives a State update from updates, it records the new status in the urlStatus map. Notice that this goroutine owns the urlStatus data structure, ensuring that it can only be accessed sequentially. This prevents memory corruption issues that might arise from parallel reads and/or writes to a shared map. doc/codewalk/urlpoll.go:39,48 Conclusion In this codewalk we have explored a simple example of using Go's concurrency primitives to share memory through communication. This should provide a starting point from which to explore the ways in which goroutines and channels can be used to write expressive and concise concurrent programs. doc/codewalk/urlpoll.go previous step • next step\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.382Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":0,"totalLines":5,"estimatedTokens":1800}}13{"id":"doc-the_go_programming_language-b55a234d","source":"documentation","title":"- The Go Programming Language","url":"https://go.dev/doc/articles/wiki/part3.go","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n1  // Copyright 2010 The Go Authors. All rights reserved.\n     2  // Use of this source code is governed by a BSD-style\n     3  // license that can be found in the LICENSE file.\n     4  \n     5  //go:build ignore\n     6  \n     7  package main\n     8  \n     9  import (\n    10  \t\"html/template\"\n    11  \t\"log\"\n    12  \t\"net/http\"\n    13  \t\"os\"\n    14  )\n    15  \n    16  type Page struct {\n    17  \tTitle string\n    18  \tBody  []byte\n    19  }\n    20  \n    21  func (p *Page) save() error {\n    22  \tfilename := p.Title + \".txt\"\n    23  \treturn os.WriteFile(filename, p.Body, 0600)\n    24  }\n    25  \n    26  func loadPage(title string) (*Page, error) {\n    27  \tfilename := title + \".txt\"\n    28  \tbody, err := os.ReadFile(filename)\n    29  \tif err != nil {\n    30  \t\treturn nil, err\n    31  \t}\n    32  \treturn &Page{Title: title, Body: body}, nil\n    33  }\n    34  \n    35  func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {\n    36  \tt, _ := template.ParseFiles(tmpl + \".html\")\n    37  \tt.Execute(w, p)\n    38  }\n    39  \n    40  func viewHandler(w http.ResponseWriter, r *http.Request) {\n    41  \ttitle := r.URL.Path[len(\"/view/\"):]\n    42  \tp, _ := loadPage(title)\n    43  \trenderTemplate(w, \"view\", p)\n    44  }\n    45  \n    46  func editHandler(w http.ResponseWriter, r *http.Request) {\n    47  \ttitle := r.URL.Path[len(\"/edit/\"):]\n    48  \tp, err := loadPage(title)\n    49  \tif err != nil {\n    50  \t\tp = &Page{Title: title}\n    51  \t}\n    52  \trenderTemplate(w, \"edit\", p)\n    53  }\n    54  \n    55  func main() {\n    56  \thttp.HandleFunc(\"/view/\", viewHandler)\n    57  \thttp.HandleFunc(\"/edit/\", editHandler)\n    58  \t//http.HandleFunc(\"/save/\", saveHandler)\n    59  \tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n    60  }\n    61\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.383Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":68,"estimatedTokens":479}}14{"id":"doc-the_go_programming_language-2f13092f","source":"documentation","title":"- The Go Programming Language","url":"https://go.dev/doc/articles/wiki/part2.go","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n1  // Copyright 2010 The Go Authors. All rights reserved.\n     2  // Use of this source code is governed by a BSD-style\n     3  // license that can be found in the LICENSE file.\n     4  \n     5  //go:build ignore\n     6  \n     7  package main\n     8  \n     9  import (\n    10  \t\"fmt\"\n    11  \t\"log\"\n    12  \t\"net/http\"\n    13  \t\"os\"\n    14  )\n    15  \n    16  type Page struct {\n    17  \tTitle string\n    18  \tBody  []byte\n    19  }\n    20  \n    21  func (p *Page) save() error {\n    22  \tfilename := p.Title + \".txt\"\n    23  \treturn os.WriteFile(filename, p.Body, 0600)\n    24  }\n    25  \n    26  func loadPage(title string) (*Page, error) {\n    27  \tfilename := title + \".txt\"\n    28  \tbody, err := os.ReadFile(filename)\n    29  \tif err != nil {\n    30  \t\treturn nil, err\n    31  \t}\n    32  \treturn &Page{Title: title, Body: body}, nil\n    33  }\n    34  \n    35  func viewHandler(w http.ResponseWriter, r *http.Request) {\n    36  \ttitle := r.URL.Path[len(\"/view/\"):]\n    37  \tp, _ := loadPage(title)\n    38  \tfmt.Fprintf(w, \"<h1>%s</h1><div>%s</div>\", p.Title, p.Body)\n    39  }\n    40  \n    41  func main() {\n    42  \thttp.HandleFunc(\"/view/\", viewHandler)\n    43  \tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n    44  }\n    45\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.383Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":52,"estimatedTokens":348}}15{"id":"doc-the_go_programming_language-97e05ed6","source":"documentation","title":"- The Go Programming Language","url":"https://go.dev/doc/articles/wiki/final.go","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n1  // Copyright 2010 The Go Authors. All rights reserved.\n     2  // Use of this source code is governed by a BSD-style\n     3  // license that can be found in the LICENSE file.\n     4  \n     5  //go:build ignore\n     6  \n     7  package main\n     8  \n     9  import (\n    10  \t\"html/template\"\n    11  \t\"log\"\n    12  \t\"net/http\"\n    13  \t\"os\"\n    14  \t\"regexp\"\n    15  )\n    16  \n    17  type Page struct {\n    18  \tTitle string\n    19  \tBody  []byte\n    20  }\n    21  \n    22  func (p *Page) save() error {\n    23  \tfilename := p.Title + \".txt\"\n    24  \treturn os.WriteFile(filename, p.Body, 0600)\n    25  }\n    26  \n    27  func loadPage(title string) (*Page, error) {\n    28  \tfilename := title + \".txt\"\n    29  \tbody, err := os.ReadFile(filename)\n    30  \tif err != nil {\n    31  \t\treturn nil, err\n    32  \t}\n    33  \treturn &Page{Title: title, Body: body}, nil\n    34  }\n    35  \n    36  func viewHandler(w http.ResponseWriter, r *http.Request, title string) {\n    37  \tp, err := loadPage(title)\n    38  \tif err != nil {\n    39  \t\thttp.Redirect(w, r, \"/edit/\"+title, http.StatusFound)\n    40  \t\treturn\n    41  \t}\n    42  \trenderTemplate(w, \"view\", p)\n    43  }\n    44  \n    45  func editHandler(w http.ResponseWriter, r *http.Request, title string) {\n    46  \tp, err := loadPage(title)\n    47  \tif err != nil {\n    48  \t\tp = &Page{Title: title}\n    49  \t}\n    50  \trenderTemplate(w, \"edit\", p)\n    51  }\n    52  \n    53  func saveHandler(w http.ResponseWriter, r *http.Request, title string) {\n    54  \tbody := r.FormValue(\"body\")\n    55  \tp := &Page{Title: title, Body: []byte(body)}\n    56  \terr := p.save()\n    57  \tif err != nil {\n    58  \t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n    59  \t\treturn\n    60  \t}\n    61  \thttp.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n    62  }\n    63  \n    64  var templates = template.Must(template.ParseFiles(\"edit.html\", \"view.html\"))\n    65  \n    66  func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {\n    67  \terr := templates.ExecuteTemplate(w, tmpl+\".html\", p)\n    68  \tif err != nil {\n    69  \t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n    70  \t}\n    71  }\n    72  \n    73  var validPath = regexp.MustCompile(\"^/(edit|save|view)/([a-zA-Z0-9]+)$\")\n    74  \n    75  func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {\n    76  \treturn func(w http.ResponseWriter, r *http.Request) {\n    77  \t\tm := validPath.FindStringSubmatch(r.URL.Path)\n    78  \t\tif m == nil {\n    79  \t\t\thttp.NotFound(w, r)\n    80  \t\t\treturn\n    81  \t\t}\n    82  \t\tfn(w, r, m[2])\n    83  \t}\n    84  }\n    85  \n    86  func main() {\n    87  \thttp.HandleFunc(\"/view/\", makeHandler(viewHandler))\n    88  \thttp.HandleFunc(\"/edit/\", makeHandler(editHandler))\n    89  \thttp.HandleFunc(\"/save/\", makeHandler(saveHandler))\n    90  \n    91  \tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n    92  }\n    93\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.383Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":100,"estimatedTokens":766}}16{"id":"doc-the_go_programming_language-2d5223b3","source":"documentation","title":"- The Go Programming Language","url":"https://go.dev/doc/articles/wiki/part1.go","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n1  // Copyright 2010 The Go Authors. All rights reserved.\n     2  // Use of this source code is governed by a BSD-style\n     3  // license that can be found in the LICENSE file.\n     4  \n     5  //go:build ignore\n     6  \n     7  package main\n     8  \n     9  import (\n    10  \t\"fmt\"\n    11  \t\"os\"\n    12  )\n    13  \n    14  type Page struct {\n    15  \tTitle string\n    16  \tBody  []byte\n    17  }\n    18  \n    19  func (p *Page) save() error {\n    20  \tfilename := p.Title + \".txt\"\n    21  \treturn os.WriteFile(filename, p.Body, 0600)\n    22  }\n    23  \n    24  func loadPage(title string) (*Page, error) {\n    25  \tfilename := title + \".txt\"\n    26  \tbody, err := os.ReadFile(filename)\n    27  \tif err != nil {\n    28  \t\treturn nil, err\n    29  \t}\n    30  \treturn &Page{Title: title, Body: body}, nil\n    31  }\n    32  \n    33  func main() {\n    34  \tp1 := &Page{Title: \"TestPage\", Body: []byte(\"This is a sample Page.\")}\n    35  \tp1.save()\n    36  \tp2, _ := loadPage(\"TestPage\")\n    37  \tfmt.Println(string(p2.Body))\n    38  }\n    39\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.384Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":46,"estimatedTokens":299}}17{"id":"doc-data_race_detector_the_go_programming_language-1fa7d1d2","source":"documentation","title":"Data Race Detector - The Go Programming Language","url":"https://go.dev/doc/articles/race_detector.html","text":"Data Race Detector Introduction Data races are among the most common and hardest to debug types of bugs in concurrent systems. A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write. See the The Go Memory Model for details. Here is an example of a data race that can lead to crashes and memory main() { c := make(chan bool) m := make(map[string]string) go func() { m[\"1\"] = \"a\" // First conflicting access. c <- true }() m[\"2\"] = \"b\" // Second conflicting access. <-c for k, v := range m { fmt.Println(k, v) } } Usage To help diagnose such bugs, Go includes a built-in data race detector. To use it, add the -race flag to the go command: $ go test -race mypkg // to test the package $ go run -race mysrc.go // to run the source file $ go build -race mycmd // to build the command $ go install -race mypkg // to install the package Report Format When the race detector finds a data race in the program, it prints a report. The report contains stack traces for conflicting accesses, as well as stacks where the involved goroutines were created. Here is an : DATA RACE Read by goroutine (*pollServer).AddFD() src/net/fd_unix.go:89 +0x398 net.(*pollServer).WaitWrite() src/net/fd_unix.go:247 +0x45 net.(*netFD).Write() src/net/fd_unix.go:540 +0x4d4 net.(*conn).Write() src/net/net.go:129 +0x101 net.func·060() src/net/timeout_test.go:603 +0xaf Previous write by goroutine () src/net/sockopt_posix.go:135 +0xdf net.setDeadline() src/net/sockopt_posix.go:144 +0x9c net.(*conn).SetDeadline() src/net/net.go:161 +0xe3 net.func·061() src/net/timeout_test.go:616 +0x3ed Goroutine 185 (running) created ·061() src/net/timeout_test.go:609 +0x288 Goroutine 184 (running) created () src/net/timeout_test.go:618 +0x298 testing.tRunner() src/testing/testing.go:301 +0xe8 Options The GORACE environment variable sets race detector options. The format =\"option1=val1 option2=val2\" The options (default stderr): The race detector writes its report to a file named log_path.pid. The special names stdout and stderr cause reports to be written to standard output and standard error, respectively. exitcode (default 66): The exit status to use when exiting after a detected race. strip_path_prefix (default \"\"): Strip this prefix from all reported file paths, to make reports more concise. history_size (default 1): The per-goroutine memory access history is 32K * 2**history_size elements. Increasing this value can avoid a \"failed to restore the stack\" error in reports, at the cost of increased memory usage. halt_on_error (default 0): Controls whether the program exits after reporting first data race. atexit_sleep_ms (default 1000): Amount of milliseconds to sleep in the main goroutine before exiting. Example: $ GORACE=\"log_path=/tmp/race/report strip_path_prefix=/my/go/sources/\" go test -race Excluding Tests When you build with -race flag, the go command defines additional build tag race. You can use the tag to exclude some code and tests when running the race detector. Some examples: // +build !race package foo // The test contains a data race. See issue 123. func TestFoo(t *testing.T) { // ... } // The test fails under the race detector due to timeouts. func TestBar(t *testing.T) { // ... } // The test takes too long under the race detector. func TestBaz(t *testing.T) { // ... } How To Use To start, run your tests using the race detector (go test -race). The race detector only finds races that happen at runtime, so it can't find races in code paths that are not executed. If your tests have incomplete coverage, you may find more races by running a binary built with -race under a realistic workload. Typical Data Races Here are some typical data races. All of them can be detected with the race detector. Race on loop counter func main() { var wg sync.WaitGroup wg.Add(5) var i int for i = 0; i < 5; i++ { go func() { fmt.Println(i) // Not the 'i' you are looking for. wg.Done() }() } wg.Wait() } The variable i in the function literal is the same variable used by the loop, so the read in the goroutine races with the loop increment. (This program typically prints 55555, not 01234.) The program can be fixed by making a copy of the main() { var wg sync.WaitGroup wg.Add(5) var i int for i = 0; i < 5; i++ { go func(j int) { fmt.Println(j) // Good. Read local copy of the loop counter. wg.Done() }(i) } wg.Wait() } Accidentally shared variable // ParallelWrite writes data to file1 and file2, returns the errors. func ParallelWrite(data []byte) chan error { res := make(chan error, 2) f1, err := os.Create(\"file1\") if err != nil { res <- err } else { go func() { // This err is shared with the main goroutine, // so the write races with the write below. _, err = f1.Write(data) res <- err f1.Close() }() } f2, err := os.Create(\"file2\") // The second conflicting write to err. if err != nil { res <- err } else { go func() { _, err = f2.Write(data) res <- err f2.Close() }() } return res } The fix is to introduce new variables in the goroutines (note the use of :=): ... _, err := f1.Write(data) ... _, err := f2.Write(data) ... Unprotected global variable If the following code is called from several goroutines, it leads to races on the service map. Concurrent reads and writes of the same map are not service map[string]net.Addr func RegisterService(name string, addr net.Addr) { service[name] = addr } func LookupService(name string) net.Addr { return service[name] } To make the code safe, protect the accesses with a ( service map[string]net.Addr serviceMu sync.Mutex ) func RegisterService(name string, addr net.Addr) { serviceMu.Lock() defer serviceMu.Unlock() service[name] = addr } func LookupService(name string) net.Addr { serviceMu.Lock() defer serviceMu.Unlock() return service[name] } Primitive unprotected variable Data races can happen on variables of primitive types as well (bool, int, int64, etc.), as in this Watchdog struct{ last int64 } func (w *Watchdog) KeepAlive() { w.last = time.Now().UnixNano() // First conflicting access. } func (w *Watchdog) Start() { go func() { for { time.Sleep(time.Second) // Second conflicting access. if w.last < time.Now().Add(-10*time.Second).UnixNano() { fmt.Println(\"No keepalives for 10 seconds. Dying.\") os.Exit(1) } } }() } Even such \"innocent\" data races can lead to hard-to-debug problems caused by non-atomicity of the memory accesses, interference with compiler optimizations, or reordering issues accessing processor memory . A typical fix for this race is to use a channel or a mutex. To preserve the lock-free behavior, one can also use the sync/atomic package. type Watchdog struct{ last int64 } func (w *Watchdog) KeepAlive() { atomic.StoreInt64(&w.last, time.Now().UnixNano()) } func (w *Watchdog) Start() { go func() { for { time.Sleep(time.Second) if atomic.LoadInt64(&w.last) < time.Now().Add(-10*time.Second).UnixNano() { fmt.Println(\"No keepalives for 10 seconds. Dying.\") os.Exit(1) } } }() } Unsynchronized send and close operations As this example demonstrates, unsynchronized send and close operations on the same channel can also be a race := make(chan struct{}) // or buffered channel // The race detector cannot derive the happens before relation // for the following send and close operations. These two operations // are unsynchronized and happen concurrently. go func() { c <- struct{}{} }() close(c) According to the Go memory model, a send on a channel happens before the corresponding receive from that channel completes. To synchronize send and close operations, use a receive operation that guarantees the send is done before the := make(chan struct{}) // or buffered channel go func() { c <- struct{}{} }() <-c close(c) Requirements The race detector requires cgo to be enabled, and on non-Darwin systems requires an installed C compiler. The race detector supports linux/amd64, linux/ppc64le, linux/arm64, linux/s390x, linux/loong64, freebsd/amd64, netbsd/amd64, darwin/amd64, darwin/arm64, and windows/amd64. On Windows, the race detector runtime is sensitive to the version of the C compiler installed; as of Go 1.21, building a program with -race requires a C compiler that incorporates version 8 or later of the mingw-w64 runtime libraries. You can test your C compiler by invoking it with the arguments --print-file-name libsynchronization.a. A newer compliant C compiler will print a full path for this library, whereas older C compilers will just echo the argument. Runtime Overhead The cost of race detection varies by program, but for a typical program, memory usage may increase by 5-10x and execution time by 2-20x. The race detector currently allocates an extra 8 bytes per defer and recover statement. Those extra allocations are not recovered until the goroutine exits. This means that if you have a long-running goroutine that is periodically issuing defer and recover calls, the program memory usage may grow without bound. These memory allocations will not show up in the output of runtime.ReadMemStats or runtime/pprof.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\nfunc main() {\n\tc := make(chan bool)\n\tm := make(map[string]string)\n\tgo func() {\n\t\tm[\"1\"] = \"a\" // First conflicting access.\n\t\tc <- true\n\t}()\n\tm[\"2\"] = \"b\" // Second conflicting access.\n\t<-c\n\tfor k, v := range m {\n\t\tfmt.Println(k, v)\n\t}\n}\n```\n\nExample:\n```text\n$ go test -race mypkg    // to test the package\n$ go run -race mysrc.go  // to run the source file\n$ go build -race mycmd   // to build the command\n$ go install -race mypkg // to install the package\n```\n\nExample:\n```text\nWARNING: DATA RACE\nRead by goroutine 185:\n  net.(*pollServer).AddFD()\n      src/net/fd_unix.go:89 +0x398\n  net.(*pollServer).WaitWrite()\n      src/net/fd_unix.go:247 +0x45\n  net.(*netFD).Write()\n      src/net/fd_unix.go:540 +0x4d4\n  net.(*conn).Write()\n      src/net/net.go:129 +0x101\n  net.func·060()\n      src/net/timeout_test.go:603 +0xaf\n\nPrevious write by goroutine 184:\n  net.setWriteDeadline()\n      src/net/sockopt_posix.go:135 +0xdf\n  net.setDeadline()\n      src/net/sockopt_posix.go:144 +0x9c\n  net.(*conn).SetDeadline()\n      src/net/net.go:161 +0xe3\n  net.func·061()\n      src/net/timeout_test.go:616 +0x3ed\n\nGoroutine 185 (running) created at:\n  net.func·061()\n      src/net/timeout_test.go:609 +0x288\n\nGoroutine 184 (running) created at:\n  net.TestProlongTimeout()\n      src/net/timeout_test.go:618 +0x298\n  testing.tRunner()\n      src/testing/testing.go:301 +0xe8\n```\n\nExample:\n```text\nGORACE=\"option1=val1 option2=val2\"\n```\n\nExample:\n```text\n$ GORACE=\"log_path=/tmp/race/report strip_path_prefix=/my/go/sources/\" go test -race\n```\n\nExample:\n```text\n// +build !race\n\npackage foo\n\n// The test contains a data race. See issue 123.\nfunc TestFoo(t *testing.T) {\n\t// ...\n}\n\n// The test fails under the race detector due to timeouts.\nfunc TestBar(t *testing.T) {\n\t// ...\n}\n\n// The test takes too long under the race detector.\nfunc TestBaz(t *testing.T) {\n\t// ...\n}\n```\n\nExample:\n```text\nfunc main() {\n\tvar wg sync.WaitGroup\n\twg.Add(5)\n\tvar i int\n\tfor i = 0; i < 5; i++ {\n\t\tgo func() {\n\t\t\tfmt.Println(i) // Not the 'i' you are looking for.\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n}\n```\n\nExample:\n```text\nfunc main() {\n\tvar wg sync.WaitGroup\n\twg.Add(5)\n\tvar i int\n\tfor i = 0; i < 5; i++ {\n\t\tgo func(j int) {\n\t\t\tfmt.Println(j) // Good. Read local copy of the loop counter.\n\t\t\twg.Done()\n\t\t}(i)\n\t}\n\twg.Wait()\n}\n```\n\nExample:\n```text\n// ParallelWrite writes data to file1 and file2, returns the errors.\nfunc ParallelWrite(data []byte) chan error {\n\tres := make(chan error, 2)\n\tf1, err := os.Create(\"file1\")\n\tif err != nil {\n\t\tres <- err\n\t} else {\n\t\tgo func() {\n\t\t\t// This err is shared with the main goroutine,\n\t\t\t// so the write races with the write below.\n\t\t\t_, err = f1.Write(data)\n\t\t\tres <- err\n\t\t\tf1.Close()\n\t\t}()\n\t}\n\tf2, err := os.Create(\"file2\") // The second conflicting write to err.\n\tif err != nil {\n\t\tres <- err\n\t} else {\n\t\tgo func() {\n\t\t\t_, err = f2.Write(data)\n\t\t\tres <- err\n\t\t\tf2.Close()\n\t\t}()\n\t}\n\treturn res\n}\n```\n\nExample:\n```text\n...\n\t\t\t_, err := f1.Write(data)\n\t\t\t...\n\t\t\t_, err := f2.Write(data)\n\t\t\t...\n```\n\nExample:\n```text\nvar service map[string]net.Addr\n\nfunc RegisterService(name string, addr net.Addr) {\n\tservice[name] = addr\n}\n\nfunc LookupService(name string) net.Addr {\n\treturn service[name]\n}\n```\n\nExample:\n```text\nvar (\n\tservice   map[string]net.Addr\n\tserviceMu sync.Mutex\n)\n\nfunc RegisterService(name string, addr net.Addr) {\n\tserviceMu.Lock()\n\tdefer serviceMu.Unlock()\n\tservice[name] = addr\n}\n\nfunc LookupService(name string) net.Addr {\n\tserviceMu.Lock()\n\tdefer serviceMu.Unlock()\n\treturn service[name]\n}\n```\n\nExample:\n```text\ntype Watchdog struct{ last int64 }\n\nfunc (w *Watchdog) KeepAlive() {\n\tw.last = time.Now().UnixNano() // First conflicting access.\n}\n\nfunc (w *Watchdog) Start() {\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Second)\n\t\t\t// Second conflicting access.\n\t\t\tif w.last < time.Now().Add(-10*time.Second).UnixNano() {\n\t\t\t\tfmt.Println(\"No keepalives for 10 seconds. Dying.\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}()\n}\n```\n\nExample:\n```text\ntype Watchdog struct{ last int64 }\n\nfunc (w *Watchdog) KeepAlive() {\n\tatomic.StoreInt64(&w.last, time.Now().UnixNano())\n}\n\nfunc (w *Watchdog) Start() {\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Second)\n\t\t\tif atomic.LoadInt64(&w.last) < time.Now().Add(-10*time.Second).UnixNano() {\n\t\t\t\tfmt.Println(\"No keepalives for 10 seconds. Dying.\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}()\n}\n```\n\nExample:\n```text\nc := make(chan struct{}) // or buffered channel\n\n// The race detector cannot derive the happens before relation\n// for the following send and close operations. These two operations\n// are unsynchronized and happen concurrently.\ngo func() { c <- struct{}{} }()\nclose(c)\n```\n\nExample:\n```text\nc := make(chan struct{}) // or buffered channel\n\ngo func() { c <- struct{}{} }()\n<-c\nclose(c)\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.385Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":16,"totalLines":266,"estimatedTokens":3470}}18{"id":"doc-codewalk_generating_arbitrary_text_a_markov_chai-75353dd9","source":"documentation","title":"Codewalk: Generating arbitrary text: a Markov chain algorithm - The Go Programming Language","url":"https://go.dev/doc/codewalk/markov","text":"arbitrary Markov chain algorithm doc/codewalk/markov.go code on left • right code width 70% filepaths shown • hidden Introduction This codewalk describes a program that generates random text using a Markov chain algorithm. The package comment describes the algorithm and the operation of the program. Please read it before continuing. doc/codewalk/markov.go:6,44 Modeling Markov chains A chain consists of a prefix and a suffix. Each prefix is a set number of words, while a suffix is a single word. A prefix can have an arbitrary number of suffixes. To model this data, we use a map[string][]string. Each map key is a prefix (a string) and its values are lists of suffixes (a slice of strings, []string). Here is the example table from the package comment as modeled by this data [string][]string{ \" \": {\"I\"}, \" I\": {\"am\"}, \"I am\": {\"a\", \"not\"}, \"a free\": {\"man!\"}, \"am a\": {\"free\"}, \"am not\": {\"a\"}, \"a number!\": {\"I\"}, \"number! I\": {\"am\"}, \"not a\": {\"number!\"}, } While each prefix consists of multiple words, we store prefixes in the map as a single string. It would seem more natural to store the prefix as a []string, but we can't do this with a map because the key type of a map must implement equality (and slices do not). Therefore, in most of our code we will model prefixes as a []string and join the strings together with a space to generate the map Map key []string{\"\", \"\"} \" \" []string{\"\", \"I\"} \" I\" []string{\"I\", \"am\"} \"I am\" doc/codewalk/markov.go:77 The Chain struct The complete state of the chain table consists of the table itself and the word length of the prefixes. The Chain struct stores this data. doc/codewalk/markov.go:76,79 The NewChain constructor function The Chain struct has two unexported fields (those that do not begin with an upper case character), and so we write a NewChain constructor function that initializes the chain map with make and sets the prefixLen field. This is constructor function is not strictly necessary as this entire program is within a single package (main) and therefore there is little practical difference between exported and unexported fields. We could just as easily write out the contents of this function when we want to construct a new Chain. But using these unexported fields is good practice; it clearly denotes that only methods of Chain and its constructor function should access those fields. Also, structuring Chain like this means we could easily move it into its own package at some later date. doc/codewalk/markov.go:82,84 The Prefix type Since we'll be working with prefixes often, we define a Prefix type with the concrete type []string. Defining a named type clearly allows us to be explicit when we are working with a prefix instead of just a []string. Also, in Go we can define methods on any named type (not just structs), so we can add methods that operate on Prefix if we need to. doc/codewalk/markov.go:60 The String method The first method we define on Prefix is String. It returns a string representation of a Prefix by joining the slice elements together with spaces. We will use this method to generate keys when working with the chain map. doc/codewalk/markov.go:63,65 Building the chain The Build method reads text from an io.Reader and parses it into prefixes and suffixes that are stored in the Chain. The io.Reader is an interface type that is widely used by the standard library and other Go code. Our code uses the fmt.Fscan function, which reads space-separated values from an io.Reader. The Build method returns once the Reader's Read method returns io.EOF (end of file) or some other read error occurs. doc/codewalk/markov.go:88,100 Buffering the input This function does many small reads, which can be inefficient for some Readers. For efficiency we wrap the provided io.Reader with bufio.NewReader to create a new io.Reader that provides buffering. doc/codewalk/markov.go:89 The Prefix variable At the top of the function we make a Prefix slice p using the Chain's prefixLen field as its length. We'll use this variable to hold the current prefix and mutate it with each new word we encounter. doc/codewalk/markov.go:90 Scanning words In our loop we read words from the Reader into a string variable s using fmt.Fscan. Since Fscan uses space to separate each input value, each call will yield just one word (including punctuation), which is exactly what we need. Fscan returns an error if it encounters a read error (io.EOF, for example) or if it can't scan the requested value (in our case, a single string). In either case we just want to stop scanning, so we break out of the loop. doc/codewalk/markov.go:92,95 Adding a prefix and suffix to the chain The word stored in s is a new suffix. We add the new prefix/suffix combination to the chain map by computing the map key with p.String and appending the suffix to the slice stored under that key. The built-in append function appends elements to a slice and allocates new storage when necessary. When the provided slice is nil, append allocates a new slice. This behavior conveniently ties in with the semantics of our an unset key returns the zero value of the value type and the zero value of []string is nil. When our program encounters a new prefix (yielding a nil value in the map) append will allocate a new slice. For more information about the append function and slices in general see the and internals article. doc/codewalk/markov.go:96,97 Pushing the suffix onto the prefix Before reading the next word our algorithm requires us to drop the first word from the prefix and push the current suffix onto the prefix. When in this state p == Prefix{\"I\", \"am\"} s == \"not\" the new value for p would be p == Prefix{\"am\", \"not\"} This operation is also required during text generation so we put the code to perform this mutation of the slice inside a method on Prefix named Shift. doc/codewalk/markov.go:98 The Shift method The Shift method uses the built-in copy function to copy the last len(p)-1 elements of p to the start of the slice, effectively moving the elements one index to the left (if you consider zero as the leftmost index). p := Prefix{\"I\", \"am\"} copy(p, p[1:]) // p == Prefix{\"am\", \"am\"} We then assign the provided word to the last index of the slice: // suffix == \"not\" p[len(p)-1] = suffix // p == Prefix{\"am\", \"not\"} doc/codewalk/markov.go:68,71 Generating text The Generate method is similar to Build except that instead of reading words from a Reader and storing them in a map, it reads words from the map and appends them to a slice (words). Generate uses a conditional for loop to generate up to n words. doc/codewalk/markov.go:103,116 Getting potential suffixes At each iteration of the loop we retrieve a list of potential suffixes for the current prefix. We access the chain map at key p.String() and assign its contents to choices. If len(choices) is zero we break out of the loop as there are no potential suffixes for that prefix. This test also works if the key isn't present in the map at that case, choices will be nil and the length of a nil slice is zero. doc/codewalk/markov.go:107,110 Choosing a suffix at random To choose a suffix we use the rand.Intn function. It returns a random integer up to (but not including) the provided value. Passing in len(choices) gives us a random index into the full length of the list. We use that index to pick our new suffix, assign it to next and append it to the words slice. Next, we Shift the new suffix onto the prefix just as we did in the Build method. doc/codewalk/markov.go:111,113 Returning the generated text Before returning the generated text as a string, we use the strings.Join function to join the elements of the words slice together, separated by spaces. doc/codewalk/markov.go:115 Command-line flags To make it easy to tweak the prefix and generated text lengths we use the flag package to parse command-line flags. These calls to flag.Int register new flags with the flag package. The arguments to Int are the flag name, its default value, and a description. The Int function returns a pointer to an integer that will contain the user-supplied value (or the default value if the flag was omitted on the command-line). doc/codewalk/markov.go:119,121 Program set up The main function begins by parsing the command-line flags with flag.Parse and seeding the rand package's random number generator with the current time. If the command-line flags provided by the user are invalid the flag.Parse function will print an informative usage message and terminate the program. doc/codewalk/markov.go:123,124 Creating and building a new Chain To create the new Chain we call NewChain with the value of the prefix flag. To build the chain we call Build with os.Stdin (which implements io.Reader) so that it will read its input from standard input. doc/codewalk/markov.go:126,127 Generating and printing text Finally, to generate text we call Generate with the value of the words flag and assigning the result to the variable text. Then we call fmt.Println to write the text to standard output, followed by a carriage return. doc/codewalk/markov.go:128,129 Using this program To use this program, first build it with the go command: $ go build markov.go And then execute it while piping in some input text: $ echo \"a man a plan a canal panama\" \\ | ./markov -prefix=1 a plan a man a plan a canal panama Here's a transcript of generating some text using the Go distribution's README file as source material: $ ./markov -words=10 < $GOROOT/README This is the source code repository for the Go source $ ./markov -prefix=1 -words=10 < $GOROOT/README This is the go directory (the one containing this README). $ ./markov -prefix=1 -words=10 < $GOROOT/README This is the variable if you have just untarred a doc/codewalk/markov.go An exercise for the reader The Generate function does a lot of allocations when it builds the words slice. As an exercise, modify it to take an io.Writer to which it incrementally writes the generated text with Fprint. Aside from being more efficient this makes Generate more symmetrical to Build. doc/codewalk/markov.go previous step • next step\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\nmap[string][]string{\n\t\" \":          {\"I\"},\n\t\" I\":         {\"am\"},\n\t\"I am\":       {\"a\", \"not\"},\n\t\"a free\":     {\"man!\"},\n\t\"am a\":       {\"free\"},\n\t\"am not\":     {\"a\"},\n\t\"a number!\":  {\"I\"},\n\t\"number! I\":  {\"am\"},\n\t\"not a\":      {\"number!\"},\n}\n```\n\nExample:\n```text\nPrefix               Map key\n\n[]string{\"\", \"\"}     \" \"\n[]string{\"\", \"I\"}    \" I\"\n[]string{\"I\", \"am\"}  \"I am\"\n```\n\nExample:\n```text\np == Prefix{\"I\", \"am\"}\ns == \"not\"\n```\n\nExample:\n```text\np == Prefix{\"am\", \"not\"}\n```\n\nExample:\n```text\np := Prefix{\"I\", \"am\"}\ncopy(p, p[1:])\n// p == Prefix{\"am\", \"am\"}\n```\n\nExample:\n```text\n// suffix == \"not\"\np[len(p)-1] = suffix\n// p == Prefix{\"am\", \"not\"}\n```\n\nExample:\n```text\n$ go build markov.go\n```\n\nExample:\n```text\n$ echo \"a man a plan a canal panama\" \\\n\t| ./markov -prefix=1\na plan a man a plan a canal panama\n```\n\nExample:\n```text\n$ ./markov -words=10 < $GOROOT/README\nThis is the source code repository for the Go source\n$ ./markov -prefix=1 -words=10 < $GOROOT/README\nThis is the go directory (the one containing this README).\n$ ./markov -prefix=1 -words=10 < $GOROOT/README\nThis is the variable if you have just untarred a\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.386Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":9,"totalLines":76,"estimatedTokens":2850}}19{"id":"doc-codewalk_first_class_functions_in_go_the_go_prog-450083f1","source":"documentation","title":"Codewalk: First-Class Functions in Go - The Go Programming Language","url":"https://go.dev/doc/codewalk/functions","text":"Functions in Go doc/codewalk/pig.go code on left • right code width 70% filepaths shown • hidden Introduction Go supports first class functions, higher-order functions, user-defined function types, function literals, closures, and multiple return values. This rich feature set supports a functional programming style in a strongly typed language. In this codewalk we will look at a simple program that simulates a dice game called Pig and evaluates basic strategies. doc/codewalk/pig.go Game overview Pig is a two-player game played with a 6-sided die. Each turn, you may roll or stay. If you roll a 1, you lose all points for your turn and play passes to your opponent. Any other roll adds its value to your turn score. If you stay, your turn score is added to your total score, and play passes to your opponent. The first person to reach 100 total points wins. The score type stores the scores of the current and opposing players, in addition to the points accumulated during the current turn. doc/codewalk/pig.go:17,21 User-defined function types In Go, functions can be passed around just like any other value. A function's type signature describes the types of its arguments and return values. The action type is a function that takes a score and returns the resulting score and whether the current turn is over. If the turn is over, the player and opponent fields in the resulting score should be swapped, as it is now the other player's turn. doc/codewalk/pig.go:23,24 Multiple return values Go functions can return multiple values. The functions roll and stay each return a pair of values. They also match the action type signature. These action functions define the rules of Pig. doc/codewalk/pig.go:26,41 Higher-order functions A function can use other functions as arguments and return values. A strategy is a function that takes a score as input and returns an action to perform. (Remember, an action is itself a function.) doc/codewalk/pig.go:43,44 Function literals and closures Anonymous functions can be declared in Go, as in this example. Function literals are inherit the scope of the function in which they are declared. One basic strategy in Pig is to continue rolling until you have accumulated at least k points in a turn, and then stay. The argument k is enclosed by this function literal, which matches the strategy type signature. doc/codewalk/pig.go:48,53 Simulating games We simulate a game of Pig by calling an action to update the score until one player reaches 100 points. Each action is selected by calling the strategy function associated with the current player. doc/codewalk/pig.go:56,70 Simulating a tournament The roundRobin function simulates a tournament and tallies wins. Each strategy plays each other strategy gamesPerSeries times. doc/codewalk/pig.go:72,89 Variadic function declarations Variadic functions like ratioString take a variable number of arguments. These arguments are available as a slice inside the function. doc/codewalk/pig.go:91,94 Simulation results The main function defines 100 basic strategies, simulates a round robin tournament, and then prints the win/loss record of each strategy. Among these strategies, staying at 25 is best, but the optimal strategy for Pig is much more complex. doc/codewalk/pig.go:110,121 previous step • next step\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.387Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":0,"totalLines":5,"estimatedTokens":861}}20{"id":"doc-a_quick_guide_to_go_s_assembler_the_go_programmi-6d29edca","source":"documentation","title":"A Quick Guide to Go's Assembler - The Go Programming Language","url":"https://go.dev/doc/asm","text":"A Quick Guide to Go's Assembler A Quick Guide to Go's Assembler This document is a quick outline of the unusual form of assembly language used by the gc Go compiler. The document is not comprehensive. The assembler is based on the input style of the Plan 9 assemblers, which is documented in detail elsewhere. If you plan to write assembly language, you should read that document although much of it is Plan 9-specific. The current document provides a summary of the syntax and the differences with what is explained in that document, and describes the peculiarities that apply when writing assembly code to interact with Go. The most important thing to know about Go's assembler is that it is not a direct representation of the underlying machine. Some of the details map precisely to the machine, but some do not. This is because the compiler suite (see this description) needs no assembler pass in the usual pipeline. Instead, the compiler operates on a kind of semi-abstract instruction set, and instruction selection occurs partly after code generation. The assembler works on the semi-abstract form, so when you see an instruction like MOV what the toolchain actually generates for that operation might not be a move instruction at all, perhaps a clear or load. Or it might correspond exactly to the machine instruction with that name. In general, machine-specific operations tend to appear as themselves, while more general concepts like memory move and subroutine call and return are more abstract. The details vary with architecture, and we apologize for the imprecision; the situation is not well-defined. The assembler program is a way to parse a description of that semi-abstract instruction set and turn it into instructions to be input to the linker. If you want to see what the instructions look like in assembly for a given architecture, say amd64, there are many examples in the sources of the standard library, in packages such as runtime and math/big. You can also examine what the compiler emits as assembly code (the actual output may differ from what you see here): $ cat x.go package main func main() { println(3) } $ GOOS=linux GOARCH=amd64 go tool compile -S x.go # build -gcflags -S x.go \"\".main STEXT size=74 args=0x0 locals=0x10 0x0000 00000 (x.go:3) TEXT \"\".main(SB), $16-0 0x0000 00000 (x.go:3) MOVQ (TLS), CX 0x0009 00009 (x.go:3) CMPQ SP, 16(CX) 0x000d 00013 (x.go:3) JLS 67 0x000f 00015 (x.go:3) SUBQ $16, SP 0x0013 00019 (x.go:3) MOVQ BP, 8(SP) 0x0018 00024 (x.go:3) LEAQ 8(SP), BP 0x001d 00029 (x.go:3) FUNCDATA $0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB) 0x001d 00029 (x.go:3) FUNCDATA $1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB) 0x001d 00029 (x.go:3) FUNCDATA $2, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB) 0x001d 00029 (x.go:4) PCDATA $0, $0 0x001d 00029 (x.go:4) PCDATA $1, $0 0x001d 00029 (x.go:4) CALL runtime.printlock(SB) 0x0022 00034 (x.go:4) MOVQ $3, (SP) 0x002a 00042 (x.go:4) CALL runtime.printint(SB) 0x002f 00047 (x.go:4) CALL runtime.printnl(SB) 0x0034 00052 (x.go:4) CALL runtime.printunlock(SB) 0x0039 00057 (x.go:5) MOVQ 8(SP), BP 0x003e 00062 (x.go:5) ADDQ $16, SP 0x0042 00066 (x.go:5) RET 0x0043 00067 (x.go:5) NOP 0x0043 00067 (x.go:3) PCDATA $1, $-1 0x0043 00067 (x.go:3) PCDATA $0, $-1 0x0043 00067 (x.go:3) CALL runtime.morestack_noctxt(SB) 0x0048 00072 (x.go:3) JMP 0 ... The FUNCDATA and PCDATA directives contain information for use by the garbage collector; they are introduced by the compiler. To see what gets put in the binary after linking, use go tool objdump: $ go build -o x.exe x.go $ go tool objdump -s main.main x.exe TEXT main.main(SB) /tmp/x.go x.go:3 0x10501c0 65488b0c2530000000 MOVQ , CX x.go:3 0x10501c9 483b6110 CMPQ 0x10(CX), SP x.go:3 0x10501cd 7634 JBE 0x1050203 x.go:3 0x10501cf 4883ec10 SUBQ $0x10, SP x.go:3 0x10501d3 48896c2408 MOVQ BP, 0x8(SP) x.go:3 0x10501d8 488d6c2408 LEAQ 0x8(SP), BP x.go:4 0x10501dd e86e45fdff CALL runtime.printlock(SB) x.go:4 0x10501e2 48c7042403000000 MOVQ $0x3, 0(SP) x.go:4 0x10501ea e8e14cfdff CALL runtime.printint(SB) x.go:4 0x10501ef e8ec47fdff CALL runtime.printnl(SB) x.go:4 0x10501f4 e8d745fdff CALL runtime.printunlock(SB) x.go:5 0x10501f9 488b6c2408 MOVQ 0x8(SP), BP x.go:5 0x10501fe 4883c410 ADDQ $0x10, SP x.go:5 0x1050202 c3 RET x.go:3 0x1050203 e83882ffff CALL runtime.morestack_noctxt(SB) x.go:3 0x1050208 ebb6 JMP main.main(SB) Constants Although the assembler takes its guidance from the Plan 9 assemblers, it is a distinct program, so there are some differences. One is in constant evaluation. Constant expressions in the assembler are parsed using Go's operator precedence, not the C-like precedence of the original. Thus 3&1<<2 is 4, not 0—it parses as (3&1)<<2 not 3&(1<<2). Also, constants are always evaluated as 64-bit unsigned integers. Thus -2 is not the integer value minus two, but the unsigned 64-bit integer with the same bit pattern. The distinction rarely matters but to avoid ambiguity, division or right shift where the right operand's high bit is set is rejected. Symbols Some symbols, such as R1 or LR, are predefined and refer to registers. The exact set depends on the architecture. There are four predeclared symbols that refer to pseudo-registers. These are not real registers, but rather virtual registers maintained by the toolchain, such as a frame pointer. The set of pseudo-registers is the same for all : Frame and locals. and branches. base symbols. highest address within the local stack frame. All user-defined symbols are written as offsets to the pseudo-registers FP (arguments and locals) and SB (globals). The SB pseudo-register can be thought of as the origin of memory, so the symbol foo(SB) is the name foo as an address in memory. This form is used to name global functions and data. Adding <> to the name, as in foo<>(SB), makes the name visible only in the current source file, like a top-level static declaration in a C file. Adding an offset to the name refers to that offset from the symbol's address, so foo+4(SB) is four bytes past the start of foo. The FP pseudo-register is a virtual frame pointer used to refer to function arguments. The compilers maintain a virtual frame pointer and refer to the arguments on the stack as offsets from that pseudo-register. Thus 0(FP) is the first argument to the function, 8(FP) is the second (on a 64-bit machine), and so on. However, when referring to a function argument this way, it is necessary to place a name at the beginning, as in first_arg+0(FP) and second_arg+8(FP). (The meaning of the offset—offset from the frame pointer—distinct from its use with SB, where it is an offset from the symbol.) The assembler enforces this convention, rejecting plain 0(FP) and 8(FP). The actual name is semantically irrelevant but should be used to document the argument's name. It is worth stressing that FP is always a pseudo-register, not a hardware register, even on architectures with a hardware frame pointer. For assembly functions with Go prototypes, go vet will check that the argument names and offsets match. On 32-bit systems, the low and high 32 bits of a 64-bit value are distinguished by adding a _lo or _hi suffix to the name, as in arg_lo+0(FP) or arg_hi+4(FP). If a Go prototype does not name its result, the expected assembly name is ret. The SP pseudo-register is a virtual stack pointer used to refer to frame-local variables and the arguments being prepared for function calls. It points to the highest address within the local stack frame, so references should use negative offsets in the range [−framesize, 0): x-8(SP), y-4(SP), and so on. On architectures with a hardware register named SP, the name prefix distinguishes references to the virtual stack pointer from references to the architectural SP register. That is, x-8(SP) and -8(SP) are different memory first refers to the virtual stack pointer pseudo-register, while the second refers to the hardware's SP register. On machines where SP and PC are traditionally aliases for a physical, numbered register, in the Go assembler the names SP and PC are still treated specially; for instance, references to SP require a symbol, much like FP. To access the actual hardware register use the true R name. For example, on the ARM architecture the hardware SP and PC are accessible as R13 and R15. Branches and direct jumps are always written as offsets to the PC, or as jumps to : MOVW $0, R1 JMP label Each label is visible only within the function in which it is defined. It is therefore permitted for multiple functions in a file to define and use the same label names. Direct jumps and call instructions can target text symbols, such as name(SB), but not offsets from symbols, such as name+4(SB). Instructions, registers, and assembler directives are always in UPPER CASE to remind you that assembly programming is a fraught endeavor. (Exception: the g register renaming on ARM.) In Go object files and binaries, the full name of a symbol is the package path followed by a period and the symbol or math/rand.Int. Because the assembler's parser treats period and slash as punctuation, those strings cannot be used directly as identifier names. Instead, the assembler allows the middle dot character U+00B7 and the division slash U+2215 in identifiers and rewrites them to plain period and slash. Within an assembler source file, the symbols above are written as fmt·Printf and math∕rand·Int. The assembly listings generated by the compilers when using the -S flag show the period and slash directly instead of the Unicode replacements required by the assemblers. Most hand-written assembly files do not include the full package path in symbol names, because the linker inserts the package path of the current object file at the beginning of any name starting with a an assembly source file within the math/rand package implementation, the package's Int function can be referred to as ·Int. This convention avoids the need to hard-code a package's import path in its own source code, making it easier to move the code from one location to another. Directives The assembler uses various directives to bind text and data to symbol names. For example, here is a simple complete function definition. The TEXT directive declares the symbol runtime·profileloop and the instructions that follow form the body of the function. The last instruction in a TEXT block must be some sort of jump, usually a RET (pseudo-)instruction. (If it's not, the linker will append a jump-to-itself instruction; there is no fallthrough in TEXTs.) After the symbol, the arguments are flags (see below) and the frame size, a constant (but see below): TEXT runtime·profileloop(SB),NOSPLIT,$8 MOVQ $runtime·profileloop1(SB), CX MOVQ CX, 0(SP) CALL runtime·externalthreadhandler(SB) RET In the general case, the frame size is followed by an argument size, separated by a minus sign. (It's not a subtraction, just idiosyncratic syntax.) The frame size $24-8 states that the function has a 24-byte frame and is called with 8 bytes of argument, which live on the caller's frame. If NOSPLIT is not specified for the TEXT, the argument size must be provided. For assembly functions with Go prototypes, go vet will check that the argument size is correct. Note that the symbol name uses a middle dot to separate the components and is specified as an offset from the static base pseudo-register SB. This function would be called from Go source for package runtime using the simple name profileloop. Global data symbols are defined by a sequence of initializing DATA directives followed by a GLOBL directive. Each DATA directive initializes a section of the corresponding memory. The memory not explicitly initialized is zeroed. The general form of the DATA directive is DATA symbol+offset(SB)/width, value which initializes the symbol memory at the given offset and width with the given value. The DATA directives for a given symbol must be written with increasing offsets. The GLOBL directive declares a symbol to be global. The arguments are optional flags and the size of the data being declared as a global, which will have initial value all zeros unless a DATA directive has initialized it. The GLOBL directive must follow any corresponding DATA directives. For example, DATA divtab<>+0x00(SB)/4, $0xf4f8fcff DATA divtab<>+0x04(SB)/4, $0xe6eaedf0 ... DATA divtab<>+0x3c(SB)/4, $0x81828384 GLOBL divtab<>(SB), RODATA, $64 GLOBL runtime·tlsoffset(SB), NOPTR, $4 declares and initializes divtab<>, a read-only 64-byte table of 4-byte integer values, and declares runtime·tlsoffset, a 4-byte, implicitly zeroed variable that contains no pointers. There may be one or two arguments to the directives. If there are two, the first is a bit mask of flags, which can be written as numeric expressions, added or or-ed together, or can be set symbolically for easier absorption by a human. Their values, defined in the standard Assembly can refer to the size of this struct as reader__size and the offsets of the two fields as reader_buf and reader_r. Hence, if register R1 contains a pointer to a reader, assembly can reference the r field as reader_r(R1). If any of these #define names are ambiguous (for example, a struct with a _size field), #include \"go_asm.h\" will fail with a \"redefinition of macro\" error. Runtime Coordination For garbage collection to run correctly, the runtime must know the location of pointers in all global data and in most stack frames. The Go compiler emits this information when compiling Go source files, but assembly programs must define it explicitly. A data symbol marked with the NOPTR flag (see above) is treated as containing no pointers to runtime-allocated data. A data symbol with the RODATA flag is allocated in read-only memory and is therefore treated as implicitly marked NOPTR. A data symbol with a total size smaller than a pointer is also treated as implicitly marked NOPTR. It is not possible to define a symbol containing pointers in an assembly source file; such a symbol must be defined in a Go source file instead. Assembly source can still refer to the symbol by name even without DATA and GLOBL directives. A good general rule of thumb is to define all non-RODATA symbols in Go instead of in assembly. Each function also needs annotations giving the location of live pointers in its arguments, results, and local stack frame. For an assembly function with no pointer results and either no local stack frame or no function calls, the only requirement is to define a Go prototype for the function in a Go source file in the same package. The name of the assembly function must not contain the package name component (for example, function Syscall in package syscall should use the name ·Syscall instead of the equivalent name syscall·Syscall in its TEXT directive). For more complex situations, explicit annotation is needed. These annotations use pseudo-instructions defined in the standard #include file funcdata.h. If a function has no arguments and no results, the pointer information can be omitted. This is indicated by an argument size annotation of $n-0 on the TEXT instruction. Otherwise, pointer information must be provided by a Go prototype for the function in a Go source file, even for assembly functions not called directly from Go. (The prototype will also let go vet check the argument references.) At the start of the function, the arguments are assumed to be initialized but the results are assumed uninitialized. If the results will hold live pointers during a call instruction, the function should start by zeroing the results and then executing the pseudo-instruction GO_RESULTS_INITIALIZED. This instruction records that the results are now initialized and should be scanned during stack movement and garbage collection. It is typically easier to arrange that assembly functions do not return pointers or do not contain call instructions; no assembly functions in the standard library use GO_RESULTS_INITIALIZED. If a function has no local stack frame, the pointer information can be omitted. This is indicated by a local frame size annotation of $0-n on the TEXT instruction. The pointer information can also be omitted if the function contains no call instructions. Otherwise, the local stack frame must not contain pointers, and the assembly must confirm this fact by executing the pseudo-instruction NO_LOCAL_POINTERS. Because stack resizing is implemented by moving the stack, the stack pointer may change during any function pointers to stack data must not be kept in local variables. Assembly functions should always be given Go prototypes, both to provide pointer information for the arguments and results and to let go vet check that the offsets being used to access them are correct. Architecture-specific details It is impractical to list all the instructions and other details for each machine. To see what instructions are defined for a given machine, say ARM, look in the source for the obj support library for that architecture, located in the directory src/cmd/internal/obj/arm. In that directory is a file a.out.go; it contains a long list of constants starting with A, like ( AAND = obj.ABaseARM + obj.A_ARCHSPECIFIC + iota AEOR ASUB ARSB AADD ... This is the list of instructions and their spellings as known to the assembler and linker for that architecture. Each instruction begins with an initial capital A in this list, so AAND represents the bitwise and instruction, AND (without the leading A), and is written in assembly source as AND. The enumeration is mostly in alphabetical order. (The architecture-independent AXXX, defined in the cmd/internal/obj package, represents an invalid instruction). The sequence of the A names has nothing to do with the actual encoding of the machine instructions. The cmd/internal/obj package takes care of that detail. The instructions for both the 386 and AMD64 architectures are listed in cmd/internal/obj/x86/a.out.go. The architectures share syntax for common addressing modes such as (R1) (register indirect), 4(R1) (register indirect with offset), and $foo(SB) (absolute address). The assembler also supports some (not necessarily all) addressing modes specific to each architecture. The sections below list these. One detail evident in the examples from the previous sections is that data in the instructions flows from left to $0, CX clears CX. This rule applies even on architectures where the conventional notation uses the opposite direction. Here follow some descriptions of key Go-specific details for the supported architectures. 32-bit Intel 386 The runtime pointer to the g structure is maintained through the value of an otherwise unused (as far as Go is concerned) register in the MMU. In the runtime package, assembly code can include go_tls.h, which defines an OS- and architecture-dependent macro get_tls for accessing this register. The get_tls macro takes one argument, which is the register to load the g pointer into. For example, the sequence to load g and m using CX looks like this: #include \"go_tls.h\" #include \"go_asm.h\" ... get_tls(CX) MOVL g(CX), AX // Move g into AX. MOVL g_m(AX), BX // Move g.m into BX. The get_tls macro is also defined on amd64. Addressing modes: (DI)(BX*2): The location at address DI plus BX*2. 64(DI)(BX*2): The location at address DI plus BX*2 plus 64. These modes accept only 1, 2, 4, and 8 as scale factors. When using the compiler and assembler's -dynlink or -shared modes, any load or store of a fixed memory location such as a global variable must be assumed to overwrite CX. Therefore, to be safe for use with these modes, assembly sources should typically avoid CX except between memory references. 64-bit Intel 386 (a.k.a. amd64) The two architectures behave largely the same at the assembler level. Assembly code to access the m and g pointers on the 64-bit version is the same as on the 32-bit 386, except it uses MOVQ rather than (CX) MOVQ g(CX), AX // Move g into AX. MOVQ g_m(AX), BX // Move g.m into BX. Register BP is callee-save. The assembler automatically inserts BP save/restore when frame size is larger than zero. Using BP as a general purpose register is allowed, however it can interfere with sampling-based profiling. ARM The registers R10 and R11 are reserved by the compiler and linker. R10 points to the g (goroutine) structure. Within assembler source code, this pointer must be referred to as g; the name R10 is not recognized. To make it easier for people and compilers to write assembly, the ARM linker allows general addressing forms and pseudo-operations like DIV or MOD that may not be expressible using a single hardware instruction. It implements these forms as multiple instructions, often using the R11 register to hold temporary values. Hand-written assembly can use R11, but doing so requires being sure that the linker is not also using it to implement any of the other instructions in the function. When defining a TEXT, specifying frame size $-4 tells the linker that this is a leaf function that does not need to save LR on entry. The name SP always refers to the virtual stack pointer described earlier. For the hardware register, use R13. Condition code syntax is to append a period and the one- or two-letter code to the instruction, as in MOVW.EQ. Multiple codes may be The order of the code modifiers is irrelevant. Addressing >16 R0>>16 R0<<16 R0@>16: For <<, left shift R0 by 16 bits. The other codes are -> (arithmetic right shift), >> (logical right shift), and @> (rotate right). R0->R1 R0>>R1 R0<<R1 R0@>R1: For <<, left shift R0 by the count in R1. The other codes are -> (arithmetic right shift), >> (logical right shift), and @> (rotate right). [R0,g,R12-R15]: For multi-register instructions, the set comprising R0, g, and R12 through R15 inclusive. (R5, R6): Destination register pair. ARM64 R18 is the \"platform register\", reserved on the Apple platform. To prevent accidental misuse, the register is named R18_PLATFORM. R27 and R28 are reserved by the compiler and linker. R29 is the frame pointer. R30 is the link register. Instruction modifiers are appended to the instruction following a period. The only modifiers are P (postincrement) and W (preincrement): MOVW.P, MOVW.W Addressing >16 R0>>16 R0<<16 R0@>16: These are the same as on the 32-bit ARM. $(8<<12): Left shift the immediate value 8 by 12 bits. 8(R0): Add the value of R0 and 8. (R2)(R0): The location at R0 plus R2. R0.UXTB R0.UXTB<<imm: an 8-bit value from the low-order bits of R0 and zero-extend it to the size of R0. R0.UXTB<<imm: left shift the result of R0.UXTB by imm bits. The imm value can be 0, 1, 2, 3, or 4. The other extensions include UXTH (16-bit), UXTW (32-bit), and UXTX (64-bit). R0.SXTB R0.SXTB<<imm: an 8-bit value from the low-order bits of R0 and sign-extend it to the size of R0. R0.SXTB<<imm: left shift the result of R0.SXTB by imm bits. The imm value can be 0, 1, 2, 3, or 4. The other extensions include SXTH (16-bit), SXTW (32-bit), and SXTX (64-bit). (R5, R6): Register pair for LDAXP/LDP/LDXP/STLXP/STP/STP. ARM64 Assembly Instructions Reference Manual PPC64 This assembler is used by GOARCH values ppc64 and ppc64le. PPC64 Assembly Instructions Reference Manual IBM z/Architecture, a.k.a. s390x The registers R10 and R11 are reserved. The assembler uses them to hold temporary values when assembling some instructions. R13 points to the g (goroutine) structure. This register must be referred to as g; the name R13 is not recognized. R15 points to the stack frame and should typically only be accessed using the virtual registers SP and FP. Load- and store-multiple instructions operate on a range of registers. The range of registers is specified by a start register and an end register. For example, LMG (R9), R5, R7 would load R5, R6 and R7 with the 64-bit values at 0(R9), 8(R9) and 16(R9) respectively. Storage-and-storage instructions such as MVC and XC are written with the length as the first argument. For example, XC $8, (R9), (R9) would clear eight bytes at the address specified in R9. If a vector instruction takes a length or an index as an argument then it will be the first argument. For example, VLEIF $1, $16, V2 will load the value sixteen into index one of V2. Care should be taken when using vector instructions to ensure that they are available at runtime. To use vector instructions a machine must have both the vector facility (bit 129 in the facility list) and kernel support. Without kernel support a vector instruction will have no effect (it will be equivalent to a NOP instruction). Addressing modes: (R5)(R6*1): The location at R5 plus R6. It is a scaled mode as on the x86, but the only scale allowed is 1. MIPS, MIPS64 General purpose registers are named R0 through R31, floating point registers are F0 through F31. R30 is reserved to point to g. R23 is used as a temporary register. In a TEXT directive, the frame size $-4 for MIPS or $-8 for MIPS64 instructs the linker not to save LR. SP refers to the virtual stack pointer. For the hardware register, use R29. Addressing (R1): The location at R1 plus 16. (R1): Alias for 0(R1). The value of GOMIPS environment variable (hardfloat or softfloat) is made available to assembly code by predefining either GOMIPS_hardfloat or GOMIPS_softfloat. The value of GOMIPS64 environment variable (hardfloat or softfloat) is made available to assembly code by predefining either GOMIPS64_hardfloat or GOMIPS64_softfloat. RISCV64 RISCV64 Assembly Instructions Reference Manual Unsupported opcodes The assemblers are designed to support the compiler so not all hardware instructions are defined for all the compiler doesn't generate it, it might not be there. If you need to use a missing instruction, there are two ways to proceed. One is to update the assembler to support that instruction, which is straightforward but only worthwhile if it's likely the instruction will be used again. Instead, for simple one-off cases, it's possible to use the BYTE and WORD directives to lay down explicit data into the instruction stream within a TEXT. Here's how the 386 runtime defines the 64-bit atomic load function. // uint64 atomicload64(uint64 volatile* addr); // so actually // void atomicload64(uint64 *res, uint64 volatile *addr); TEXT runtime·atomicload64(SB), NOSPLIT, $0-12 MOVL ptr+0(FP), AX TESTL $7, AX JZ 2(PC) MOVL 0, AX // crash with nil ptr deref LEAL ret_lo+4(FP), BX // MOVQ (%EAX), %MM0 BYTE $0x0f; BYTE $0x6f; BYTE $0x00 // MOVQ %MM0, 0(%EBX) BYTE $0x0f; BYTE $0x7f; BYTE $0x03 // EMMS BYTE $0x0F; BYTE $0x77 RET\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ cat x.go\npackage main\n\nfunc main() {\n\tprintln(3)\n}\n$ GOOS=linux GOARCH=amd64 go tool compile -S x.go        # or: go build -gcflags -S x.go\n\"\".main STEXT size=74 args=0x0 locals=0x10\n\t0x0000 00000 (x.go:3)\tTEXT\t\"\".main(SB), $16-0\n\t0x0000 00000 (x.go:3)\tMOVQ\t(TLS), CX\n\t0x0009 00009 (x.go:3)\tCMPQ\tSP, 16(CX)\n\t0x000d 00013 (x.go:3)\tJLS\t67\n\t0x000f 00015 (x.go:3)\tSUBQ\t$16, SP\n\t0x0013 00019 (x.go:3)\tMOVQ\tBP, 8(SP)\n\t0x0018 00024 (x.go:3)\tLEAQ\t8(SP), BP\n\t0x001d 00029 (x.go:3)\tFUNCDATA\t$0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)\n\t0x001d 00029 (x.go:3)\tFUNCDATA\t$1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)\n\t0x001d 00029 (x.go:3)\tFUNCDATA\t$2, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)\n\t0x001d 00029 (x.go:4)\tPCDATA\t$0, $0\n\t0x001d 00029 (x.go:4)\tPCDATA\t$1, $0\n\t0x001d 00029 (x.go:4)\tCALL\truntime.printlock(SB)\n\t0x0022 00034 (x.go:4)\tMOVQ\t$3, (SP)\n\t0x002a 00042 (x.go:4)\tCALL\truntime.printint(SB)\n\t0x002f 00047 (x.go:4)\tCALL\truntime.printnl(SB)\n\t0x0034 00052 (x.go:4)\tCALL\truntime.printunlock(SB)\n\t0x0039 00057 (x.go:5)\tMOVQ\t8(SP), BP\n\t0x003e 00062 (x.go:5)\tADDQ\t$16, SP\n\t0x0042 00066 (x.go:5)\tRET\n\t0x0043 00067 (x.go:5)\tNOP\n\t0x0043 00067 (x.go:3)\tPCDATA\t$1, $-1\n\t0x0043 00067 (x.go:3)\tPCDATA\t$0, $-1\n\t0x0043 00067 (x.go:3)\tCALL\truntime.morestack_noctxt(SB)\n\t0x0048 00072 (x.go:3)\tJMP\t0\n...\n```\n\nExample:\n```text\n$ go build -o x.exe x.go\n$ go tool objdump -s main.main x.exe\nTEXT main.main(SB) /tmp/x.go\n  x.go:3\t\t0x10501c0\t\t65488b0c2530000000\tMOVQ GS:0x30, CX\n  x.go:3\t\t0x10501c9\t\t483b6110\t\tCMPQ 0x10(CX), SP\n  x.go:3\t\t0x10501cd\t\t7634\t\t\tJBE 0x1050203\n  x.go:3\t\t0x10501cf\t\t4883ec10\t\tSUBQ $0x10, SP\n  x.go:3\t\t0x10501d3\t\t48896c2408\t\tMOVQ BP, 0x8(SP)\n  x.go:3\t\t0x10501d8\t\t488d6c2408\t\tLEAQ 0x8(SP), BP\n  x.go:4\t\t0x10501dd\t\te86e45fdff\t\tCALL runtime.printlock(SB)\n  x.go:4\t\t0x10501e2\t\t48c7042403000000\tMOVQ $0x3, 0(SP)\n  x.go:4\t\t0x10501ea\t\te8e14cfdff\t\tCALL runtime.printint(SB)\n  x.go:4\t\t0x10501ef\t\te8ec47fdff\t\tCALL runtime.printnl(SB)\n  x.go:4\t\t0x10501f4\t\te8d745fdff\t\tCALL runtime.printunlock(SB)\n  x.go:5\t\t0x10501f9\t\t488b6c2408\t\tMOVQ 0x8(SP), BP\n  x.go:5\t\t0x10501fe\t\t4883c410\t\tADDQ $0x10, SP\n  x.go:5\t\t0x1050202\t\tc3\t\t\tRET\n  x.go:3\t\t0x1050203\t\te83882ffff\t\tCALL runtime.morestack_noctxt(SB)\n  x.go:3\t\t0x1050208\t\tebb6\t\t\tJMP main.main(SB)\n```\n\nExample:\n```text\nlabel:\n\tMOVW $0, R1\n\tJMP label\n```\n\nExample:\n```text\nTEXT runtime·profileloop(SB),NOSPLIT,$8\n\tMOVQ\t$runtime·profileloop1(SB), CX\n\tMOVQ\tCX, 0(SP)\n\tCALL\truntime·externalthreadhandler(SB)\n\tRET\n```\n\nExample:\n```text\nDATA\tsymbol+offset(SB)/width, value\n```\n\nExample:\n```text\nDATA divtab<>+0x00(SB)/4, $0xf4f8fcff\nDATA divtab<>+0x04(SB)/4, $0xe6eaedf0\n...\nDATA divtab<>+0x3c(SB)/4, $0x81828384\nGLOBL divtab<>(SB), RODATA, $64\n\nGLOBL runtime·tlsoffset(SB), NOPTR, $4\n```\n\nExample:\n```text\nPCALIGN $32\nMOVD $2, R0\n```\n\nExample:\n```text\ntype reader struct {\n\tbuf [bufSize]byte\n\tr   int\n}\n```\n\nExample:\n```text\nconst (\n\tAAND = obj.ABaseARM + obj.A_ARCHSPECIFIC + iota\n\tAEOR\n\tASUB\n\tARSB\n\tAADD\n\t...\n```\n\nExample:\n```text\n#include \"go_tls.h\"\n#include \"go_asm.h\"\n...\nget_tls(CX)\nMOVL\tg(CX), AX     // Move g into AX.\nMOVL\tg_m(AX), BX   // Move g.m into BX.\n```\n\nExample:\n```text\nget_tls(CX)\nMOVQ\tg(CX), AX     // Move g into AX.\nMOVQ\tg_m(AX), BX   // Move g.m into BX.\n```\n\nExample:\n```text\n// uint64 atomicload64(uint64 volatile* addr);\n// so actually\n// void atomicload64(uint64 *res, uint64 volatile *addr);\nTEXT runtime·atomicload64(SB), NOSPLIT, $0-12\n\tMOVL\tptr+0(FP), AX\n\tTESTL\t$7, AX\n\tJZ\t2(PC)\n\tMOVL\t0, AX // crash with nil ptr deref\n\tLEAL\tret_lo+4(FP), BX\n\t// MOVQ (%EAX), %MM0\n\tBYTE $0x0f; BYTE $0x6f; BYTE $0x00\n\t// MOVQ %MM0, 0(%EBX)\n\tBYTE $0x0f; BYTE $0x7f; BYTE $0x03\n\t// EMMS\n\tBYTE $0x0F; BYTE $0x77\n\tRET\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.390Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":12,"totalLines":160,"estimatedTokens":7586}}21{"id":"doc-installing_go_from_source_the_go_programming_lan-5ca34d6c","source":"documentation","title":"Installing Go from source - The Go Programming Language","url":"https://go.dev/doc/install/source","text":"Documentation Download and install Installing Go from source Installing Go from source This topic describes how to build and run Go from source code. To install with an installer, see Download and install. Introduction Go is an open source project, distributed under a BSD-style license. This document explains how to check out the sources, build them on your own machine, and run them. Most users don't need to do this, and will instead install from precompiled binary packages as described in Download and install, a much simpler process. If you want to help develop what goes into those precompiled packages, though, read on. There are two official Go compiler toolchains. This document focuses on the gc Go compiler and tools. For information on how to work on gccgo, a more traditional compiler using the GCC back end, see Setting up and using gccgo. The Go compilers support the following instruction , 386 The x86 instruction set, 64- and 32-bit. arm64, arm The ARM instruction set, 64-bit (AArch64) and 32-bit. loong64 The 64-bit LoongArch instruction set. mips64, mips64le, mips, mipsle The MIPS instruction set, big- and little-endian, 64- and 32-bit. ppc64, ppc64le The 64-bit PowerPC instruction set, big- and little-endian. riscv64 The 64-bit RISC-V instruction set. s390x The IBM z/Architecture. wasm WebAssembly. The compilers can target the AIX, Android, DragonFly BSD, FreeBSD, Illumos, Linux, macOS/iOS (Darwin), NetBSD, OpenBSD, Plan 9, Solaris, and Windows operating systems (although not all operating systems support all architectures). A list of ports which are considered \"first class\" is available at the first class ports wiki page. The full set of supported combinations is listed in the discussion of environment variables below. See the Go Wiki MinimumRequirements page for the overall system requirements. Install Go compiler binaries for bootstrap The Go toolchain is written in Go. To build it, you need a Go compiler installed. The scripts that do the initial build of the tools look for a \"go\" command in $PATH, so as long as you have Go installed in your system and configured in your $PATH, you are ready to build Go from source. Or if you prefer you can set $GOROOT_BOOTSTRAP to the root of a Go installation to use to build the new Go toolchain; $GOROOT_BOOTSTRAP/bin/go should be the go command to use. The minimum version of Go required depends on the target version of <= 1.4: a C toolchain. 1.5 <= Go <= 1.19: a Go 1.4 compiler. 1.20 <= Go <= 1.21: a Go 1.17 compiler. 1.22 <= Go <= 1.23: a Go 1.20 compiler. Going forward, Go version 1.N will require a Go 1.M compiler, where M is N-2 rounded down to an even number. 1.24 and 1.25 require Go 1.22. There are four possible ways to obtain a bootstrap a recent binary release of Go. Cross-compile a toolchain using a system with a working Go installation. Use gccgo. Compile a toolchain from Go 1.4, the last Go release with a compiler written in C. These approaches are detailed below. Bootstrap toolchain from binary release To use a binary release as a bootstrap toolchain, see the downloads page or use any other packaged Go distribution meeting the minimum version requirements. Bootstrap toolchain from cross-compiled source To cross-compile a bootstrap toolchain from source, which is necessary on systems Go 1.4 did not target (for example, linux/ppc64le), install Go on a different system and run bootstrap.bash. When run as (for example) $ GOOS=linux GOARCH=ppc64 ./bootstrap.bash bootstrap.bash cross-compiles a toolchain for that GOOS/GOARCH combination, leaving the resulting tree in ../../go-${GOOS}-${GOARCH}-bootstrap. That tree can be copied to a machine of the given target type and used as GOROOT_BOOTSTRAP to bootstrap a local build. Bootstrap toolchain using gccgo To use gccgo as the bootstrap toolchain, you need to arrange for $GOROOT_BOOTSTRAP/bin/go to be the go tool that comes as part of gccgo 5. For example on Ubuntu Vivid: $ sudo apt-get install gccgo-5 $ sudo update-alternatives --set go /usr/bin/go-5 $ GOROOT_BOOTSTRAP=/usr ./make.bash Bootstrap toolchain from C source code To build a bootstrap toolchain from C source code, use either the git branch release-branch.go1.4 or go1.4-bootstrap-20171003.tar.gz, which contains the Go 1.4 source code plus accumulated fixes to keep the tools running on newer operating systems. (Go 1.4 was the last distribution in which the toolchain was written in C.) After unpacking the Go 1.4 source, cd to the src subdirectory, set CGO_ENABLED=0 in the environment, and run make.bash (or, on Windows, make.bat). Once the Go 1.4 source has been unpacked into your GOROOT_BOOTSTRAP directory, you must keep this git clone instance checked out to branch release-branch.go1.4. Specifically, do not attempt to reuse this git clone in the later step named \"Fetch the repository.\" The go1.4 bootstrap toolchain must be able to properly traverse the go1.4 sources that it assumes are present under this repository root. Note that Go 1.4 does not run on all systems that later versions of Go do. In particular, Go 1.4 does not support current versions of macOS. On such systems, the bootstrap toolchain must be obtained using one of the other methods. Install Git, if needed To perform the next step you must have Git installed. (Check that you have a git command before proceeding.) If you do not have a working Git installation, follow the instructions on the Git downloads page. (Optional) Install a C compiler To build a Go installation with cgo support, which permits Go programs to import C libraries, a C compiler such as gcc or clang must be installed first. Do this using whatever installation method is standard on the system. To build without cgo, set the environment variable CGO_ENABLED=0 before running all.bash or make.bash. Fetch the repository Change to the directory where you intend to install Go, and make sure the goroot directory does not exist. Then clone the repository and check out the latest release tag or release branch (go1.22.0, or release-branch.go1.22, for example): $ git clone https://go.googlesource.com/go goroot $ cd goroot $ git checkout <tag> Where <tag> is the version string of the release. Go will be installed in the directory where it is checked out. For example, if Go is checked out in $HOME/goroot, executables will be installed in $HOME/goroot/bin. The directory may have any name, but note that if Go is checked out in $HOME/go, it will conflict with the default location of $GOPATH. See GOPATH below. you opted to also compile the bootstrap binaries from source (in an earlier section), you still need to git clone again at this point (to checkout the latest <tag>), because you must keep your go1.4 repository distinct. (Optional) Switch to the master branch If you intend to modify the go source code, and contribute your changes to the project, then move your repository off the release tag, and onto the master (development) branch. Otherwise, skip this step. $ git checkout master Install Go To build the Go distribution, run $ cd src $ ./make.bash (To build under Windows use make.bat.) If all goes well, it will finish by printing output Installed Go for linux/amd64 in /home/you/go. Installed commands in /home/you/go/bin. *** You need to add /home/you/go/bin to your $PATH. *** where the details on the last few lines reflect the operating system, architecture, and root directory used during the install. For more information about ways to control the build, see the discussion of environment variables below. You can also run all.bash (or all.bat) to run important tests for Go, which can take more time than simply building Go. Testing your installation Check that Go is installed correctly by building a simple program. Create a file named hello.go and put the following program in main import \"fmt\" func main() { fmt.Printf(\"hello, world\\n\") } Then run it with the go tool: $ go run hello.go hello, world If you see the \"hello, world\" message then Go is installed correctly. Set up your work environment You're almost done. You just need to do a little more setup. How to Write Go Code Learn how to set up and use the Go tools The How to Write Go Code document provides essential setup instructions for using the Go tools. Install additional tools The source code for several Go tools (including gopls) is kept in the golang.org/x/tools repository. To install one of the tools (gopls in this case): $ go install golang.org/x/tools/gopls@latest Community resources The usual community resources listed on the help page have active developers that can help you with problems with your installation or your development work. For those who wish to keep up to date, there is another mailing list, golang-checkins, that receives a message summarizing each checkin to the Go repository. Bugs can be reported using the Go issue tracker. Keeping up with releases New releases are announced on the golang-announce mailing list. Each announcement mentions the latest release tag, for instance, go1.9. To update an existing tree to the latest release, you can run: $ cd go/src $ git fetch $ git checkout <tag> $ ./all.bash Where <tag> is the version string of the release. Optional environment variables The Go tools can be customized by environment variables. None is required by the build, but you may wish to set some to override the defaults. Setting these environment variables while running make.bash will set the default for the newly built tools. When using the tools, you may override these defaults for a particular build, as described by the go command documentation. $GOROOT The root of the Go tree, often $HOME/go1.X. Its value is built into the tree when it is compiled, and defaults to the parent of the directory where all.bash was run. There is no need to set this unless you want to switch between multiple local copies of the repository. $GOOS and $GOARCH The name of the target operating system and compilation architecture. $GOOS defaults to the value of runtime.GOOS in the bootstrap toolchain. $GOARCH defaults to the value of $GOHOSTARCH, described below. Choices for $GOOS are android, darwin, dragonfly, freebsd, illumos, ios, js, linux, netbsd, openbsd, plan9, solaris, wasip1, and windows. Choices for $GOARCH are amd64 (64-bit x86, the most mature port), 386 (32-bit x86), arm (32-bit ARM), arm64 (64-bit ARM), ppc64le (PowerPC 64-bit, little-endian), ppc64 (PowerPC 64-bit, big-endian), mips64le (MIPS 64-bit, little-endian), mips64 (MIPS 64-bit, big-endian), mipsle (MIPS 32-bit, little-endian), mips (MIPS 32-bit, big-endian), s390x (IBM System z 64-bit, big-endian), and wasm (WebAssembly 32-bit). The valid combinations of $GOOS and $GOARCH are: $GOOS $GOARCH aix ppc64 android 386 android amd64 android arm android arm64 darwin amd64 darwin arm64 dragonfly amd64 freebsd 386 freebsd amd64 freebsd arm illumos amd64 ios arm64 js wasm linux 386 linux amd64 linux arm linux arm64 linux loong64 linux mips linux mipsle linux mips64 linux mips64le linux ppc64 linux ppc64le linux riscv64 linux s390x netbsd 386 netbsd amd64 netbsd arm openbsd 386 openbsd amd64 openbsd arm openbsd arm64 plan9 386 plan9 amd64 plan9 arm solaris amd64 wasip1 wasm windows 386 windows amd64 windows arm windows arm64 $GOHOSTARCH The name of the host compilation architecture. This defaults to the local system's architecture. Valid choices are the same as for $GOARCH, listed above. The specified values must be compatible with the local system. For example, you should not set $GOHOSTARCH to arm on an x86 system. $GO386 (for 386 only, defaults to sse2) This variable controls how gc implements floating point computations. GO386=softfloat: use software floating point operations; should support all x86 chips (Pentium MMX or later). GO386=sse2: use SSE2 for floating point operations; has better performance but only available on Pentium 4/Opteron/Athlon 64 or later. $GOARM (for arm only; default is auto-detected if building on the target processor, 7 if not) This sets the ARM floating point co-processor architecture version the run-time should target. If you are compiling on the target system, its value will be auto-detected. GOARM=5: use software floating point; when CPU doesn't have VFP co-processor GOARM=6: use VFPv1 only; default if cross compiling; usually ARM11 or better cores (VFPv2 or better is also supported) GOARM=7: use VFPv3; usually Cortex-A cores If in doubt, leave this variable unset, and adjust it if required when you first run the Go executable. The GoARM page on the Go community wiki contains further details regarding Go's ARM support. $GOARM64 (for arm64 only; default is v8.0) This sets the ARM64 architecture version for which to compile. See the Go wiki MinimumRequirements page for allowed options. $GOAMD64 (for amd64 only; default is v1) This sets the microarchitecture level for which to compile. Valid values are v1 (default), v2, v3, v4. See the Go wiki MinimumRequirements page for more information. $GOMIPS (for mips and mipsle only) $GOMIPS64 (for mips64 and mips64le only) These variables set whether to use floating point instructions. Set to \"hardfloat\" to use floating point instructions; this is the default. Set to \"softfloat\" to use soft floating point. $GOPPC64 (for ppc64 and ppc64le only) This variable sets the processor level (i.e. Instruction Set Architecture version) for which the compiler will target. The default is power8. GOPPC64=power8: generate ISA v2.07 instructions GOPPC64=power9: generate ISA v3.00 instructions $GORISCV64 (for riscv64 only) This variable sets the RISC-V user-mode application profile for which to compile. The default is rva20u64. GORISCV64=rva20u64: only use RISC-V extensions that are mandatory in the RVA20U64 profile GORISCV64=rva22u64: only use RISC-V extensions that are mandatory in the RVA22U64 profile GORISCV64=rva23u64: only use RISC-V extensions that are mandatory in the RVA23U64 profile $GOWASM (for wasm only) This variable is a comma separated list of experimental WebAssembly features that the compiled WebAssembly binary is allowed to use. The default is to use no experimental features. GOWASM=satconv: generate saturating (non-trapping) float-to-int conversions GOWASM=signext: generate sign-extension operators Note that $GOARCH and $GOOS identify the target environment, not the environment you are running on. In effect, you are always cross-compiling. By architecture, we mean the kind of binaries that the target environment can x86-64 system running a 32-bit-only operating system must set GOARCH to 386, not amd64. To reiterate, none of these variables needs to be set to build, install, and develop the Go tree.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ GOOS=linux GOARCH=ppc64 ./bootstrap.bash\n```\n\nExample:\n```text\n$ sudo apt-get install gccgo-5\n$ sudo update-alternatives --set go /usr/bin/go-5\n$ GOROOT_BOOTSTRAP=/usr ./make.bash\n```\n\nExample:\n```text\n$ git clone https://go.googlesource.com/go goroot\n$ cd goroot\n$ git checkout <tag>\n```\n\nExample:\n```text\n$ git checkout master\n```\n\nExample:\n```text\n$ cd src\n$ ./make.bash\n```\n\nExample:\n```text\n---\nInstalled Go for linux/amd64 in /home/you/go.\nInstalled commands in /home/you/go/bin.\n*** You need to add /home/you/go/bin to your $PATH. ***\n```\n\nExample:\n```text\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Printf(\"hello, world\\n\")\n}\n```\n\nExample:\n```text\n$ go run hello.go\nhello, world\n```\n\nExample:\n```text\n$ go install golang.org/x/tools/gopls@latest\n```\n\nExample:\n```text\n$ cd go/src\n$ git fetch\n$ git checkout <tag>\n$ ./all.bash\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.402Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":10,"totalLines":73,"estimatedTokens":3912}}22{"id":"doc-documentation_the_go_programming_language-f6886b0a","source":"documentation","title":"Documentation - The Go Programming Language","url":"https://go.dev/doc/","text":"Documentation The Go programming language is an open source project to make programmers more productive. Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel type system enables flexible and modular program construction. Go compiles quickly to machine code yet has the convenience of garbage collection and the power of run-time reflection. It's a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language. Getting Started Installing Go Instructions for downloading and installing Go. started A brief Hello, World tutorial to get started. Learn a bit about Go code, tools, packages, and modules. a module A tutorial of short topics introducing functions, error handling, arrays, maps, unit testing, and compiling. started with multi-module workspaces Introduces the basics of creating and using multi-module workspaces in Go. Multi-module workspaces are useful for making changes across multiple modules. a RESTful API with Go and Gin Introduces the basics of writing a RESTful web service API with Go and the Gin Web Framework. started with generics With generics, you can declare and use functions or types that are written to work with any of a set of types provided by calling code. started with fuzzing Fuzzing can generate inputs to your tests that can catch edge cases and security issues that you may have missed. Writing Web Applications Building a simple web application. How to write Go code This doc explains how to develop a simple set of Go packages inside a module, and it shows how to use the go command to build and test packages. A Tour of Go An interactive introduction to Go in four sections. The first section covers basic syntax and data structures; the second discusses methods and interfaces; the third is about Generics; and the fourth introduces Go's concurrency primitives. Each section concludes with a few exercises so you can practice what you've learned. You can take the tour online or install it locally with: $ go install golang.org/x/website/tour@latest This will place the tour binary in your GOPATH's bin directory. Using and understanding Go Effective Go A document that gives tips for writing clear, idiomatic Go code. A must read for any new Go programmer. It augments the tour and the language specification, both of which should be read first. Frequently Asked Questions (FAQ) Answers to common questions about Go. Editor plugins and IDEs A document that summarizes commonly used editor plugins and IDEs with Go support. Diagnostics Summarizes tools and methodologies to diagnose problems in Go programs. A Guide to the Go Garbage Collector A document that describes how Go manages memory, and how to make the most of it. Managing dependencies When your code uses external packages, those packages (distributed as modules) become dependencies. Fuzzing Main documentation page for Go fuzzing. Coverage for Go applications Main documentation page for coverage testing of Go applications. Profile-guided optimization Main documentation page for profile-guided optimization (PGO) of Go applications. encoding/json/v2 Migration Guide Guide for safe step-by-step migration from encoding/json to encoding/json/v2. References Package Documentation The documentation for the Go standard library. Command Documentation The documentation for the Go tools. Language Specification The official Go Language specification. Go Modules Reference A detailed reference manual for Go's dependency management system. go.mod file reference Reference for the directives included in a go.mod file. The Go Memory Model A document that specifies the conditions under which reads of a variable in one goroutine can be guaranteed to observe values produced by writes to the same variable in a different goroutine. Contribution Guide Contributing to Go. Release History A summary of the changes between Go releases. Accessing databases a relational database Introduces the basics of accessing a relational database using Go and the database/sql package in the standard library. Accessing relational databases An overview of Go's data access features. Opening a database handle You use the Go database handle to execute database operations. Once you open a handle with database connection properties, the handle represents a connection pool it manages on your behalf. Executing SQL statements that don't return data For SQL operations that might change the database, including SQL INSERT, UPDATE, and DELETE, you use Exec methods. Querying for data For SELECT statements that return data from a query, using the Query or QueryRow method. Using prepared statements Defining a prepared statement for repeated use can help your code run a bit faster by avoiding the overhead of re-creating the statement each time your code performs the database operation. Executing transactions sql.Tx exports methods representing transaction-specific semantics, including Commit and Rollback, as well as methods you use to perform common database operations. Canceling in-progress database operations Using context.Context, you can have your application's function calls and services stop working early and return an error when their processing is no longer needed. Managing connections For some advanced programs, you might need to tune connection pool parameters or work with connections explicitly. Avoiding SQL injection risk You can avoid an SQL injection risk by providing SQL parameter values as sql package function arguments Developing modules Developing and publishing modules You can collect related packages into modules, then publish the modules for other developers to use. This topic gives an overview of developing and publishing modules. Module release and versioning workflow When you develop modules for use by other developers, you can follow a workflow that helps ensure a reliable, consistent experience for developers using the module. This topic describes the high-level steps in that workflow. Managing module source When you're developing modules to publish for others to use, you can help ensure that your modules are easier for other developers to use by following the repository conventions described in this topic. Organizing a Go module What is the right way to organize the files and directories in a typical Go project? This topic discusses some common layouts depending on the kind of module you have. Developing a major version update A major version update can be very disruptive to your module's users because it includes breaking changes and represents a new module. Learn more in this topic. Publishing a module When you want to make a module available for other developers, you publish it so that it's visible to Go tools. Once you've published the module, developers importing its packages will be able to resolve a dependency on the module by running commands such as go get. Module version numbering A module's developer uses each part of a module's version number to signal the version’s stability and backward compatibility. For each new release, a module's release version number specifically reflects the nature of the module's changes since the preceding release. Talks A Video Tour of Go Three things that make Go fast, fun, and , reflection, and concurrency. Builds a toy web crawler to demonstrate these. Code that grows with grace One of Go's key design goals is code adaptability; that it should be easy to take a simple design and build upon it in a clean and natural way. In this talk Andrew Gerrand describes a simple \"chat roulette\" server that matches pairs of incoming TCP connections, and then use Go's concurrency mechanisms, interfaces, and standard library to extend it with a web interface and other features. While the function of the program changes dramatically, Go's flexibility preserves the original design as it grows. Go Concurrency Patterns Concurrency is the key to designing high performance network services. Go's concurrency primitives (goroutines and channels) provide a simple and efficient means of expressing concurrent execution. In this talk we see how tricky concurrency problems can be solved gracefully with simple Go code. Advanced Go Concurrency Patterns This talk expands on the Go Concurrency Patterns talk to dive deeper into Go's concurrency primitives. More See the Go Talks site and wiki page for more Go talks. Codewalks Guided tours of Go programs. First-Class Functions in Go Generating arbitrary Markov chain algorithm Share Memory by Communicating Language tale of interfaces Go's Declaration Syntax Defer, Panic, and Recover Go Concurrency out, moving on Go and internals A GIF exercise in Go interfaces Error Handling and Go Packages JSON and Go - using the json package. Gobs of data - the design and use of the gob package. The Laws of Reflection - the fundamentals of the reflect package. The Go image package - the fundamentals of the image package. The Go image/draw package - the fundamentals of the image/draw package. Modules Using Go Modules - an introduction to using modules in a simple project. Migrating to Go Modules - converting an existing project to use modules. Publishing Go Modules - how to make new versions of modules available to others. Go and Beyond - creating and publishing major versions 2 and higher. Keeping Your Modules Compatible - how to keep your modules compatible with prior minor/patch versions. Tools About the Go command - why we wrote it, what it is, what it's not, and how to use it. Go Doc Comments - writing good program documentation Debugging Go Code with GDB Data Race Detector - a manual for the data race detector. A Quick Guide to Go's Assembler - an introduction to the assembler used by Go. C? Go? Cgo! - linking against C code with cgo. Profiling Go Programs - tools for measuring your code's CPU and memory usage Introducing the Go Race Detector - an introduction to the race detector. language server for Go - getting the most out your editor when working in Go. Wiki The Go Wiki, maintained by the Go community, includes articles about the Go language, tools, and other resources. See the Learn page at the Wiki for more Go learning resources. Non-English Documentation See the NonEnglish page at the Wiki for localized documentation. Opens in new window.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ go install golang.org/x/website/tour@latest\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.404Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":1,"totalLines":10,"estimatedTokens":2646}}23{"id":"doc-tutorial_create_a_go_module_the_go_programming_l-5ba657a1","source":"documentation","title":"Tutorial: Create a Go module - The Go Programming Language","url":"https://go.dev/doc/tutorial/create-module.html","text":"Documentation Tutorials a Go module a Go module This is the first part of a tutorial that introduces a few fundamental features of the Go language. If you're just getting started with Go, be sure to take a look at started with Go, which introduces the go command, Go modules, and very simple Go code. In this tutorial you'll create two modules. The first is a library which is intended to be imported by other libraries or applications. The second is a caller application which will use the first. This tutorial's sequence includes seven brief topics that each illustrate a different part of the language. Create a module -- Write a small module with functions you can call from another module. Call your code from another module -- Import and use your new module. Return and handle an error -- Add simple error handling. Return a random greeting -- Handle data in slices (Go's dynamically-sized arrays). Return greetings for multiple people -- Store key/value pairs in a map. Add a test -- Use Go's built-in unit testing features to test your code. Compile and install the application -- Compile and install your code locally. other tutorials, see Tutorials. Prerequisites Some programming experience. The code here is pretty simple, but it helps to know something about functions, loops, and arrays. Go. We recommend using the latest version of Go to follow this tutorial. For installation instructions, see Installing Go. A tool to edit your code. Any text editor you have will work fine. Most text editors have good support for Go. The most popular are VSCode (free), GoLand (paid), and Vim (free). A command terminal. Go works well using any terminal on Linux and Mac, and on PowerShell or cmd in Windows. Start a module that others can use Start by creating a Go module. In a module, you collect one or more related packages for a discrete and useful set of functions. For example, you might create a module with packages that have functions for doing financial analysis so that others writing financial applications can use your work. For more about developing modules, see Developing and publishing modules. Go code is grouped into packages, and packages are grouped into modules. Your module specifies dependencies needed to run your code, including the Go version and the set of other modules it requires. As you add or improve functionality in your module, you publish new versions of the module. Developers writing code that calls functions in your module can import the module's updated packages and test with the new version before putting it into production use. Open a command prompt and cd to your home directory. On Linux or On %HOMEPATH% Create a greetings directory for your Go module source code. For example, from your home directory use the following greetings cd greetings Start your module using the go mod init command. Run the go mod init command, giving it your module path -- here, use example.com/greetings. If you publish a module, this must be a path from which your module can be downloaded by Go tools. That would be your code's repository. For more on naming your module with a module path, see Managing dependencies. $ go mod init example.com/greetings new go.mod: module example.com/greetings The go mod init command creates a go.mod file to track your code's dependencies. So far, the file includes only the name of your module and the Go version your code supports. But as you add dependencies, the go.mod file will list the versions your code depends on. This keeps builds reproducible and gives you direct control over which module versions to use. In your text editor, create a file in which to write your code and call it greetings.go. Paste the following code into your greetings.go file and save the file. package greetings import \"fmt\" // Hello returns a greeting for the named person. func Hello(name string) string { // Return a greeting that embeds the name in a message. message := fmt.Sprintf(\"Hi, %v. Welcome!\", name) return message } This is the first code for your module. It returns a greeting to any caller that asks for one. You'll write code that calls this function in the next step. In this code, a greetings package to collect related functions. Implement a Hello function to return the greeting. This function takes a name parameter whose type is string. The function also returns a string. In Go, a function whose name starts with a capital letter can be called by a function not in the same package. This is known in Go as an exported name. For more about exported names, see Exported names in the Go tour. Declare a message variable to hold your greeting. In Go, the := operator is a shortcut for declaring and initializing a variable in one line (Go uses the value on the right to determine the variable's type). Taking the long way, you might have written this message string message = fmt.Sprintf(\"Hi, %v. Welcome!\", name) Use the fmt package's Sprintf function to create a greeting message. The first argument is a format string, and Sprintf substitutes the name parameter's value for the %v format verb. Inserting the value of the name parameter completes the greeting text. Return the formatted greeting text to the caller. In the next step, you'll call this function from another module. Call your code from another module >\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\ncd\n```\n\nExample:\n```text\ncd %HOMEPATH%\n```\n\nExample:\n```text\nmkdir greetings\ncd greetings\n```\n\nExample:\n```text\n$ go mod init example.com/greetings\ngo: creating new go.mod: module example.com/greetings\n```\n\nExample:\n```text\npackage greetings\n\nimport \"fmt\"\n\n// Hello returns a greeting for the named person.\nfunc Hello(name string) string {\n    // Return a greeting that embeds the name in a message.\n    message := fmt.Sprintf(\"Hi, %v. Welcome!\", name)\n    return message\n}\n```\n\nExample:\n```text\nvar message string\nmessage = fmt.Sprintf(\"Hi, %v. Welcome!\", name)\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.405Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":6,"totalLines":47,"estimatedTokens":1505}}24{"id":"doc-download_and_install_the_go_programming_language-84fe41f0","source":"documentation","title":"Download and install - The Go Programming Language","url":"https://go.dev/doc/install","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ rm -rf /usr/local/go && tar -C /usr/local -xzf go1.14.3.linux-amd64.tar.gz\n```\n\nExample:\n```text\nexport PATH=$PATH:/usr/local/go/bin\n```\n\nExample:\n```text\nexport PATH=\"$PATH:$(go env GOPATH)/bin\"\n```\n\nExample:\n```text\n$ go version\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.405Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":23,"estimatedTokens":98}}25{"id":"doc-release_history_the_go_programming_language-b0a0ff88","source":"documentation","title":"Release History - The Go Programming Language","url":"https://go.dev/doc/devel/release","text":"Release History This page summarizes the changes between official stable releases of Go. The change log has the full details. To update to a specific release, fetch --tags git checkout goX.Y.Z Release Policy Each major Go release is supported until there are two newer major releases. For example, Go 1.5 was supported until the Go 1.7 release, and Go 1.6 was supported until the Go 1.8 release. We fix critical problems, including critical security problems, in supported releases as needed by issuing minor revisions (for example, Go 1.6.1, Go 1.6.2, and so on). go1.26.0 (released 2026-02-10) Go 1.26.0 is a major release of Go. Read the Go 1.26 Release Notes for more information. Minor revisions go1.26.1 (released 2026-03-05) includes security fixes to the crypto/x509, html/template, net/url, and os packages, as well as bug fixes to the go command, the go fix command, the compiler, and the os and reflect packages. See the Go 1.26.1 milestone on our issue tracker for details. go1.26.2 (released 2026-04-07) includes security fixes to the go command, the compiler, and the archive/tar, crypto/tls, crypto/x509, html/template, and os packages, as well as bug fixes to the go command, the go fix command, the compiler, the linker, the runtime, and the net, net/http, and net/url packages. See the Go 1.26.2 milestone on our issue tracker for details. go1.26.3 (released 2026-05-07) includes security fixes to the go command, the pack tool, and the html/template, net, net/http, net/http/httputil, net/mail, and syscall packages, as well as bug fixes to the go command, the go fix command, the compiler, the linker, the runtime, and the crypto/fips140, crypto/tls, go/types, and os packages. See the Go 1.26.3 milestone on our issue tracker for details. go1.26.4 (released 2026-06-02) includes security fixes to the crypto/x509, mime, and net/textproto packages, as well as bug fixes to the compiler, the runtime, the go fix command, and the crypto/fips140 package. See the Go 1.26.4 milestone on our issue tracker for details. go1.26.5 (released 2026-07-07) includes security fixes to the crypto/tls and os packages, as well as bug fixes to the compiler, the runtime, the go command, and the net, os, and syscall packages. See the Go 1.26.5 milestone on our issue tracker for details. go1.26.6 (released 2026-08-13) includes security fixes to the go command, and the crypto/tls, encoding/asn1, encoding/xml, html/template, net, net/http, and net/url packages, as well as bug fixes to the compiler, the linker, the runtime, and the crypto/tls and os packages. See the Go 1.26.6 milestone on our issue tracker for details. go1.25.0 (released 2025-08-12) Go 1.25.0 is a major release of Go. Read the Go 1.25 Release Notes for more information. Minor revisions go1.25.1 (released 2025-09-03) includes security fixes to the net/http package, as well as bug fixes to the go command, and the net, os, os/exec, and testing/synctest packages. See the Go 1.25.1 milestone on our issue tracker for details. go1.25.2 (released 2025-10-07) includes security fixes to the archive/tar, crypto/tls, crypto/x509, encoding/asn1, encoding/pem, net/http, net/mail, net/textproto, and net/url packages, as well as bug fixes to the compiler, the runtime, and the context, debug/pe, net/http, os, and sync/atomic packages. See the Go 1.25.2 milestone on our issue tracker for details. go1.25.3 (released 2025-10-13) includes fixes to the crypto/x509 package. See the Go 1.25.3 milestone on our issue tracker for details. go1.25.4 (released 2025-11-05) includes fixes to the compiler, the runtime, and the crypto/subtle, encoding/pem, net/url, and os packages. See the Go 1.25.4 milestone on our issue tracker for details. go1.25.5 (released 2025-12-02) includes two security fixes to the crypto/x509 package, as well as bug fixes to the mime and os packages. See the Go 1.25.5 milestone on our issue tracker for details. go1.25.6 (released 2026-01-15) includes security fixes to the go command, and the archive/zip, crypto/tls, and net/url packages, as well as bug fixes to the compiler, the runtime, and the crypto/tls, errors, and os packages. See the Go 1.25.6 milestone on our issue tracker for details. go1.25.7 (released 2026-02-04) includes security fixes to the go command and the crypto/tls package, as well as bug fixes to the compiler and the crypto/x509 package. See the Go 1.25.7 milestone on our issue tracker for details. go1.25.8 (released 2026-03-05) includes security fixes to the html/template, net/url, and os packages, as well as bug fixes to the go command, the compiler, and the os package. See the Go 1.25.8 milestone on our issue tracker for details. go1.25.9 (released 2026-04-07) includes security fixes to the go command, the compiler, and the archive/tar, crypto/tls, crypto/x509, html/template, and os packages, as well as bug fixes to the go command, the compiler, and the runtime. See the Go 1.25.9 milestone on our issue tracker for details. go1.25.10 (released 2026-05-07) includes security fixes to the go command, the pack tool, and the html/template, net, net/http, net/http/httputil, net/mail, and syscall packages, as well as bug fixes to the go command, the compiler, the linker, the runtime, and the crypto/fips140, go/types, and os packages. See the Go 1.25.10 milestone on our issue tracker for details. go1.25.11 (released 2026-06-02) includes security fixes to the crypto/x509, mime, and net/textproto packages, as well as bug fixes to the compiler and the runtime. See the Go 1.25.11 milestone on our issue tracker for details. go1.25.12 (released 2026-07-07) includes security fixes to the crypto/tls and os packages, as well as bug fixes to the compiler, the go command, and the net and os packages. See the Go 1.25.12 milestone on our issue tracker for details. go1.25.13 (released 2026-08-13) includes security fixes to the go command, and the crypto/tls, encoding/asn1, encoding/xml, html/template, net/http, and net/url packages, as well as bug fixes to the compiler, the runtime, and the crypto/tls and os packages. See the Go 1.25.13 milestone on our issue tracker for details. go1.24.0 (released 2025-02-11) Go 1.24.0 is a major release of Go. Read the Go 1.24 Release Notes for more information. Minor revisions go1.24.1 (released 2025-03-04) includes security fixes to the net/http package, as well as bug fixes to cgo, the compiler, the go command, and the reflect, runtime, and syscall packages. See the Go 1.24.1 milestone on our issue tracker for details. go1.24.2 (released 2025-04-01) includes security fixes to the net/http package, as well as bug fixes to the compiler, the runtime, the go command, and the crypto/tls, go/types, net/http, and testing packages. See the Go 1.24.2 milestone on our issue tracker for details. go1.24.3 (released 2025-05-06) includes security fixes to the os package, as well as bug fixes to the runtime, the compiler, the linker, the go command, and the crypto/tls and os packages. See the Go 1.24.3 milestone on our issue tracker for details. go1.24.4 (released 2025-06-05) includes security fixes to the crypto/x509, net/http, and os packages, as well as bug fixes to the linker, the go command, and the hash/maphash and os packages. See the Go 1.24.4 milestone on our issue tracker for details. go1.24.5 (released 2025-07-08) includes security fixes to the go command, as well as bug fixes to the compiler, the linker, the runtime, and the go command. See the Go 1.24.5 milestone on our issue tracker for details. go1.24.6 (released 2025-08-06) includes security fixes to the database/sql and os/exec packages, as well as bug fixes to the runtime. See the Go 1.24.6 milestone on our issue tracker for details. go1.24.7 (released 2025-09-03) includes fixes to the go command, and the net and os/exec packages. See the Go 1.24.7 milestone on our issue tracker for details. go1.24.8 (released 2025-10-07) includes security fixes to the archive/tar, crypto/tls, crypto/x509, encoding/asn1, encoding/pem, net/http, net/mail, net/textproto, and net/url packages, as well as bug fixes to the compiler, the linker, and the debug/pe, net/http, os, and sync/atomic packages. See the Go 1.24.8 milestone on our issue tracker for details. go1.24.9 (released 2025-10-13) includes fixes to the crypto/x509 package. See the Go 1.24.9 milestone on our issue tracker for details. go1.24.10 (released 2025-11-05) includes fixes to the encoding/pem and net/url packages. See the Go 1.24.10 milestone on our issue tracker for details. go1.24.11 (released 2025-12-02) includes two security fixes to the crypto/x509 package, as well as bug fixes to the runtime. See the Go 1.24.11 milestone on our issue tracker for details. go1.24.12 (released 2026-01-15) includes security fixes to the go command, and the archive/zip, crypto/tls, and net/url packages, as well as bug fixes to the compiler, the runtime, and the crypto/tls and os packages. See the Go 1.24.12 milestone on our issue tracker for details. go1.24.13 (released 2026-02-04) includes security fixes to the go command and the crypto/tls package, as well as bug fixes to the crypto/x509 package. See the Go 1.24.13 milestone on our issue tracker for details. go1.23.0 (released 2024-08-13) Go 1.23.0 is a major release of Go. Read the Go 1.23 Release Notes for more information. Minor revisions go1.23.1 (released 2024-09-05) includes security fixes to the encoding/gob, go/build/constraint, and go/parser packages, as well as bug fixes to the compiler, the go command, the runtime, and the database/sql, go/types, os, runtime/trace, and unique packages. See the Go 1.23.1 milestone on our issue tracker for details. go1.23.2 (released 2024-10-01) includes fixes to the compiler, cgo, the runtime, and the maps, os, os/exec, time, and unique packages. See the Go 1.23.2 milestone on our issue tracker for details. go1.23.3 (released 2024-11-06) includes fixes to the linker, the runtime, and the net/http, os, and syscall packages. See the Go 1.23.3 milestone on our issue tracker for details. go1.23.4 (released 2024-12-03) includes fixes to the compiler, the runtime, the trace command, and the syscall package. See the Go 1.23.4 milestone on our issue tracker for details. go1.23.5 (released 2025-01-16) includes security fixes to the crypto/x509 and net/http packages, as well as bug fixes to the compiler, the runtime, and the net package. See the Go 1.23.5 milestone on our issue tracker for details. go1.23.6 (released 2025-02-04) includes security fixes to the crypto/elliptic package, as well as bug fixes to the compiler and the go command. See the Go 1.23.6 milestone on our issue tracker for details. go1.23.7 (released 2025-03-04) includes security fixes to the net/http package, as well as bug fixes to cgo, the compiler, and the reflect, runtime, and syscall packages. See the Go 1.23.7 milestone on our issue tracker for details. go1.23.8 (released 2025-04-01) includes security fixes to the net/http package, as well as bug fixes to the runtime and the go command. See the Go 1.23.8 milestone on our issue tracker for details. go1.23.9 (released 2025-05-06) includes fixes to the runtime and the linker. See the Go 1.23.9 milestone on our issue tracker for details. go1.23.10 (released 2025-06-05) includes security fixes to the net/http and os packages, as well as bug fixes to the linker. See the Go 1.23.10 milestone on our issue tracker for details. go1.23.11 (released 2025-07-08) includes security fixes to the go command, as well as bug fixes to the compiler, the linker, and the runtime. See the Go 1.23.11 milestone on our issue tracker for details. go1.23.12 (released 2025-08-06) includes security fixes to the database/sql and os/exec packages, as well as bug fixes to the runtime. See the Go 1.23.12 milestone on our issue tracker for details. go1.22.0 (released 2024-02-06) Go 1.22.0 is a major release of Go. Read the Go 1.22 Release Notes for more information. Minor revisions go1.22.1 (released 2024-03-05) includes security fixes to the crypto/x509, html/template, net/http, net/http/cookiejar, and net/mail packages, as well as bug fixes to the compiler, the go command, the runtime, the trace command, and the go/types and net/http packages. See the Go 1.22.1 milestone on our issue tracker for details. go1.22.2 (released 2024-04-03) includes a security fix to the net/http package, as well as bug fixes to the compiler, the go command, the linker, and the encoding/gob, go/types, net/http, and runtime/trace packages. See the Go 1.22.2 milestone on our issue tracker for details. go1.22.3 (released 2024-05-07) includes security fixes to the go command and the net package, as well as bug fixes to the compiler, the runtime, and the net/http package. See the Go 1.22.3 milestone on our issue tracker for details. go1.22.4 (released 2024-06-04) includes security fixes to the archive/zip and net/netip packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the os package. See the Go 1.22.4 milestone on our issue tracker for details. go1.22.5 (released 2024-07-02) includes security fixes to the net/http package, as well as bug fixes to the compiler, cgo, the go command, the linker, the runtime, and the crypto/tls, go/types, net, net/http, and os/exec packages. See the Go 1.22.5 milestone on our issue tracker for details. go1.22.6 (released 2024-08-06) includes fixes to the go command, the compiler, the linker, the trace command, the covdata command, and the bytes, go/types, and os/exec packages. See the Go 1.22.6 milestone on our issue tracker for details. go1.22.7 (released 2024-09-05) includes security fixes to the encoding/gob, go/build/constraint, and go/parser packages, as well as bug fixes to the fix command and the runtime. See the Go 1.22.7 milestone on our issue tracker for details. go1.22.8 (released 2024-10-01) includes fixes to cgo, and the maps and syscall packages. See the Go 1.22.8 milestone on our issue tracker for details. go1.22.9 (released 2024-11-06) includes fixes to the linker. See the Go 1.22.9 milestone on our issue tracker for details. go1.22.10 (released 2024-12-03) includes fixes to the runtime and the syscall package. See the Go 1.22.10 milestone on our issue tracker for details. go1.22.11 (released 2025-01-16) includes security fixes to the crypto/x509 and net/http packages, as well as bug fixes to the runtime. See the Go 1.22.11 milestone on our issue tracker for details. go1.22.12 (released 2025-02-04) includes security fixes to the crypto/elliptic package, as well as bug fixes to the compiler and the go command. See the Go 1.22.12 milestone on our issue tracker for details. go1.21.0 (released 2023-08-08) Go 1.21.0 is a major release of Go. Read the Go 1.21 Release Notes for more information. Minor revisions go1.21.1 (released 2023-09-06) includes four security fixes to the cmd/go, crypto/tls, and html/template packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the context, crypto/tls, encoding/gob, encoding/xml, go/types, net/http, os, and path/filepath packages. See the Go 1.21.1 milestone on our issue tracker for details. go1.21.2 (released 2023-10-05) includes one security fix to the cmd/go package, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the runtime/metrics package. See the Go 1.21.2 milestone on our issue tracker for details. go1.21.3 (released 2023-10-10) includes a security fix to the net/http package. See the Go 1.21.3 milestone on our issue tracker for details. go1.21.4 (released 2023-11-07) includes security fixes to the path/filepath package, as well as bug fixes to the linker, the runtime, the compiler, and the go/types, net/http, and runtime/cgo packages. See the Go 1.21.4 milestone on our issue tracker for details. go1.21.5 (released 2023-12-05) includes security fixes to the go command, and the net/http and path/filepath packages, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/rand, net, os, and syscall packages. See the Go 1.21.5 milestone on our issue tracker for details. go1.21.6 (released 2024-01-09) includes fixes to the compiler, the runtime, and the crypto/tls, maps, and runtime/pprof packages. See the Go 1.21.6 milestone on our issue tracker for details. go1.21.7 (released 2024-02-06) includes fixes to the compiler, the go command, the runtime, and the crypto/x509 package. See the Go 1.21.7 milestone on our issue tracker for details. go1.21.8 (released 2024-03-05) includes security fixes to the crypto/x509, html/template, net/http, net/http/cookiejar, and net/mail packages, as well as bug fixes to the go command and the runtime. See the Go 1.21.8 milestone on our issue tracker for details. go1.21.9 (released 2024-04-03) includes a security fix to the net/http package, as well as bug fixes to the linker, and the go/types and net/http packages. See the Go 1.21.9 milestone on our issue tracker for details. go1.21.10 (released 2024-05-07) includes security fixes to the go command, as well as bug fixes to the net/http package. See the Go 1.21.10 milestone on our issue tracker for details. go1.21.11 (released 2024-06-04) includes security fixes to the archive/zip and net/netip packages, as well as bug fixes to the compiler, the go command, the runtime, and the os package. See the Go 1.21.11 milestone on our issue tracker for details. go1.21.12 (released 2024-07-02) includes security fixes to the net/http package, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/x509, net/http, net/netip, and os packages. See the Go 1.21.12 milestone on our issue tracker for details. go1.21.13 (released 2024-08-06) includes fixes to the go command, the covdata command, and the bytes package. See the Go 1.21.13 milestone on our issue tracker for details. go1.20 (released 2023-02-01) Go 1.20 is a major release of Go. Read the Go 1.20 Release Notes for more information. Minor revisions go1.20.1 (released 2023-02-14) includes security fixes to the crypto/tls, mime/multipart, net/http, and path/filepath packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the time package. See the Go 1.20.1 milestone on our issue tracker for details. go1.20.2 (released 2023-03-07) includes a security fix to the crypto/elliptic package, as well as bug fixes to the compiler, the covdata command, the linker, the runtime, and the crypto/ecdh, crypto/rsa, crypto/x509, os, and syscall packages. See the Go 1.20.2 milestone on our issue tracker for details. go1.20.3 (released 2023-04-04) includes security fixes to the go/parser, html/template, mime/multipart, net/http, and net/textproto packages, as well as bug fixes to the compiler, the linker, the runtime, and the time package. See the Go 1.20.3 milestone on our issue tracker for details. go1.20.4 (released 2023-05-02) includes three security fixes to the html/template package, as well as bug fixes to the compiler, the runtime, and the crypto/subtle, crypto/tls, net/http, and syscall packages. See the Go 1.20.4 milestone on our issue tracker for details. go1.20.5 (released 2023-06-06) includes four security fixes to the cmd/go and runtime packages, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/rsa, net, and os packages. See the Go 1.20.5 milestone on our issue tracker for details. go1.20.6 (released 2023-07-11) includes a security fix to the net/http package, as well as bug fixes to the compiler, cgo, the cover tool, the go command, the runtime, and the crypto/ecdsa, go/build, go/printer, net/mail, and text/template packages. See the Go 1.20.6 milestone on our issue tracker for details. go1.20.7 (released 2023-08-01) includes a security fix to the crypto/tls package, as well as bug fixes to the assembler and the compiler. See the Go 1.20.7 milestone on our issue tracker for details. go1.20.8 (released 2023-09-06) includes two security fixes to the html/template package, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/tls, go/types, net/http, and path/filepath packages. See the Go 1.20.8 milestone on our issue tracker for details. go1.20.9 (released 2023-10-05) includes one security fix to the cmd/go package, as well as bug fixes to the go command and the linker. See the Go 1.20.9 milestone on our issue tracker for details. go1.20.10 (released 2023-10-10) includes a security fix to the net/http package. See the Go 1.20.10 milestone on our issue tracker for details. go1.20.11 (released 2023-11-07) includes security fixes to the path/filepath package, as well as bug fixes to the linker and the net/http package. See the Go 1.20.11 milestone on our issue tracker for details. go1.20.12 (released 2023-12-05) includes security fixes to the go command, and the net/http and path/filepath packages, as well as bug fixes to the compiler and the go command. See the Go 1.20.12 milestone on our issue tracker for details. go1.20.13 (released 2024-01-09) includes fixes to the runtime and the crypto/tls package. See the Go 1.20.13 milestone on our issue tracker for details. go1.20.14 (released 2024-02-06) includes fixes to the crypto/x509 package. See the Go 1.20.14 milestone on our issue tracker for details. go1.19 (released 2022-08-02) Go 1.19 is a major release of Go. Read the Go 1.19 Release Notes for more information. Minor revisions go1.19.1 (released 2022-09-06) includes security fixes to the net/http and net/url packages, as well as bug fixes to the compiler, the go command, the pprof command, the linker, the runtime, and the crypto/tls and crypto/x509 packages. See the Go 1.19.1 milestone on our issue tracker for details. go1.19.2 (released 2022-10-04) includes security fixes to the archive/tar, net/http/httputil, and regexp packages, as well as bug fixes to the compiler, the linker, the runtime, and the go/types package. See the Go 1.19.2 milestone on our issue tracker for details. go1.19.3 (released 2022-11-01) includes security fixes to the os/exec and syscall packages, as well as bug fixes to the compiler and the runtime. See the Go 1.19.3 milestone on our issue tracker for details. go1.19.4 (released 2022-12-06) includes security fixes to the net/http and os packages, as well as bug fixes to the compiler, the runtime, and the crypto/x509, os/exec, and sync/atomic packages. See the Go 1.19.4 milestone on our issue tracker for details. go1.19.5 (released 2023-01-10) includes fixes to the compiler, the linker, and the crypto/x509, net/http, sync/atomic, and syscall packages. See the Go 1.19.5 milestone on our issue tracker for details. go1.19.6 (released 2023-02-14) includes security fixes to the crypto/tls, mime/multipart, net/http, and path/filepath packages, as well as bug fixes to the go command, the linker, the runtime, and the crypto/x509, net/http, and time packages. See the Go 1.19.6 milestone on our issue tracker for details. go1.19.7 (released 2023-03-07) includes a security fix to the crypto/elliptic package, as well as bug fixes to the linker, the runtime, and the crypto/x509 and syscall packages. See the Go 1.19.7 milestone on our issue tracker for details. go1.19.8 (released 2023-04-04) includes security fixes to the go/parser, html/template, mime/multipart, net/http, and net/textproto packages, as well as bug fixes to the linker, the runtime, and the time package. See the Go 1.19.8 milestone on our issue tracker for details. go1.19.9 (released 2023-05-02) includes three security fixes to the html/template package, as well as bug fixes to the compiler, the runtime, and the crypto/tls and syscall packages. See the Go 1.19.9 milestone on our issue tracker for details. go1.19.10 (released 2023-06-06) includes four security fixes to the cmd/go and runtime packages, as well as bug fixes to the compiler, the go command, and the runtime. See the Go 1.19.10 milestone on our issue tracker for details. go1.19.11 (released 2023-07-11) includes a security fix to the net/http package, as well as bug fixes to cgo, the cover tool, the go command, the runtime, and the go/printer package. See the Go 1.19.11 milestone on our issue tracker for details. go1.19.12 (released 2023-08-01) includes a security fix to the crypto/tls package, as well as bug fixes to the assembler and the compiler. See the Go 1.19.12 milestone on our issue tracker for details. go1.19.13 (released 2023-09-06) includes fixes to the go command, and the crypto/tls and net/http packages. See the Go 1.19.13 milestone on our issue tracker for details. go1.18 (released 2022-03-15) Go 1.18 is a major release of Go. Read the Go 1.18 Release Notes for more information. Minor revisions go1.18.1 (released 2022-04-12) includes security fixes to the crypto/elliptic, crypto/x509, and encoding/pem packages, as well as bug fixes to the compiler, linker, runtime, the go command, vet, and the bytes, crypto/x509, and go/types packages. See the Go 1.18.1 milestone on our issue tracker for details. go1.18.2 (released 2022-05-10) includes security fixes to the syscall package, as well as bug fixes to the compiler, runtime, the go command, and the crypto/x509, go/types, net/http/httptest, reflect, and sync/atomic packages. See the Go 1.18.2 milestone on our issue tracker for details. go1.18.3 (released 2022-06-01) includes security fixes to the crypto/rand, crypto/tls, os/exec, and path/filepath packages, as well as bug fixes to the compiler, and the crypto/tls and text/template/parse packages. See the Go 1.18.3 milestone on our issue tracker for details. go1.18.4 (released 2022-07-12) includes security fixes to the compress/gzip, encoding/gob, encoding/xml, go/parser, io/fs, net/http, and path/filepath packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the runtime/metrics package. See the Go 1.18.4 milestone on our issue tracker for details. go1.18.5 (released 2022-08-01) includes security fixes to the encoding/gob and math/big packages, as well as bug fixes to the compiler, the go command, the runtime, and the testing package. See the Go 1.18.5 milestone on our issue tracker for details. go1.18.6 (released 2022-09-06) includes security fixes to the net/http package, as well as bug fixes to the compiler, the go command, the pprof command, the runtime, and the crypto/tls, encoding/xml, and net packages. See the Go 1.18.6 milestone on our issue tracker for details. go1.18.7 (released 2022-10-04) includes security fixes to the archive/tar, net/http/httputil, and regexp packages, as well as bug fixes to the compiler, the linker, and the go/types package. See the Go 1.18.7 milestone on our issue tracker for details. go1.18.8 (released 2022-11-01) includes security fixes to the os/exec and syscall packages, as well as bug fixes to the runtime. See the Go 1.18.8 milestone on our issue tracker for details. go1.18.9 (released 2022-12-06) includes security fixes to the net/http and os packages, as well as bug fixes to cgo, the compiler, the runtime, and the crypto/x509 and os/exec packages. See the Go 1.18.9 milestone on our issue tracker for details. go1.18.10 (released 2023-01-10) includes fixes to cgo, the compiler, the linker, and the crypto/x509, net/http, and syscall packages. See the Go 1.18.10 milestone on our issue tracker for details. go1.17 (released 2021-08-16) Go 1.17 is a major release of Go. Read the Go 1.17 Release Notes for more information. Minor revisions go1.17.1 (released 2021-09-09) includes a security fix to the archive/zip package, as well as bug fixes to the compiler, linker, the go command, and the crypto/rand, embed, go/types, html/template, and net/http packages. See the Go 1.17.1 milestone on our issue tracker for details. go1.17.2 (released 2021-10-07) includes security fixes to linker and the misc/wasm directory, as well as bug fixes to the compiler, runtime, the go command, and the text/template and time packages. See the Go 1.17.2 milestone on our issue tracker for details. go1.17.3 (released 2021-11-04) includes security fixes to the archive/zip and debug/macho packages, as well as bug fixes to the compiler, linker, runtime, the go command, the misc/wasm directory, and the net/http and syscall packages. See the Go 1.17.3 milestone on our issue tracker for details. go1.17.4 (released 2021-12-02) includes fixes to the compiler, linker, runtime, and the go/types, net/http, and time packages. See the Go 1.17.4 milestone on our issue tracker for details. go1.17.5 (released 2021-12-09) includes security fixes to the net/http and syscall packages. See the Go 1.17.5 milestone on our issue tracker for details. go1.17.6 (released 2022-01-06) includes fixes to the compiler, linker, runtime, and the crypto/x509, net/http, and reflect packages. See the Go 1.17.6 milestone on our issue tracker for details. go1.17.7 (released 2022-02-10) includes security fixes to the go command, and the crypto/elliptic and math/big packages, as well as bug fixes to the compiler, linker, runtime, the go command, and the debug/macho, debug/pe, and net/http/httptest packages. See the Go 1.17.7 milestone on our issue tracker for details. go1.17.8 (released 2022-03-03) includes a security fix to the regexp/syntax package, as well as bug fixes to the compiler, runtime, the go command, and the crypto/x509 and net packages. See the Go 1.17.8 milestone on our issue tracker for details. go1.17.9 (released 2022-04-12) includes security fixes to the crypto/elliptic and encoding/pem packages, as well as bug fixes to the linker and runtime. See the Go 1.17.9 milestone on our issue tracker for details. go1.17.10 (released 2022-05-10) includes security fixes to the syscall package, as well as bug fixes to the compiler, runtime, and the crypto/x509 and net/http/httptest packages. See the Go 1.17.10 milestone on our issue tracker for details. go1.17.11 (released 2022-06-01) includes security fixes to the crypto/rand, crypto/tls, os/exec, and path/filepath packages, as well as bug fixes to the crypto/tls package. See the Go 1.17.11 milestone on our issue tracker for details. go1.17.12 (released 2022-07-12) includes security fixes to the compress/gzip, encoding/gob, encoding/xml, go/parser, io/fs, net/http, and path/filepath packages, as well as bug fixes to the compiler, the go command, the runtime, and the runtime/metrics package. See the Go 1.17.12 milestone on our issue tracker for details. go1.17.13 (released 2022-08-01) includes security fixes to the encoding/gob and math/big packages, as well as bug fixes to the compiler and the runtime. See the Go 1.17.13 milestone on our issue tracker for details. go1.16 (released 2021-02-16) Go 1.16 is a major release of Go. Read the Go 1.16 Release Notes for more information. Minor revisions go1.16.1 (released 2021-03-10) includes security fixes to the archive/zip and encoding/xml packages. See the Go 1.16.1 milestone on our issue tracker for details. go1.16.2 (released 2021-03-11) includes fixes to cgo, the compiler, linker, the go command, and the syscall and time packages. See the Go 1.16.2 milestone on our issue tracker for details. go1.16.3 (released 2021-04-01) includes fixes to the compiler, linker, runtime, the go command, and the testing and time packages. See the Go 1.16.3 milestone on our issue tracker for details. go1.16.4 (released 2021-05-06) includes a security fix to the net/http package, as well as bug fixes to the compiler, runtime, and the archive/zip, syscall, and time packages. See the Go 1.16.4 milestone on our issue tracker for details. go1.16.5 (released 2021-06-03) includes security fixes to the archive/zip, math/big, net, and net/http/httputil packages, as well as bug fixes to the linker, the go command, and the net/http package. See the Go 1.16.5 milestone on our issue tracker for details. go1.16.6 (released 2021-07-12) includes a security fix to the crypto/tls package, as well as bug fixes to the compiler, and the net and net/http packages. See the Go 1.16.6 milestone on our issue tracker for details. go1.16.7 (released 2021-08-05) includes a security fix to the net/http/httputil package, as well as bug fixes to the compiler, linker, runtime, the go command, and the net/http package. See the Go 1.16.7 milestone on our issue tracker for details. go1.16.8 (released 2021-09-09) includes a security fix to the archive/zip package, as well as bug fixes to the archive/zip, go/internal/gccgoimporter, html/template, net/http, and runtime/pprof packages. See the Go 1.16.8 milestone on our issue tracker for details. go1.16.9 (released 2021-10-07) includes security fixes to linker and the misc/wasm directory, as well as bug fixes to runtime and the text/template package. See the Go 1.16.9 milestone on our issue tracker for details. go1.16.10 (released 2021-11-04) includes security fixes to the archive/zip and debug/macho packages, as well as bug fixes to the compiler, linker, runtime, the misc/wasm directory, and the net/http package. See the Go 1.16.10 milestone on our issue tracker for details. go1.16.11 (released 2021-12-02) includes fixes to the compiler, runtime, and the net/http, net/http/httptest, and time packages. See the Go 1.16.11 milestone on our issue tracker for details. go1.16.12 (released 2021-12-09) includes security fixes to the net/http and syscall packages. See the Go 1.16.12 milestone on our issue tracker for details. go1.16.13 (released 2022-01-06) includes fixes to the compiler, linker, runtime, and the net/http package. See the Go 1.16.13 milestone on our issue tracker for details. go1.16.14 (released 2022-02-10) includes security fixes to the go command, and the crypto/elliptic and math/big packages, as well as bug fixes to the compiler, linker, runtime, the go command, and the debug/macho, debug/pe, net/http/httptest, and testing packages. See the Go 1.16.14 milestone on our issue tracker for details. go1.16.15 (released 2022-03-03) includes a security fix to the regexp/syntax package, as well as bug fixes to the compiler, runtime, the go command, and the net package. See the Go 1.16.15 milestone on our issue tracker for details. go1.15 (released 2020-08-11) Go 1.15 is a major release of Go. Read the Go 1.15 Release Notes for more information. Minor revisions go1.15.1 (released 2020-09-01) includes security fixes to the net/http/cgi and net/http/fcgi packages. See the Go 1.15.1 milestone on our issue tracker for details. go1.15.2 (released 2020-09-09) includes fixes to the compiler, runtime, documentation, the go command, and the net/mail, os, sync, and testing packages. See the Go 1.15.2 milestone on our issue tracker for details. go1.15.3 (released 2020-10-14) includes fixes to cgo, the compiler, runtime, the go command, and the bytes, plugin, and testing packages. See the Go 1.15.3 milestone on our issue tracker for details. go1.15.4 (released 2020-11-05) includes fixes to cgo, the compiler, linker, runtime, and the compress/flate, net/http, reflect, and time packages. See the Go 1.15.4 milestone on our issue tracker for details. go1.15.5 (released 2020-11-12) includes security fixes to the go command and the math/big package. See the Go 1.15.5 milestone on our issue tracker for details. go1.15.6 (released 2020-12-03) includes fixes to the compiler, linker, runtime, the go command, and the io package. See the Go 1.15.6 milestone on our issue tracker for details. go1.15.7 (released 2021-01-19) includes security fixes to the go command and the crypto/elliptic package. See the Go 1.15.7 milestone on our issue tracker for details. go1.15.8 (released 2021-02-04) includes fixes to the compiler, linker, runtime, the go command, and the net/http package. See the Go 1.15.8 milestone on our issue tracker for details. go1.15.9 (released 2021-03-10) includes security fixes to the encoding/xml package. See the Go 1.15.9 milestone on our issue tracker for details. go1.15.10 (released 2021-03-11) includes fixes to the compiler, the go command, and the net/http, os, syscall, and time packages. See the Go 1.15.10 milestone on our issue tracker for details. go1.15.11 (released 2021-04-01) includes fixes to cgo, the compiler, linker, runtime, the go command, and the database/sql and net/http packages. See the Go 1.15.11 milestone on our issue tracker for details. go1.15.12 (released 2021-05-06) includes a security fix to the net/http package, as well as bug fixes to the compiler, runtime, and the archive/zip, syscall, and time packages. See the Go 1.15.12 milestone on our issue tracker for details. go1.15.13 (released 2021-06-03) includes security fixes to the archive/zip, math/big, net, and net/http/httputil packages, as well as bug fixes to the linker, the go command, and the math/big and net/http packages. See the Go 1.15.13 milestone on our issue tracker for details. go1.15.14 (released 2021-07-12) includes a security fix to the crypto/tls package, as well as bug fixes to the linker and the net package. See the Go 1.15.14 milestone on our issue tracker for details. go1.15.15 (released 2021-08-05) includes a security fix to the net/http/httputil package, as well as bug fixes to the compiler, runtime, the go command, and the net/http package. See the Go 1.15.15 milestone on our issue tracker for details. go1.14 (released 2020-02-25) Go 1.14 is a major release of Go. Read the Go 1.14 Release Notes for more information. Minor revisions go1.14.1 (released 2020-03-19) includes fixes to the go command, tools, and the runtime. See the Go 1.14.1 milestone on our issue tracker for details. go1.14.2 (released 2020-04-08) includes fixes to cgo, the go command, the runtime, and the os/exec and testing packages. See the Go 1.14.2 milestone on our issue tracker for details. go1.14.3 (released 2020-05-14) includes fixes to cgo, the compiler, the runtime, and the go/doc and math/big packages. See the Go 1.14.3 milestone on our issue tracker for details. go1.14.4 (released 2020-06-01) includes fixes to the go doc command, the runtime, and the encoding/json and os packages. See the Go 1.14.4 milestone on our issue tracker for details. go1.14.5 (released 2020-07-14) includes security fixes to the crypto/x509 and net/http packages. See the Go 1.14.5 milestone on our issue tracker for details. go1.14.6 (released 2020-07-16) includes fixes to the go command, the compiler, the linker, vet, and the database/sql, encoding/json, net/http, reflect, and testing packages. See the Go 1.14.6 milestone on our issue tracker for details. go1.14.7 (released 2020-08-06) includes security fixes to the encoding/binary package. See the Go 1.14.7 milestone on our issue tracker for details. go1.14.8 (released 2020-09-01) includes security fixes to the net/http/cgi and net/http/fcgi packages. See the Go 1.14.8 milestone on our issue tracker for details. go1.14.9 (released 2020-09-09) includes fixes to the compiler, linker, runtime, documentation, and the net/http and testing packages. See the Go 1.14.9 milestone on our issue tracker for details. go1.14.10 (released 2020-10-14) includes fixes to the compiler, runtime, and the plugin and testing packages. See the Go 1.14.10 milestone on our issue tracker for details. go1.14.11 (released 2020-11-05) includes fixes to the runtime, and the net/http and time packages. See the Go 1.14.11 milestone on our issue tracker for details. go1.14.12 (released 2020-11-12) includes security fixes to the go command and the math/big package. See the Go 1.14.12 milestone on our issue tracker for details. go1.14.13 (released 2020-12-03) includes fixes to the compiler, runtime, and the go command. See the Go 1.14.13 milestone on our issue tracker for details. go1.14.14 (released 2021-01-19) includes security fixes to the go command and the crypto/elliptic package. See the Go 1.14.14 milestone on our issue tracker for details. go1.14.15 (released 2021-02-04) includes fixes to the compiler, runtime, the go command, and the net/http package. See the Go 1.14.15 milestone on our issue tracker for details. go1.13 (released 2019-09-03) Go 1.13 is a major release of Go. Read the Go 1.13 Release Notes for more information. Minor revisions go1.13.1 (released 2019-09-25) includes security fixes to the net/http and net/textproto packages. See the Go 1.13.1 milestone on our issue tracker for details. go1.13.2 (released 2019-10-17) includes security fixes to the compiler and the crypto/dsa package. See the Go 1.13.2 milestone on our issue tracker for details. go1.13.3 (released 2019-10-17) includes fixes to the go command, the toolchain, the runtime, and the crypto/ecdsa, net, net/http, and syscall packages. See the Go 1.13.3 milestone on our issue tracker for details. go1.13.4 (released 2019-10-31) includes fixes to the net/http and syscall packages. It also fixes an issue on macOS 10.15 Catalina where the non-notarized installer and binaries were being rejected by Gatekeeper. See the Go 1.13.4 milestone on our issue tracker for details. go1.13.5 (released 2019-12-04) includes fixes to the go command, the runtime, the linker, and the net/http package. See the Go 1.13.5 milestone on our issue tracker for details. go1.13.6 (released 2020-01-09) includes fixes to the runtime and the net/http package. See the Go 1.13.6 milestone on our issue tracker for details. go1.13.7 (released 2020-01-28) includes two security fixes to the crypto/x509 package. See the Go 1.13.7 milestone on our issue tracker for details. go1.13.8 (released 2020-02-12) includes fixes to the runtime, and the crypto/x509 and net/http packages. See the Go 1.13.8 milestone on our issue tracker for details. go1.13.9 (released 2020-03-19) includes fixes to the go command, tools, the runtime, the toolchain, and the crypto/cypher package. See the Go 1.13.9 milestone on our issue tracker for details. go1.13.10 (released 2020-04-08) includes fixes to the go command, the runtime, and the os/exec and time packages. See the Go 1.13.10 milestone on our issue tracker for details. go1.13.11 (released 2020-05-14) includes fixes to the compiler. See the Go 1.13.11 milestone on our issue tracker for details. go1.13.12 (released 2020-06-01) includes fixes to the runtime, and the go/types and math/big packages. See the Go 1.13.12 milestone on our issue tracker for details. go1.13.13 (released 2020-07-14) includes security fixes to the crypto/x509 and net/http packages. See the Go 1.13.13 milestone on our issue tracker for details. go1.13.14 (released 2020-07-16) includes fixes to the compiler, vet, and the database/sql, net/http, and reflect packages. See the Go 1.13.14 milestone on our issue tracker for details. go1.13.15 (released 2020-08-06) includes security fixes to the encoding/binary package. See the Go 1.13.15 milestone on our issue tracker for details. go1.12 (released 2019-02-25) Go 1.12 is a major release of Go. Read the Go 1.12 Release Notes for more information. Minor revisions go1.12.1 (released 2019-03-14) includes fixes to cgo, the compiler, the go command, and the fmt, net/smtp, os, path/filepath, sync, and text/template packages. See the Go 1.12.1 milestone on our issue tracker for details. go1.12.2 (released 2019-04-05) includes security fixes to the runtime, as well as bug fixes to the compiler, the go command, and the doc, net, net/http/httputil, and os packages. See the Go 1.12.2 milestone on our issue tracker for details. go1.12.3 (released 2019-04-08) was accidentally released without its intended fix. It is identical to go1.12.2, except for its version number. The intended fix is in go1.12.4. go1.12.4 (released 2019-04-11) fixes an issue where using the prebuilt binary releases on older versions of GNU/Linux led to failures when linking programs that used cgo. Only Linux users who hit this issue need to update. go1.12.5 (released 2019-05-06) includes fixes to the compiler, the linker, the go command, the runtime, and the os package. See the Go 1.12.5 milestone on our issue tracker for details. go1.12.6 (released 2019-06-11) includes fixes to the compiler, the linker, the go command, and the crypto/x509, net/http, and os packages. See the Go 1.12.6 milestone on our issue tracker for details. go1.12.7 (released 2019-07-08) includes fixes to cgo, the compiler, and the linker. See the Go 1.12.7 milestone on our issue tracker for details. go1.12.8 (released 2019-08-13) includes security fixes to the net/http and net/url packages. See the Go 1.12.8 milestone on our issue tracker for details. go1.12.9 (released 2019-08-15) includes fixes to the linker, and the math/big and os packages. See the Go 1.12.9 milestone on our issue tracker for details. go1.12.10 (released 2019-09-25) includes security fixes to the net/http and net/textproto packages. See the Go 1.12.10 milestone on our issue tracker for details. go1.12.11 (released 2019-10-17) includes security fixes to the crypto/dsa package. See the Go 1.12.11 milestone on our issue tracker for details. go1.12.12 (released 2019-10-17) includes fixes to the go command, runtime, and the net and syscall packages. See the Go 1.12.12 milestone on our issue tracker for details. go1.12.13 (released 2019-10-31) fixes an issue on macOS 10.15 Catalina where the non-notarized installer and binaries were being rejected by Gatekeeper. Only macOS users who hit this issue need to update. go1.12.14 (released 2019-12-04) includes a fix to the runtime. See the Go 1.12.14 milestone on our issue tracker for details. go1.12.15 (released 2020-01-09) includes fixes to the runtime and the net/http package. See the Go 1.12.15 milestone on our issue tracker for details. go1.12.16 (released 2020-01-28) includes two security fixes to the crypto/x509 package. See the Go 1.12.16 milestone on our issue tracker for details. go1.12.17 (released 2020-02-12) includes a fix to the runtime. See the Go 1.12.17 milestone on our issue tracker for details. go1.11 (released 2018-08-24) Go 1.11 is a major release of Go. Read the Go 1.11 Release Notes for more information. Minor revisions go1.11.1 (released 2018-10-01) includes fixes to the compiler, documentation, go command, runtime, and the crypto/x509, encoding/json, go/types, net, net/http, and reflect packages. See the Go 1.11.1 milestone on our issue tracker for details. go1.11.2 (released 2018-11-02) includes fixes to the compiler, linker, documentation, go command, and the database/sql and go/types packages. See the Go 1.11.2 milestone on our issue tracker for details. go1.11.3 (released 2018-12-12) includes three security fixes to \"go get\" and the crypto/x509 package. See the Go 1.11.3 milestone on our issue tracker for details. go1.11.4 (released 2018-12-14) includes fixes to cgo, the compiler, linker, runtime, documentation, go command, and the go/types and net/http packages. It includes a fix to a bug introduced in Go 1.11.3 that broke go get for import path patterns containing \"...\". See the Go 1.11.4 milestone on our issue tracker for details. go1.11.5 (released 2019-01-23) includes a security fix to the crypto/elliptic package. See the Go 1.11.5 milestone on our issue tracker for details. go1.11.6 (released 2019-03-14) includes fixes to cgo, the compiler, linker, runtime, go command, and the crypto/x509, encoding/json, net, and net/url packages. See the Go 1.11.6 milestone on our issue tracker for details. go1.11.7 (released 2019-04-05) includes fixes to the runtime and the net package. See the Go 1.11.7 milestone on our issue tracker for details. go1.11.8 (released 2019-04-08) was accidentally released without its intended fix. It is identical to go1.11.7, except for its version number. The intended fix is in go1.11.9. go1.11.9 (released 2019-04-11) fixes an issue where using the prebuilt binary releases on older versions of GNU/Linux led to failures when linking programs that used cgo. Only Linux users who hit this issue need to update. go1.11.10 (released 2019-05-06) includes security fixes to the runtime, as well as bug fixes to the linker. See the Go 1.11.10 milestone on our issue tracker for details. go1.11.11 (released 2019-06-11) includes a fix to the crypto/x509 package. See the Go 1.11.11 milestone on our issue tracker for details. go1.11.12 (released 2019-07-08) includes fixes to the compiler and the linker. See the Go 1.11.12 milestone on our issue tracker for details. go1.11.13 (released 2019-08-13) includes security fixes to the net/http and net/url packages. See the Go 1.11.13 milestone on our issue tracker for details. go1.10 (released 2018-02-16) Go 1.10 is a major release of Go. Read the Go 1.10 Release Notes for more information. Minor revisions go1.10.1 (released 2018-03-28) includes security fixes to the go command, as well as bug fixes to the compiler, runtime, and the archive/zip, crypto/tls, crypto/x509, encoding/json, net, net/http, and net/http/pprof packages. See the Go 1.10.1 milestone on our issue tracker for details. go1.10.2 (released 2018-05-01) includes fixes to the compiler, linker, and go command. See the Go 1.10.2 milestone on our issue tracker for details. go1.10.3 (released 2018-06-05) includes fixes to the go command, and the crypto/tls, crypto/x509, and strings packages. In particular, it adds minimal support to the go command for the vgo transition. See the Go 1.10.3 milestone on our issue tracker for details. go1.10.4 (released 2018-08-24) includes fixes to the go command, linker, and the bytes, mime/multipart, net/http, and strings packages. See the Go 1.10.4 milestone on our issue tracker for details. go1.10.5 (released 2018-11-02) includes fixes to the go command, linker, runtime, and the database/sql package. See the Go 1.10.5 milestone on our issue tracker for details. go1.10.6 (released 2018-12-12) includes three security fixes to \"go get\" and the crypto/x509 package. It contains the same fixes as Go 1.11.3 and was released at the same time. See the Go 1.10.6 milestone on our issue tracker for details. go1.10.7 (released 2018-12-14) includes a fix to a bug introduced in Go 1.10.6 that broke go get for import path patterns containing \"...\". See the Go 1.10.7 milestone on our issue tracker for details. go1.10.8 (released 2019-01-23) includes a security fix to the crypto/elliptic package. See the Go 1.10.8 milestone on our issue tracker for details. go1.9 (released 2017-08-24) Go 1.9 is a major release of Go. Read the Go 1.9 Release Notes for more information. Minor revisions go1.9.1 (released 2017-10-04) includes two security fixes. See the Go 1.9.1 milestone on our issue tracker for details. go1.9.2 (released 2017-10-25) includes fixes to the compiler, linker, runtime, documentation, go command, and the crypto/x509, database/sql, log, and net/smtp packages. It includes a fix to a bug introduced in Go 1.9.1 that broke go get of non-Git repositories under certain conditions. See the Go 1.9.2 milestone on our issue tracker for details. go1.9.3 (released 2018-01-22) includes security fixes to the net/url package, as well as bug fixes to the compiler, runtime, and the database/sql, math/big, and net/http packages. See the Go 1.9.3 milestone on our issue tracker for details. go1.9.4 (released 2018-02-07) includes a security fix to \"go get\". See the Go 1.9.4 milestone on our issue tracker for details. go1.9.5 (released 2018-03-28) includes security fixes to the go command, as well as bug fixes to the compiler, go command, and the net/http/pprof package. See the Go 1.9.5 milestone on our issue tracker for details. go1.9.6 (released 2018-05-01) includes fixes to the compiler and go command. See the Go 1.9.6 milestone on our issue tracker for details. go1.9.7 (released 2018-06-05) includes fixes to the go command, and the crypto/x509 and strings packages. In particular, it adds minimal support to the go command for the vgo transition. See the Go 1.9.7 milestone on our issue tracker for details. go1.8 (released 2017-02-16) Go 1.8 is a major release of Go. Read the Go 1.8 Release Notes for more information. Minor revisions go1.8.1 (released 2017-04-07) includes fixes to the compiler, linker, runtime, documentation, go command and the crypto/tls, encoding/xml, image/png, net, net/http, reflect, text/template, and time packages. See the Go 1.8.1 milestone on our issue tracker for details. go1.8.2 (released 2017-05-23) includes a security fix to the crypto/elliptic package. See the Go 1.8.2 milestone on our issue tracker for details. go1.8.3 (released 2017-05-24) includes fixes to the compiler, runtime, documentation, and the database/sql package. See the Go 1.8.3 milestone on our issue tracker for details. go1.8.4 (released 2017-10-04) includes two security fixes. It contains the same fixes as Go 1.9.1 and was released at the same time. See the Go 1.8.4 milestone on our issue tracker for details. go1.8.5 (released 2017-10-25) includes fixes to the compiler, linker, runtime, documentation, go command, and the crypto/x509 and net/smtp packages. It includes a fix to a bug introduced in Go 1.8.4 that broke go get of non-Git repositories under certain conditions. See the Go 1.8.5 milestone on our issue tracker for details. go1.8.6 (released 2018-01-22) includes the same fix in math/big as Go 1.9.3 and was released at the same time. See the Go 1.8.6 milestone on our issue tracker for details. go1.8.7 (released 2018-02-07) includes a security fix to \"go get\". It contains the same fix as Go 1.9.4 and was released at the same time. See the Go 1.8.7 milestone on our issue tracker for details. go1.7 (released 2016-08-15) Go 1.7 is a major release of Go. Read the Go 1.7 Release Notes for more information. Minor revisions go1.7.1 (released 2016-09-07) includes fixes to the compiler, runtime, documentation, and the compress/flate, hash/crc32, io, net, net/http, path/filepath, reflect, and syscall packages. See the Go 1.7.1 milestone on our issue tracker for details. go1.7.2 should not be used. It was tagged but not fully released. The release was deferred due to a last minute bug report. Use go1.7.3 instead, and refer to the summary of changes below. go1.7.3 (released 2016-10-19) includes fixes to the compiler, runtime, and the crypto/cipher, crypto/tls, net/http, and strings packages. See the Go 1.7.3 milestone on our issue tracker for details. go1.7.4 (released 2016-12-01) includes two security fixes. See the Go 1.7.4 milestone on our issue tracker for details. go1.7.5 (released 2017-01-26) includes fixes to the compiler, runtime, and the crypto/x509 and time packages. See the Go 1.7.5 milestone on our issue tracker for details. go1.7.6 (released 2017-05-23) includes the same security fix as Go 1.8.2 and was released at the same time. See the Go 1.8.2 milestone on our issue tracker for details. go1.6 (released 2016-02-17) Go 1.6 is a major release of Go. Read the Go 1.6 Release Notes for more information. Minor revisions go1.6.1 (released 2016-04-12) includes two security fixes. See the Go 1.6.1 milestone on our issue tracker for details. go1.6.2 (released 2016-04-20) includes fixes to the compiler, runtime, tools, documentation, and the mime/multipart, net/http, and sort packages. See the Go 1.6.2 milestone on our issue tracker for details. go1.6.3 (released 2016-07-17) includes security fixes to the net/http/cgi package and net/http package when used in a CGI environment. See the Go 1.6.3 milestone on our issue tracker for details. go1.6.4 (released 2016-12-01) includes two security fixes. It contains the same fixes as Go 1.7.4 and was released at the same time. See the Go 1.7.4 milestone on our issue tracker for details. go1.5 (released 2015-08-19) Go 1.5 is a major release of Go. Read the Go 1.5 Release Notes for more information. Minor revisions go1.5.1 (released 2015-09-08) includes bug fixes to the compiler, assembler, and the fmt, net/textproto, net/http, and runtime packages. See the Go 1.5.1 milestone on our issue tracker for details. go1.5.2 (released 2015-12-02) includes bug fixes to the compiler, linker, and the mime/multipart, net, and runtime packages. See the Go 1.5.2 milestone on our issue tracker for details. go1.5.3 (released 2016-01-13) includes a security fix to the math/big package affecting the crypto/tls package. See the release announcement for details. go1.5.4 (released 2016-04-12) includes two security fixes. It contains the same fixes as Go 1.6.1 and was released at the same time. See the Go 1.6.1 milestone on our issue tracker for details. go1.4 (released 2014-12-10) Go 1.4 is a major release of Go. Read the Go 1.4 Release Notes for more information. Minor revisions go1.4.1 (released 2015-01-15) includes bug fixes to the linker and the log, syscall, and runtime packages. See the Go 1.4.1 milestone on our issue tracker for details. go1.4.2 (released 2015-02-17) includes security fixes to the compiler, and bug fixes to the go command, the compiler and linker, and the runtime, syscall, reflect, and math/big packages. See the Go 1.4.2 milestone on our issue tracker for details. go1.4.3 (released 2015-09-22) includes security fixes to the net/http package and bug fixes to the runtime package. See the Go 1.4.3 milestone on our issue tracker for details. go1.3 (released 2014-06-18) Go 1.3 is a major release of Go. Read the Go 1.3 Release Notes for more information. Minor revisions go1.3.1 (released 2014-08-13) includes bug fixes to the compiler and the runtime, net, and crypto/rsa packages. See the change history for details. go1.3.2 (released 2014-09-25) includes security fixes to the crypto/tls package and bug fixes to cgo. See the change history for details. go1.3.3 (released 2014-09-30) includes further bug fixes to cgo, the runtime package, and the nacl port. See the change history for details. go1.2 (released 2013-12-01) Go 1.2 is a major release of Go. Read the Go 1.2 Release Notes for more information. Minor revisions go1.2.1 (released 2014-03-02) includes bug fixes to the runtime, net, and database/sql packages. See the change history for details. go1.2.2 (released 2014-05-05) includes a security fix that affects the tour binary included in the binary distributions (thanks to Guillaume T). go1.1 (released 2013-05-13) Go 1.1 is a major release of Go. Read the Go 1.1 Release Notes for more information. Minor revisions go1.1.1 (released 2013-06-13) includes a security fix to the compiler and several bug fixes to the compiler and runtime. See the change history for details. go1.1.2 (released 2013-08-13) includes fixes to the gc compiler and cgo, and the bufio, runtime, syscall, and time packages. See the change history for details. If you use package syscall's Getrlimit and Setrlimit functions under Linux on the ARM or 386 architectures, please note change 11803043 that fixes issue 5949. go1 (released 2012-03-28) Go 1 is a major release of Go that will be stable in the long term. Read the Go 1 Release Notes for more information. It is intended that programs written for Go 1 will continue to compile and run correctly, unchanged, under future versions of Go 1. Read the Go 1 compatibility document for more about the future of Go 1. The go1 release corresponds to weekly.2012-03-27. Minor revisions go1.0.1 (released 2012-04-25) was issued to fix an escape analysis bug that can lead to memory corruption. It also includes several minor code and documentation fixes. go1.0.2 (released 2012-06-13) was issued to fix two bugs in the implementation of maps using struct or array 3695 and issue 3573. It also includes many minor code and documentation fixes. go1.0.3 (released 2012-09-21) includes minor code and documentation fixes. See the go1 release branch history for the complete list of changes. Older releases See the Pre-Go 1 Release History page for notes on earlier releases.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\ngit fetch --tags\ngit checkout goX.Y.Z\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.410Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":1,"totalLines":11,"estimatedTokens":14941}}26{"id":"doc-documentation_the_go_programming_language-cf7690ce","source":"documentation","title":"Documentation - The Go Programming Language","url":"https://go.dev/doc","text":"Documentation The Go programming language is an open source project to make programmers more productive. Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel type system enables flexible and modular program construction. Go compiles quickly to machine code yet has the convenience of garbage collection and the power of run-time reflection. It's a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language. Getting Started Installing Go Instructions for downloading and installing Go. started A brief Hello, World tutorial to get started. Learn a bit about Go code, tools, packages, and modules. a module A tutorial of short topics introducing functions, error handling, arrays, maps, unit testing, and compiling. started with multi-module workspaces Introduces the basics of creating and using multi-module workspaces in Go. Multi-module workspaces are useful for making changes across multiple modules. a RESTful API with Go and Gin Introduces the basics of writing a RESTful web service API with Go and the Gin Web Framework. started with generics With generics, you can declare and use functions or types that are written to work with any of a set of types provided by calling code. started with fuzzing Fuzzing can generate inputs to your tests that can catch edge cases and security issues that you may have missed. Writing Web Applications Building a simple web application. How to write Go code This doc explains how to develop a simple set of Go packages inside a module, and it shows how to use the go command to build and test packages. A Tour of Go An interactive introduction to Go in four sections. The first section covers basic syntax and data structures; the second discusses methods and interfaces; the third is about Generics; and the fourth introduces Go's concurrency primitives. Each section concludes with a few exercises so you can practice what you've learned. You can take the tour online or install it locally with: $ go install golang.org/x/website/tour@latest This will place the tour binary in your GOPATH's bin directory. Using and understanding Go Effective Go A document that gives tips for writing clear, idiomatic Go code. A must read for any new Go programmer. It augments the tour and the language specification, both of which should be read first. Frequently Asked Questions (FAQ) Answers to common questions about Go. Editor plugins and IDEs A document that summarizes commonly used editor plugins and IDEs with Go support. Diagnostics Summarizes tools and methodologies to diagnose problems in Go programs. A Guide to the Go Garbage Collector A document that describes how Go manages memory, and how to make the most of it. Managing dependencies When your code uses external packages, those packages (distributed as modules) become dependencies. Fuzzing Main documentation page for Go fuzzing. Coverage for Go applications Main documentation page for coverage testing of Go applications. Profile-guided optimization Main documentation page for profile-guided optimization (PGO) of Go applications. encoding/json/v2 Migration Guide Guide for safe step-by-step migration from encoding/json to encoding/json/v2. References Package Documentation The documentation for the Go standard library. Command Documentation The documentation for the Go tools. Language Specification The official Go Language specification. Go Modules Reference A detailed reference manual for Go's dependency management system. go.mod file reference Reference for the directives included in a go.mod file. The Go Memory Model A document that specifies the conditions under which reads of a variable in one goroutine can be guaranteed to observe values produced by writes to the same variable in a different goroutine. Contribution Guide Contributing to Go. Release History A summary of the changes between Go releases. Accessing databases a relational database Introduces the basics of accessing a relational database using Go and the database/sql package in the standard library. Accessing relational databases An overview of Go's data access features. Opening a database handle You use the Go database handle to execute database operations. Once you open a handle with database connection properties, the handle represents a connection pool it manages on your behalf. Executing SQL statements that don't return data For SQL operations that might change the database, including SQL INSERT, UPDATE, and DELETE, you use Exec methods. Querying for data For SELECT statements that return data from a query, using the Query or QueryRow method. Using prepared statements Defining a prepared statement for repeated use can help your code run a bit faster by avoiding the overhead of re-creating the statement each time your code performs the database operation. Executing transactions sql.Tx exports methods representing transaction-specific semantics, including Commit and Rollback, as well as methods you use to perform common database operations. Canceling in-progress database operations Using context.Context, you can have your application's function calls and services stop working early and return an error when their processing is no longer needed. Managing connections For some advanced programs, you might need to tune connection pool parameters or work with connections explicitly. Avoiding SQL injection risk You can avoid an SQL injection risk by providing SQL parameter values as sql package function arguments Developing modules Developing and publishing modules You can collect related packages into modules, then publish the modules for other developers to use. This topic gives an overview of developing and publishing modules. Module release and versioning workflow When you develop modules for use by other developers, you can follow a workflow that helps ensure a reliable, consistent experience for developers using the module. This topic describes the high-level steps in that workflow. Managing module source When you're developing modules to publish for others to use, you can help ensure that your modules are easier for other developers to use by following the repository conventions described in this topic. Organizing a Go module What is the right way to organize the files and directories in a typical Go project? This topic discusses some common layouts depending on the kind of module you have. Developing a major version update A major version update can be very disruptive to your module's users because it includes breaking changes and represents a new module. Learn more in this topic. Publishing a module When you want to make a module available for other developers, you publish it so that it's visible to Go tools. Once you've published the module, developers importing its packages will be able to resolve a dependency on the module by running commands such as go get. Module version numbering A module's developer uses each part of a module's version number to signal the version’s stability and backward compatibility. For each new release, a module's release version number specifically reflects the nature of the module's changes since the preceding release. Talks A Video Tour of Go Three things that make Go fast, fun, and , reflection, and concurrency. Builds a toy web crawler to demonstrate these. Code that grows with grace One of Go's key design goals is code adaptability; that it should be easy to take a simple design and build upon it in a clean and natural way. In this talk Andrew Gerrand describes a simple \"chat roulette\" server that matches pairs of incoming TCP connections, and then use Go's concurrency mechanisms, interfaces, and standard library to extend it with a web interface and other features. While the function of the program changes dramatically, Go's flexibility preserves the original design as it grows. Go Concurrency Patterns Concurrency is the key to designing high performance network services. Go's concurrency primitives (goroutines and channels) provide a simple and efficient means of expressing concurrent execution. In this talk we see how tricky concurrency problems can be solved gracefully with simple Go code. Advanced Go Concurrency Patterns This talk expands on the Go Concurrency Patterns talk to dive deeper into Go's concurrency primitives. More See the Go Talks site and wiki page for more Go talks. Codewalks Guided tours of Go programs. First-Class Functions in Go Generating arbitrary Markov chain algorithm Share Memory by Communicating Language tale of interfaces Go's Declaration Syntax Defer, Panic, and Recover Go Concurrency out, moving on Go and internals A GIF exercise in Go interfaces Error Handling and Go Packages JSON and Go - using the json package. Gobs of data - the design and use of the gob package. The Laws of Reflection - the fundamentals of the reflect package. The Go image package - the fundamentals of the image package. The Go image/draw package - the fundamentals of the image/draw package. Modules Using Go Modules - an introduction to using modules in a simple project. Migrating to Go Modules - converting an existing project to use modules. Publishing Go Modules - how to make new versions of modules available to others. Go and Beyond - creating and publishing major versions 2 and higher. Keeping Your Modules Compatible - how to keep your modules compatible with prior minor/patch versions. Tools About the Go command - why we wrote it, what it is, what it's not, and how to use it. Go Doc Comments - writing good program documentation Debugging Go Code with GDB Data Race Detector - a manual for the data race detector. A Quick Guide to Go's Assembler - an introduction to the assembler used by Go. C? Go? Cgo! - linking against C code with cgo. Profiling Go Programs - tools for measuring your code's CPU and memory usage Introducing the Go Race Detector - an introduction to the race detector. language server for Go - getting the most out your editor when working in Go. Wiki The Go Wiki, maintained by the Go community, includes articles about the Go language, tools, and other resources. See the Learn page at the Wiki for more Go learning resources. Non-English Documentation See the NonEnglish page at the Wiki for localized documentation. Opens in new window.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ go install golang.org/x/website/tour@latest\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.484Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":1,"totalLines":10,"estimatedTokens":2646}}27{"id":"doc-tutorial_getting_started_with_multi_module_works-76ae22ce","source":"documentation","title":"Tutorial: Getting started with multi-module workspaces - The Go Programming Language","url":"https://go.dev/doc/tutorial/workspaces.html","text":"Documentation Tutorials started with multi-module workspaces started with multi-module workspaces This tutorial introduces the basics of multi-module workspaces in Go. With multi-module workspaces, you can tell the Go command that you’re writing code in multiple modules at the same time and easily build and run code in those modules. In this tutorial, you’ll create two modules in a shared multi-module workspace, make changes across those modules, and see the results of those changes in a build. other tutorials, see Tutorials. Prerequisites Go. We recommend using the latest version of Go to follow this tutorial. For installation instructions, see Installing Go. A tool to edit your code. Any text editor you have will work fine. A command terminal. Go works well using any terminal on Linux and Mac, and on PowerShell or cmd in Windows. Create a module for your code To begin, create a module for the code you’ll write. Open a command prompt and change to your home directory. On Linux or Mac: $ cd On :\\> cd %HOMEPATH% The rest of the tutorial will show a $ as the prompt. The commands you use will work on Windows too. From the command prompt, create a directory for your code called workspace. $ mkdir workspace $ cd workspace Initialize the module Our example will create a new module hello that will depend on the golang.org/x/example module. Create the hello module: $ mkdir hello $ cd hello $ go mod init example.com/hello new go.mod: module example.com/hello Add a dependency on the golang.org/x/example/hello/reverse package by using go get. $ go get golang.org/x/example/hello/reverse Create hello.go in the hello directory with the following main import ( \"fmt\" \"golang.org/x/example/hello/reverse\" ) func main() { fmt.Println(reverse.String(\"Hello\")) } Now, run the hello program: $ go run . olleH Create the workspace In this step, we’ll create a go.work file to specify a workspace with the module. Initialize the workspace In the workspace directory, run: $ go work init ./hello The go work init command tells go to create a go.work file for a workspace containing the modules in the ./hello directory. The go command produces a go.work file that looks like 1.18 use ./hello The go.work file has similar syntax to go.mod. The go directive tells Go which version of Go the file should be interpreted with. It’s similar to the go directive in the go.mod file. The use directive tells Go that the module in the hello directory should be main modules when doing a build. So in any subdirectory of workspace the module will be active. Run the program in the workspace directory In the workspace directory, run: $ go run ./hello olleH The Go command includes all the modules in the workspace as main modules. This allows us to refer to a package in the module, even outside the module. Running the go run command outside the module or the workspace would result in an error because the go command wouldn’t know which modules to use. Next, we’ll add a local copy of the golang.org/x/example/hello module to the workspace. That module is stored in a subdirectory of the go.googlesource.com/example Git repository. We’ll then add a new function to the reverse package that we can use instead of String. Download and modify the golang.org/x/example/hello module In this step, we’ll download a copy of the Git repo containing the golang.org/x/example/hello module, add it to the workspace, and then add a new function to it that we will use from the hello program. Clone the repository From the workspace directory, run the git command to clone the repository: $ git clone https://go.googlesource.com/example Cloning into 'example'... 165 (delta 27), reused 165 (delta 27) Receiving % (165/165), 434.18 KiB | 1022.00 KiB/s, done. Resolving % (27/27), done. Add the module to the workspace The Git repo was just checked out into ./example. The source code for the golang.org/x/example/hello module is in ./example/hello. Add it to the workspace: $ go work use ./example/hello The go work use command adds a new module to the go.work file. It will now look like 1.18 use ( ./hello ./example/hello ) The workspace now includes both the example.com/hello module and the golang.org/x/example/hello module, which provides the golang.org/x/example/hello/reverse package. This will allow us to use the new code we will write in our copy of the reverse package instead of the version of the package in the module cache that we downloaded with the go get command. Add the new function. We’ll add a new function to reverse a number to the golang.org/x/example/hello/reverse package. Create a new file named int.go in the workspace/example/hello/reverse directory containing the following reverse import \"strconv\" // Int returns the decimal reversal of the integer i. func Int(i int) int { i, _ = strconv.Atoi(String(strconv.Itoa(i))) return i } Modify the hello program to use the function. Modify the contents of workspace/hello/hello.go to contain the following main import ( \"fmt\" \"golang.org/x/example/hello/reverse\" ) func main() { fmt.Println(reverse.String(\"Hello\"), reverse.Int(24601)) } Run the code in the workspace From the workspace directory, run $ go run ./hello olleH 10642 The Go command finds the example.com/hello module specified in the command line in the hello directory specified by the go.work file, and similarly resolves the golang.org/x/example/hello/reverse import using the go.work file. go.work can be used instead of adding replace directives to work across multiple modules. Since the two modules are in the same workspace it’s easy to make a change in one module and use it in another. Future step Now, to properly release these modules we’d need to make a release of the golang.org/x/example/hello module, for example at v0.1.0. This is usually done by tagging a commit on the module’s version control repository. See the module release workflow documentation for more details. Once the release is done, we can increase the requirement on the golang.org/x/example/hello module in hello/go.mod: cd hello go get golang.org/x/example/hello@v0.1.0 That way, the go command can properly resolve the modules outside the workspace. Learn more about workspaces The go command has a couple of subcommands for working with workspaces in addition to go work init which we saw earlier in the work use [-r] [dir] adds a use directive to the go.work file for dir, if it exists, and removes the use directory if the argument directory doesn’t exist. The -r flag examines subdirectories of dir recursively. go work edit edits the go.work file similarly to go mod edit go work sync syncs dependencies from the workspace’s build list into each of the workspace modules. See Workspaces in the Go Modules Reference for more detail on workspaces and go.work files.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ cd\n```\n\nExample:\n```text\nC:\\> cd %HOMEPATH%\n```\n\nExample:\n```text\n$ mkdir workspace\n$ cd workspace\n```\n\nExample:\n```text\n$ mkdir hello\n$ cd hello\n$ go mod init example.com/hello\ngo: creating new go.mod: module example.com/hello\n```\n\nExample:\n```text\n$ go get golang.org/x/example/hello/reverse\n```\n\nExample:\n```text\npackage main\n\nimport (\n    \"fmt\"\n\n    \"golang.org/x/example/hello/reverse\"\n)\n\nfunc main() {\n    fmt.Println(reverse.String(\"Hello\"))\n}\n```\n\nExample:\n```text\n$ go run .\nolleH\n```\n\nExample:\n```text\n$ go work init ./hello\n```\n\nExample:\n```text\ngo 1.18\n\nuse ./hello\n```\n\nExample:\n```text\n$ go run ./hello\nolleH\n```\n\nExample:\n```text\n$ git clone https://go.googlesource.com/example\nCloning into 'example'...\nremote: Total 165 (delta 27), reused 165 (delta 27)\nReceiving objects: 100% (165/165), 434.18 KiB | 1022.00 KiB/s, done.\nResolving deltas: 100% (27/27), done.\n```\n\nExample:\n```text\n$ go work use ./example/hello\n```\n\nExample:\n```text\ngo 1.18\n\nuse (\n    ./hello\n    ./example/hello\n)\n```\n\nExample:\n```text\npackage reverse\n\nimport \"strconv\"\n\n// Int returns the decimal reversal of the integer i.\nfunc Int(i int) int {\n    i, _ = strconv.Atoi(String(strconv.Itoa(i)))\n    return i\n}\n```\n\nExample:\n```text\npackage main\n\nimport (\n    \"fmt\"\n\n    \"golang.org/x/example/hello/reverse\"\n)\n\nfunc main() {\n    fmt.Println(reverse.String(\"Hello\"), reverse.Int(24601))\n}\n```\n\nExample:\n```text\n$ go run ./hello\nolleH 10642\n```\n\nExample:\n```text\ncd hello\ngo get golang.org/x/example/hello@v0.1.0\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.485Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":17,"totalLines":137,"estimatedTokens":2110}}28{"id":"doc-editor_plugins_and_ides_the_go_programming_langu-e80f0768","source":"documentation","title":"Editor plugins and IDEs - The Go Programming Language","url":"https://go.dev/doc/editors.html","text":"Documentation Editor plugins and IDEs Editor plugins and IDEs Introduction This document lists commonly used editor plugins and IDEs from the Go ecosystem that make Go development more productive and seamless. A comprehensive list of editor support and IDEs for Go development is available at the wiki. Options The Go ecosystem provides a variety of editor plugins and IDEs to enhance your day-to-day editing, navigation, testing, and debugging experience. Visual Studio extension provides support for the Go programming language is distributed either as a standalone IDE or as a plugin for IntelliJ IDEA Ultimate plugin provides Go programming language support Note that these are only a few top solutions; a more comprehensive community-maintained list of IDEs and text editor plugins is available at the Wiki.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.486Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":0,"totalLines":5,"estimatedTokens":238}}29{"id":"doc-how_to_write_go_code_the_go_programming_language-89f881d0","source":"documentation","title":"How to Write Go Code - The Go Programming Language","url":"https://go.dev/doc/code.html","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ mkdir hello # Alternatively, clone it if it already exists in version control.\n$ cd hello\n$ go mod init example/user/hello\ngo: creating new go.mod: module example/user/hello\n$ cat go.mod\nmodule example/user/hello\n\ngo 1.16\n$\n```\n\nExample:\n```text\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    fmt.Println(\"Hello, world.\")\n}\n```\n\nExample:\n```text\n$ go install example/user/hello\n$\n```\n\nExample:\n```text\n$ go env -w GOBIN=/somewhere/else/bin\n$\n```\n\nExample:\n```text\n$ go env -u GOBIN\n$\n```\n\nExample:\n```text\n$ go install example/user/hello\n```\n\nExample:\n```text\n$ go install .\n```\n\nExample:\n```text\n$ go install\n```\n\nExample:\n```text\n# Windows users should consult /wiki/SettingGOPATH\n# for setting %PATH%.\n$ export PATH=$PATH:$(dirname $(go list -f '{{.Target}}' .))\n$ hello\nHello, world.\n$\n```\n\nExample:\n```text\n$ git init\nInitialized empty Git repository in /home/user/hello/.git/\n$ git add go.mod hello.go\n$ git commit -m \"initial commit\"\n[master (root-commit) 0b4507d] initial commit\n 1 file changed, 7 insertion(+)\n create mode 100644 go.mod hello.go\n$\n```\n\nExample:\n```text\n// Package morestrings implements additional functions to manipulate UTF-8\n// encoded strings, beyond what is provided in the standard \"strings\" package.\npackage morestrings\n\n// ReverseRunes returns its argument string reversed rune-wise left to right.\nfunc ReverseRunes(s string) string {\n    r := []rune(s)\n    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n        r[i], r[j] = r[j], r[i]\n    }\n    return string(r)\n}\n```\n\nExample:\n```text\n$ cd $HOME/hello/morestrings\n$ go build\n$\n```\n\nExample:\n```text\npackage main\n\nimport (\n    \"fmt\"\n\n    \"example/user/hello/morestrings\"\n)\n\nfunc main() {\n    fmt.Println(morestrings.ReverseRunes(\"!oG ,olleH\"))\n}\n```\n\nExample:\n```text\n$ hello\nHello, Go!\n```\n\nExample:\n```text\npackage main\n\nimport (\n    \"fmt\"\n\n    \"example/user/hello/morestrings\"\n    \"github.com/google/go-cmp/cmp\"\n)\n\nfunc main() {\n    fmt.Println(morestrings.ReverseRunes(\"!oG ,olleH\"))\n    fmt.Println(cmp.Diff(\"Hello World\", \"Hello Go\"))\n}\n```\n\nExample:\n```text\n$ go mod tidy\ngo: finding module for package github.com/google/go-cmp/cmp\ngo: found github.com/google/go-cmp/cmp in github.com/google/go-cmp v0.5.4\n$ go install example/user/hello\n$ hello\nHello, Go!\n  string(\n-     \"Hello World\",\n+     \"Hello Go\",\n  )\n$ cat go.mod\nmodule example/user/hello\n\ngo 1.16\n\nrequire github.com/google/go-cmp v0.5.4\n$\n```\n\nExample:\n```text\n$ go clean -modcache\n$\n```\n\nExample:\n```text\npackage morestrings\n\nimport \"testing\"\n\nfunc TestReverseRunes(t *testing.T) {\n    cases := []struct {\n        in, want string\n    }{\n        {\"Hello, world\", \"dlrow ,olleH\"},\n        {\"Hello, 世界\", \"界世 ,olleH\"},\n        {\"\", \"\"},\n    }\n    for _, c := range cases {\n        got := ReverseRunes(c.in)\n        if got != c.want {\n            t.Errorf(\"ReverseRunes(%q) == %q, want %q\", c.in, got, c.want)\n        }\n    }\n}\n```\n\nExample:\n```text\n$ cd $HOME/hello/morestrings\n$ go test\nPASS\nok  \texample/user/hello/morestrings 0.165s\n$\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.487Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":202,"estimatedTokens":790}}30{"id":"doc-diagnostics_the_go_programming_language-e6d9aadf","source":"documentation","title":"Diagnostics - The Go Programming Language","url":"https://go.dev/doc/diagnostics.html","text":"Documentation Diagnostics Diagnostics Introduction The Go ecosystem provides a large suite of APIs and tools to diagnose logic and performance problems in Go programs. This page summarizes the available tools and helps Go users pick the right one for their specific problem. Diagnostics solutions can be categorized into the following : Profiling tools analyze the complexity and costs of a Go program such as its memory usage and frequently called functions to identify the expensive sections of a Go program. is a way to instrument code to analyze latency throughout the lifecycle of a call or user request. Traces provide an overview of how much latency each component contributes to the overall latency in a system. Traces can span multiple Go processes. allows us to pause a Go program and examine its execution. Program state and flow can be verified with debugging. Runtime statistics and and analysis of runtime stats and events provides a high-level overview of the health of Go programs. Spikes/dips of metrics helps us to identify changes in throughput, utilization, and performance. diagnostics tools may interfere with each other. For example, precise memory profiling skews CPU profiles and goroutine blocking profiling affects scheduler trace. Use tools in isolation to get more precise info. Profiling Profiling is useful for identifying expensive or frequently called sections of code. The Go runtime provides profiling data in the format expected by the pprof visualization tool. The profiling data can be collected during testing via go test or endpoints made available from the net/http/pprof package. Users need to collect the profiling data and use pprof tools to filter and visualize the top code paths. Predefined profiles provided by the runtime/pprof : CPU profile determines where a program spends its time while actively consuming CPU cycles (as opposed to while sleeping or waiting for I/O). profile reports memory allocation samples; used to monitor current and historical memory usage, and to check for memory leaks. creation profile reports the sections of the program that lead the creation of new OS threads. profile reports the stack traces of all current goroutines. profile shows where goroutines block waiting on synchronization primitives (including timer channels). Block profile is not enabled by default; use runtime.SetBlockProfileRate to enable it. profile reports the lock contentions. When you think your CPU is not fully utilized due to a mutex contention, use this profile. Mutex profile is not enabled by default, see runtime.SetMutexProfileFraction to enable it. What other profilers can I use to profile Go programs? On Linux, perf tools can be used for profiling Go programs. Perf can profile and unwind cgo/SWIG code and kernel, so it can be useful to get insights into native/kernel performance bottlenecks. On macOS, Instruments suite can be used profile Go programs. Can I profile my production services? Yes. It is safe to profile programs in production, but enabling some profiles (e.g. the CPU profile) adds cost. You should expect to see performance downgrade. The performance penalty can be estimated by measuring the overhead of the profiler before turning it on in production. You may want to periodically profile your production services. Especially in a system with many replicas of a single process, selecting a random replica periodically is a safe option. Select a production process, profile it for X seconds for every Y seconds and save the results for visualization and analysis; then repeat periodically. Results may be manually and/or automatically reviewed to find problems. Collection of profiles can interfere with each other, so it is recommended to collect only a single profile at a time. What are the best ways to visualize the profiling data? The Go tools provide text, graph, and callgrind visualization of the profile data using go tool pprof. Read Profiling Go programs to see them in action. Listing of the most expensive calls as text. Visualization of the most expensive calls as a graph. Weblist view displays the expensive parts of the source line by line in an HTML page. In the following example, 530ms is spent in the runtime.concatstrings and cost of each line is presented in the listing. Visualization of the most expensive calls as weblist. Another way to visualize profile data is a flame graph. Flame graphs allow you to move in a specific ancestry path, so you can zoom in/out of specific sections of code. The upstream pprof has support for flame graphs. Flame graphs offers visualization to spot the most expensive code-paths. Am I restricted to the built-in profiles? Additionally to what is provided by the runtime, Go users can create their custom profiles via pprof.Profile and use the existing tools to examine them. Can I serve the profiler handlers (/debug/pprof/...) on a different path and port? Yes. The net/http/pprof package registers its handlers to the default mux by default, but you can also register them yourself by using the handlers exported from the package. For example, the following example will serve the pprof.Profile handler at /custom_debug_path/profile: package main import ( \"log\" \"net/http\" \"net/http/pprof\" ) func main() { mux := http.NewServeMux() mux.HandleFunc(\"/custom_debug_path/profile\", pprof.Profile) log.Fatal(http.ListenAndServe(\":7777\", mux)) } Tracing Tracing is a way to instrument code to analyze latency throughout the lifecycle of a chain of calls. Go provides golang.org/x/net/trace package as a minimal tracing backend per Go node and provides a minimal instrumentation library with a simple dashboard. Go also provides an execution tracer to trace the runtime events within an interval. Tracing enables us and analyze application latency in a Go process. Measure the cost of specific calls in a long chain of calls. Figure out the utilization and performance improvements. Bottlenecks are not always obvious without tracing data. In monolithic systems, it's relatively easy to collect diagnostic data from the building blocks of a program. All modules live within one process and share common resources to report logs, errors, and other diagnostic information. Once your system grows beyond a single process and starts to become distributed, it becomes harder to follow a call starting from the front-end web server to all of its back-ends until a response is returned back to the user. This is where distributed tracing plays a big role to instrument and analyze your production systems. Distributed tracing is a way to instrument code to analyze latency throughout the lifecycle of a user request. When a system is distributed and when conventional profiling and debugging tools don’t scale, you might want to use distributed tracing tools to analyze the performance of your user requests and RPCs. Distributed tracing enables us and profile application latency in a large system. Track all RPCs within the lifecycle of a user request and see integration issues that are only visible in production. Figure out performance improvements that can be applied to our systems. Many bottlenecks are not obvious before the collection of tracing data. The Go ecosystem provides various distributed tracing libraries per tracing system and backend-agnostic ones. Is there a way to automatically intercept each function call and create traces? Go doesn’t provide a way to automatically intercept every function call and create trace spans. You need to manually instrument your code to create, end, and annotate spans. How should I propagate trace headers in Go libraries? You can propagate trace identifiers and tags in the context.Context. There is no canonical trace key or common representation of trace headers in the industry yet. Each tracing provider is responsible for providing propagation utilities in their Go libraries. What other low-level events from the standard library or runtime can be included in a trace? The standard library and runtime are trying to expose several additional APIs to notify on low level internal events. For example, httptrace.ClientTrace provides APIs to follow low-level events in the life cycle of an outgoing request. There is an ongoing effort to retrieve low-level runtime events from the runtime execution tracer and allow users to define and record their user events. Debugging Debugging is the process of identifying why a program misbehaves. Debuggers allow us to understand a program’s execution flow and current state. There are several styles of debugging; this section will only focus on attaching a debugger to a program and core dump debugging. Go users mostly use the following : Delve is a debugger for the Go programming language. It has support for Go’s runtime concepts and built-in types. Delve is trying to be a fully featured reliable debugger for Go programs. provides GDB support via the standard Go compiler and Gccgo. The stack management, threading, and runtime contain aspects that differ enough from the execution model GDB expects that they can confuse the debugger, even when the program is compiled with gccgo. Even though GDB can be used to debug Go programs, it is not ideal and may create confusion. How well do debuggers work with Go programs? The gc compiler performs optimizations such as function inlining and variable registerization. These optimizations sometimes make debugging with debuggers harder. There is an ongoing effort to improve the quality of the DWARF information generated for optimized binaries. Until those improvements are available, we recommend disabling optimizations when building the code being debugged. The following command builds a package with no compiler optimizations: $ go build -gcflags=all=\"-N -l\" As part of the improvement effort, Go 1.10 introduced a new compiler flag -dwarflocationlists. The flag causes the compiler to add location lists that helps debuggers work with optimized binaries. The following command builds a package with optimizations but with the DWARF location lists: $ go build -gcflags=\"-dwarflocationlists=true\" What’s the recommended debugger user interface? Even though both delve and gdb provides CLIs, most editor integrations and IDEs provides debugging-specific user interfaces. Is it possible to do postmortem debugging with Go programs? A core dump file is a file that contains the memory dump of a running process and its process status. It is primarily used for post-mortem debugging of a program and to understand its state while it is still running. These two cases make debugging of core dumps a good diagnostic aid to postmortem and analyze production services. It is possible to obtain core files from Go programs and use delve or gdb to debug, see the core dump debugging page for a step-by-step guide. Runtime statistics and events The runtime provides stats and reporting of internal events for users to diagnose performance and utilization problems at the runtime level. Users can monitor these stats to better understand the overall health and performance of Go programs. Some frequently monitored stats and reports the metrics related to heap allocation and garbage collection. Memory stats are useful for monitoring how much memory resources a process is consuming, whether the process can utilize memory well, and to catch memory leaks. debug.ReadGCStats reads statistics about garbage collection. It is useful to see how much of the resources are spent on GC pauses. It also reports a timeline of garbage collector pauses and pause time percentiles. debug.Stack returns the current stack trace. Stack trace is useful to see how many goroutines are currently running, what they are doing, and whether they are blocked or not. debug.WriteHeapDump suspends the execution of all goroutines and allows you to dump the heap to a file. A heap dump is a snapshot of a Go process' memory at a given time. It contains all allocated objects as well as goroutines, finalizers, and more. runtime.NumGoroutine returns the number of current goroutines. The value can be monitored to see whether enough goroutines are utilized, or to detect goroutine leaks. Execution tracer Go comes with a runtime execution tracer to capture a wide range of runtime events. Scheduling, syscall, garbage collections, heap size, and other events are collected by runtime and available for visualization by the go tool trace. Execution tracer is a tool to detect latency and utilization problems. You can examine how well the CPU is utilized, and when networking or syscalls are a cause of preemption for the goroutines. Tracer is useful how your goroutines execute. Understand some of the core runtime events such as GC runs. Identify poorly parallelized execution. However, it is not great for identifying hot spots such as analyzing the cause of excessive memory or CPU usage. Use profiling tools instead first to address them. Above, the go tool trace visualization shows the execution started fine, and then it became serialized. It suggests that there might be lock contention for a shared resource that creates a bottleneck. See go tool trace to collect and analyze runtime traces. GODEBUG Runtime also emits events and information if GODEBUG environmental variable is set accordingly. GODEBUG=gctrace=1 prints garbage collector events at each collection, summarizing the amount of memory collected and the length of the pause. GODEBUG=inittrace=1 prints a summary of execution time and memory allocation information for completed package initialization work. GODEBUG=schedtrace=X prints scheduling events every X milliseconds. The GODEBUG environmental variable can be used to disable use of instruction set extensions in the standard library and runtime. GODEBUG=cpu.all=off disables the use of all optional instruction set extensions. GODEBUG=cpu.extension=off disables use of instructions from the specified instruction set extension. extension is the lower case name for the instruction set extension such as sse41 or avx.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\npackage main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/pprof\"\n)\n\nfunc main() {\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/custom_debug_path/profile\", pprof.Profile)\n\tlog.Fatal(http.ListenAndServe(\":7777\", mux))\n}\n```\n\nExample:\n```text\n$ go build -gcflags=all=\"-N -l\"\n```\n\nExample:\n```text\n$ go build -gcflags=\"-dwarflocationlists=true\"\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.488Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":3,"totalLines":32,"estimatedTokens":3626}}31{"id":"doc-writing_web_applications_the_go_programming_lang-e28ea09e","source":"documentation","title":"Writing Web Applications - The Go Programming Language","url":"https://go.dev/doc/articles/wiki/","text":"Documentation /doc/articles/ Writing Web Applications Writing Web Applications Introduction Covered in this a data structure with load and save methods Using the net/http package to build web applications Using the html/template package to process HTML templates Using the regexp package to validate user input Using closures Assumed experience Understanding of basic web technologies (HTTP, HTML) Some UNIX/DOS command-line knowledge Getting Started At present, you need to have a FreeBSD, Linux, macOS, or Windows machine to run Go. We will use $ to represent the command prompt. Install Go (see the Installation Instructions). Make a new directory for this tutorial inside your GOPATH and cd to it: $ mkdir gowiki $ cd gowiki Create a file named wiki.go, open it in your favorite editor, and add the following main import ( \"fmt\" \"os\" ) We import the fmt and os packages from the Go standard library. Later, as we implement additional functionality, we will add more packages to this import declaration. Data Structures Let's start by defining the data structures. A wiki consists of a series of interconnected pages, each of which has a title and a body (the page content). Here, we define Page as a struct with two fields representing the title and body. type Page struct { Title string Body []byte } The type []byte means \"a byte slice\". (See and internals for more on slices.) The Body element is a []byte rather than string because that is the type expected by the io libraries we will use, as you'll see below. The Page struct describes how page data will be stored in memory. But what about persistent storage? We can address that by creating a save method on (p *Page) save() error { filename := p.Title + \".txt\" return os.WriteFile(filename, p.Body, 0600) } This method's signature reads: \"This is a method named save that takes as its receiver p, a pointer to Page . It takes no parameters, and returns a value of type error.\" This method will save the Page's Body to a text file. For simplicity, we will use the Title as the file name. The save method returns an error value because that is the return type of WriteFile (a standard library function that writes a byte slice to a file). The save method returns the error value, to let the application handle it should anything go wrong while writing the file. If all goes well, Page.save() will return nil (the zero-value for pointers, interfaces, and some other types). The octal integer literal 0600, passed as the third parameter to WriteFile, indicates that the file should be created with read-write permissions for the current user only. (See the Unix man page open(2) for details.) In addition to saving pages, we will want to load pages, loadPage(title string) *Page { filename := title + \".txt\" body, _ := os.ReadFile(filename) return &Page{Title: title, } } The function loadPage constructs the file name from the title parameter, reads the file's contents into a new variable body, and returns a pointer to a Page literal constructed with the proper title and body values. Functions can return multiple values. The standard library function os.ReadFile returns []byte and error. In loadPage, error isn't being handled yet; the \"blank identifier\" represented by the underscore (_) symbol is used to throw away the error return value (in essence, assigning the value to nothing). But what happens if ReadFile encounters an error? For example, the file might not exist. We should not ignore such errors. Let's modify the function to return *Page and error. func loadPage(title string) (*Page, error) { filename := title + \".txt\" body, err := os.ReadFile(filename) if err != nil { return nil, err } return &Page{Title: title, }, nil } Callers of this function can now check the second parameter; if it is nil then it has successfully loaded a Page. If not, it will be an error that can be handled by the caller (see the language specification for details). At this point we have a simple data structure and the ability to save to and load from a file. Let's write a main function to test what we've main() { p1 := &Page{Title: \"TestPage\", Body: []byte(\"This is a sample Page.\")} p1.save() p2, _ := loadPage(\"TestPage\") fmt.Println(string(p2.Body)) } After compiling and executing this code, a file named TestPage.txt would be created, containing the contents of p1. The file would then be read into the struct p2, and its Body element printed to the screen. You can compile and run the program like this: $ go build wiki.go $ ./wiki This is a sample Page. (If you're using Windows you must type \"wiki\" without the \"./\" to run the program.) Click here to view the code we've written so far. Introducing the net/http package (an interlude) Here's a full working example of a simple web server: //go:build ignore package main import ( \"fmt\" \"log\" \"net/http\" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, \"Hi there, I love %s!\", r.URL.Path[1:]) } func main() { http.HandleFunc(\"/\", handler) log.Fatal(http.ListenAndServe(\":8080\", nil)) } The main function begins with a call to http.HandleFunc, which tells the http package to handle all requests to the web root (\"/\") with handler. It then calls http.ListenAndServe, specifying that it should listen on port 8080 on any interface (\":8080\"). (Don't worry about its second parameter, nil, for now.) This function will block until the program is terminated. ListenAndServe always returns an error, since it only returns when an unexpected error occurs. In order to log that error we wrap the function call with log.Fatal. The function handler is of the type http.HandlerFunc. It takes an http.ResponseWriter and an http.Request as its arguments. An http.ResponseWriter value assembles the HTTP server's response; by writing to it, we send data to the HTTP client. An http.Request is a data structure that represents the client HTTP request. r.URL.Path is the path component of the request URL. The trailing [1:] means \"create a sub-slice of Path from the 1st character to the end.\" This drops the leading \"/\" from the path name. If you run this program and access the ://localhost:8080/monkeys the program would present a page there, I love monkeys! Using net/http to serve wiki pages To use the net/http package, it must be ( \"fmt\" \"os\" \"log\" \"net/http\" ) Let's create a handler, viewHandler that will allow users to view a wiki page. It will handle URLs prefixed with \"/view/\". func viewHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len(\"/view/\"):] p, _ := loadPage(title) fmt.Fprintf(w, \"<h1>%s</h1><div>%s</div>\", p.Title, p.Body) } Again, note the use of _ to ignore the error return value from loadPage. This is done here for simplicity and generally considered bad practice. We will attend to this later. First, this function extracts the page title from r.URL.Path, the path component of the request URL. The Path is re-sliced with [len(\"/view/\"):] to drop the leading \"/view/\" component of the request path. This is because the path will invariably begin with \"/view/\", which is not part of the page's title. The function then loads the page data, formats the page with a string of simple HTML, and writes it to w, the http.ResponseWriter. To use this handler, we rewrite our main function to initialize http using the viewHandler to handle any requests under the path /view/. func main() { http.HandleFunc(\"/view/\", viewHandler) log.Fatal(http.ListenAndServe(\":8080\", nil)) } Click here to view the code we've written so far. Let's create some page data (as test.txt), compile our code, and try serving a wiki page. Open test.txt file in your editor, and save the string \"Hello world\" (without quotes) in it. $ go build wiki.go $ ./wiki (If you're using Windows you must type \"wiki\" without the \"./\" to run the program.) With this web server running, a visit to http://localhost:8080/view/test should show a page titled \"test\" containing the words \"Hello world\". Editing Pages A wiki is not a wiki without the ability to edit pages. Let's create two new named editHandler to display an 'edit page' form, and the other named saveHandler to save the data entered via the form. First, we add them to main(): func main() { http.HandleFunc(\"/view/\", viewHandler) http.HandleFunc(\"/edit/\", editHandler) http.HandleFunc(\"/save/\", saveHandler) log.Fatal(http.ListenAndServe(\":8080\", nil)) } The function editHandler loads the page (or, if it doesn't exist, create an empty Page struct), and displays an HTML form. func editHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len(\"/edit/\"):] p, err := loadPage(title) if err != nil { p = &Page{Title: title} } fmt.Fprintf(w, \"<h1>Editing %s</h1>\"+ \"<form action=\\\"/save/%s\\\" method=\\\"POST\\\">\"+ \"<textarea name=\\\"body\\\">%s</textarea><br>\"+ \"<input type=\\\"submit\\\" value=\\\"Save\\\">\"+ \"</form>\", p.Title, p.Title, p.Body) } This function will work fine, but all that hard-coded HTML is ugly. Of course, there is a better way. The html/template package The html/template package is part of the Go standard library. We can use html/template to keep the HTML in a separate file, allowing us to change the layout of our edit page without modifying the underlying Go code. First, we must add html/template to the list of imports. We also won't be using fmt anymore, so we have to remove that. import ( \"html/template\" \"os\" \"net/http\" ) Let's create a template file containing the HTML form. Open a new file named edit.html, and add the following lines: <h1>Editing {{.Title}}</h1> <form action=\"/save/{{.Title}}\" method=\"POST\"> <div><textarea name=\"body\" rows=\"20\" cols=\"80\">{{printf \"%s\" .Body}}</textarea></div> <div><input type=\"submit\" value=\"Save\"></div> </form> Modify editHandler to use the template, instead of the hard-coded editHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len(\"/edit/\"):] p, err := loadPage(title) if err != nil { p = &Page{Title: title} } t, _ := template.ParseFiles(\"edit.html\") t.Execute(w, p) } The function template.ParseFiles will read the contents of edit.html and return a *template.Template. The method t.Execute executes the template, writing the generated HTML to the http.ResponseWriter. The </h1> <p>[<a href=\"/edit/{{.Title}}\">edit</a>]</p> <div>{{printf \"%s\" Notice that we've used almost exactly the same templating code in both handlers. Let's remove this duplication by moving the templating code to its own renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { t, _ := template.ParseFiles(tmpl + \".html\") t.Execute(w, p) } And modify the handlers to use that viewHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len(\"/view/\"):] p, _ := loadPage(title) renderTemplate(w, \"view\", p) } func editHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len(\"/edit/\"):] p, err := loadPage(title) if err != nil { p = &Page{Title: title} } renderTemplate(w, \"edit\", p) } If we comment out the registration of our unimplemented save handler in main, we can once again build and test our program. Click here to view the code we've written so far. Handling non-existent pages What if you visit /view/APageThatDoesntExist? You'll see a page containing HTML. This is because it ignores the error return value from loadPage and continues to try and fill out the template with no data. Instead, if the requested Page doesn't exist, it should redirect the client to the edit Page so the content may be viewHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len(\"/view/\"):] p, err := loadPage(title) if err != nil { http.Redirect(w, r, \"/edit/\"+title, http.StatusFound) return } renderTemplate(w, \"view\", p) } The http.Redirect function adds an HTTP status code of http.StatusFound (302) and a Location header to the HTTP response. Saving Pages The function saveHandler will handle the submission of forms located on the edit pages. After uncommenting the related line in main, let's implement the saveHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len(\"/save/\"):] body := r.FormValue(\"body\") p := &Page{Title: title, Body: []byte(body)} p.save() http.Redirect(w, r, \"/view/\"+title, http.StatusFound) } The page title (provided in the URL) and the form's only field, Body, are stored in a new Page. The save() method is then called to write the data to a file, and the client is redirected to the /view/ page. The value returned by FormValue is of type string. We must convert that value to []byte before it will fit into the Page struct. We use []byte(body) to perform the conversion. Error handling There are several places in our program where errors are being ignored. This is bad practice, not least because when an error does occur the program will have unintended behavior. A better solution is to handle the errors and return an error message to the user. That way if something does go wrong, the server will function exactly how we want and the user can be notified. First, let's handle the errors in renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { t, err := template.ParseFiles(tmpl + \".html\") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } err = t.Execute(w, p) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } The http.Error function sends a specified HTTP response code (in this case \"Internal Server Error\") and error message. Already the decision to put this in a separate function is paying off. Now let's fix up saveHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len(\"/save/\"):] body := r.FormValue(\"body\") p := &Page{Title: title, Body: []byte(body)} err := p.save() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, \"/view/\"+title, http.StatusFound) } Any errors that occur during p.save() will be reported to the user. Template caching There is an inefficiency in this calls ParseFiles every time a page is rendered. A better approach would be to call ParseFiles once at program initialization, parsing all templates into a single *Template. Then we can use the ExecuteTemplate method to render a specific template. First we create a global variable named templates, and initialize it with ParseFiles. var templates = template.Must(template.ParseFiles(\"edit.html\", \"view.html\")) The function template.Must is a convenience wrapper that panics when passed a non-nil error value, and otherwise returns the *Template unaltered. A panic is appropriate here; if the templates can't be loaded the only sensible thing to do is exit the program. The ParseFiles function takes any number of string arguments that identify our template files, and parses those files into templates that are named after the base file name. If we were to add more templates to our program, we would add their names to the ParseFiles call's arguments. We then modify the renderTemplate function to call the templates.ExecuteTemplate method with the name of the appropriate renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { err := templates.ExecuteTemplate(w, tmpl+\".html\", p) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } Note that the template name is the template file name, so we must append \".html\" to the tmpl argument. Validation As you may have observed, this program has a serious security user can supply an arbitrary path to be read/written on the server. To mitigate this, we can write a function to validate the title with a regular expression. First, add \"regexp\" to the import list. Then we can create a global variable to store our validation validPath = regexp.MustCompile(\"^/(edit|save|view)/([a-zA-Z0-9]+)$\") The function regexp.MustCompile will parse and compile the regular expression, and return a regexp.Regexp. MustCompile is distinct from Compile in that it will panic if the expression compilation fails, while Compile returns an error as a second parameter. Now, let's write a function that uses the validPath expression to validate path and extract the page getTitle(w http.ResponseWriter, r *http.Request) (string, error) { m := validPath.FindStringSubmatch(r.URL.Path) if m == nil { http.NotFound(w, r) return \"\", errors.New(\"invalid Page Title\") } return m[2], nil // The title is the second subexpression. } If the title is valid, it will be returned along with a nil error value. If the title is invalid, the function will write a \"404 Not Found\" error to the HTTP connection, and return an error to the handler. To create a new error, we have to import the errors package. Let's put a call to getTitle in each of the viewHandler(w http.ResponseWriter, r *http.Request) { title, err := getTitle(w, r) if err != nil { return } p, err := loadPage(title) if err != nil { http.Redirect(w, r, \"/edit/\"+title, http.StatusFound) return } renderTemplate(w, \"view\", p) } func editHandler(w http.ResponseWriter, r *http.Request) { title, err := getTitle(w, r) if err != nil { return } p, err := loadPage(title) if err != nil { p = &Page{Title: title} } renderTemplate(w, \"edit\", p) } func saveHandler(w http.ResponseWriter, r *http.Request) { title, err := getTitle(w, r) if err != nil { return } body := r.FormValue(\"body\") p := &Page{Title: title, Body: []byte(body)} err = p.save() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, \"/view/\"+title, http.StatusFound) } Introducing Function Literals and Closures Catching the error condition in each handler introduces a lot of repeated code. What if we could wrap each of the handlers in a function that does this validation and error checking? Go's function literals provide a powerful means of abstracting functionality that can help us here. First, we re-write the function definition of each of the handlers to accept a title viewHandler(w http.ResponseWriter, r *http.Request, title string) func editHandler(w http.ResponseWriter, r *http.Request, title string) func saveHandler(w http.ResponseWriter, r *http.Request, title string) Now let's define a wrapper function that takes a function of the above type, and returns a function of type http.HandlerFunc (suitable to be passed to the function http.HandleFunc): func makeHandler(fn func (http.ResponseWriter, *http.Request, string)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Here we will extract the page title from the Request, // and call the provided handler 'fn' } } The returned function is called a closure because it encloses values defined outside of it. In this case, the variable fn (the single argument to makeHandler) is enclosed by the closure. The variable fn will be one of our save, edit, or view handlers. Now we can take the code from getTitle and use it here (with some minor modifications): func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { m := validPath.FindStringSubmatch(r.URL.Path) if m == nil { http.NotFound(w, r) return } fn(w, r, m[2]) } } The closure returned by makeHandler is a function that takes an http.ResponseWriter and http.Request (in other words, an http.HandlerFunc). The closure extracts the title from the request path, and validates it with the validPath regexp. If the title is invalid, an error will be written to the ResponseWriter using the http.NotFound function. If the title is valid, the enclosed handler function fn will be called with the ResponseWriter, Request, and title as arguments. Now we can wrap the handler functions with makeHandler in main, before they are registered with the http main() { http.HandleFunc(\"/view/\", makeHandler(viewHandler)) http.HandleFunc(\"/edit/\", makeHandler(editHandler)) http.HandleFunc(\"/save/\", makeHandler(saveHandler)) log.Fatal(http.ListenAndServe(\":8080\", nil)) } Finally we remove the calls to getTitle from the handler functions, making them much viewHandler(w http.ResponseWriter, r *http.Request, title string) { p, err := loadPage(title) if err != nil { http.Redirect(w, r, \"/edit/\"+title, http.StatusFound) return } renderTemplate(w, \"view\", p) } func editHandler(w http.ResponseWriter, r *http.Request, title string) { p, err := loadPage(title) if err != nil { p = &Page{Title: title} } renderTemplate(w, \"edit\", p) } func saveHandler(w http.ResponseWriter, r *http.Request, title string) { body := r.FormValue(\"body\") p := &Page{Title: title, Body: []byte(body)} err := p.save() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, \"/view/\"+title, http.StatusFound) } Try it out! Click here to view the final code listing. Recompile the code, and run the app: $ go build wiki.go $ ./wiki Visiting http://localhost:8080/view/ANewPage should present you with the page edit form. You should then be able to enter some text, click 'Save', and be redirected to the newly created page. Other tasks Here are some simple tasks you might want to tackle on your templates in tmpl/ and page data in data/. Add a handler to make the web root redirect to /view/FrontPage. Spruce up the page templates by making them valid HTML and adding some CSS rules. Implement inter-page linking by converting instances of [PageName] to <a href=\"/view/PageName\">PageName</a>. (hint: you could use regexp.ReplaceAllFunc to do this)\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ mkdir gowiki\n$ cd gowiki\n```\n\nExample:\n```text\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n```\n\nExample:\n```text\ntype Page struct {\n    Title string\n    Body  []byte\n}\n```\n\nExample:\n```text\nfunc (p *Page) save() error {\n    filename := p.Title + \".txt\"\n    return os.WriteFile(filename, p.Body, 0600)\n}\n```\n\nExample:\n```text\nfunc loadPage(title string) *Page {\n    filename := title + \".txt\"\n    body, _ := os.ReadFile(filename)\n    return &Page{Title: title, Body: body}\n}\n```\n\nExample:\n```text\nfunc loadPage(title string) (*Page, error) {\n    filename := title + \".txt\"\n    body, err := os.ReadFile(filename)\n    if err != nil {\n        return nil, err\n    }\n    return &Page{Title: title, Body: body}, nil\n}\n```\n\nExample:\n```text\nfunc main() {\n    p1 := &Page{Title: \"TestPage\", Body: []byte(\"This is a sample Page.\")}\n    p1.save()\n    p2, _ := loadPage(\"TestPage\")\n    fmt.Println(string(p2.Body))\n}\n```\n\nExample:\n```text\n$ go build wiki.go\n$ ./wiki\nThis is a sample Page.\n```\n\nExample:\n```text\n//go:build ignore\n\npackage main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"net/http\"\n)\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n    fmt.Fprintf(w, \"Hi there, I love %s!\", r.URL.Path[1:])\n}\n\nfunc main() {\n    http.HandleFunc(\"/\", handler)\n    log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\nExample:\n```text\nhttp://localhost:8080/monkeys\n```\n\nExample:\n```text\nHi there, I love monkeys!\n```\n\nExample:\n```text\nimport (\n    \"fmt\"\n    \"os\"\n    \"log\"\n    \"net/http\"\n)\n```\n\nExample:\n```text\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n    title := r.URL.Path[len(\"/view/\"):]\n    p, _ := loadPage(title)\n    fmt.Fprintf(w, \"<h1>%s</h1><div>%s</div>\", p.Title, p.Body)\n}\n```\n\nExample:\n```text\nfunc main() {\n    http.HandleFunc(\"/view/\", viewHandler)\n    log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\nExample:\n```text\n$ go build wiki.go\n$ ./wiki\n```\n\nExample:\n```text\nfunc main() {\n    http.HandleFunc(\"/view/\", viewHandler)\n    http.HandleFunc(\"/edit/\", editHandler)\n    http.HandleFunc(\"/save/\", saveHandler)\n    log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\nExample:\n```text\nfunc editHandler(w http.ResponseWriter, r *http.Request) {\n    title := r.URL.Path[len(\"/edit/\"):]\n    p, err := loadPage(title)\n    if err != nil {\n        p = &Page{Title: title}\n    }\n    fmt.Fprintf(w, \"<h1>Editing %s</h1>\"+\n        \"<form action=\\\"/save/%s\\\" method=\\\"POST\\\">\"+\n        \"<textarea name=\\\"body\\\">%s</textarea><br>\"+\n        \"<input type=\\\"submit\\\" value=\\\"Save\\\">\"+\n        \"</form>\",\n        p.Title, p.Title, p.Body)\n}\n```\n\nExample:\n```text\nimport (\n    \"html/template\"\n    \"os\"\n    \"net/http\"\n)\n```\n\nExample:\n```text\n<h1>Editing {{.Title}}</h1>\n\n<form action=\"/save/{{.Title}}\" method=\"POST\">\n<div><textarea name=\"body\" rows=\"20\" cols=\"80\">{{printf \"%s\" .Body}}</textarea></div>\n<div><input type=\"submit\" value=\"Save\"></div>\n</form>\n```\n\nExample:\n```text\nfunc editHandler(w http.ResponseWriter, r *http.Request) {\n    title := r.URL.Path[len(\"/edit/\"):]\n    p, err := loadPage(title)\n    if err != nil {\n        p = &Page{Title: title}\n    }\n    t, _ := template.ParseFiles(\"edit.html\")\n    t.Execute(w, p)\n}\n```\n\nExample:\n```text\n<h1>{{.Title}}</h1>\n\n<p>[<a href=\"/edit/{{.Title}}\">edit</a>]</p>\n\n<div>{{printf \"%s\" .Body}}</div>\n```\n\nExample:\n```text\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n    title := r.URL.Path[len(\"/view/\"):]\n    p, _ := loadPage(title)\n    t, _ := template.ParseFiles(\"view.html\")\n    t.Execute(w, p)\n}\n```\n\nExample:\n```text\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {\n    t, _ := template.ParseFiles(tmpl + \".html\")\n    t.Execute(w, p)\n}\n```\n\nExample:\n```text\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n    title := r.URL.Path[len(\"/view/\"):]\n    p, _ := loadPage(title)\n    renderTemplate(w, \"view\", p)\n}\n```\n\nExample:\n```text\nfunc editHandler(w http.ResponseWriter, r *http.Request) {\n    title := r.URL.Path[len(\"/edit/\"):]\n    p, err := loadPage(title)\n    if err != nil {\n        p = &Page{Title: title}\n    }\n    renderTemplate(w, \"edit\", p)\n}\n```\n\nExample:\n```text\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n    title := r.URL.Path[len(\"/view/\"):]\n    p, err := loadPage(title)\n    if err != nil {\n        http.Redirect(w, r, \"/edit/\"+title, http.StatusFound)\n        return\n    }\n    renderTemplate(w, \"view\", p)\n}\n```\n\nExample:\n```text\nfunc saveHandler(w http.ResponseWriter, r *http.Request) {\n    title := r.URL.Path[len(\"/save/\"):]\n    body := r.FormValue(\"body\")\n    p := &Page{Title: title, Body: []byte(body)}\n    p.save()\n    http.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}\n```\n\nExample:\n```text\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {\n    t, err := template.ParseFiles(tmpl + \".html\")\n    if err != nil {\n        http.Error(w, err.Error(), http.StatusInternalServerError)\n        return\n    }\n    err = t.Execute(w, p)\n    if err != nil {\n        http.Error(w, err.Error(), http.StatusInternalServerError)\n    }\n}\n```\n\nExample:\n```text\nfunc saveHandler(w http.ResponseWriter, r *http.Request) {\n    title := r.URL.Path[len(\"/save/\"):]\n    body := r.FormValue(\"body\")\n    p := &Page{Title: title, Body: []byte(body)}\n    err := p.save()\n    if err != nil {\n        http.Error(w, err.Error(), http.StatusInternalServerError)\n        return\n    }\n    http.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}\n```\n\nExample:\n```text\nvar templates = template.Must(template.ParseFiles(\"edit.html\", \"view.html\"))\n```\n\nExample:\n```text\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {\n    err := templates.ExecuteTemplate(w, tmpl+\".html\", p)\n    if err != nil {\n        http.Error(w, err.Error(), http.StatusInternalServerError)\n    }\n}\n```\n\nExample:\n```text\nvar validPath = regexp.MustCompile(\"^/(edit|save|view)/([a-zA-Z0-9]+)$\")\n```\n\nExample:\n```text\nfunc getTitle(w http.ResponseWriter, r *http.Request) (string, error) {\n    m := validPath.FindStringSubmatch(r.URL.Path)\n    if m == nil {\n        http.NotFound(w, r)\n        return \"\", errors.New(\"invalid Page Title\")\n    }\n    return m[2], nil // The title is the second subexpression.\n}\n```\n\nExample:\n```text\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n    title, err := getTitle(w, r)\n    if err != nil {\n        return\n    }\n    p, err := loadPage(title)\n    if err != nil {\n        http.Redirect(w, r, \"/edit/\"+title, http.StatusFound)\n        return\n    }\n    renderTemplate(w, \"view\", p)\n}\n```\n\nExample:\n```text\nfunc editHandler(w http.ResponseWriter, r *http.Request) {\n    title, err := getTitle(w, r)\n    if err != nil {\n        return\n    }\n    p, err := loadPage(title)\n    if err != nil {\n        p = &Page{Title: title}\n    }\n    renderTemplate(w, \"edit\", p)\n}\n```\n\nExample:\n```text\nfunc saveHandler(w http.ResponseWriter, r *http.Request) {\n    title, err := getTitle(w, r)\n    if err != nil {\n        return\n    }\n    body := r.FormValue(\"body\")\n    p := &Page{Title: title, Body: []byte(body)}\n    err = p.save()\n    if err != nil {\n        http.Error(w, err.Error(), http.StatusInternalServerError)\n        return\n    }\n    http.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}\n```\n\nExample:\n```text\nfunc viewHandler(w http.ResponseWriter, r *http.Request, title string)\nfunc editHandler(w http.ResponseWriter, r *http.Request, title string)\nfunc saveHandler(w http.ResponseWriter, r *http.Request, title string)\n```\n\nExample:\n```text\nfunc makeHandler(fn func (http.ResponseWriter, *http.Request, string)) http.HandlerFunc {\n    return func(w http.ResponseWriter, r *http.Request) {\n        // Here we will extract the page title from the Request,\n        // and call the provided handler 'fn'\n    }\n}\n```\n\nExample:\n```text\nfunc makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {\n    return func(w http.ResponseWriter, r *http.Request) {\n        m := validPath.FindStringSubmatch(r.URL.Path)\n        if m == nil {\n            http.NotFound(w, r)\n            return\n        }\n        fn(w, r, m[2])\n    }\n}\n```\n\nExample:\n```text\nfunc main() {\n    http.HandleFunc(\"/view/\", makeHandler(viewHandler))\n    http.HandleFunc(\"/edit/\", makeHandler(editHandler))\n    http.HandleFunc(\"/save/\", makeHandler(saveHandler))\n\n    log.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\nExample:\n```text\nfunc viewHandler(w http.ResponseWriter, r *http.Request, title string) {\n    p, err := loadPage(title)\n    if err != nil {\n        http.Redirect(w, r, \"/edit/\"+title, http.StatusFound)\n        return\n    }\n    renderTemplate(w, \"view\", p)\n}\n```\n\nExample:\n```text\nfunc editHandler(w http.ResponseWriter, r *http.Request, title string) {\n    p, err := loadPage(title)\n    if err != nil {\n        p = &Page{Title: title}\n    }\n    renderTemplate(w, \"edit\", p)\n}\n```\n\nExample:\n```text\nfunc saveHandler(w http.ResponseWriter, r *http.Request, title string) {\n    body := r.FormValue(\"body\")\n    p := &Page{Title: title, Body: []byte(body)}\n    err := p.save()\n    if err != nil {\n        http.Error(w, err.Error(), http.StatusInternalServerError)\n        return\n    }\n    http.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.491Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":43,"totalLines":461,"estimatedTokens":7653}}32{"id":"doc-tutorial_developing_a_restful_api_with_go_and_gi-c24f45fd","source":"documentation","title":"Tutorial: Developing a RESTful API with Go and Gin - The Go Programming Language","url":"https://go.dev/doc/tutorial/web-service-gin.html","text":"Documentation Tutorials a RESTful API with Go and Gin a RESTful API with Go and Gin This tutorial introduces the basics of writing a RESTful web service API with Go and the Gin Web Framework (Gin). You’ll get the most out of this tutorial if you have a basic familiarity with Go and its tooling. If this is your first exposure to Go, please see started with Go for a quick introduction. Gin simplifies many coding tasks associated with building web applications, including web services. In this tutorial, you’ll use Gin to route requests, retrieve request details, and marshal JSON for responses. In this tutorial, you will build a RESTful API server with two endpoints. Your example project will be a repository of data about vintage jazz records. The tutorial includes the following API endpoints. Create a folder for your code. Create the data. Write a handler to return all items. Write a handler to add a new item. Write a handler to return a specific item. other tutorials, see Tutorials. To try this as an interactive tutorial you complete in Google Cloud Shell, click the button below. Prerequisites Go. We recommend using the latest version of Go to follow this tutorial. For installation instructions, see Installing Go. A tool to edit your code. Any text editor you have will work fine. A command terminal. Go works well using any terminal on Linux and Mac, and on PowerShell or cmd in Windows. The curl tool. On Linux and Mac, this should already be installed. On Windows, it’s included on Windows 10 Insider build 17063 and later. For earlier Windows versions, you might need to install it. For more, see Tar and Curl Come to Windows. Design API endpoints You’ll build an API that provides access to a store selling vintage recordings on vinyl. So you’ll need to provide endpoints through which a client can get and add albums for users. When developing an API, you typically begin by designing the endpoints. Your API’s users will have more success if the endpoints are easy to understand. Here are the endpoints you’ll create in this tutorial. /albums GET – Get a list of all albums, returned as JSON. POST – Add a new album from request data sent as JSON. /albums/:id GET – Get an album by its ID, returning the album data as JSON. Next, you’ll create a folder for your code. Create a folder for your code To begin, create a project for the code you’ll write. Open a command prompt and change to your home directory. On Linux or Mac: $ cd On :\\> cd %HOMEPATH% Using the command prompt, create a directory for your code called web-service-gin. $ mkdir web-service-gin $ cd web-service-gin Create a module in which you can manage dependencies. Run the go mod init command, giving it the path of the module your code will be in. $ go mod init example/web-service-gin new go.mod: module example/web-service-gin This command creates a go.mod file in which dependencies you add will be listed for tracking. For more about naming a module with a module path, see Managing dependencies. Next, you’ll design data structures for handling data. Create the data To keep things simple for the tutorial, you’ll store data in memory. A more typical API would interact with a database. Note that storing data in memory means that the set of albums will be lost each time you stop the server, then recreated when you start it. Write the code Using your text editor, create a file called main.go in the web-service directory. You’ll write your Go code in this file. Into main.go, at the top of the file, paste the following package declaration. package main A standalone program (as opposed to a library) is always in package main. Beneath the package declaration, paste the following declaration of an album struct. You’ll use this to store album data in memory. Struct tags such as json:\"artist\" specify what a field’s name should be when the struct’s contents are serialized into JSON. Without them, the JSON would use the struct’s capitalized field names – a style not as common in JSON. // album represents data about a record album. type album struct { ID string `json:\"id\"` Title string `json:\"title\"` Artist string `json:\"artist\"` Price float64 `json:\"price\"` } Beneath the struct declaration you just added, paste the following slice of album structs containing data you’ll use to start. // albums slice to seed record album data. var albums = []album{ {ID: \"1\", Title: \"Blue Train\", Artist: \"John Coltrane\", }, {ID: \"2\", Title: \"Jeru\", Artist: \"Gerry Mulligan\", }, {ID: \"3\", Title: \"Sarah Vaughan and Clifford Brown\", Artist: \"Sarah Vaughan\", }, } Next, you’ll write code to implement your first endpoint. Write a handler to return all items When the client makes a request at GET /albums, you want to return all the albums as JSON. To do this, you’ll write the to prepare a response Code to map the request path to your logic Note that this is the reverse of how they’ll be executed at runtime, but you’re adding dependencies first, then the code that depends on them. Write the code Beneath the struct code you added in the preceding section, paste the following code to get the album list. This getAlbums function creates JSON from the slice of album structs, writing the JSON into the response. // getAlbums responds with the list of all albums as JSON. func getAlbums(c *gin.Context) { c.IndentedJSON(http.StatusOK, albums) } In this code, a getAlbums function that takes a gin.Context parameter. Note that you could have given this function any name – neither Gin nor Go require a particular function name format. gin.Context is the most important part of Gin. It carries request details, validates and serializes JSON, and more. (Despite the similar name, this is different from Go’s built-in context package.) Call Context.IndentedJSON to serialize the struct into JSON and add it to the response. The function’s first argument is the HTTP status code you want to send to the client. Here, you’re passing the StatusOK constant from the net/http package to indicate 200 OK. Note that you can replace Context.IndentedJSON with a call to Context.JSON to send more compact JSON. In practice, the indented form is much easier to work with when debugging and the size difference is usually small. Near the top of main.go, just beneath the albums slice declaration, paste the code below to assign the handler function to an endpoint path. This sets up an association in which getAlbums handles requests to the /albums endpoint path. func main() { router := gin.Default() router.GET(\"/albums\", getAlbums) router.Run(\"localhost:8080\") } In this code, a Gin router using Default. Use the GET function to associate the GET HTTP method and /albums path with a handler function. Note that you’re passing the name of the getAlbums function. This is different from passing the result of the function, which you would do by passing getAlbums() (note the parenthesis). Use the Run function to attach the router to an http.Server and start the server. Near the top of main.go, just beneath the package declaration, import the packages you’ll need to support the code you’ve just written. The first lines of code should look like main import ( \"net/http\" \"github.com/gin-gonic/gin\" ) Save main.go. Run the code Begin tracking the Gin module as a dependency. At the command line, use go get to add the github.com/gin-gonic/gin module as a dependency for your module. Use a dot argument to mean “get dependencies for code in the current directory.” $ go get . go github.com/gin-gonic/gin v1.7.2 Go resolved and downloaded this dependency to satisfy the import declaration you added in the previous step. From the command line in the directory containing main.go, run the code. Use a dot argument to mean “run code in the current directory.” $ go run . Once the code is running, you have a running HTTP server to which you can send requests. From a new command line window, use curl to make a request to your running web service. $ curl http://localhost:8080/albums The command should display the data you seeded the service with. [ { \"id\": \"1\", \"title\": \"Blue Train\", \"artist\": \"John Coltrane\", \"price\": 56.99 }, { \"id\": \"2\", \"title\": \"Jeru\", \"artist\": \"Gerry Mulligan\", \"price\": 17.99 }, { \"id\": \"3\", \"title\": \"Sarah Vaughan and Clifford Brown\", \"artist\": \"Sarah Vaughan\", \"price\": 39.99 } ] You’ve started an API! In the next section, you’ll create another endpoint with code to handle a POST request to add an item. Write a handler to add a new item When the client makes a POST request at /albums, you want to add the album described in the request body to the existing albums’ data. To do this, you’ll write the to add the new album to the existing list. A bit of code to route the POST request to your logic. Write the code Add code to add albums data to the list of albums. Somewhere after the import statements, paste the following code. (The end of the file is a good place for this code, but Go doesn’t enforce the order in which you declare functions.) // postAlbums adds an album from JSON received in the request body. func postAlbums(c *gin.Context) { var newAlbum album // Call BindJSON to bind the received JSON to // newAlbum. if err := c.BindJSON(&newAlbum); err != nil { return } // Add the new album to the slice. albums = append(albums, newAlbum) c.IndentedJSON(http.StatusCreated, newAlbum) } In this code, Context.BindJSON to bind the request body to newAlbum. Append the album struct initialized from the JSON to the albums slice. Add a 201 status code to the response, along with JSON representing the album you added. Change your main function so that it includes the router.POST function, as in the following. func main() { router := gin.Default() router.GET(\"/albums\", getAlbums) router.POST(\"/albums\", postAlbums) router.Run(\"localhost:8080\") } In this code, the POST method at the /albums path with the postAlbums function. With Gin, you can associate a handler with an HTTP method-and-path combination. In this way, you can separately route requests sent to a single path based on the method the client is using. Run the code If the server is still running from the last section, stop it. From the command line in the directory containing main.go, run the code. $ go run . From a different command line window, use curl to make a request to your running web service. $ curl http://localhost:8080/albums \\ --include \\ --header \"Content-Type: application/json\" \\ --request \"POST\" \\ --data '{\"id\": \"4\",\"title\": \"The Modern Sound of Betty Carter\",\"artist\": \"Betty Carter\",\"price\": 49.99}' The command should display headers and JSON for the added album. HTTP/1.1 201 Created /json; charset=utf-8 , 02 Jun 2021 :12 GMT { \"id\": \"4\", \"title\": \"The Modern Sound of Betty Carter\", \"artist\": \"Betty Carter\", \"price\": 49.99 } As in the previous section, use curl to retrieve the full list of albums, which you can use to confirm that the new album was added. $ curl http://localhost:8080/albums \\ --header \"Content-Type: application/json\" \\ --request \"GET\" The command should display the album list. [ { \"id\": \"1\", \"title\": \"Blue Train\", \"artist\": \"John Coltrane\", \"price\": 56.99 }, { \"id\": \"2\", \"title\": \"Jeru\", \"artist\": \"Gerry Mulligan\", \"price\": 17.99 }, { \"id\": \"3\", \"title\": \"Sarah Vaughan and Clifford Brown\", \"artist\": \"Sarah Vaughan\", \"price\": 39.99 }, { \"id\": \"4\", \"title\": \"The Modern Sound of Betty Carter\", \"artist\": \"Betty Carter\", \"price\": 49.99 } ] In the next section, you’ll add code to handle a GET for a specific item. Write a handler to return a specific item When the client makes a request to GET /albums/[id], you want to return the album whose ID matches the id path parameter. To do this, you logic to retrieve the requested album. Map the path to the logic. Write the code Beneath the postAlbums function you added in the preceding section, paste the following code to retrieve a specific album. This getAlbumByID function will extract the ID in the request path, then locate an album that matches. // getAlbumByID locates the album whose ID value matches the id // parameter sent by the client, then returns that album as a response. func getAlbumByID(c *gin.Context) { id := c.Param(\"id\") // Loop over the list of albums, looking for // an album whose ID value matches the parameter. for _, a := range albums { if a.ID == id { c.IndentedJSON(http.StatusOK, a) return } } c.IndentedJSON(http.StatusNotFound, gin.H{\"message\": \"album not found\"}) } In this code, Context.Param to retrieve the id path parameter from the URL. When you map this handler to a path, you’ll include a placeholder for the parameter in the path. Loop over the album structs in the slice, looking for one whose ID field value matches the id parameter value. If it’s found, you serialize that album struct to JSON and return it as a response with a 200 OK HTTP code. As mentioned above, a real-world service would likely use a database query to perform this lookup. Return an HTTP 404 error with http.StatusNotFound if the album isn’t found. Finally, change your main so that it includes a new call to router.GET, where the path is now /albums/:id, as shown in the following example. func main() { router := gin.Default() router.GET(\"/albums\", getAlbums) router.GET(\"/albums/:id\", getAlbumByID) router.POST(\"/albums\", postAlbums) router.Run(\"localhost:8080\") } In this code, the /albums/:id path with the getAlbumByID function. In Gin, the colon preceding an item in the path signifies that the item is a path parameter. Run the code If the server is still running from the last section, stop it. From the command line in the directory containing main.go, run the code to start the server. $ go run . From a different command line window, use curl to make a request to your running web service. $ curl http://localhost:8080/albums/2 The command should display JSON for the album whose ID you used. If the album wasn’t found, you’ll get JSON with an error message. { \"id\": \"2\", \"title\": \"Jeru\", \"artist\": \"Gerry Mulligan\", \"price\": 17.99 } Conclusion Congratulations! You’ve just used Go and Gin to write a simple RESTful web service. Suggested next you’re new to Go, you’ll find useful best practices described in Effective Go and How to write Go code. The Go Tour is a great step-by-step introduction to Go fundamentals. For more about Gin, see the Gin Web Framework package documentation or the Gin Web Framework docs. Completed code This section contains the code for the application you build with this tutorial. package main import ( \"net/http\" \"github.com/gin-gonic/gin\" ) // album represents data about a record album. type album struct { ID string `json:\"id\"` Title string `json:\"title\"` Artist string `json:\"artist\"` Price float64 `json:\"price\"` } // albums slice to seed record album data. var albums = []album{ {ID: \"1\", Title: \"Blue Train\", Artist: \"John Coltrane\", }, {ID: \"2\", Title: \"Jeru\", Artist: \"Gerry Mulligan\", }, {ID: \"3\", Title: \"Sarah Vaughan and Clifford Brown\", Artist: \"Sarah Vaughan\", }, } func main() { router := gin.Default() router.GET(\"/albums\", getAlbums) router.GET(\"/albums/:id\", getAlbumByID) router.POST(\"/albums\", postAlbums) router.Run(\"localhost:8080\") } // getAlbums responds with the list of all albums as JSON. func getAlbums(c *gin.Context) { c.IndentedJSON(http.StatusOK, albums) } // postAlbums adds an album from JSON received in the request body. func postAlbums(c *gin.Context) { var newAlbum album // Call BindJSON to bind the received JSON to // newAlbum. if err := c.BindJSON(&newAlbum); err != nil { return } // Add the new album to the slice. albums = append(albums, newAlbum) c.IndentedJSON(http.StatusCreated, newAlbum) } // getAlbumByID locates the album whose ID value matches the id // parameter sent by the client, then returns that album as a response. func getAlbumByID(c *gin.Context) { id := c.Param(\"id\") // Loop through the list of albums, looking for // an album whose ID value matches the parameter. for _, a := range albums { if a.ID == id { c.IndentedJSON(http.StatusOK, a) return } } c.IndentedJSON(http.StatusNotFound, gin.H{\"message\": \"album not found\"}) }\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ cd\n```\n\nExample:\n```text\nC:\\> cd %HOMEPATH%\n```\n\nExample:\n```text\n$ mkdir web-service-gin\n$ cd web-service-gin\n```\n\nExample:\n```text\n$ go mod init example/web-service-gin\ngo: creating new go.mod: module example/web-service-gin\n```\n\nExample:\n```text\npackage main\n```\n\nExample:\n```text\n// album represents data about a record album.\ntype album struct {\n    ID     string  `json:\"id\"`\n    Title  string  `json:\"title\"`\n    Artist string  `json:\"artist\"`\n    Price  float64 `json:\"price\"`\n}\n```\n\nExample:\n```text\n// albums slice to seed record album data.\nvar albums = []album{\n    {ID: \"1\", Title: \"Blue Train\", Artist: \"John Coltrane\", Price: 56.99},\n    {ID: \"2\", Title: \"Jeru\", Artist: \"Gerry Mulligan\", Price: 17.99},\n    {ID: \"3\", Title: \"Sarah Vaughan and Clifford Brown\", Artist: \"Sarah Vaughan\", Price: 39.99},\n}\n```\n\nExample:\n```text\n// getAlbums responds with the list of all albums as JSON.\nfunc getAlbums(c *gin.Context) {\n    c.IndentedJSON(http.StatusOK, albums)\n}\n```\n\nExample:\n```text\nfunc main() {\n    router := gin.Default()\n    router.GET(\"/albums\", getAlbums)\n\n    router.Run(\"localhost:8080\")\n}\n```\n\nExample:\n```text\npackage main\n\nimport (\n    \"net/http\"\n\n    \"github.com/gin-gonic/gin\"\n)\n```\n\nExample:\n```text\n$ go get .\ngo get: added github.com/gin-gonic/gin v1.7.2\n```\n\nExample:\n```text\n$ go run .\n```\n\nExample:\n```text\n$ curl http://localhost:8080/albums\n```\n\nExample:\n```text\n[\n        {\n                \"id\": \"1\",\n                \"title\": \"Blue Train\",\n                \"artist\": \"John Coltrane\",\n                \"price\": 56.99\n        },\n        {\n                \"id\": \"2\",\n                \"title\": \"Jeru\",\n                \"artist\": \"Gerry Mulligan\",\n                \"price\": 17.99\n        },\n        {\n                \"id\": \"3\",\n                \"title\": \"Sarah Vaughan and Clifford Brown\",\n                \"artist\": \"Sarah Vaughan\",\n                \"price\": 39.99\n        }\n]\n```\n\nExample:\n```text\n// postAlbums adds an album from JSON received in the request body.\nfunc postAlbums(c *gin.Context) {\n    var newAlbum album\n\n    // Call BindJSON to bind the received JSON to\n    // newAlbum.\n    if err := c.BindJSON(&newAlbum); err != nil {\n        return\n    }\n\n    // Add the new album to the slice.\n    albums = append(albums, newAlbum)\n    c.IndentedJSON(http.StatusCreated, newAlbum)\n}\n```\n\nExample:\n```text\nfunc main() {\n    router := gin.Default()\n    router.GET(\"/albums\", getAlbums)\n    router.POST(\"/albums\", postAlbums)\n\n    router.Run(\"localhost:8080\")\n}\n```\n\nExample:\n```text\n$ curl http://localhost:8080/albums \\\n    --include \\\n    --header \"Content-Type: application/json\" \\\n    --request \"POST\" \\\n    --data '{\"id\": \"4\",\"title\": \"The Modern Sound of Betty Carter\",\"artist\": \"Betty Carter\",\"price\": 49.99}'\n```\n\nExample:\n```text\nHTTP/1.1 201 Created\nContent-Type: application/json; charset=utf-8\nDate: Wed, 02 Jun 2021 00:34:12 GMT\nContent-Length: 116\n\n{\n    \"id\": \"4\",\n    \"title\": \"The Modern Sound of Betty Carter\",\n    \"artist\": \"Betty Carter\",\n    \"price\": 49.99\n}\n```\n\nExample:\n```text\n$ curl http://localhost:8080/albums \\\n    --header \"Content-Type: application/json\" \\\n    --request \"GET\"\n```\n\nExample:\n```text\n[\n        {\n                \"id\": \"1\",\n                \"title\": \"Blue Train\",\n                \"artist\": \"John Coltrane\",\n                \"price\": 56.99\n        },\n        {\n                \"id\": \"2\",\n                \"title\": \"Jeru\",\n                \"artist\": \"Gerry Mulligan\",\n                \"price\": 17.99\n        },\n        {\n                \"id\": \"3\",\n                \"title\": \"Sarah Vaughan and Clifford Brown\",\n                \"artist\": \"Sarah Vaughan\",\n                \"price\": 39.99\n        },\n        {\n                \"id\": \"4\",\n                \"title\": \"The Modern Sound of Betty Carter\",\n                \"artist\": \"Betty Carter\",\n                \"price\": 49.99\n        }\n]\n```\n\nExample:\n```text\n// getAlbumByID locates the album whose ID value matches the id\n// parameter sent by the client, then returns that album as a response.\nfunc getAlbumByID(c *gin.Context) {\n    id := c.Param(\"id\")\n\n    // Loop over the list of albums, looking for\n    // an album whose ID value matches the parameter.\n    for _, a := range albums {\n        if a.ID == id {\n            c.IndentedJSON(http.StatusOK, a)\n            return\n        }\n    }\n    c.IndentedJSON(http.StatusNotFound, gin.H{\"message\": \"album not found\"})\n}\n```\n\nExample:\n```text\nfunc main() {\n    router := gin.Default()\n    router.GET(\"/albums\", getAlbums)\n    router.GET(\"/albums/:id\", getAlbumByID)\n    router.POST(\"/albums\", postAlbums)\n\n    router.Run(\"localhost:8080\")\n}\n```\n\nExample:\n```text\n$ curl http://localhost:8080/albums/2\n```\n\nExample:\n```text\n{\n        \"id\": \"2\",\n        \"title\": \"Jeru\",\n        \"artist\": \"Gerry Mulligan\",\n        \"price\": 17.99\n}\n```\n\nExample:\n```text\npackage main\n\nimport (\n    \"net/http\"\n\n    \"github.com/gin-gonic/gin\"\n)\n\n// album represents data about a record album.\ntype album struct {\n    ID     string  `json:\"id\"`\n    Title  string  `json:\"title\"`\n    Artist string  `json:\"artist\"`\n    Price  float64 `json:\"price\"`\n}\n\n// albums slice to seed record album data.\nvar albums = []album{\n    {ID: \"1\", Title: \"Blue Train\", Artist: \"John Coltrane\", Price: 56.99},\n    {ID: \"2\", Title: \"Jeru\", Artist: \"Gerry Mulligan\", Price: 17.99},\n    {ID: \"3\", Title: \"Sarah Vaughan and Clifford Brown\", Artist: \"Sarah Vaughan\", Price: 39.99},\n}\n\nfunc main() {\n    router := gin.Default()\n    router.GET(\"/albums\", getAlbums)\n    router.GET(\"/albums/:id\", getAlbumByID)\n    router.POST(\"/albums\", postAlbums)\n\n    router.Run(\"localhost:8080\")\n}\n\n// getAlbums responds with the list of all albums as JSON.\nfunc getAlbums(c *gin.Context) {\n    c.IndentedJSON(http.StatusOK, albums)\n}\n\n// postAlbums adds an album from JSON received in the request body.\nfunc postAlbums(c *gin.Context) {\n    var newAlbum album\n\n    // Call BindJSON to bind the received JSON to\n    // newAlbum.\n    if err := c.BindJSON(&newAlbum); err != nil {\n        return\n    }\n\n    // Add the new album to the slice.\n    albums = append(albums, newAlbum)\n    c.IndentedJSON(http.StatusCreated, newAlbum)\n}\n\n// getAlbumByID locates the album whose ID value matches the id\n// parameter sent by the client, then returns that album as a response.\nfunc getAlbumByID(c *gin.Context) {\n    id := c.Param(\"id\")\n\n    // Loop through the list of albums, looking for\n    // an album whose ID value matches the parameter.\n    for _, a := range albums {\n        if a.ID == id {\n            c.IndentedJSON(http.StatusOK, a)\n            return\n        }\n    }\n    c.IndentedJSON(http.StatusNotFound, gin.H{\"message\": \"album not found\"})\n}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.493Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":25,"totalLines":329,"estimatedTokens":5714}}33{"id":"doc-tutorial_get_started_with_go_the_go_programming_-74095209","source":"documentation","title":"Tutorial: Get started with Go - The Go Programming Language","url":"https://go.dev/doc/tutorial/getting-started.html","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\ncd\n```\n\nExample:\n```text\ncd %HOMEPATH%\n```\n\nExample:\n```text\nmkdir hello\ncd hello\n```\n\nExample:\n```text\n$ go mod init example/hello\ngo: creating new go.mod: module example/hello\n```\n\nExample:\n```text\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    fmt.Println(\"Hello, World!\")\n}\n```\n\nExample:\n```text\n$ go run .\nHello, World!\n```\n\nExample:\n```text\n$ go help\n```\n\nExample:\n```text\npackage main\n\nimport \"fmt\"\n\nimport \"rsc.io/quote\"\n\nfunc main() {\n    fmt.Println(quote.Go())\n}\n```\n\nExample:\n```text\n$ go mod tidy\ngo: finding module for package rsc.io/quote\ngo: found rsc.io/quote in rsc.io/quote v1.5.2\n```\n\nExample:\n```text\n$ go run .\nDon't communicate by sharing memory, share memory by communicating.\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.496Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":73,"estimatedTokens":215}}34{"id":"doc-encoding_json_v2_migration_guide_the_go_programm-6d43948e","source":"documentation","title":"encoding/json/v2 Migration Guide - The Go Programming Language","url":"https://go.dev/doc/jsonv2-migration","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\npackage main\n\nimport (\n    \"encoding/json\"\n    \"fmt\"\n)\n\ntype Pet struct {\n    Name      string\n    Nicknames []string\n}\n\nfunc main() {\n    pets := []Pet{\n        {Name: \"Oliver\", Nicknames: []string{\"Ollie\", \"Olliepop\"}},\n        {Name: \"Remi\"},\n    }\n    b, err := json.Marshal(pets)\n    if err != nil {\n        panic(err)\n    }\n    fmt.Println(string(b))\n}\n```\n\nExample:\n```text\n[{\"Name\":\"Oliver\",\"Nicknames\":[\"Ollie\",\"Olliepop\"]},{\"Name\":\"Remi\",\"Nicknames\":null}]\n```\n\nExample:\n```text\n[{\"Name\":\"Oliver\",\"Nicknames\":[\"Ollie\",\"Olliepop\"]},{\"Name\":\"Remi\",\"Nicknames\":[]}]\n```\n\nExample:\n```text\npackage main\n\nimport (\n    jsonv1 \"encoding/json\"\n    \"encoding/json/v2\"\n    \"fmt\"\n)\n\ntype Pet struct {\n    Name      string\n    Nicknames []string\n}\n\nfunc main() {\n    pets := []Pet{\n        {Name: \"Oliver\", Nicknames: []string{\"Ollie\", \"Olliepop\"}},\n        {Name: \"Remi\"},\n    }\n    b, err := json.Marshal(pets, jsonv1.DefaultOptionsV1())\n    if err != nil {\n        panic(err)\n    }\n    fmt.Println(string(b))\n}\n```\n\nExample:\n```text\npackage main\n\nimport (\n    \"fmt\"\n\n    \"github.com/go-json-experiment/jsonsplit\"\n)\n\nfunc init() {\n    // Call both v1 and v2 so we can detect differences, but continue using\n    // v1 output.\n    jsonsplit.GlobalCodec.SetMarshalCallMode(jsonsplit.CallBothButReturnV1)\n\n    // Specify that when a difference is detected, to auto-detect which\n    // options are causing the difference.\n    jsonsplit.GlobalCodec.AutoDetectOptions = true\n\n    // Log every time we detect a difference between v1 and v2.\n    jsonsplit.GlobalCodec.ReportDifference = func(d jsonsplit.Difference) {\n        fmt.Printf(\"detected jsonv1-to-jsonv2 difference: %v\\n\", d)\n    }\n}\n\ntype Pet struct {\n    Name      string\n    Nicknames []string\n}\n\nfunc main() {\n    pets := []Pet{\n        {Name: \"Oliver\", Nicknames: []string{\"Ollie\", \"Olliepop\"}},\n        {Name: \"Remi\"},\n    }\n    b, err := jsonsplit.Marshal(pets)\n    if err != nil {\n        panic(err)\n    }\n    fmt.Println(string(b))\n}\n```\n\nExample:\n```text\ndetected jsonv1-to-jsonv2 difference: {\"Caller\":\"main.main+5\",\"Func\":\"Marshal\",\"GoType\":\"[]main.Pet\",\"JSONValueV1\":[{\"Name\":\"Oliver\",\"Nicknames\":[\"Ollie\",\"Olliepop\"]},{\"Name\":\"Remi\",\"Nicknames\":null}],\"JSONValueV2\":[{\"Name\":\"Oliver\",\"Nicknames\":[\"Ollie\",\"Olliepop\"]},{\"Name\":\"Remi\",\"Nicknames\":[]}],\"Options\":[\"jsonv2.FormatNilSliceAsNull\"]}\n[{\"Name\":\"Oliver\",\"Nicknames\":[\"Ollie\",\"Olliepop\"]},{\"Name\":\"Remi\",\"Nicknames\":null}]\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.496Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":117,"estimatedTokens":651}}35{"id":"doc-tutorial_getting_started_with_generics_the_go_pr-d1a30991","source":"documentation","title":"Tutorial: Getting started with generics - The Go Programming Language","url":"https://go.dev/doc/tutorial/generics.html","text":"Documentation Tutorials started with generics started with generics This tutorial introduces the basics of generics in Go. With generics, you can declare and use functions or types that are written to work with any of a set of types provided by calling code. In this tutorial, you’ll declare two simple non-generic functions, then capture the same logic in a single generic function. You’ll progress through the following a folder for your code. Add non-generic functions. Add a generic function to handle multiple types. Remove type arguments when calling the generic function. Declare a type constraint. other tutorials, see Tutorials. Prerequisites Go. We recommend using the latest version of Go to follow this tutorial. For installation instructions, see Installing Go. A tool to edit your code. Any text editor you have will work fine. A command terminal. Go works well using any terminal on Linux and Mac, and on PowerShell or cmd in Windows. Create a folder for your code To begin, create a folder for the code you’ll write. Open a command prompt and change to your home directory. On Linux or Mac: $ cd On :\\> cd %HOMEPATH% The rest of the tutorial will show a $ as the prompt. The commands you use will work on Windows too. From the command prompt, create a directory for your code called generics. $ mkdir generics $ cd generics Create a module to hold your code. Run the go mod init command, giving it your new code’s module path. $ go mod init example/generics new go.mod: module example/generics production code, you’d specify a module path that’s more specific to your own needs. For more, be sure to see Managing dependencies. Next, you’ll add some simple code to work with maps. Add non-generic functions In this step, you’ll add two functions that each add together the values of a map and return the total. You’re declaring two functions instead of one because you’re working with two different types of that stores int64 values, and one that stores float64 values. Write the code Using your text editor, create a file called main.go in the generics directory. You’ll write your Go code in this file. Into main.go, at the top of the file, paste the following package declaration. package main A standalone program (as opposed to a library) is always in package main. Beneath the package declaration, paste the following two function declarations. // SumInts adds together the values of m. func SumInts(m map[string]int64) int64 { var s int64 for _, v := range m { s += v } return s } // SumFloats adds together the values of m. func SumFloats(m map[string]float64) float64 { var s float64 for _, v := range m { s += v } return s } In this code, two functions to add together the values of a map and return the sum. SumFloats takes a map of string to float64 values. SumInts takes a map of string to int64 values. At the top of main.go, beneath the package declaration, paste the following main function to initialize the two maps and use them as arguments when calling the functions you declared in the preceding step. func main() { // Initialize a map for the integer values ints := map[string]int64{ \"first\": 34, \"second\": 12, } // Initialize a map for the float values floats := map[string]float64{ \"first\": 35.98, \"second\": 26.99, } fmt.Printf(\"Non-Generic Sums: %v and %v\\n\", SumInts(ints), SumFloats(floats)) } In this code, a map of float64 values and a map of int64 values, each with two entries. Call the two functions you declared earlier to find the sum of each map’s values. Print the result. Near the top of main.go, just beneath the package declaration, import the package you’ll need to support the code you’ve just written. The first lines of code should look like main import \"fmt\" Save main.go. Run the code From the command line in the directory containing main.go, run the code. $ go run . Non-Generic and 62.97 With generics, you can write one function here instead of two. Next, you’ll add a single generic function for maps containing either integer or float values. Add a generic function to handle multiple types In this section, you’ll add a single generic function that can receive a map containing either integer or float values, effectively replacing the two functions you just wrote with a single function. To support values of either type, that single function will need a way to declare what types it supports. Calling code, on the other hand, will need a way to specify whether it is calling with an integer or float map. To support this, you’ll write a function that declares type parameters in addition to its ordinary function parameters. These type parameters make the function generic, enabling it to work with arguments of different types. You’ll call the function with type arguments and ordinary function arguments. Each type parameter has a type constraint that acts as a kind of meta-type for the type parameter. Each type constraint specifies the permissible type arguments that calling code can use for the respective type parameter. While a type parameter’s constraint typically represents a set of types, at compile time the type parameter stands for a single type – the type provided as a type argument by the calling code. If the type argument’s type isn’t allowed by the type parameter’s constraint, the code won’t compile. Keep in mind that a type parameter must support all the operations the generic code is performing on it. For example, if your function’s code were to try to perform string operations (such as indexing) on a type parameter whose constraint included numeric types, the code wouldn’t compile. In the code you’re about to write, you’ll use a constraint that allows either integer or float types. Write the code Beneath the two functions you added previously, paste the following generic function. // SumIntsOrFloats sums the values of map m. It supports both int64 and float64 // as types for map values. func SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V { var s V for _, v := range m { s += v } return s } In this code, a SumIntsOrFloats function with two type parameters (inside the square brackets), K and V, and one argument that uses the type parameters, m of type map[K]V. The function returns a value of type V. Specify for the K type parameter the type constraint comparable. Intended specifically for cases like these, the comparable constraint is predeclared in Go. It allows any type whose values may be used as an operand of the comparison operators == and !=. Go requires that map keys be comparable. So declaring K as comparable is necessary so you can use K as the key in the map variable. It also ensures that calling code uses an allowable type for map keys. Specify for the V type parameter a constraint that is a union of two and float64. Using | specifies a union of the two types, meaning that this constraint allows either type. Either type will be permitted by the compiler as an argument in the calling code. Specify that the m argument is of type map[K]V, where K and V are the types already specified for the type parameters. Note that we know map[K]V is a valid map type because K is a comparable type. If we hadn’t declared K comparable, the compiler would reject the reference to map[K]V. In main.go, beneath the code you already have, paste the following code. fmt.Printf(\"Generic Sums: %v and %v\\n\", SumIntsOrFloats[string, int64](ints), SumIntsOrFloats[string, float64](floats)) In this code, the generic function you just declared, passing each of the maps you created. Specify type arguments – the type names in square brackets – to be clear about the types that should replace type parameters in the function you’re calling. As you’ll see in the next section, you can often omit the type arguments in the function call. Go can often infer them from your code. Print the sums returned by the function. Run the code From the command line in the directory containing main.go, run the code. $ go run . Non-Generic and 62.97 Generic and 62.97 To run your code, in each call the compiler replaced the type parameters with the concrete types specified in that call. In calling the generic function you wrote, you specified type arguments that told the compiler what types to use in place of the function’s type parameters. As you’ll see in the next section, in many cases you can omit these type arguments because the compiler can infer them. Remove type arguments when calling the generic function In this section, you’ll add a modified version of the generic function call, making a small change to simplify the calling code. You’ll remove the type arguments, which aren’t needed in this case. You can omit type arguments in calling code when the Go compiler can infer the types you want to use. The compiler infers type arguments from the types of function arguments. Note that this isn’t always possible. For example, if you needed to call a generic function that had no arguments, you would need to include the type arguments in the function call. Write the code In main.go, beneath the code you already have, paste the following code. fmt.Printf(\"Generic Sums, type parameters inferred: %v and %v\\n\", SumIntsOrFloats(ints), SumIntsOrFloats(floats)) In this code, the generic function, omitting the type arguments. Run the code From the command line in the directory containing main.go, run the code. $ go run . Non-Generic and 62.97 Generic and 62.97 Generic Sums, type parameters and 62.97 Next, you’ll further simplify the function by capturing the union of integers and floats into a type constraint you can reuse, such as from other code. Declare a type constraint In this last section, you’ll move the constraint you defined earlier into its own interface so that you can reuse it in multiple places. Declaring constraints in this way helps streamline code, such as when a constraint is more complex. You declare a type constraint as an interface. The constraint allows any type implementing the interface. For example, if you declare a type constraint interface with three methods, then use it with a type parameter in a generic function, type arguments used to call the function must have all of those methods. Constraint interfaces can also refer to specific types, as you’ll see in this section. Write the code Just above main, immediately after the import statements, paste the following code to declare a type constraint. type Number interface { int64 | float64 } In this code, the Number interface type to use as a type constraint. Declare a union of int64 and float64 inside the interface. Essentially, you’re moving the union from the function declaration into a new type constraint. That way, when you want to constrain a type parameter to either int64 or float64, you can use this Number type constraint instead of writing out int64 | float64. Beneath the functions you already have, paste the following generic SumNumbers function. // SumNumbers sums the values of map m. It supports both integers // and floats as map values. func SumNumbers[K comparable, V Number](m map[K]V) V { var s V for _, v := range m { s += v } return s } In this code, a generic function with the same logic as the generic function you declared previously, but with the new interface type instead of the union as the type constraint. As before, you use the type parameters for the argument and return types. In main.go, beneath the code you already have, paste the following code. fmt.Printf(\"Generic Sums with Constraint: %v and %v\\n\", SumNumbers(ints), SumNumbers(floats)) In this code, SumNumbers with each map, printing the sum from the values of each. As in the preceding section, you omit the type arguments (the type names in square brackets) in calls to the generic function. The Go compiler can infer the type argument from other arguments. Run the code From the command line in the directory containing main.go, run the code. $ go run . Non-Generic and 62.97 Generic and 62.97 Generic Sums, type parameters and 62.97 Generic Sums with and 62.97 Conclusion Nicely done! You’ve just introduced yourself to generics in Go. Suggested next Go Tour is a great step-by-step introduction to Go fundamentals. You’ll find useful Go best practices described in Effective Go and How to write Go code. Completed code You can run this program in the Go playground. On the playground simply click the Run button. package main import \"fmt\" type Number interface { int64 | float64 } func main() { // Initialize a map for the integer values ints := map[string]int64{ \"first\": 34, \"second\": 12, } // Initialize a map for the float values floats := map[string]float64{ \"first\": 35.98, \"second\": 26.99, } fmt.Printf(\"Non-Generic Sums: %v and %v\\n\", SumInts(ints), SumFloats(floats)) fmt.Printf(\"Generic Sums: %v and %v\\n\", SumIntsOrFloats[string, int64](ints), SumIntsOrFloats[string, float64](floats)) fmt.Printf(\"Generic Sums, type parameters inferred: %v and %v\\n\", SumIntsOrFloats(ints), SumIntsOrFloats(floats)) fmt.Printf(\"Generic Sums with Constraint: %v and %v\\n\", SumNumbers(ints), SumNumbers(floats)) } // SumInts adds together the values of m. func SumInts(m map[string]int64) int64 { var s int64 for _, v := range m { s += v } return s } // SumFloats adds together the values of m. func SumFloats(m map[string]float64) float64 { var s float64 for _, v := range m { s += v } return s } // SumIntsOrFloats sums the values of map m. It supports both floats and integers // as map values. func SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V { var s V for _, v := range m { s += v } return s } // SumNumbers sums the values of map m. It supports both integers // and floats as map values. func SumNumbers[K comparable, V Number](m map[K]V) V { var s V for _, v := range m { s += v } return s }\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ cd\n```\n\nExample:\n```text\nC:\\> cd %HOMEPATH%\n```\n\nExample:\n```text\n$ mkdir generics\n$ cd generics\n```\n\nExample:\n```text\n$ go mod init example/generics\ngo: creating new go.mod: module example/generics\n```\n\nExample:\n```text\npackage main\n```\n\nExample:\n```text\n// SumInts adds together the values of m.\nfunc SumInts(m map[string]int64) int64 {\n    var s int64\n    for _, v := range m {\n        s += v\n    }\n    return s\n}\n\n// SumFloats adds together the values of m.\nfunc SumFloats(m map[string]float64) float64 {\n    var s float64\n    for _, v := range m {\n        s += v\n    }\n    return s\n}\n```\n\nExample:\n```text\nfunc main() {\n    // Initialize a map for the integer values\n    ints := map[string]int64{\n        \"first\":  34,\n        \"second\": 12,\n    }\n\n    // Initialize a map for the float values\n    floats := map[string]float64{\n        \"first\":  35.98,\n        \"second\": 26.99,\n    }\n\n    fmt.Printf(\"Non-Generic Sums: %v and %v\\n\",\n        SumInts(ints),\n        SumFloats(floats))\n}\n```\n\nExample:\n```text\npackage main\n\nimport \"fmt\"\n```\n\nExample:\n```text\n$ go run .\nNon-Generic Sums: 46 and 62.97\n```\n\nExample:\n```text\n// SumIntsOrFloats sums the values of map m. It supports both int64 and float64\n// as types for map values.\nfunc SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V {\n    var s V\n    for _, v := range m {\n        s += v\n    }\n    return s\n}\n```\n\nExample:\n```text\nfmt.Printf(\"Generic Sums: %v and %v\\n\",\n    SumIntsOrFloats[string, int64](ints),\n    SumIntsOrFloats[string, float64](floats))\n```\n\nExample:\n```text\n$ go run .\nNon-Generic Sums: 46 and 62.97\nGeneric Sums: 46 and 62.97\n```\n\nExample:\n```text\nfmt.Printf(\"Generic Sums, type parameters inferred: %v and %v\\n\",\n    SumIntsOrFloats(ints),\n    SumIntsOrFloats(floats))\n```\n\nExample:\n```text\n$ go run .\nNon-Generic Sums: 46 and 62.97\nGeneric Sums: 46 and 62.97\nGeneric Sums, type parameters inferred: 46 and 62.97\n```\n\nExample:\n```text\ntype Number interface {\n    int64 | float64\n}\n```\n\nExample:\n```text\n// SumNumbers sums the values of map m. It supports both integers\n// and floats as map values.\nfunc SumNumbers[K comparable, V Number](m map[K]V) V {\n    var s V\n    for _, v := range m {\n        s += v\n    }\n    return s\n}\n```\n\nExample:\n```text\nfmt.Printf(\"Generic Sums with Constraint: %v and %v\\n\",\n    SumNumbers(ints),\n    SumNumbers(floats))\n```\n\nExample:\n```text\n$ go run .\nNon-Generic Sums: 46 and 62.97\nGeneric Sums: 46 and 62.97\nGeneric Sums, type parameters inferred: 46 and 62.97\nGeneric Sums with Constraint: 46 and 62.97\n```\n\nExample:\n```text\npackage main\n\nimport \"fmt\"\n\ntype Number interface {\n    int64 | float64\n}\n\nfunc main() {\n    // Initialize a map for the integer values\n    ints := map[string]int64{\n        \"first\": 34,\n        \"second\": 12,\n    }\n\n    // Initialize a map for the float values\n    floats := map[string]float64{\n        \"first\": 35.98,\n        \"second\": 26.99,\n    }\n\n    fmt.Printf(\"Non-Generic Sums: %v and %v\\n\",\n        SumInts(ints),\n        SumFloats(floats))\n\n    fmt.Printf(\"Generic Sums: %v and %v\\n\",\n        SumIntsOrFloats[string, int64](ints),\n        SumIntsOrFloats[string, float64](floats))\n\n    fmt.Printf(\"Generic Sums, type parameters inferred: %v and %v\\n\",\n        SumIntsOrFloats(ints),\n        SumIntsOrFloats(floats))\n\n    fmt.Printf(\"Generic Sums with Constraint: %v and %v\\n\",\n        SumNumbers(ints),\n        SumNumbers(floats))\n}\n\n// SumInts adds together the values of m.\nfunc SumInts(m map[string]int64) int64 {\n    var s int64\n    for _, v := range m {\n        s += v\n    }\n    return s\n}\n\n// SumFloats adds together the values of m.\nfunc SumFloats(m map[string]float64) float64 {\n    var s float64\n    for _, v := range m {\n        s += v\n    }\n    return s\n}\n\n// SumIntsOrFloats sums the values of map m. It supports both floats and integers\n// as map values.\nfunc SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V {\n    var s V\n    for _, v := range m {\n        s += v\n    }\n    return s\n}\n\n// SumNumbers sums the values of map m. It supports both integers\n// and floats as map values.\nfunc SumNumbers[K comparable, V Number](m map[K]V) V {\n    var s V\n    for _, v := range m {\n        s += v\n    }\n    return s\n}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.498Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":19,"totalLines":244,"estimatedTokens":4525}}36{"id":"doc-executing_sql_statements_that_don_t_return_data_-49978730","source":"documentation","title":"Executing SQL statements that don't return data - The Go Programming Language","url":"https://go.dev/doc/database/change-data","text":"Executing SQL statements that don't return data When you perform database actions that don’t return data, use an Exec or ExecContext method from the database/sql package. SQL statements you’d execute this way include INSERT, DELETE, and UPDATE. When your query might return rows, use a Query or QueryContext method instead. For more, see Querying a database. An ExecContext method works as an Exec method does, but with an additional context.Context argument, as described in Canceling in-progress operations. Code in the following example uses DB.Exec to execute a statement to add a new record album to an album table. func AddAlbum(alb Album) (int64, error) { result, err := db.Exec(\"INSERT INTO album (title, artist) VALUES (?, ?)\", alb.Title, alb.Artist) if err != nil { return 0, fmt.Errorf(\"AddAlbum: %v\", err) } // Get the new album's generated ID for the client. id, err := result.LastInsertId() if err != nil { return 0, fmt.Errorf(\"AddAlbum: %v\", err) } // Return the new album's ID. return id, nil } DB.Exec returns sql.Result and an error. When the error is nil, you can use the Result to get the ID of the last inserted item (as in the example) or to retrieve the number of rows affected by the operation. placeholders in prepared statements vary depending on the DBMS and driver you’re using. For example, the pq driver for Postgres requires a placeholder like $1 instead of ?. If your code will be executing the same SQL statement repeatedly, consider using an sql.Stmt to create a reusable prepared statement from the SQL statement. For more, see Using prepared statements. ’t use string formatting functions such as fmt.Sprintf to assemble an SQL statement! You could introduce an SQL injection risk. For more, see Avoiding SQL injection risk. Functions for executing SQL statements that don’t return rows Function Description DB.Exec DB.ExecContext Execute a single SQL statement in isolation. Tx.Exec Tx.ExecContext Execute a SQL statement within a larger transaction. For more, see Executing transactions. Stmt.Exec Stmt.ExecContext Execute an already-prepared SQL statement. For more, see Using prepared statements. Conn.ExecContext For use with reserved connections. For more, see Managing connections.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\nfunc AddAlbum(alb Album) (int64, error) {\n    result, err := db.Exec(\"INSERT INTO album (title, artist) VALUES (?, ?)\", alb.Title, alb.Artist)\n    if err != nil {\n        return 0, fmt.Errorf(\"AddAlbum: %v\", err)\n    }\n\n    // Get the new album's generated ID for the client.\n    id, err := result.LastInsertId()\n    if err != nil {\n        return 0, fmt.Errorf(\"AddAlbum: %v\", err)\n    }\n    // Return the new album's ID.\n    return id, nil\n}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.515Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":1,"totalLines":23,"estimatedTokens":708}}37{"id":"doc-using_prepared_statements_the_go_programming_lan-68e28be4","source":"documentation","title":"Using prepared statements - The Go Programming Language","url":"https://go.dev/doc/database/prepared-statements","text":"Using prepared statements You can define a prepared statement for repeated use. This can help your code run a bit faster by avoiding the overhead of re-creating the statement each time your code performs the database operation. placeholders in prepared statements vary depending on the DBMS and driver you’re using. For example, the pq driver for Postgres requires a placeholder like $1 instead of ?. What is a prepared statement? A prepared statement is SQL that is parsed and saved by the DBMS, typically containing placeholders but with no actual parameter values. Later, the statement can be executed with a set of parameter values. How you use prepared statements When you expect to execute the same SQL repeatedly, you can use an sql.Stmt to prepare the SQL statement in advance, then execute it as needed. The following example creates a prepared statement that selects a specific album from the database. DB.Prepare returns an sql.Stmt representing a prepared statement for a given SQL text. You can pass the parameters for the SQL statement to Stmt.Exec, Stmt.QueryRow, or Stmt.Query to run the statement. // AlbumByID retrieves the specified album. func AlbumByID(id int) (Album, error) { // Define a prepared statement. You'd typically define the statement // elsewhere and save it for use in functions such as this one. stmt, err := db.Prepare(\"SELECT * FROM album WHERE id = ?\") if err != nil { log.Fatal(err) } defer stmt.Close() var album Album // Execute the prepared statement, passing in an id value for the // parameter whose placeholder is ? err := stmt.QueryRow(id).Scan(&album.ID, &album.Title, &album.Artist, &album.Price, &album.Quantity) if err != nil { if err == sql.ErrNoRows { // Handle the case of no rows returned. } return album, err } return album, nil } Prepared statement behavior A prepared sql.Stmt provides the usual Exec, QueryRow, and Query methods for invoking the statement. For more on using these methods, see Querying for data and Executing SQL statements that don’t return data. However, because an sql.Stmt already represents a preset SQL statement, its Exec, QueryRow, and Query methods take only the SQL parameter values corresponding to placeholders, omitting the SQL text. You can define a new sql.Stmt in different ways, depending on how you will use it. DB.Prepare and DB.PrepareContext create a prepared statement that can be executed in isolation, by itself outside a transaction, just like DB.Exec and DB.Query are. Tx.Prepare, Tx.PrepareContext, Tx.Stmt, and Tx.StmtContext create a prepared statement for use in a specific transaction. Prepare and PrepareContext use SQL text to define the statement. Stmt and StmtContext use the result of DB.Prepare or DB.PrepareContext. That is, they convert a not-for-transactions sql.Stmt into a for-this-transaction sql.Stmt. Conn.PrepareContext creates a prepared statement from an sql.Conn, which represents a reserved connection. Be sure that stmt.Close is called when your code is finished with a statement. This will release any database resources (such as underlying connections) that may be associated with it. For statements that are only local variables in a function, it’s enough to defer stmt.Close(). Functions for creating a prepared statement Function Description DB.Prepare DB.PrepareContext Prepare a statement for execution in isolation or that will be converted to an in-transaction' prepared statement using Tx.Stmt. Tx.Prepare Tx.PrepareContext Tx.Stmt Tx.StmtContext Prepare a statement for use in a specific transaction. For more, see Executing transactions. Conn.PrepareContext For use with reserved connections. For more, see Managing connections.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n// AlbumByID retrieves the specified album.\nfunc AlbumByID(id int) (Album, error) {\n    // Define a prepared statement. You'd typically define the statement\n    // elsewhere and save it for use in functions such as this one.\n    stmt, err := db.Prepare(\"SELECT * FROM album WHERE id = ?\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer stmt.Close()\n\n    var album Album\n\n    // Execute the prepared statement, passing in an id value for the\n    // parameter whose placeholder is ?\n    err := stmt.QueryRow(id).Scan(&album.ID, &album.Title, &album.Artist, &album.Price, &album.Quantity)\n    if err != nil {\n        if err == sql.ErrNoRows {\n            // Handle the case of no rows returned.\n        }\n        return album, err\n    }\n    return album, nil\n}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.515Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":1,"totalLines":32,"estimatedTokens":1150}}38{"id":"doc-profile_guided_optimization_the_go_programming_l-ce475880","source":"documentation","title":"Profile-guided optimization - The Go Programming Language","url":"https://go.dev/doc/pgo","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ go tool pprof -proto a.pprof b.pprof > merged.pprof\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.516Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":8,"estimatedTokens":54}}39{"id":"doc-frequently_asked_questions_faq_the_go_programmin-a442fae7","source":"documentation","title":"Frequently Asked Questions (FAQ) - The Go Programming Language","url":"https://go.dev/doc/faq","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\ntype T struct{}\nvar _ I = T{}       // Verify that T implements I.\nvar _ I = (*T)(nil) // Verify that *T implements I.\n```\n\nExample:\n```text\ntype Fooer interface {\n    Foo()\n    ImplementsFooer()\n}\n```\n\nExample:\n```text\ntype Bar struct{}\nfunc (b Bar) ImplementsFooer() {}\nfunc (b Bar) Foo() {}\n```\n\nExample:\n```text\ntype Equaler interface {\n    Equal(Equaler) bool\n}\n```\n\nExample:\n```text\ntype T int\nfunc (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler\n```\n\nExample:\n```text\ntype T2 int\nfunc (t T2) Equal(u Equaler) bool { return t == u.(T2) }  // satisfies Equaler\n```\n\nExample:\n```text\ntype Opener interface {\n   Open() Reader\n}\n\nfunc (t T3) Open() *os.File\n```\n\nExample:\n```text\nt := []int{1, 2, 3, 4}\ns := make([]interface{}, len(t))\nfor i, v := range t {\n    s[i] = v\n}\n```\n\nExample:\n```text\ntype T1 int\ntype T2 int\nvar t1 T1\nvar x = T2(t1) // OK\nvar st1 []T1\nvar sx = ([]T2)(st1) // NOT OK\n```\n\nExample:\n```text\nfunc returnsError() error {\n    var p *MyError = nil\n    if bad() {\n        p = ErrBad\n    }\n    return p // Will always return a non-nil error.\n}\n```\n\nExample:\n```text\nfunc returnsError() error {\n    if bad() {\n        return ErrBad\n    }\n    return nil\n}\n```\n\nExample:\n```text\nfunc main() {\n    type S struct {\n        f1 byte\n        f2 struct{}\n    }\n    fmt.Println(unsafe.Sizeof(S{}))\n}\n```\n\nExample:\n```text\ntype Copyable interface {\n    Copy() interface{}\n}\n```\n\nExample:\n```text\nfunc (v Value) Copy() Value\n```\n\nExample:\n```text\nsqrt2 := math.Sqrt(2)\n```\n\nExample:\n```text\nmachine github.com login *USERNAME* password *APIKEY*\n```\n\nExample:\n```text\n[url \"ssh://git@github.com/\"]\n    insteadOf = https://github.com/\n```\n\nExample:\n```text\ngo mod init example/project\n```\n\nExample:\n```text\ngo get golang.org/x/text@v0.3.5\n```\n\nExample:\n```text\nvar w io.Writer\n```\n\nExample:\n```text\nfmt.Fprintf(w, \"hello, world\\n\")\n```\n\nExample:\n```text\nfmt.Fprintf(&w, \"hello, world\\n\") // Compile-time error.\n```\n\nExample:\n```text\nfunc (s *MyStruct) pointerMethod() { } // method on pointer\nfunc (s MyStruct)  valueMethod()   { } // method on value\n```\n\nExample:\n```text\nvar foo float32 = 3.0\n```\n\nExample:\n```text\nvar buf bytes.Buffer\nio.Copy(buf, os.Stdin)\n```\n\nExample:\n```text\nfunc main() {\n    done := make(chan bool)\n\n    values := []string{\"a\", \"b\", \"c\"}\n    for _, v := range values {\n        go func() {\n            fmt.Println(v)\n            done <- true\n        }()\n    }\n\n    // wait for all goroutines to complete before exiting\n    for _ = range values {\n        <-done\n    }\n}\n```\n\nExample:\n```text\nfor _, v := range values {\n        go func(u string) {\n            fmt.Println(u)\n            done <- true\n        }(v)\n    }\n```\n\nExample:\n```text\nfor _, v := range values {\n        v := v // create a new 'v'.\n        go func() {\n            fmt.Println(v)\n            done <- true\n        }()\n    }\n```\n\nExample:\n```text\nif expr {\n    n = trueVal\n} else {\n    n = falseVal\n}\n```\n\nExample:\n```text\na, b = w < x, y > (z)\n```\n\nExample:\n```text\ntype Empty struct{}\n\nfunc (Empty) Nop[T any](x T) T {\n    return x\n}\n```\n\nExample:\n```text\nfunc TryNops(x any) {\n    if x, ok := x.(interface{ Nop(string) string }); ok {\n        fmt.Printf(\"string %s\\n\", x.Nop(\"hello\"))\n    }\n    if x, ok := x.(interface{ Nop(int) int }); ok {\n        fmt.Printf(\"int %d\\n\", x.Nop(42))\n    }\n    if x, ok := x.(interface{ Nop(io.Reader) io.Reader }); ok {\n        data, err := io.ReadAll(x.Nop(strings.NewReader(\"hello world\")))\n        fmt.Printf(\"reader %q %v\\n\", data, err)\n    }\n}\n```\n\nExample:\n```text\ntype S[T any] struct { f T }\n\nfunc (s S[string]) Add(t string) string {\n    return s.f + t\n}\n```\n\nExample:\n```text\nfunc TestFoo(t *testing.T) {\n    ...\n}\n```\n\nExample:\n```text\nimport \"unused\"\n\n// This declaration marks the import as used by referencing an\n// item from the package.\nvar _ = unused.Item  // TODO: Delete before committing!\n\nfunc main() {\n    debugData := debug.Profile()\n    _ = debugData // Used only during debugging.\n    ....\n}\n```\n\nExample:\n```text\nint* a, b;\n```\n\nExample:\n```text\nvar a, b *int\n```\n\nExample:\n```text\nvar a uint64 = 1\n```\n\nExample:\n```text\na := uint64(1)\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.522Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":39,"totalLines":305,"estimatedTokens":1070}}40{"id":"doc-command_documentation_the_go_programming_languag-07027858","source":"documentation","title":"Command Documentation - The Go Programming Language","url":"https://go.dev/doc/cmd","text":"Documentation Command Documentation Command Documentation There is a suite of programs to build and process Go source code. Instead of being run directly, programs in the suite are usually invoked by the go program. The most common way to run these programs is as a subcommand of the go program, for instance as go fmt. Run like this, the command operates on complete packages of Go source code, with the go program invoking the underlying binary with arguments appropriate to package-level processing. The programs can also be run as stand-alone binaries, with unmodified arguments, using the go tool subcommand, such as go tool cgo. For most commands this is mainly useful for debugging. Some of the commands, such as pprof, are accessible only through the go tool subcommand. The Go installation process also installs an executable called gofmt, equivalent to go fmt, because it is so often referenced. Click on the links for more documentation, invocation methods, and usage details. Name Synopsis go The go program manages Go source code and runs the other commands listed here. See the command docs for usage details. cgo Cgo enables the creation of Go packages that call C code. cover Cover is a program for creating and analyzing the coverage profiles generated by \"go test -coverprofile\". fix Fix finds Go programs that use old features of the language and libraries and rewrites them to use newer ones. fmt Fmt formats Go packages, it is also available as an independent gofmt command with more general options. doc Doc extracts and generates documentation for Go packages. vet Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string. This is an abridged list. See the full command reference for documentation of the compilers and more.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.522Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":0,"totalLines":5,"estimatedTokens":492}}41{"id":"doc-executing_transactions_the_go_programming_langua-434f4642","source":"documentation","title":"Executing transactions - The Go Programming Language","url":"https://go.dev/doc/database/execute-transactions","text":"Executing transactions You can execute database transactions using an sql.Tx, which represents a transaction. In addition to Commit and Rollback methods representing transaction-specific semantics, sql.Tx has all of the methods you use to perform common database operations. To get the sql.Tx, you call DB.Begin or DB.BeginTx. A database transaction groups multiple operations as part of a larger goal. All of the operations must succeed or none can, with the data’s integrity preserved in either case. Typically, a transaction workflow the transaction. Performing a set of database operations. If no error occurs, committing the transaction to make database changes. If an error occurs, rolling back the transaction to leave the database unchanged. The sql package provides methods for beginning and concluding a transaction, as well as methods for performing the intervening database operations. These methods correspond to the four steps in the workflow above. Begin a transaction. DB.Begin or DB.BeginTx begin a new database transaction, returning an sql.Tx that represents it. Perform database operations. Using an sql.Tx, you can query or update the database in a series of operations that use a single connection. To support this, Tx exports the following and ExecContext for making database changes through SQL statements such as INSERT, UPDATE, and DELETE. For more, see Executing SQL statements that don’t return data. Query, QueryContext, QueryRow, and QueryRowContext for operations that return rows. For more, see Querying for data. Prepare, PrepareContext, Stmt, and StmtContext for pre-defining prepared statements. For more, see Using prepared statements. End the transaction with one of the the transaction using Tx.Commit. If Commit succeeds (returns a nil error), then all the query results are confirmed as valid and all the executed updates are applied to the database as a single atomic change. If Commit fails, then all the results from Query and Exec on the Tx should be discarded as invalid. Roll back the transaction using Tx.Rollback. Even if Tx.Rollback fails, the transaction will no longer be valid, nor will it have been committed to the database. Best practices Follow the best practices below to better navigate the complicated semantics and connection management that transactions sometimes require. Use the APIs described in this section to manage transactions. Do not use transaction-related SQL statements such as BEGIN and COMMIT directly—doing so can leave your database in an unpredictable state, especially in concurrent programs. When using a transaction, take care not to call the non-transaction sql.DB methods directly, too, as those will execute outside the transaction, giving your code an inconsistent view of the state of the database or even causing deadlocks. Example Code in the following example uses a transaction to create a new customer order for an album. Along the way, the code a transaction. Defer the transaction’s rollback. If the transaction succeeds, it will be committed before the function exits, making the deferred rollback call a no-op. If the transaction fails it won’t be committed, meaning that the rollback will be called as the function exits. Confirm that there’s sufficient inventory for the album the customer is ordering. If there’s enough, update the inventory count, reducing it by the number of albums ordered. Create a new order and retrieve the new order’s generated ID for the client. Commit the transaction and return the ID. This example uses Tx methods that take a context.Context argument. This makes it possible for the function’s execution – including database operations – to be canceled if it runs too long or the client connection closes. For more, see Canceling in-progress operations. // CreateOrder creates an order for an album and returns the new order ID. func CreateOrder(ctx context.Context, albumID, quantity, custID int) (orderID int64, err error) { // Create a helper function for preparing failure results. fail := func(err error) (int64, error) { return 0, fmt.Errorf(\"CreateOrder: %v\", err) } // Get a Tx for making transaction requests. tx, err := db.BeginTx(ctx, nil) if err != nil { return fail(err) } // Defer a rollback in case anything fails. defer tx.Rollback() // Confirm that album inventory is enough for the order. var enough bool if err = tx.QueryRowContext(ctx, \"SELECT (quantity >= ?) from album where id = ?\", quantity, albumID).Scan(&enough); err != nil { if err == sql.ErrNoRows { return fail(fmt.Errorf(\"no such album\")) } return fail(err) } if !enough { return fail(fmt.Errorf(\"not enough inventory\")) } // Update the album inventory to remove the quantity in the order. _, err = tx.ExecContext(ctx, \"UPDATE album SET quantity = quantity - ? WHERE id = ?\", quantity, albumID) if err != nil { return fail(err) } // Create a new row in the album_order table. result, err := tx.ExecContext(ctx, \"INSERT INTO album_order (album_id, cust_id, quantity, date) VALUES (?, ?, ?, ?)\", albumID, custID, quantity, time.Now()) if err != nil { return fail(err) } // Get the ID of the order item just created. orderID, err = result.LastInsertId() if err != nil { return fail(err) } // Commit the transaction. if err = tx.Commit(); err != nil { return fail(err) } // Return the order ID. return orderID, nil }\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n// CreateOrder creates an order for an album and returns the new order ID.\nfunc CreateOrder(ctx context.Context, albumID, quantity, custID int) (orderID int64, err error) {\n\n    // Create a helper function for preparing failure results.\n    fail := func(err error) (int64, error) {\n        return 0, fmt.Errorf(\"CreateOrder: %v\", err)\n    }\n\n    // Get a Tx for making transaction requests.\n    tx, err := db.BeginTx(ctx, nil)\n    if err != nil {\n        return fail(err)\n    }\n    // Defer a rollback in case anything fails.\n    defer tx.Rollback()\n\n    // Confirm that album inventory is enough for the order.\n    var enough bool\n    if err = tx.QueryRowContext(ctx, \"SELECT (quantity >= ?) from album where id = ?\",\n        quantity, albumID).Scan(&enough); err != nil {\n        if err == sql.ErrNoRows {\n            return fail(fmt.Errorf(\"no such album\"))\n        }\n        return fail(err)\n    }\n    if !enough {\n        return fail(fmt.Errorf(\"not enough inventory\"))\n    }\n\n    // Update the album inventory to remove the quantity in the order.\n    _, err = tx.ExecContext(ctx, \"UPDATE album SET quantity = quantity - ? WHERE id = ?\",\n        quantity, albumID)\n    if err != nil {\n        return fail(err)\n    }\n\n    // Create a new row in the album_order table.\n    result, err := tx.ExecContext(ctx, \"INSERT INTO album_order (album_id, cust_id, quantity, date) VALUES (?, ?, ?, ?)\",\n        albumID, custID, quantity, time.Now())\n    if err != nil {\n        return fail(err)\n    }\n    // Get the ID of the order item just created.\n    orderID, err = result.LastInsertId()\n    if err != nil {\n        return fail(err)\n    }\n\n    // Commit the transaction.\n    if err = tx.Commit(); err != nil {\n        return fail(err)\n    }\n\n    // Return the order ID.\n    return orderID, nil\n}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.522Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":1,"totalLines":65,"estimatedTokens":1818}}42{"id":"doc-coverage_profiling_support_for_integration_tests-cdec905d","source":"documentation","title":"Coverage profiling support for integration tests - The Go Programming Language","url":"https://go.dev/doc/build-cover","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ cat go.mod\nmodule mydomain.com\n\ngo 1.20\n\nrequire rsc.io/quote v1.5.2\n\nrequire (\n    golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c // indirect\n    rsc.io/sampler v1.3.0 // indirect\n)\n\n$ cat myprogram.go\npackage main\n\nimport (\n    \"fmt\"\n    \"mydomain.com/greetings\"\n    \"rsc.io/quote\"\n)\n\nfunc main() {\n    fmt.Printf(\"I say %q and %q\\n\", quote.Hello(), greetings.Goodbye())\n}\n$ cat greetings/greetings.go\npackage greetings\n\nfunc Goodbye() string {\n    return \"see ya\"\n}\n$ go build -cover -o myprogram.exe .\n$\n```\n\nExample:\n```text\n$ go build -cover -o myprogramMorePkgs.exe -coverpkg=io,mydomain.com,rsc.io/quote .\n$\n```\n\nExample:\n```text\n$ go build -cover -o myprogram.exe myprogram.go\n$ mkdir somedata\n$ GOCOVERDIR=somedata ./myprogram.exe\nI say \"Hello, world.\" and \"see ya\"\n$ ls somedata\ncovcounters.c6de772f99010ef5925877a7b05db4cc.2424989.1670252383678349347\ncovmeta.c6de772f99010ef5925877a7b05db4cc\n$\n```\n\nExample:\n```text\n$ ./myprogram.exe\nwarning: GOCOVERDIR not set, no coverage data emitted\nI say \"Hello, world.\" and \"see ya\"\n$\n```\n\nExample:\n```text\n$ mkdir somedata2\n$ GOCOVERDIR=somedata2 ./myprogram.exe          // first run\nI say \"Hello, world.\" and \"see ya\"\n$ GOCOVERDIR=somedata2 ./myprogram.exe -flag    // second run\nI say \"Hello, world.\" and \"see ya\"\n$ ls somedata2\ncovcounters.890814fca98ac3a4d41b9bd2a7ec9f7f.2456041.1670259309405583534\ncovcounters.890814fca98ac3a4d41b9bd2a7ec9f7f.2456047.1670259309410891043\ncovmeta.890814fca98ac3a4d41b9bd2a7ec9f7f\n$\n```\n\nExample:\n```text\n$ go tool covdata <mode> -i=<dir1,dir2,...> ...flags...\n```\n\nExample:\n```text\n$ ls somedata\ncovcounters.c6de772f99010ef5925877a7b05db4cc.2424989.1670252383678349347\ncovmeta.c6de772f99010ef5925877a7b05db4cc\n$ go tool covdata percent -i=somedata\n    main    coverage: 100.0% of statements\n    mydomain.com/greetings  coverage: 100.0% of statements\n$\n```\n\nExample:\n```text\n$ ls somedata\ncovcounters.c6de772f99010ef5925877a7b05db4cc.2424989.1670252383678349347\ncovmeta.c6de772f99010ef5925877a7b05db4cc\n$ go tool covdata textfmt -i=somedata -o profile.txt\n$ cat profile.txt\nmode: set\nmydomain.com/myprogram.go:10.13,12.2 1 1\nmydomain.com/greetings/greetings.go:3.23,5.2 1 1\n$ go tool cover -func=profile.txt\nmydomain.com/greetings/greetings.go:3:  Goodbye     100.0%\nmydomain.com/myprogram.go:10:       main        100.0%\ntotal:                  (statements)    100.0%\n$\n```\n\nExample:\n```text\n$ ls windows_datadir\ncovcounters.f3833f80c91d8229544b25a855285890.1025623.1667481441036838252\ncovcounters.f3833f80c91d8229544b25a855285890.1025628.1667481441042785007\ncovmeta.f3833f80c91d8229544b25a855285890\n$ ls macos_datadir\ncovcounters.b245ad845b5068d116a4e25033b429fb.1025358.1667481440551734165\ncovcounters.b245ad845b5068d116a4e25033b429fb.1025364.1667481440557770197\ncovmeta.b245ad845b5068d116a4e25033b429fb\n$ ls macos_datadir\n$ mkdir merged\n$ go tool covdata merge -i=windows_datadir,macos_datadir -o merged\n$\n```\n\nExample:\n```text\n$ ls somedata\ncovcounters.c6de772f99010ef5925877a7b05db4cc.2424989.1670252383678349347\ncovmeta.c6de772f99010ef5925877a7b05db4cc\n$ go tool covdata percent -i=somedata -pkg=mydomain.com/greetings\n    mydomain.com/greetings  coverage: 100.0% of statements\n$ go tool covdata percent -i=somedata -pkg=nonexistentpackage\n$\n```\n\nExample:\n```text\n$ go list -f '{{if not .Standard}}{{.ImportPath}}{{end}}' -deps . | paste -sd \",\" > pkgs.txt\n$ go build -o myprogram.exe -coverpkg=`cat pkgs.txt` .\n$ mkdir somedata\n$ GOCOVERDIR=somedata ./myprogram.exe\n$ go tool covdata percent -i=somedata\n    golang.org/x/text/internal/tag  coverage: 78.4% of statements\n    golang.org/x/text/language  coverage: 35.5% of statements\n    mydomain.com    coverage: 100.0% of statements\n    mydomain.com/greetings  coverage: 100.0% of statements\n    rsc.io/quote    coverage: 25.0% of statements\n    rsc.io/sampler  coverage: 86.7% of statements\n$\n```\n\nExample:\n```text\n$ go list -m\nmydomain.com\n$ go build -coverpkg=main -o oops.exe .\nwarning: no packages being built depend on matches for pattern main\n$ go build -coverpkg=mydomain.com -o myprogram.exe .\n$ mkdir somedata\n$ GOCOVERDIR=somedata ./myprogram.exe\nI say \"Hello, world.\" and \"see ya\"\n$ go tool covdata percent -i=somedata\n    mydomain.com    coverage: 100.0% of statements\n$\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.523Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":170,"estimatedTokens":1100}}43{"id":"doc-go_mod_file_reference_the_go_programming_languag-645a389a","source":"documentation","title":"go.mod file reference - The Go Programming Language","url":"https://go.dev/doc/modules/gomod-ref","text":"go.mod file reference Each Go module is defined by a go.mod file that describes the module’s properties, including its dependencies on other modules and on versions of Go. These properties current module’s module path. This should be a location from which the module can be downloaded by Go tools, such as the module code’s repository location. This serves as a unique identifier, when combined with the module’s version number. It is also the prefix of the package path for all packages in the module. For more about how Go locates the module, see the Go Modules Reference. The minimum version of Go required by the current module. A list of minimum versions of other modules required by the current module. Instructions, optionally, to replace a required module with another module version or a local directory, to exclude a specific version of a required module, or to ignore specific directories within the module when matching package patterns. Go generates a go.mod file when you run the go mod init command. The following example creates a go.mod file, setting the module’s module path to example/mymodule: $ go mod init example/mymodule Use go commands to manage dependencies. The commands ensure that the requirements described in your go.mod file remain consistent and the content of your go.mod file is valid. These commands include the go get and go mod tidy and go mod edit commands. For reference on go commands, see Command go. You can get help from the command line by typing go help command-name, as with go help mod tidy. See also Go tools make changes to your go.mod file as you use them to manage dependencies. For more, see Managing dependencies. For more details and constraints related to go.mod files, see the Go modules reference. Example A go.mod file includes directives as shown in the following example. These are described elsewhere in this topic. module example.com/mymodule go 1.14 require ( example.com/othermodule v1.2.3 example.com/thismodule v1.2.3 example.com/thatmodule v1.2.3 ) replace example.com/thatmodule => ../thatmodule exclude example.com/thismodule v1.3.0 module Declares the module’s module path, which is the module’s unique identifier (when combined with the module version number). The module path becomes the import prefix for all packages the module contains. For more, see module directive in the Go Modules Reference. Syntax module module-path module-path The module's module path, usually the repository location from which the module can be downloaded by Go tools. For module versions v2 and later, this value must end with the major version number, such as /v2. Examples The following examples substitute example.com for a repository domain from which the module could be downloaded. Module declaration for a v0 or v1 example.com/mymodule Module path for a v2 example.com/mymodule/v2 Notes The module path must uniquely identify your module. For most modules, the path is a URL where the go command can find the code (or a redirect to the code). For modules that won’t ever be downloaded directly, the module path can be just some name you control that will ensure uniqueness. The prefix example/ is also reserved for use in examples like these. For more details, see Managing dependencies. In practice, the module path is typically the module source’s repository domain and path to the module code within the repository. The go command relies on this form when downloading module versions to resolve dependencies on the module user’s behalf. Even if you’re not at first intending to make your module available for use from other code, using its repository path is a best practice that will help you avoid having to rename the module if you publish it later. If at first you don’t know the module’s eventual repository location, consider temporarily using a safe substitute, such as the name of a domain you own or a name you control (such as your company name), along with a path following from the module’s name or source directory. For more, see Managing dependencies. For example, if you’re developing in a stringtools directory, your temporary module path might be <company-name>/stringtools, as in the following example, where company-name is your company’s mod init <company-name>/stringtools go Indicates that the module was written assuming the semantics of the Go version specified by the directive. For more, see go directive in the Go Modules Reference. Syntax go minimum-go-version minimum-go-version The minimum version of Go required to compile packages in this module. Examples Module must run on Go version 1.14 or 1.14 Notes The go directive sets the minimum version of Go required to use this module. Before Go 1.21, the directive was advisory only; now it is a mandatory toolchains refuse to use modules declaring newer Go versions. The go directive is an input into selecting which Go toolchain to run. See “Go toolchains” for details. The go directive affects use of new language packages within the module, the compiler rejects use of language features introduced after the version specified by the go directive. For example, if a module has the directive go 1.12, its packages may not use numeric literals like 1_000_000, which were introduced in Go 1.13. If an older Go version builds one of the module’s packages and encounters a compile error, the error notes that the module was written for a newer Go version. For example, suppose a module has go 1.13 and a package uses the numeric literal 1_000_000. If that package is built with Go 1.12, the compiler notes that the code is written for Go 1.13. The go directive also affects the behavior of the go go 1.14 or higher, automatic vendoring may be enabled. If the file vendor/modules.txt is present and consistent with go.mod, there is no need to explicitly use the -mod=vendor flag. At go 1.16 or higher, the all package pattern matches only packages transitively imported by packages and tests in the main module. This is the same set of packages retained by go mod vendor since modules were introduced. In lower versions, all also includes tests of packages imported by packages in the main module, tests of those packages, and so on. At go 1.17 or go.mod file includes an explicit require directive for each module that provides any package transitively imported by a package or test in the main module. (At go 1.16 and lower, an indirect dependency is included only if minimal version selection would otherwise select a different version.) This extra information enables module graph pruning and lazy module loading. Because there may be many more // indirect dependencies than in previous go versions, indirect dependencies are recorded in a separate block within the go.mod file. go mod vendor omits go.mod and go.sum files for vendored dependencies. (That allows invocations of the go command within subdirectories of vendor to identify the correct main module.) go mod vendor records the go version from each dependency’s go.mod file in vendor/modules.txt. At go 1.21 or go line declares a required minimum version of Go to use with this module. The go line must be greater than or equal to the go line of all dependencies. The go command no longer attempts to maintain compatibility with the previous older version of Go. The go command is more careful about keeping checksums of go.mod files in the go.sum file. A go.mod file may contain at most one go directive. Most commands will add a go directive with the current Go version if one is not present. toolchain Declares a suggested Go toolchain to use with this module. Only takes effect when the module is the main module and the default toolchain is older than the suggested toolchain. For more see “Go toolchains” and toolchain directive in the Go Modules Reference. Syntax toolchain toolchain-name toolchain-name The suggested Go toolchain's name. Standard toolchain names take the form goV for a Go version V, as in go1.21.0 and go1.18rc1. The special value default disables automatic toolchain switching. Examples Suggest using Go 1.21.0 or go1.21.0 Notes See “Go toolchains” for details about how the toolchain line affects Go toolchain selection. godebug Indicates the default GODEBUG settings to be applied to the main packages of this module. These override any toolchain defaults, and are overridden by explicit //go:debug lines in main packages. Syntax godebug debug-key=debug-value debug-key The name of the setting to be applied. A list of settings and the versions they were introduced in can be found at GODEBUG History. debug-value The value provided to the setting. If not otherwise specified, 0 to disable and 1 to enable the named behavior. Examples Use the new 1.23 asynctimerchan=0 asynctimerchan=0 Use the default GODEBUGs from Go 1.21, but the old panicnil=1 ( default=go1.21 panicnil=1 ) Notes GODEBUG settings only apply for builds of main packages and test binaries in the current module. They have no effect when a module is used as a dependency. See “Go, Backwards Compatibility, and GODEBUG” for details on backwards compatibility. require Declares a module as a dependency of the current module, specifying the minimum version of the module required. For more, see require directive in the Go Modules Reference. Syntax require module-path module-version module-path The module's module path, usually a concatenation of the module source's repository domain and the module name. For module versions v2 and later, this value must end with the major version number, such as /v2. module-version The module's version. This can be either a release version number, such as v1.2.3, or a Go-generated pseudo-version number, such as v0.0.0-20200921210052-fa0125251cc4. Examples Requiring a released version v1.2.3: require example.com/othermodule v1.2.3 Requiring a version not yet tagged in its repository by using a pseudo-version number generated by Go example.com/othermodule v0.0.0-20200921210052-fa0125251cc4 Notes When you run a go command such as go get, Go inserts require directives for each module containing imported packages. When a module isn’t yet tagged in its repository, Go assigns a pseudo-version number it generates when you run the command. You can have Go require a module from a location other than its repository by using the replace directive. For more about version numbers, see Module version numbering. For more about managing dependencies, see the a dependency Getting a specific dependency version Discovering available updates Upgrading or downgrading a dependency Synchronizing your code’s dependencies tool Adds a package as a dependency of the current module, and makes it available to run with go tool when the current working directory is within this module. Syntax tool package-path package-path The tool's package path, a concatenation of the module containing the tool and the (possibly empty) path to the package implementing the tool within the module. Examples Declaring a tool implemented in the current example.com/mymodule tool example.com/mymodule/cmd/mytool Declaring a tool implemented in a separate example.com/mymodule tool example.com/atool/cmd/atool require example.com/atool v1.2.3 Notes You can use go tool to run tools declared in your module by fully qualified package path or, if there is no ambiguity, by the last path segment. In the first example above you could run go tool mytool or go tool example.com/mymodule/cmd/mytool. In workspace mode, you can use go tool to run a tool declared in any workspace module. Tools are built using the same module graph as the module itself. A require directive is needed to select the version of the module that implements the tool. Any replace directives, or exclude directives also apply to the tool and its dependencies. For more information see Tool dependencies. replace Replaces the content of a module at a specific version (or all versions) with another module version or with a local directory. Go tools will use the replacement path when resolving the dependency. For more, see replace directive in the Go Modules Reference. Syntax replace module-path [module-version] => replacement-path [replacement-version] module-path The module path of the module to replace. module-version Optional. A specific version to replace. If this version number is omitted, all versions of the module are replaced with the content on the right side of the arrow. replacement-path The path at which Go should look for the required module. This can be a module path or a path to a directory on the file system local to the replacement module. If this is a module path, you must specify a replacement-version value. If this is a local path, you may not use a replacement-version value. replacement-version The version of the replacement module. The replacement version may only be specified if replacement-path is a module path (not a local directory). Examples Replacing with a fork of the module repository In the following example, any version of example.com/othermodule is replaced with the specified fork of its code. require example.com/othermodule v1.2.3 replace example.com/othermodule => example.com/myfork/othermodule v1.2.3-fixed When you replace one module path with another, do not change import statements for packages in the module you’re replacing. For more on using a forked copy of module code, see Requiring external module code from your own repository fork. Replacing with a different version number The following example specifies that version v1.2.3 should be used instead of any other version of the module. require example.com/othermodule v1.2.2 replace example.com/othermodule => example.com/othermodule v1.2.3 The following example replaces module version v1.2.5 with version v1.2.3 of the same module. replace example.com/othermodule v1.2.5 => example.com/othermodule v1.2.3 Replacing with local code The following example specifies that a local directory should be used as a replacement for all versions of the module. require example.com/othermodule v1.2.3 replace example.com/othermodule => ../othermodule The following example specifies that a local directory should be used as a replacement for v1.2.5 only. require example.com/othermodule v1.2.5 replace example.com/othermodule v1.2.5 => ../othermodule For more on using a local copy of module code, see Requiring module code in a local directory. Notes Use the replace directive to temporarily substitute a module path value with another value when you want Go to use the other path to find the module’s source. This has the effect of redirecting Go’s search for the module to the replacement’s location. You needn’t change package import paths to use the replacement path. Use the exclude and replace directives to control build-time dependency resolution when building the current module. These directives are ignored in modules that depend on the current module. The replace directive can be useful in situations such as the ’re developing a new module whose code is not yet in the repository. You want to test with clients using a local version. You’ve identified an issue with a dependency, have cloned the dependency’s repository, and you’re testing a fix with the local repository. Note that a replace directive alone does not add a module to the module graph. A require directive that refers to a replaced module version is also needed, either in the main module’s go.mod file or a dependency’s go.mod file. If you don’t have a specific version to replace, you can use a fake version, as in the example below. Note that this will break modules that depend on your module, since replace directives are only applied in the main module. require example.com/mod v0.0.0-replace replace example.com/mod v0.0.0-replace => ./mod For more on replacing a required module, including using Go tools to make the change, external module code from your own repository fork Requiring module code in a local directory For more about version numbers, see Module version numbering. exclude Specifies a module or module version to exclude from the current module’s dependency graph. For more, see exclude directive in the Go Modules Reference. Syntax exclude module-path module-version module-path The module path of the module to exclude. module-version The specific version to exclude. Example Exclude example.com/theirmodule version v1.3.0 exclude example.com/theirmodule v1.3.0 Notes Use the exclude directive to exclude a specific version of a module that is indirectly required but can’t be loaded for some reason. For example, you might use it to exclude a version of a module that has an invalid checksum. Use the exclude and replace directives to control build-time dependency resolution when building the current module (the main module you’re building). These directives are ignored in modules that depend on the current module. You can use the go mod edit command to exclude a module, as in the following example. go mod edit -exclude=example.com/theirmodule@v1.3.0 For more about version numbers, see Module version numbering. retract Indicates that a version or range of versions of the module defined by go.mod should not be depended upon. A retract directive is useful when a version was published prematurely or a severe problem was discovered after the version was published. For more, see retract directive in the Go Modules Reference. Syntax retract version // rationale retract [version-low,version-high] // rationale version A single version to retract. version-low Lower bound of a range of versions to retract. version-high Upper bound of a range of versions to retract. Both version-low and version-high are included in the range. rationale Optional comment explaining the retraction. May be shown in messages to the user. Example Retracting a single version retract v1.1.0 // Published accidentally. Retracting a range of versions retract [v1.0.0,v1.0.5] // Build broken on some platforms. Notes Use the retract directive to indicate that a previous version of your module should not be used. Users will not automatically upgrade to a retracted version with go get, go mod tidy, or other commands. Users will not see a retracted version as an available update with go list -m -u. Retracted versions should remain available so users that already depend on them are able to build their packages. Even if a retracted version is deleted from the source repository, it may remain available on mirrors such as proxy.golang.org. Users that depend on retracted versions may be notified when they run go get or go list -m -u on related modules. The go command discovers retracted versions by reading retract directives in the go.mod file in the latest version of a module. The latest version is, in order of highest release version, if any Its highest pre-release version, if any A pseudo-version for the tip of the repository’s default branch. When you add a retraction, you almost always need to tag a new, higher version so the command will see it in the latest version of the module. You can publish a version whose sole purpose is to signal retractions. In this case, the new version may also retract itself. For example, if you accidentally tag v1.0.0, you can tag v1.0.1 with the following v1.0.0 // Published accidentally. retract v1.0.1 // Contains retraction only. Unfortunately, once a version is published, it cannot be changed. If you later tag v1.0.0 at a different commit, the go command may detect a mismatched sum in go.sum or in the checksum database. Retracted versions of a module do not normally appear in the output of go list -m -versions, but you can use the -retracted to show them. For more, see go list -m in the Go Modules Reference. ignore Specifies directory paths within the module that the go command should ignore when matching package patterns. For more, see ignore directive in the Go Modules Reference. Syntax ignore path path A slash-separated path to ignore. If the path starts with ./, it is interpreted relative to the module root directory. Otherwise, any directory with that name at any depth within the module is ignored. Examples Ignore a local directory relative to the module root ignore ./node_modules Ignore all directories named generated anywhere in the module ignore generated Ignore multiple paths using a block ignore ( static content/html ./third_party/javascript ) Notes Use the ignore directive to prevent the go command from matching packages in generated or non-Go directories when using wildcard patterns like ./.... Ignored directories and their contents are excluded from package patterns but are still present in the module file tree. The ignore directive only applies in the main module’s go.mod file. It has no effect in go.mod files of dependencies.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ go mod init example/mymodule\n```\n\nExample:\n```text\nmodule example.com/mymodule\n\ngo 1.14\n\nrequire (\n    example.com/othermodule v1.2.3\n    example.com/thismodule v1.2.3\n    example.com/thatmodule v1.2.3\n)\n\nreplace example.com/thatmodule => ../thatmodule\nexclude example.com/thismodule v1.3.0\n```\n\nExample:\n```text\nmodule module-path\n```\n\nExample:\n```text\nmodule example.com/mymodule\n```\n\nExample:\n```text\nmodule example.com/mymodule/v2\n```\n\nExample:\n```text\ngo mod init <company-name>/stringtools\n```\n\nExample:\n```text\ngo minimum-go-version\n```\n\nExample:\n```text\ngo 1.14\n```\n\nExample:\n```text\ntoolchain toolchain-name\n```\n\nExample:\n```text\ntoolchain go1.21.0\n```\n\nExample:\n```text\ngodebug debug-key=debug-value\n```\n\nExample:\n```text\ngodebug asynctimerchan=0\n```\n\nExample:\n```text\ngodebug (\n    default=go1.21\n    panicnil=1\n)\n```\n\nExample:\n```text\nrequire module-path module-version\n```\n\nExample:\n```text\nrequire example.com/othermodule v1.2.3\n```\n\nExample:\n```text\nrequire example.com/othermodule v0.0.0-20200921210052-fa0125251cc4\n```\n\nExample:\n```text\ntool package-path\n```\n\nExample:\n```text\nmodule example.com/mymodule\n\ntool example.com/mymodule/cmd/mytool\n```\n\nExample:\n```text\nmodule example.com/mymodule\n\ntool example.com/atool/cmd/atool\n\nrequire example.com/atool v1.2.3\n```\n\nExample:\n```text\nreplace module-path [module-version] => replacement-path [replacement-version]\n```\n\nExample:\n```text\nrequire example.com/othermodule v1.2.3\n\nreplace example.com/othermodule => example.com/myfork/othermodule v1.2.3-fixed\n```\n\nExample:\n```text\nrequire example.com/othermodule v1.2.2\n\nreplace example.com/othermodule => example.com/othermodule v1.2.3\n```\n\nExample:\n```text\nreplace example.com/othermodule v1.2.5 => example.com/othermodule v1.2.3\n```\n\nExample:\n```text\nrequire example.com/othermodule v1.2.3\n\nreplace example.com/othermodule => ../othermodule\n```\n\nExample:\n```text\nrequire example.com/othermodule v1.2.5\n\nreplace example.com/othermodule v1.2.5 => ../othermodule\n```\n\nExample:\n```text\nrequire example.com/mod v0.0.0-replace\n\nreplace example.com/mod v0.0.0-replace => ./mod\n```\n\nExample:\n```text\nexclude module-path module-version\n```\n\nExample:\n```text\nexclude example.com/theirmodule v1.3.0\n```\n\nExample:\n```text\ngo mod edit -exclude=example.com/theirmodule@v1.3.0\n```\n\nExample:\n```text\nretract version // rationale\nretract [version-low,version-high] // rationale\n```\n\nExample:\n```text\nretract v1.1.0 // Published accidentally.\n```\n\nExample:\n```text\nretract [v1.0.0,v1.0.5] // Build broken on some platforms.\n```\n\nExample:\n```text\nretract v1.0.0 // Published accidentally.\nretract v1.0.1 // Contains retraction only.\n```\n\nExample:\n```text\nignore path\n```\n\nExample:\n```text\nignore ./node_modules\n```\n\nExample:\n```text\nignore generated\n```\n\nExample:\n```text\nignore (\n    static\n    content/html\n    ./third_party/javascript\n)\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.525Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":37,"totalLines":226,"estimatedTokens":5928}}44{"id":"doc-accessing_relational_databases_the_go_programmin-f70b7db8","source":"documentation","title":"Accessing relational databases - The Go Programming Language","url":"https://go.dev/doc/database/index","text":"Documentation Accessing relational databases Accessing relational databases Using Go, you can incorporate a wide variety of databases and data access approaches into your applications. Topics in this section describe how to use the standard library’s database/sql package to access relational databases. For an introductory tutorial to data access with Go, please see a relational database. Go supports other data access technologies as well, including ORM libraries for higher-level access to relational databases, and also non-relational NoSQL data stores. Object-relational mapping (ORM) libraries. While the database/sql package includes functions for lower-level data access logic, you can also use Go to access data stores at a higher abstraction level. For more about two popular object-relational mapping (ORM) libraries for Go, see GORM (package reference) and ent (package reference). NoSQL data stores. The Go community has developed drivers for the majority of NoSQL data stores, including MongoDB and Couchbase. You can search pkg.go.dev for more. Supported database management systems Go supports all of the most common relational database management systems, including MySQL, Oracle, Postgres, SQL Server, SQLite, and more. You’ll find a complete list of drivers at the SQLDrivers page. Functions to execute queries or make database changes The database/sql package includes functions specifically designed for the kind of database operation you’re executing. For example, while you can use Query or QueryRow to execute queries, QueryRow is designed for the case when you’re expecting only a single row, omitting the overhead of returning an sql.Rows that includes only one row. You can use the Exec function to make database changes with SQL statements such as INSERT, UPDATE, or DELETE. For more, see the SQL statements that don’t return data Querying for data Transactions Through sql.Tx, you can write code to execute database operations in a transaction. In a transaction, multiple operations can be performed together and conclude with a final commit, to apply all the changes in one atomic step, or a rollback, to discard them. For more about transactions, see Executing transactions. Query cancellation You can use context.Context when you want the ability to cancel a database operation, such as when the client’s connection closes or the operation runs longer than you want it to. For any database operation, you can use a database/sql package function that takes Context as an argument. Using the Context, you can specify a timeout or deadline for the operation. You can also use the Context to propagate a cancellation request through your application to the function executing an SQL statement, ensuring that resources are freed up if they’re no longer needed. For more, see Canceling in-progress operations. Managed connection pool When you use the sql.DB database handle, you’re connecting with a built-in connection pool that creates and disposes of connections according to your code’s needs. A handle through sql.DB is the most common way to do database access with Go. For more, see Opening a database handle. The database/sql package manages the connection pool for you. However, for more advanced needs, you can set connection pool properties as described in Setting connection pool properties. For those operations in which you need a single reserved connection, the database/sql package provides sql.Conn. Conn is especially useful when a transaction with sql.Tx would be a poor choice. For example, your code might need schema changes through a DDL, including logic that contains its own transaction semantics. Mixing sql package transaction functions with SQL transaction statements is a poor practice, as described in Executing transactions. Perform query locking operations that create temporary tables. For more, see Using dedicated connections.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.532Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":0,"totalLines":5,"estimatedTokens":1007}}45{"id":"doc-querying_for_data_the_go_programming_language-f6f79ec7","source":"documentation","title":"Querying for data - The Go Programming Language","url":"https://go.dev/doc/database/querying","text":"Querying for data When executing an SQL statement that returns data, use one of the Query methods provided in the database/sql package. Each of these returns a Row or Rows whose data you can copy to variables using the Scan method. You’d use these methods to, for example, execute SELECT statements. When executing a statement that doesn’t return data, you can use an Exec or ExecContext method instead. For more, see Executing statements that don’t return data. The database/sql package provides two ways to execute a query for results. Querying for a single row – QueryRow returns at most a single Row from the database. For more, see Querying for a single row. Querying for multiple rows – Query returns all matching rows as a Rows struct your code can loop over. For more, see Querying for multiple rows. If your code will be executing the same SQL statement repeatedly, consider using a prepared statement. For more, see Using prepared statements. ’t use string formatting functions such as fmt.Sprintf to assemble an SQL statement! You could introduce an SQL injection risk. For more, see Avoiding SQL injection risk. Querying for a single row QueryRow retrieves at most a single database row, such as when you want to look up data by a unique ID. If multiple rows are returned by the query, the Scan method discards all but the first. QueryRowContext works like QueryRow but with a context.Context argument. For more, see Canceling in-progress operations. The following example uses a query to find out if there’s enough inventory to support a purchase. The SQL statement returns true if there’s enough, false if not. Row.Scan copies the boolean return value into the enough variable through a pointer. func canPurchase(id int, quantity int) (bool, error) { var enough bool // Query for a value based on a single row. if err := db.QueryRow(\"SELECT (quantity >= ?) from album where id = ?\", quantity, id).Scan(&enough); err != nil { if err == sql.ErrNoRows { return false, fmt.Errorf(\"canPurchase %d: unknown album\", id) } return false, fmt.Errorf(\"canPurchase %d: %v\", id, err) } return enough, nil } placeholders in prepared statements vary depending on the DBMS and driver you’re using. For example, the pq driver for Postgres requires a placeholder like $1 instead of ?. Handling errors QueryRow itself returns no error. Instead, Scan reports any error from the combined lookup and scan. It returns sql.ErrNoRows when the query finds no rows. Functions for returning a single row Function Description DB.QueryRow DB.QueryRowContext Run a single-row query in isolation. Tx.QueryRow Tx.QueryRowContext Run a single-row query inside a larger transaction. For more, see Executing transactions. Stmt.QueryRow Stmt.QueryRowContext Run a single-row query using an already-prepared statement. For more, see Using prepared statements. Conn.QueryRowContext For use with reserved connections. For more, see Managing connections. Querying for multiple rows You can query for multiple rows using Query or QueryContext, which return a Rows representing the query results. Your code iterates over the returned rows using Rows.Next. Each iteration calls Scan to copy column values into variables. QueryContext works like Query but with a context.Context argument. For more, see Canceling in-progress operations. The following example executes a query to return the albums by a specified artist. The albums are returned in an sql.Rows. The code uses Rows.Scan to copy column values into variables represented by pointers. func albumsByArtist(artist string) ([]Album, error) { rows, err := db.Query(\"SELECT * FROM album WHERE artist = ?\", artist) if err != nil { return nil, err } defer rows.Close() // An album slice to hold data from returned rows. var albums []Album // Loop through rows, using Scan to assign column data to struct fields. for rows.Next() { var alb Album if err := rows.Scan(&alb.ID, &alb.Title, &alb.Artist, &alb.Price, &alb.Quantity); err != nil { return albums, err } albums = append(albums, alb) } if err = rows.Err(); err != nil { return albums, err } return albums, nil } Note the deferred call to rows.Close. This releases any resources held by the rows no matter how the function returns. Looping all the way through the rows also closes it implicitly, but it is better to use defer to make sure rows is closed no matter what. placeholders in prepared statements vary depending on the DBMS and driver you’re using. For example, the pq driver for Postgres requires a placeholder like $1 instead of ?. Handling errors Be sure to check for an error from sql.Rows after looping over query results. If the query failed, this is how your code finds out. Functions for returning multiple rows Function Description DB.Query DB.QueryContext Run a query in isolation. Tx.Query Tx.QueryContext Run a query inside a larger transaction. For more, see Executing transactions. Stmt.Query Stmt.QueryContext Run a query using an already-prepared statement. For more, see Using prepared statements. Conn.QueryContext For use with reserved connections. For more, see Managing connections. Handling nullable column values The database/sql package provides several special types you can use as arguments for the Scan function when a column’s value might be null. Each includes a Valid field that reports whether the value is non-null, and a field holding the value if so. Code in the following example queries for a customer name. If the name value is null, the code substitutes another value for use in the application. var s sql.NullString err := db.QueryRow(\"SELECT name FROM customer WHERE id = ?\", id).Scan(&s) if err != nil { log.Fatal(err) } // Find customer name, using placeholder if not present. name := \"Valued Customer\" if s.Valid { name = s.String } See more about each type in the sql package NullFloat64 NullInt32 NullInt64 NullString NullTime Getting data from columns When looping over the rows returned by a query, you use Scan to copy a row’s column values into Go values, as described in the Rows.Scan reference. There is a base set of data conversions supported by all drivers, such as converting SQL INT to Go int. Some drivers extend this set of conversions; see each individual driver’s documentation for details. As you might expect, Scan will convert from column types to Go types that are similar. For example, Scan will convert from SQL CHAR, VARCHAR, and TEXT to Go string. However, Scan will also perform a conversion to another Go type that is a good fit for the column value. For example, if the column is a VARCHAR that will always contain a number, you can specify a numeric Go type, such as int, to receive the value, and Scan will convert it using strconv.Atoi for you. For more detail about conversions made by the Scan function, see the Rows.Scan reference. Handling multiple result sets When your database operation might return multiple result sets, you can retrieve those by using Rows.NextResultSet. This can be useful, for example, when you’re sending SQL that separately queries multiple tables, returning a result set for each. Rows.NextResultSet prepares the next result set so that a call to Rows.Next retrieves the first row from that next set. It returns a boolean indicating whether there is a next result set at all. Code in the following example uses DB.Query to execute two SQL statements. The first result set is from the first query in the procedure, retrieving all of the rows in the album table. The next result set is from the second query, retrieving rows from the song table. rows, err := db.Query(\"SELECT * from album; SELECT * from song;\") if err != nil { log.Fatal(err) } defer rows.Close() // Loop through the first result set. for rows.Next() { // Handle result set. } // Advance to next result set. rows.NextResultSet() // Loop through the second result set. for rows.Next() { // Handle second set. } // Check for any error in either result set. if err := rows.Err(); err != nil { log.Fatal(err) }\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\nfunc canPurchase(id int, quantity int) (bool, error) {\n    var enough bool\n    // Query for a value based on a single row.\n    if err := db.QueryRow(\"SELECT (quantity >= ?) from album where id = ?\",\n        quantity, id).Scan(&enough); err != nil {\n        if err == sql.ErrNoRows {\n            return false, fmt.Errorf(\"canPurchase %d: unknown album\", id)\n        }\n        return false, fmt.Errorf(\"canPurchase %d: %v\", id, err)\n    }\n    return enough, nil\n}\n```\n\nExample:\n```text\nfunc albumsByArtist(artist string) ([]Album, error) {\n    rows, err := db.Query(\"SELECT * FROM album WHERE artist = ?\", artist)\n    if err != nil {\n        return nil, err\n    }\n    defer rows.Close()\n\n    // An album slice to hold data from returned rows.\n    var albums []Album\n\n    // Loop through rows, using Scan to assign column data to struct fields.\n    for rows.Next() {\n        var alb Album\n        if err := rows.Scan(&alb.ID, &alb.Title, &alb.Artist,\n            &alb.Price, &alb.Quantity); err != nil {\n            return albums, err\n        }\n        albums = append(albums, alb)\n    }\n    if err = rows.Err(); err != nil {\n        return albums, err\n    }\n    return albums, nil\n}\n```\n\nExample:\n```text\nvar s sql.NullString\nerr := db.QueryRow(\"SELECT name FROM customer WHERE id = ?\", id).Scan(&s)\nif err != nil {\n    log.Fatal(err)\n}\n\n// Find customer name, using placeholder if not present.\nname := \"Valued Customer\"\nif s.Valid {\n    name = s.String\n}\n```\n\nExample:\n```text\nrows, err := db.Query(\"SELECT * from album; SELECT * from song;\")\nif err != nil {\n    log.Fatal(err)\n}\ndefer rows.Close()\n\n// Loop through the first result set.\nfor rows.Next() {\n    // Handle result set.\n}\n\n// Advance to next result set.\nrows.NextResultSet()\n\n// Loop through the second result set.\nfor rows.Next() {\n    // Handle second set.\n}\n\n// Check for any error in either result set.\nif err := rows.Err(); err != nil {\n    log.Fatal(err)\n}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.533Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":4,"totalLines":91,"estimatedTokens":2512}}46{"id":"doc-tutorial_accessing_a_relational_database_the_go_-98489c34","source":"documentation","title":"Tutorial: Accessing a relational database - The Go Programming Language","url":"https://go.dev/doc/tutorial/database-access","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ cd\n```\n\nExample:\n```text\nC:\\> cd %HOMEPATH%\n```\n\nExample:\n```text\n$ mkdir data-access\n$ cd data-access\n```\n\nExample:\n```text\n$ go mod init example/data-access\ngo: creating new go.mod: module example/data-access\n```\n\nExample:\n```text\n$ mysql -u root -p\nEnter password:\n\nmysql>\n```\n\nExample:\n```text\nmysql> create database recordings;\n```\n\nExample:\n```text\nmysql> use recordings;\nDatabase changed\n```\n\nExample:\n```text\nDROP TABLE IF EXISTS album;\nCREATE TABLE album (\n  id         INT AUTO_INCREMENT NOT NULL,\n  title      VARCHAR(128) NOT NULL,\n  artist     VARCHAR(255) NOT NULL,\n  price      DECIMAL(5,2) NOT NULL,\n  PRIMARY KEY (`id`)\n);\n\nINSERT INTO album\n  (title, artist, price)\nVALUES\n  ('Blue Train', 'John Coltrane', 56.99),\n  ('Giant Steps', 'John Coltrane', 63.99),\n  ('Jeru', 'Gerry Mulligan', 17.99),\n  ('Sarah Vaughan', 'Sarah Vaughan', 34.98);\n```\n\nExample:\n```text\nmysql> source /path/to/create-tables.sql\n```\n\nExample:\n```text\nmysql> select * from album;\n+----+---------------+----------------+-------+\n| id | title         | artist         | price |\n+----+---------------+----------------+-------+\n|  1 | Blue Train    | John Coltrane  | 56.99 |\n|  2 | Giant Steps   | John Coltrane  | 63.99 |\n|  3 | Jeru          | Gerry Mulligan | 17.99 |\n|  4 | Sarah Vaughan | Sarah Vaughan  | 34.98 |\n+----+---------------+----------------+-------+\n4 rows in set (0.00 sec)\n```\n\nExample:\n```text\npackage main\n\nimport \"github.com/go-sql-driver/mysql\"\n```\n\nExample:\n```text\nvar db *sql.DB\n\nfunc main() {\n    // Capture connection properties.\n    cfg := mysql.NewConfig()\n    cfg.User = os.Getenv(\"DBUSER\")\n    cfg.Passwd = os.Getenv(\"DBPASS\")\n    cfg.Net = \"tcp\"\n    cfg.Addr = \"127.0.0.1:3306\"\n    cfg.DBName = \"recordings\"\n\n    // Get a database handle.\n    var err error\n    db, err = sql.Open(\"mysql\", cfg.FormatDSN())\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    pingErr := db.Ping()\n    if pingErr != nil {\n        log.Fatal(pingErr)\n    }\n    fmt.Println(\"Connected!\")\n}\n```\n\nExample:\n```text\npackage main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n\n    \"github.com/go-sql-driver/mysql\"\n)\n```\n\nExample:\n```text\n$ go get .\ngo: added filippo.io/edwards25519 v1.1.0\ngo: added github.com/go-sql-driver/mysql v1.8.1\n```\n\nExample:\n```text\n$ export DBUSER=username\n$ export DBPASS=password\n```\n\nExample:\n```text\nC:\\Users\\you\\data-access> set DBUSER=username\nC:\\Users\\you\\data-access> set DBPASS=password\n```\n\nExample:\n```text\n$ go run .\nConnected!\n```\n\nExample:\n```text\ntype Album struct {\n    ID     int64\n    Title  string\n    Artist string\n    Price  float32\n}\n```\n\nExample:\n```text\n// albumsByArtist queries for albums that have the specified artist name.\nfunc albumsByArtist(name string) ([]Album, error) {\n    // An albums slice to hold data from returned rows.\n    var albums []Album\n\n    rows, err := db.Query(\"SELECT * FROM album WHERE artist = ?\", name)\n    if err != nil {\n        return nil, fmt.Errorf(\"albumsByArtist %q: %v\", name, err)\n    }\n    defer rows.Close()\n    // Loop through rows, using Scan to assign column data to struct fields.\n    for rows.Next() {\n        var alb Album\n        if err := rows.Scan(&alb.ID, &alb.Title, &alb.Artist, &alb.Price); err != nil {\n            return nil, fmt.Errorf(\"albumsByArtist %q: %v\", name, err)\n        }\n        albums = append(albums, alb)\n    }\n    if err := rows.Err(); err != nil {\n        return nil, fmt.Errorf(\"albumsByArtist %q: %v\", name, err)\n    }\n    return albums, nil\n}\n```\n\nExample:\n```text\nalbums, err := albumsByArtist(\"John Coltrane\")\nif err != nil {\n    log.Fatal(err)\n}\nfmt.Printf(\"Albums found: %v\\n\", albums)\n```\n\nExample:\n```text\n$ go run .\nConnected!\nAlbums found: [{1 Blue Train John Coltrane 56.99} {2 Giant Steps John Coltrane 63.99}]\n```\n\nExample:\n```text\n// albumByID queries for the album with the specified ID.\nfunc albumByID(id int64) (Album, error) {\n    // An album to hold data from the returned row.\n    var alb Album\n\n    row := db.QueryRow(\"SELECT * FROM album WHERE id = ?\", id)\n    if err := row.Scan(&alb.ID, &alb.Title, &alb.Artist, &alb.Price); err != nil {\n        if err == sql.ErrNoRows {\n            return alb, fmt.Errorf(\"albumsById %d: no such album\", id)\n        }\n        return alb, fmt.Errorf(\"albumsById %d: %v\", id, err)\n    }\n    return alb, nil\n}\n```\n\nExample:\n```text\n// Hard-code ID 2 here to test the query.\nalb, err := albumByID(2)\nif err != nil {\n    log.Fatal(err)\n}\nfmt.Printf(\"Album found: %v\\n\", alb)\n```\n\nExample:\n```text\n$ go run .\nConnected!\nAlbums found: [{1 Blue Train John Coltrane 56.99} {2 Giant Steps John Coltrane 63.99}]\nAlbum found: {2 Giant Steps John Coltrane 63.99}\n```\n\nExample:\n```text\n// addAlbum adds the specified album to the database,\n// returning the album ID of the new entry\nfunc addAlbum(alb Album) (int64, error) {\n    result, err := db.Exec(\"INSERT INTO album (title, artist, price) VALUES (?, ?, ?)\", alb.Title, alb.Artist, alb.Price)\n    if err != nil {\n        return 0, fmt.Errorf(\"addAlbum: %v\", err)\n    }\n    id, err := result.LastInsertId()\n    if err != nil {\n        return 0, fmt.Errorf(\"addAlbum: %v\", err)\n    }\n    return id, nil\n}\n```\n\nExample:\n```text\nalbID, err := addAlbum(Album{\n    Title:  \"The Modern Sound of Betty Carter\",\n    Artist: \"Betty Carter\",\n    Price:  49.99,\n})\nif err != nil {\n    log.Fatal(err)\n}\nfmt.Printf(\"ID of added album: %v\\n\", albID)\n```\n\nExample:\n```text\n$ go run .\nConnected!\nAlbums found: [{1 Blue Train John Coltrane 56.99} {2 Giant Steps John Coltrane 63.99}]\nAlbum found: {2 Giant Steps John Coltrane 63.99}\nID of added album: 5\n```\n\nExample:\n```text\npackage main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n\n    \"github.com/go-sql-driver/mysql\"\n)\n\nvar db *sql.DB\n\ntype Album struct {\n    ID     int64\n    Title  string\n    Artist string\n    Price  float32\n}\n\nfunc main() {\n    // Capture connection properties.\n    cfg := mysql.NewConfig()\n    cfg.User = os.Getenv(\"DBUSER\")\n    cfg.Passwd = os.Getenv(\"DBPASS\")\n    cfg.Net = \"tcp\"\n    cfg.Addr = \"127.0.0.1:3306\"\n    cfg.DBName = \"recordings\"\n\n    // Get a database handle.\n    var err error\n    db, err = sql.Open(\"mysql\", cfg.FormatDSN())\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    pingErr := db.Ping()\n    if pingErr != nil {\n        log.Fatal(pingErr)\n    }\n    fmt.Println(\"Connected!\")\n\n    albums, err := albumsByArtist(\"John Coltrane\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Printf(\"Albums found: %v\\n\", albums)\n\n    // Hard-code ID 2 here to test the query.\n    alb, err := albumByID(2)\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Printf(\"Album found: %v\\n\", alb)\n\n    albID, err := addAlbum(Album{\n        Title:  \"The Modern Sound of Betty Carter\",\n        Artist: \"Betty Carter\",\n        Price:  49.99,\n    })\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Printf(\"ID of added album: %v\\n\", albID)\n}\n\n// albumsByArtist queries for albums that have the specified artist name.\nfunc albumsByArtist(name string) ([]Album, error) {\n    // An albums slice to hold data from returned rows.\n    var albums []Album\n\n    rows, err := db.Query(\"SELECT * FROM album WHERE artist = ?\", name)\n    if err != nil {\n        return nil, fmt.Errorf(\"albumsByArtist %q: %v\", name, err)\n    }\n    defer rows.Close()\n    // Loop through rows, using Scan to assign column data to struct fields.\n    for rows.Next() {\n        var alb Album\n        if err := rows.Scan(&alb.ID, &alb.Title, &alb.Artist, &alb.Price); err != nil {\n            return nil, fmt.Errorf(\"albumsByArtist %q: %v\", name, err)\n        }\n        albums = append(albums, alb)\n    }\n    if err := rows.Err(); err != nil {\n        return nil, fmt.Errorf(\"albumsByArtist %q: %v\", name, err)\n    }\n    return albums, nil\n}\n\n// albumByID queries for the album with the specified ID.\nfunc albumByID(id int64) (Album, error) {\n    // An album to hold data from the returned row.\n    var alb Album\n\n    row := db.QueryRow(\"SELECT * FROM album WHERE id = ?\", id)\n    if err := row.Scan(&alb.ID, &alb.Title, &alb.Artist, &alb.Price); err != nil {\n        if err == sql.ErrNoRows {\n            return alb, fmt.Errorf(\"albumsById %d: no such album\", id)\n        }\n        return alb, fmt.Errorf(\"albumsById %d: %v\", id, err)\n    }\n    return alb, nil\n}\n\n// addAlbum adds the specified album to the database,\n// returning the album ID of the new entry\nfunc addAlbum(alb Album) (int64, error) {\n    result, err := db.Exec(\"INSERT INTO album (title, artist, price) VALUES (?, ?, ?)\", alb.Title, alb.Artist, alb.Price)\n    if err != nil {\n        return 0, fmt.Errorf(\"addAlbum: %v\", err)\n    }\n    id, err := result.LastInsertId()\n    if err != nil {\n        return 0, fmt.Errorf(\"addAlbum: %v\", err)\n    }\n    return id, nil\n}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.552Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":407,"estimatedTokens":2223}}47{"id":"doc-opening_a_database_handle_the_go_programming_lan-65d37761","source":"documentation","title":"Opening a database handle - The Go Programming Language","url":"https://go.dev/doc/database/open-handle","text":"Documentation Accessing relational databases Opening a database handle Opening a database handle The database/sql package simplifies database access by reducing the need for you to manage connections. Unlike many data access APIs, with database/sql you don’t explicitly open a connection, do work, then close the connection. Instead, your code opens a database handle that represents a connection pool, then executes data access operations with the handle, calling a Close method only when needed to free resources, such as those held by retrieved rows or a prepared statement. In other words, it’s the database handle, represented by an sql.DB, that handles connections, opening and closing them on your code’s behalf. As your code uses the handle to execute database operations, those operations have concurrent access to the database. For more, see Managing connections. can also reserve a database connection. For more information, see Using dedicated connections. In addition to the APIs available in the database/sql package, the Go community has developed drivers for all of the most common (and many uncommon) database management systems (DBMSes). When opening a database handle, you follow these high-level a driver. A driver translates requests and responses between your Go code and the database. For more, see Locating and importing a database driver. Open a database handle. After you’ve imported the driver, you can open a handle for a specific database. For more, see Opening a database handle. Confirm a connection. Once you’ve opened a database handle, your code can check that a connection is available. For more, see Confirming a connection. Your code typically won’t explicitly open or close database connections – that’s done by the database handle. However, your code should free resources it obtains along the way, such as an sql.Rows containing query results. For more, see Freeing resources. Locating and importing a database driver You’ll need a database driver that supports the DBMS you’re using. To locate a driver for your database, see SQLDrivers. To make the driver available to your code, you import it as you would another Go package. Here’s an \"github.com/go-sql-driver/mysql\" Note that if you’re not calling any functions directly from the driver package –- such as when it’s being used implicitly by the sql package – you’ll need to use a blank import, which prefixes the import path with an _ \"github.com/go-sql-driver/mysql\" a best practice, avoid using the database driver’s own API for database operations. Instead, use functions in the database/sql package. This will help keep your code loosely coupled with the DBMS, making it easier to switch to a different DBMS if you need to. Opening a database handle An sql.DB database handle provides the ability to read from and write to a database, either individually or in a transaction. You can get a database handle by calling either sql.Open (which takes a connection string) or sql.OpenDB (which takes a driver.Connector). Both return a pointer to an sql.DB. sure to keep your database credentials out of your Go source. For more, see Storing database credentials. Opening with a connection string Use the sql.Open function when you want to connect using a connection string. The format for the string will vary depending on the driver you’re using. Here’s an example for , err = sql.Open(\"mysql\", \"username:password@tcp(127.0.0.1:3306)/jazzrecords\") if err != nil { log.Fatal(err) } However, you’ll likely find that capturing connection properties in a more structured way gives you code that’s more readable. The details will vary by driver. For example, you could replace the preceding example with the following, which uses the MySQL driver’s Config to specify properties and its FormatDSN method to build a connection string. // Specify connection properties. cfg := mysql.NewConfig() cfg.User = username cfg.Passwd = password cfg.Net = \"tcp\" cfg.Addr = \"127.0.0.1:3306\" cfg.DBName = \"jazzrecords\" // Get a database handle. db, err = sql.Open(\"mysql\", cfg.FormatDSN()) if err != nil { log.Fatal(err) } Opening with a Connector Use the sql.OpenDB function when you want to take advantage of driver-specific connection features that aren’t available in a connection string. Each driver supports its own set of connection properties, often providing ways to customize the connection request specific to the DBMS. Adapting the preceding sql.Open example to use sql.OpenDB, you could create a handle with code such as the following: // Specify connection properties. cfg := mysql.NewConfig() cfg.User = username cfg.Passwd = password cfg.Net = \"tcp\" cfg.Addr = \"127.0.0.1:3306\" cfg.DBName = \"jazzrecords\" // Get a driver-specific connector. connector, err := mysql.NewConnector(&cfg) if err != nil { log.Fatal(err) } // Get a database handle. db = sql.OpenDB(connector) Handling errors Your code should check for an error from attempting to create a handle, such as with sql.Open. This won’t be a connection error. Instead, you’ll get an error if sql.Open was unable to initialize the handle. This could happen, for example, if it’s unable to parse the DSN you specified. Confirming a connection When you open a database handle, the sql package may not create a new database connection itself right away. Instead, it may create the connection when your code needs it. If you won’t be using the database right away and want to confirm that a connection could be established, call Ping or PingContext. Code in the following example pings the database to confirm a connection. db, err = sql.Open(\"mysql\", connString) // Confirm a successful connection. if err := db.Ping(); err != nil { log.Fatal(err) } Storing database credentials Avoid storing database credentials in your Go source, which could expose the contents of your database to others. Instead, find a way to store them in a location outside your code but available to it. For example, consider a secret keeper app that stores credentials and provides an API your code can use to retrieve credentials for authenticating with your DBMS. One popular approach is to store the secrets in the environment before the program starts, perhaps loaded from a secret manager, and then your Go program can read them using os.Getenv: username := os.Getenv(\"DB_USER\") password := os.Getenv(\"DB_PASS\") This approach also lets you set the environment variables yourself for local testing. Freeing resources Although you don’t manage or close connections explicitly with the database/sql package, your code should free resources it has obtained when they’re no longer needed. Those can include resources held by an sql.Rows representing data returned from a query or an sql.Stmt representing a prepared statement. Typically, you close resources by deferring a call to a Close function so that resources are released before the enclosing function exits. Code in the following example defers Close to free the resource held by sql.Rows. rows, err := db.Query(\"SELECT * FROM album WHERE artist = ?\", artist) if err != nil { log.Fatal(err) } defer rows.Close() // Loop through returned rows.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\nimport \"github.com/go-sql-driver/mysql\"\n```\n\nExample:\n```text\nimport _ \"github.com/go-sql-driver/mysql\"\n```\n\nExample:\n```text\ndb, err = sql.Open(\"mysql\", \"username:password@tcp(127.0.0.1:3306)/jazzrecords\")\nif err != nil {\n    log.Fatal(err)\n}\n```\n\nExample:\n```text\n// Specify connection properties.\ncfg := mysql.NewConfig()\ncfg.User = username\ncfg.Passwd = password\ncfg.Net = \"tcp\"\ncfg.Addr = \"127.0.0.1:3306\"\ncfg.DBName = \"jazzrecords\"\n\n// Get a database handle.\ndb, err = sql.Open(\"mysql\", cfg.FormatDSN())\nif err != nil {\n    log.Fatal(err)\n}\n```\n\nExample:\n```text\n// Specify connection properties.\ncfg := mysql.NewConfig()\ncfg.User = username\ncfg.Passwd = password\ncfg.Net = \"tcp\"\ncfg.Addr = \"127.0.0.1:3306\"\ncfg.DBName = \"jazzrecords\"\n\n// Get a driver-specific connector.\nconnector, err := mysql.NewConnector(&cfg)\nif err != nil {\n    log.Fatal(err)\n}\n\n// Get a database handle.\ndb = sql.OpenDB(connector)\n```\n\nExample:\n```text\ndb, err = sql.Open(\"mysql\", connString)\n\n// Confirm a successful connection.\nif err := db.Ping(); err != nil {\n    log.Fatal(err)\n}\n```\n\nExample:\n```text\nusername := os.Getenv(\"DB_USER\")\npassword := os.Getenv(\"DB_PASS\")\n```\n\nExample:\n```text\nrows, err := db.Query(\"SELECT * FROM album WHERE artist = ?\", artist)\nif err != nil {\n    log.Fatal(err)\n}\ndefer rows.Close()\n\n// Loop through returned rows.\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.553Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":8,"totalLines":87,"estimatedTokens":2154}}48{"id":"doc-managing_dependencies_the_go_programming_languag-f7f3b0f1","source":"documentation","title":"Managing dependencies - The Go Programming Language","url":"https://go.dev/doc/modules/managing-dependencies","text":"Managing dependencies When your code uses external packages, those packages (distributed as modules) become dependencies. Over time, you may need to upgrade them or replace them. Go provides dependency management tools that help you keep your Go applications secure as you incorporate external dependencies. This topic describes how to perform tasks to manage dependencies you take on in your code. You can perform most of these with Go tools. This topic also describes how to perform a few other dependency-related tasks you might find useful. See also If you’re new to working with dependencies as modules, take a look at the Getting started tutorial for a brief introduction. Using the go command to manage dependencies helps ensure that your requirements remain consistent and the content of your go.mod file is valid. For reference on the commands, see Command go. You can also get help from the command line by typing go help command-name, as with go help mod tidy. Go commands you use to make dependency changes edit your go.mod file. For more about the contents of the file, see go.mod file reference. Making your editor or IDE aware of Go modules can make the work of managing them easier. For more on editors that support Go, see Editor plugins and IDEs. This topic doesn’t describe how to develop, publish, and version modules for others to use. For more on that, see Developing and publishing modules. Workflow for using and managing dependencies You can get and use useful packages with Go tools. On pkg.go.dev, you can search for packages you might find useful, then use the go command to import those packages into your own code to call their functions. The following lists the most common dependency management steps. For more about each, see the sections in this topic. Locate useful packages on pkg.go.dev. Import the packages you want in your code. Add your code to a module for dependency tracking (if it isn’t in a module already). See Enabling dependency tracking Add external packages as dependencies so you can manage them. Upgrade or downgrade dependency versions as needed over time. Managing dependencies as modules In Go, you manage dependencies as modules that contain the packages you import. This process is supported decentralized system for publishing modules and retrieving their code. Developers make their modules available for other developers to use from their own repository and publish with a version number. A package search engine and documentation browser (pkg.go.dev) at which you can find modules. See Locating and importing useful packages. A module version numbering convention to help you understand a module’s stability and backward compatibility guarantees. See Module version numbering. Go tools that make it easier for you to manage dependencies, including getting a module’s source, upgrading, and so on. See sections of this topic for more. Locating and importing useful packages You can search pkg.go.dev to find packages with functions you might find useful. When you’ve found a package you want to use in your code, locate the package path at the top of the page and click the Copy path button to copy the path to your clipboard. In your own code, paste the path into an import statement, as in the following \"rsc.io/quote\" After your code imports the package, enable dependency tracking and get the package’s code to compile with. For more, see Enabling dependency tracking in your code and Adding a dependency. Enabling dependency tracking in your code To track and manage the dependencies you add, you begin by putting your code in its own module. This creates a go.mod file at the root of your source tree. Dependencies you add will be listed in that file. To add your code to its own module, use the go mod init command. For example, from the command line, change to your code’s root directory, then run the command as in the following example: $ go mod init example/mymodule The go mod init command’s argument is your module’s module path. If possible, the module path should be the repository location of your source code. If at first you don’t know the module’s eventual repository location, use a safe substitute. This might be the name of a domain you own or another name you control (such as your company name), along with a path following from the module’s name or source directory. For more, see Naming a module. As you use Go tools to manage dependencies, the tools update the go.mod file so that it maintains a current list of your dependencies. When you add dependencies, Go tools also create a go.sum file that contains checksums of modules you depend on. Go uses this to verify the integrity of downloaded module files, especially for other developers working on your project. Include the go.mod and go.sum files in your repository with your code. See the go.mod reference for more. Naming a module When you run go mod init to create a module for tracking dependencies, you specify a module path that serves as the module’s name. The module path becomes the import path prefix for packages in the module. Be sure to specify a module path that won’t conflict with the module path of other modules. At a minimum, a module path need only indicate something about its origin, such as a company or author or owner name. But the path might also be more descriptive about what the module is or does. The module path is typically of the following form: <prefix>/<descriptive-text> The prefix is typically a string that partially describes the module, such as a string that describes its origin. This might location of the repository where Go tools can find the module’s source code (required if you’re publishing the module). For example, it might be github.com/<project-name>/. Use this best practice if you think you might publish the module for others to use. For more about publishing, see Developing and publishing modules. A name you control. If you’re not using a repository name, be sure to choose a prefix that you’re confident won’t be used by others. A good choice is your company’s name. Avoid common terms such as widgets, utilities, or app. For the descriptive text, a good choice would be a project name. Remember that package names carry most of the weight of describing functionality. The module path creates a namespace for those package names. Reserved module path prefixes Go guarantees that the following strings won’t be used in package names. test – You can use test as a module path prefix for a module whose code is designed to locally test functions in another module. Use the test path prefix for modules that are created as part of a test. For example, your test itself might run go mod init test and then set up that module in some particular way in order to test with a Go source code analysis tool. example – Used as a module path prefix in some Go documentation, such as in tutorials where you’re creating a module just to track dependencies. Note that Go documentation also uses example.com to illustrate when the example might be a published module. Adding a dependency Once you’re importing packages from a published module, you can add that module to manage as a dependency by using the go get command. The command does the needed, it adds require directives to your go.mod file for modules needed to build packages named on the command line. A require directive tracks the minimum version of a module that your module depends on. See the go.mod reference for more. If needed, it downloads module source code so you can compile packages that depend on them. It can download modules from a module proxy like proxy.golang.org or directly from version control repositories. The source is cached locally. You can set the location from which Go tools download modules. For more, see Specifying a module proxy server. The following describes a few examples. To add all dependencies for a package in your module, run a command like the one below (\".\" refers to the package in the current directory): $ go get . To add a specific dependency, specify its module path as an argument to the command. $ go get example.com/theirmodule The command also authenticates each module it downloads. This ensures that it’s unchanged from when the module was published. If the module has changed since it was published – for example, the developer changed the contents of the commit – Go tools will present a security error. This authentication check protects you from modules that might have been tampered with. Getting a specific dependency version You can get a specific version of a dependency module by specifying its version in the go get command. The command updates the require directive in your go.mod file (though you can also update that manually). You might want to do this want to get a specific pre-release version of a module to try out. You’ve discovered that the version you’re currently requiring isn’t working for you, so you want to get a version you know you can rely on. You want to upgrade or downgrade a module you’re already requiring. Here are examples for using the go get get a specific numbered version, append the module path with an @ sign followed by the version you want: $ go get example.com/theirmodule@v1.3.4 To get the latest version, append the module path with @latest: $ go get example.com/theirmodule@latest The following go.mod file require directive example (see the go.mod reference for more) illustrates how to require a specific version example.com/theirmodule v1.3.4 Discovering available updates You can check to see if there are newer versions of dependencies you’re already using in your current module. Use the go list command to display a list of your module’s dependencies, along with the latest version available for that module. Once you’ve discovered available upgrades, you can try them out with your code to decide whether or not to upgrade to new versions. For more about the go list command, see go list -m. Here are a couple of examples. List all of the modules that are dependencies of your current module, along with the latest version available for each: $ go list -m -u all Display the latest version available for a specific module: $ go list -m -u example.com/theirmodule Upgrading or downgrading a dependency You can upgrade or downgrade a dependency module by using Go tools to discover available versions, then add a different version as a dependency. To discover new versions use the go list command as described in Discovering available updates. To add a particular version as a dependency, use the go get command as described in Getting a specific dependency version. Synchronizing your code’s dependencies You can ensure that you’re managing dependencies for all of your code’s imported packages while also removing dependencies for packages you’re no longer importing. This can be useful when you’ve been making changes to your code and dependencies, possibly creating a collection of managed dependencies and downloaded modules that no longer match the collection specifically required by the packages imported in your code. To keep your managed dependency set tidy, use the go mod tidy command. Using the set of packages imported in your code, this command edits your go.mod file to add modules that are necessary but missing. It also removes unused modules that don’t provide any relevant packages. The command has no arguments except for one flag, -v, that prints information about removed modules. $ go mod tidy Developing and testing against unpublished module code You can specify that your code should use dependency modules that may not be published. The code for these modules might be in their respective repositories, in a fork of those repositories, or on a drive with the current module that consumes them. You might want to do this want to make your own changes to an external module’s code, such as after forking and/or cloning it. For example, you might want to prepare a fix to the module, then send it as a pull request to the module’s developer. You’re building a new module and haven’t yet published it, so it’s unavailable on a repository where the go get command can reach it. Requiring module code in a local directory You can specify that the code for a required module is on the same local drive as the code that requires it. You might find this useful when you your own separate module and want to test from the current module. Fixing issues in or adding features to an external module and want to test from the current module. (Note that you can also require the external module from your own fork of its repository. For more, see Requiring external module code from your own repository fork.) To tell Go commands to use the local copy of the module’s code, use the replace directive in your go.mod file to replace the module path given in a require directive. See the go.mod reference for more about directives. In the following go.mod file example, the current module requires the external module example.com/theirmodule, with a nonexistent version number (v0.0.0-unpublished) used to ensure the replacement works correctly. The replace directive then replaces the original module path with ../theirmodule, a directory that is at the same level as the current module’s directory. module example.com/mymodule go 1.23.0 require example.com/theirmodule v0.0.0-unpublished replace example.com/theirmodule v0.0.0-unpublished => ../theirmodule When setting up a require/replace pair, use the go mod edit and go get commands to ensure that requirements described by the file remain consistent: $ go mod edit -replace=example.com/theirmodule@v0.0.0-unpublished=../theirmodule $ go get example.com/theirmodule@v0.0.0-unpublished you use the replace directive, Go tools don’t authenticate external modules as described in Adding a dependency. For more about version numbers, see Module version numbering. Go 1.18 adds workspace mode to Go, which lets you work on multiple modules simultaneously. See started with multi-module workspaces. Requiring external module code from your own repository fork When you have forked an external module’s repository (such as to fix an issue in the module’s code or to add a feature), you can have Go tools use your fork for the module’s source. This can be useful for testing changes from your own code. (Note that you can also require the module code in a directory that’s on the local drive with the module that requires it. For more, see Requiring module code in a local directory.) You do this by using a replace directive in your go.mod file to replace the external module’s original module path with a path to the fork in your repository. This directs Go tools to use the replacement path (the fork’s location) when compiling, for example, while allowing you to leave import statements unchanged from the original module path. For more about the replace directive, see the go.mod file reference. In the following go.mod file example, the current module requires the external module example.com/theirmodule. The replace directive then replaces the original module path with example.com/myfork/theirmodule, a fork of the module’s own repository. module example.com/mymodule go 1.23.0 require example.com/theirmodule v1.2.3 replace example.com/theirmodule v1.2.3 => example.com/myfork/theirmodule v1.2.3-fixed When setting up a require/replace pair, use Go tool commands to ensure that requirements described by the file remain consistent. Use the go list command to get the version in use by the current module. Then use the go mod edit command to replace the required module with the fork: $ go list -m example.com/theirmodule example.com/theirmodule v1.2.3 $ go mod edit -replace=example.com/theirmodule@v1.2.3=example.com/myfork/theirmodule@v1.2.3-fixed you use the replace directive, Go tools don’t authenticate external modules as described in Adding a dependency. For more about version numbers, see Module version numbering. Getting a specific commit using a repository identifier You can use the go get command to add unpublished code for a module from a specific commit in its repository. To do this, you use the go get command, specifying the code you want with an @ sign. When you use go get, the command will add to your go.mod file a require directive that requires the external module, using a pseudo-version number based on details about the commit. The following examples provide a few illustrations. These are based on a module whose source is in a git repository. To get the module at a specific commit, append the form @commithash: $ go get example.com/theirmodule@4cf76c2 To get the module at a specific branch, append the form @branchname: $ go get example.com/theirmodule@bugfixes Removing a dependency When your code no longer uses any packages in a module, you can stop tracking the module as a dependency. To stop tracking all unused modules, run the go mod tidy command. This command may also add missing dependencies needed to build packages in your module. $ go mod tidy To remove a specific dependency, use the go get command, specifying the module’s module path and appending @none, as in the following example: $ go get example.com/theirmodule@none The go get command will also downgrade or remove other dependencies that depend on the removed module. Tool dependencies Tool dependencies let you manage developer tools that are written in Go and used when working on your module. For example, you might use stringer with go generate, or a specific linter or formatter as part of preparing your change for submission. In Go 1.24 and above, you can add a tool dependency with: $ go get -tool golang.org/x/tools/cmd/stringer This will add a tool directive to your go.mod file, and ensure the necessary require directives are present. Once this directive is added you can run the tool by passing the last non-major-version component of the tool’s import path to go tool: $ go tool stringer In the case that multiple tools share the last path fragment, or the path fragment matches one of the tools shipped with the Go distribution, you must pass the full package path instead: $ go tool golang.org/x/tools/cmd/stringer To see a list of all tools currently available, run go tool with no arguments: $ go tool You can manually add a tool directive to your go.mod, but you must ensure that there is a require directive for the module that defines the tool. The easiest way to add any missing require directives is to run: $ go mod tidy Requirements needed to satisfy tool dependencies behave like any other requirements in your module graph. They participate in minimal version selection and respect require, replace and exclude directives. Due to module pruning, when you depend on a module that itself has a tool dependency, requirements that exist just to satisfy that tool dependency do not usually become requirements of your module. The tool meta-pattern provides a way to perform operations on all tools simultaneously. For example you can upgrade all tools with go get tool, which is equivalent to go get tool@upgrade, or install them all to $GOBIN with go install tool. In Go versions before 1.24, you can achieve something similar to a tool directive by adding a blank import to a go file within the module that is excluded from the build using build constraints. If you do this, you can then use go run with the full package path to run the tool. Specifying a module proxy server When you use Go tools to work with modules, the tools by default download modules from proxy.golang.org (a public Google-run module mirror) or directly from the module’s repository. You can specify that Go tools should instead use another proxy server for downloading and authenticating modules. You might want to do this if you (or your team) have set up or chosen a different module proxy server that you want to use. For example, some set up a module proxy server in order to have greater control over how dependencies are used. To specify another module proxy server for Go tools use, set the GOPROXY environment variable to the URL of one or more servers. Go tools will try each URL in the order you specify. By default, GOPROXY specifies a public Google-run module proxy first, then direct download from the module’s repository (as specified in its module path): GOPROXY=\"https://proxy.golang.org,direct\" For more about the GOPROXY environment variable, including values to support other behavior, see the go command reference. You can set the variable to URLs for other module proxy servers, separating URLs with either a comma or a pipe. When you use a comma, Go tools will try the next URL in the list only if the current URL returns an HTTP 404 or 410. GOPROXY=\"https://proxy.example.com,https://proxy2.example.com\" When you use a pipe, Go tools will try the next URL in the list regardless of the HTTP error code. GOPROXY=\"https://proxy.example.com|https://proxy2.example.com\" Go modules are frequently developed and distributed on version control servers and module proxies that aren’t available on the public internet. You can set the GOPRIVATE environment variable to configure the go command to download and build modules from private sources. Then the go command can download and build modules from private sources. The GOPRIVATE or GONOPROXY environment variables may be set to lists of glob patterns matching module prefixes that are private and should not be requested from any proxy. For =*.corp.example.com,*.research.example.com\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\nimport \"rsc.io/quote\"\n```\n\nExample:\n```text\n$ go mod init example/mymodule\n```\n\nExample:\n```text\n<prefix>/<descriptive-text>\n```\n\nExample:\n```text\n$ go get .\n```\n\nExample:\n```text\n$ go get example.com/theirmodule\n```\n\nExample:\n```text\n$ go get example.com/theirmodule@v1.3.4\n```\n\nExample:\n```text\n$ go get example.com/theirmodule@latest\n```\n\nExample:\n```text\nrequire example.com/theirmodule v1.3.4\n```\n\nExample:\n```text\n$ go list -m -u all\n```\n\nExample:\n```text\n$ go list -m -u example.com/theirmodule\n```\n\nExample:\n```text\n$ go mod tidy\n```\n\nExample:\n```text\nmodule example.com/mymodule\n\ngo 1.23.0\n\nrequire example.com/theirmodule v0.0.0-unpublished\n\nreplace example.com/theirmodule v0.0.0-unpublished => ../theirmodule\n```\n\nExample:\n```text\n$ go mod edit -replace=example.com/theirmodule@v0.0.0-unpublished=../theirmodule\n$ go get example.com/theirmodule@v0.0.0-unpublished\n```\n\nExample:\n```text\nmodule example.com/mymodule\n\ngo 1.23.0\n\nrequire example.com/theirmodule v1.2.3\n\nreplace example.com/theirmodule v1.2.3 => example.com/myfork/theirmodule v1.2.3-fixed\n```\n\nExample:\n```text\n$ go list -m example.com/theirmodule\nexample.com/theirmodule v1.2.3\n$ go mod edit -replace=example.com/theirmodule@v1.2.3=example.com/myfork/theirmodule@v1.2.3-fixed\n```\n\nExample:\n```text\n$ go get example.com/theirmodule@4cf76c2\n```\n\nExample:\n```text\n$ go get example.com/theirmodule@bugfixes\n```\n\nExample:\n```text\n$ go get example.com/theirmodule@none\n```\n\nExample:\n```text\n$ go get -tool golang.org/x/tools/cmd/stringer\n```\n\nExample:\n```text\n$ go tool stringer\n```\n\nExample:\n```text\n$ go tool golang.org/x/tools/cmd/stringer\n```\n\nExample:\n```text\n$ go tool\n```\n\nExample:\n```text\nGOPROXY=\"https://proxy.golang.org,direct\"\n```\n\nExample:\n```text\nGOPROXY=\"https://proxy.example.com,https://proxy2.example.com\"\n```\n\nExample:\n```text\nGOPROXY=\"https://proxy.example.com|https://proxy2.example.com\"\n```\n\nExample:\n```text\nGOPRIVATE=*.corp.example.com,*.research.example.com\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.555Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":26,"totalLines":150,"estimatedTokens":5899}}49{"id":"doc-managing_module_source_the_go_programming_langua-f25a261f","source":"documentation","title":"Managing module source - The Go Programming Language","url":"https://go.dev/doc/modules/managing-source","text":"Managing module source When you’re developing modules to publish for others to use, you can help ensure that your modules are easier for other developers to use by following the repository conventions described in this topic. This topic describes actions you might take when managing your module repository. For information about the sequence of workflow steps you’d take when revising from version to version, see Module release and versioning workflow. Some of the conventions described here are required in modules, while others are best practices. This content assumes you’re familiar with the basic module use practices described in Managing dependencies. Go supports the following repositories for publishing , Subversion, Mercurial, Bazaar, and Fossil. For an overview of module development, see Developing and publishing modules. How Go tools find your published module In Go’s decentralized system for publishing modules and retrieving their code, you can publish your module while leaving the code in your repository. Go tools rely on naming rules that have repository paths and repository tags indicating a module’s name and version number. When your repository follows these requirements, your module code is downloadable from your repository by Go tools such as the go get command. When a developer uses the go get command to get source code for packages their code imports, the command does the import statements in Go source code, go get identifies the module path within the package path. Using a URL derived from the module path, the command locates the module source on a module proxy server or at its repository directly. Locates source for the module version to download by matching the module’s version number to a repository tag to discover the code in the repository. When a version number to use is not yet known, go get locates the latest release version. Retrieves module source and downloads it to the developer’s local module cache. Organizing code in the repository You can keep maintenance simple and improve developers’ experience with your module by following the conventions described here. Getting your module code into a repository is generally as simple as with other code. The following diagram illustrates a source hierarchy for a simple module with two packages. Your initial commit should include files listed in the following Description LICENSE The module's license. go.mod Describes the module, including its module path (in effect, its name) and its dependencies. For more, see the go.mod reference. The module path will be given in a module directive, such example.com/mymodule For more about choosing a module path, see Managing dependencies. Though you can edit the go.mod file, you'll find it more reliable to make changes through go commands. go.sum Contains cryptographic hashes that represent the module's dependencies. Go tools use these hashes to authenticate downloaded modules, attempting to confirm that the downloaded module is authentic. Where this confirmation fails, Go will display a security error. The file will be empty or not present when there are no dependencies. You shouldn't edit this file except by using the go mod tidy command, which removes unneeded entries. Package directories and .go sources. Directories and .go files that comprise the Go packages and sources in the module. From the command-line, you can create an empty repository, add the files that will be part of your initial commit, and commit with a message. Here’s an example using git: $ git init $ git add --all $ git commit -m \"mycode: initial commit\" $ git push Choosing repository scope You publish code in a module when the code should be versioned independently from code in other modules. Designing your repository so that it hosts a single module at its root directory will help keep maintenance simpler, particularly over time as you publish new minor and patch versions, branch into new major versions, and so on. However, if your needs require it, you can instead maintain a collection of modules in a single repository. Sourcing one module per repository You can maintain a repository that has a single module’s source in it. In this model, you place your go.mod file at the repository root, with package subdirectories containing Go source beneath. This is the simplest approach, making your module likely easier to manage over time. It helps you avoid the need to prefix a module version number with a directory path. Sourcing multiple modules in a single repository You can publish multiple modules from a single repository. For example, you might have code in a single repository that constitutes multiple modules, but want to version those modules separately. Each subdirectory that is a module root directory must have its own go.mod file. Sourcing module code in subdirectories changes the form of the version tag you must use when publishing a module. You must prefix the version number part of the tag with the name of the subdirectory that is the module root. For more about version numbers, see Module version numbering. For example, for module example.com/mymodules/module1 below, you would have the following for version v1.2.3: Module /mymodules/module1 Version /v1.2.3 Package path imported by a /mymodules/module1/package1 Module path and version as specified in a user’s require /mymodules/module1 v1.2.3\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\nmodule example.com/mymodule\n```\n\nExample:\n```text\n$ git init\n$ git add --all\n$ git commit -m \"mycode: initial commit\"\n$ git push\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.560Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":2,"totalLines":18,"estimatedTokens":1416}}50{"id":"doc-contribution_guide_the_go_programming_language-65bb8cf3","source":"documentation","title":"Contribution Guide - The Go Programming Language","url":"https://go.dev/doc/contribute","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\n$ go install golang.org/x/tools/cmd/go-contrib-init@latest\n$ cd /code/to/edit\n$ go-contrib-init\n```\n\nExample:\n```text\n$ git config --global user.email  # check current global config\n$ git config user.email           # check current local config\n```\n\nExample:\n```text\n$ git config --global user.email name@example.com   # change global config\n$ git config user.email name@example.com            # change local config\n```\n\nExample:\n```text\n$ go install golang.org/x/review/git-codereview@latest\n```\n\nExample:\n```text\n$ git codereview help\n```\n\nExample:\n```text\n$ git clone https://go.googlesource.com/go\n$ cd go/src\n$ ./all.bash                                # compile and test\n```\n\nExample:\n```text\n$ git clone https://go.googlesource.com/tools\n$ cd tools\n$ go test ./...                             # compile and test\n```\n\nExample:\n```text\n$ git checkout -b mybranch\n$ [edit files...]\n$ git add [files...]\n$ git codereview change   # create commit in the branch\n$ [edit again...]\n$ git add [files...]\n$ git codereview change   # amend the existing commit with new changes\n$ [etc.]\n```\n\nExample:\n```text\n$ ./all.bash    # recompile and test\n```\n\nExample:\n```text\n$ go test ./... # recompile and test\n```\n\nExample:\n```text\n$ git codereview mail     # send changes to Gerrit\n```\n\nExample:\n```text\n$ [edit files...]\n$ git add [files...]\n$ git codereview change   # update same commit\n$ git codereview mail     # send to Gerrit again\n```\n\nExample:\n```text\n$ git clone https://go.googlesource.com/go\n$ cd go\n```\n\nExample:\n```text\n$ git clone https://go.googlesource.com/tools\n$ cd tools\n```\n\nExample:\n```text\n$ git checkout -b mybranch\n$ [edit files...]\n$ git add [files...]\n```\n\nExample:\n```text\n$ git codereview change\n(open $EDITOR)\n```\n\nExample:\n```text\nChange-Id: I2fbdbffb3aab626c4b6f56348861b7909e3e8990\n```\n\nExample:\n```text\n$ go test\n```\n\nExample:\n```text\n$ cd go/src\n$ ./all.bash\n```\n\nExample:\n```text\nALL TESTS PASSED\n```\n\nExample:\n```text\n$ cd tools\n$ go test ./...\n```\n\nExample:\n```text\n$ git codereview mail\n```\n\nExample:\n```text\nremote: New Changes:\nremote:   https://go-review.googlesource.com/99999 math: improved Sin, Cos and Tan precision for very large arguments\n```\n\nExample:\n```text\n$ git codereview change     # amend current commit\n(open $EDITOR)\n$ git codereview mail       # send new changes to Gerrit\n```\n\nExample:\n```text\nmath: improve Sin, Cos and Tan precision for very large arguments\n\nThe existing implementation has poor numerical properties for\nlarge arguments, so use the McGillicutty algorithm to improve\naccuracy above 1e10.\n\nThe algorithm is described at https://wikipedia.org/wiki/McGillicutty_Algorithm\n\nFixes #159\n```\n\nExample:\n```text\n// Copyright 2026 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n```\n\nExample:\n```text\nremote: Processing changes: refs: 1, done\nremote:\nremote: ERROR:  In commit ab13517fa29487dcf8b0d48916c51639426c5ee9\nremote: ERROR:  author email address XXXXXXXXXXXXXXXXXXX\nremote: ERROR:  does not match your user account.\n```\n\nExample:\n```text\n$ git config user.email email@address.com\n```\n\nExample:\n```text\n$ git commit --amend --author=\"Author Name <email@address.com>\"\n```\n\nExample:\n```text\n$ cd <MYPROJECTDIR>\n$ $GOROOT/bin/go test\n```\n\nExample:\n```text\n$ cd $GOROOT/src/crypto/sha1\n$ [make changes...]\n$ $GOROOT/bin/go test .\n```\n\nExample:\n```text\n$ cd $GOROOT/src\n$ [make changes...]\n$ $GOROOT/bin/go install cmd/compile\n$ $GOROOT/bin/go build [something...]   # test the new compiler\n$ $GOROOT/bin/go run [something...]     # test the new compiler\n$ $GOROOT/bin/go test [something...]    # test the new compiler\n```\n\nExample:\n```text\n$ $GOROOT/bin/go test cmd/internal/testdir\n```\n\nExample:\n```text\n$ git codereview mail -r joe@golang.org -cc mabel@example.com,math-nuts@swtch.com\n```\n\nExample:\n```text\n$ git codereview sync\n```\n\nExample:\n```text\n$ git fetch https://go.googlesource.com/review refs/changes/21/13245/1 && git checkout FETCH_HEAD\n```\n\nExample:\n```text\n$ git sync\n```\n\nExample:\n```text\n[alias]\n\tchange = codereview change\n\tgofmt = codereview gofmt\n\tmail = codereview mail\n\tpending = codereview pending\n\tsubmit = codereview submit\n\tsync = codereview sync\n```\n\nExample:\n```text\n$ git codereview mail HEAD\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.562Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":39,"totalLines":254,"estimatedTokens":1110}}51{"id":"doc-release_history_the_go_programming_language-d1040cc9","source":"documentation","title":"Release History - The Go Programming Language","url":"https://go.dev/doc/devel/release.html","text":"Release History This page summarizes the changes between official stable releases of Go. The change log has the full details. To update to a specific release, fetch --tags git checkout goX.Y.Z Release Policy Each major Go release is supported until there are two newer major releases. For example, Go 1.5 was supported until the Go 1.7 release, and Go 1.6 was supported until the Go 1.8 release. We fix critical problems, including critical security problems, in supported releases as needed by issuing minor revisions (for example, Go 1.6.1, Go 1.6.2, and so on). go1.26.0 (released 2026-02-10) Go 1.26.0 is a major release of Go. Read the Go 1.26 Release Notes for more information. Minor revisions go1.26.1 (released 2026-03-05) includes security fixes to the crypto/x509, html/template, net/url, and os packages, as well as bug fixes to the go command, the go fix command, the compiler, and the os and reflect packages. See the Go 1.26.1 milestone on our issue tracker for details. go1.26.2 (released 2026-04-07) includes security fixes to the go command, the compiler, and the archive/tar, crypto/tls, crypto/x509, html/template, and os packages, as well as bug fixes to the go command, the go fix command, the compiler, the linker, the runtime, and the net, net/http, and net/url packages. See the Go 1.26.2 milestone on our issue tracker for details. go1.26.3 (released 2026-05-07) includes security fixes to the go command, the pack tool, and the html/template, net, net/http, net/http/httputil, net/mail, and syscall packages, as well as bug fixes to the go command, the go fix command, the compiler, the linker, the runtime, and the crypto/fips140, crypto/tls, go/types, and os packages. See the Go 1.26.3 milestone on our issue tracker for details. go1.26.4 (released 2026-06-02) includes security fixes to the crypto/x509, mime, and net/textproto packages, as well as bug fixes to the compiler, the runtime, the go fix command, and the crypto/fips140 package. See the Go 1.26.4 milestone on our issue tracker for details. go1.26.5 (released 2026-07-07) includes security fixes to the crypto/tls and os packages, as well as bug fixes to the compiler, the runtime, the go command, and the net, os, and syscall packages. See the Go 1.26.5 milestone on our issue tracker for details. go1.26.6 (released 2026-08-13) includes security fixes to the go command, and the crypto/tls, encoding/asn1, encoding/xml, html/template, net, net/http, and net/url packages, as well as bug fixes to the compiler, the linker, the runtime, and the crypto/tls and os packages. See the Go 1.26.6 milestone on our issue tracker for details. go1.25.0 (released 2025-08-12) Go 1.25.0 is a major release of Go. Read the Go 1.25 Release Notes for more information. Minor revisions go1.25.1 (released 2025-09-03) includes security fixes to the net/http package, as well as bug fixes to the go command, and the net, os, os/exec, and testing/synctest packages. See the Go 1.25.1 milestone on our issue tracker for details. go1.25.2 (released 2025-10-07) includes security fixes to the archive/tar, crypto/tls, crypto/x509, encoding/asn1, encoding/pem, net/http, net/mail, net/textproto, and net/url packages, as well as bug fixes to the compiler, the runtime, and the context, debug/pe, net/http, os, and sync/atomic packages. See the Go 1.25.2 milestone on our issue tracker for details. go1.25.3 (released 2025-10-13) includes fixes to the crypto/x509 package. See the Go 1.25.3 milestone on our issue tracker for details. go1.25.4 (released 2025-11-05) includes fixes to the compiler, the runtime, and the crypto/subtle, encoding/pem, net/url, and os packages. See the Go 1.25.4 milestone on our issue tracker for details. go1.25.5 (released 2025-12-02) includes two security fixes to the crypto/x509 package, as well as bug fixes to the mime and os packages. See the Go 1.25.5 milestone on our issue tracker for details. go1.25.6 (released 2026-01-15) includes security fixes to the go command, and the archive/zip, crypto/tls, and net/url packages, as well as bug fixes to the compiler, the runtime, and the crypto/tls, errors, and os packages. See the Go 1.25.6 milestone on our issue tracker for details. go1.25.7 (released 2026-02-04) includes security fixes to the go command and the crypto/tls package, as well as bug fixes to the compiler and the crypto/x509 package. See the Go 1.25.7 milestone on our issue tracker for details. go1.25.8 (released 2026-03-05) includes security fixes to the html/template, net/url, and os packages, as well as bug fixes to the go command, the compiler, and the os package. See the Go 1.25.8 milestone on our issue tracker for details. go1.25.9 (released 2026-04-07) includes security fixes to the go command, the compiler, and the archive/tar, crypto/tls, crypto/x509, html/template, and os packages, as well as bug fixes to the go command, the compiler, and the runtime. See the Go 1.25.9 milestone on our issue tracker for details. go1.25.10 (released 2026-05-07) includes security fixes to the go command, the pack tool, and the html/template, net, net/http, net/http/httputil, net/mail, and syscall packages, as well as bug fixes to the go command, the compiler, the linker, the runtime, and the crypto/fips140, go/types, and os packages. See the Go 1.25.10 milestone on our issue tracker for details. go1.25.11 (released 2026-06-02) includes security fixes to the crypto/x509, mime, and net/textproto packages, as well as bug fixes to the compiler and the runtime. See the Go 1.25.11 milestone on our issue tracker for details. go1.25.12 (released 2026-07-07) includes security fixes to the crypto/tls and os packages, as well as bug fixes to the compiler, the go command, and the net and os packages. See the Go 1.25.12 milestone on our issue tracker for details. go1.25.13 (released 2026-08-13) includes security fixes to the go command, and the crypto/tls, encoding/asn1, encoding/xml, html/template, net/http, and net/url packages, as well as bug fixes to the compiler, the runtime, and the crypto/tls and os packages. See the Go 1.25.13 milestone on our issue tracker for details. go1.24.0 (released 2025-02-11) Go 1.24.0 is a major release of Go. Read the Go 1.24 Release Notes for more information. Minor revisions go1.24.1 (released 2025-03-04) includes security fixes to the net/http package, as well as bug fixes to cgo, the compiler, the go command, and the reflect, runtime, and syscall packages. See the Go 1.24.1 milestone on our issue tracker for details. go1.24.2 (released 2025-04-01) includes security fixes to the net/http package, as well as bug fixes to the compiler, the runtime, the go command, and the crypto/tls, go/types, net/http, and testing packages. See the Go 1.24.2 milestone on our issue tracker for details. go1.24.3 (released 2025-05-06) includes security fixes to the os package, as well as bug fixes to the runtime, the compiler, the linker, the go command, and the crypto/tls and os packages. See the Go 1.24.3 milestone on our issue tracker for details. go1.24.4 (released 2025-06-05) includes security fixes to the crypto/x509, net/http, and os packages, as well as bug fixes to the linker, the go command, and the hash/maphash and os packages. See the Go 1.24.4 milestone on our issue tracker for details. go1.24.5 (released 2025-07-08) includes security fixes to the go command, as well as bug fixes to the compiler, the linker, the runtime, and the go command. See the Go 1.24.5 milestone on our issue tracker for details. go1.24.6 (released 2025-08-06) includes security fixes to the database/sql and os/exec packages, as well as bug fixes to the runtime. See the Go 1.24.6 milestone on our issue tracker for details. go1.24.7 (released 2025-09-03) includes fixes to the go command, and the net and os/exec packages. See the Go 1.24.7 milestone on our issue tracker for details. go1.24.8 (released 2025-10-07) includes security fixes to the archive/tar, crypto/tls, crypto/x509, encoding/asn1, encoding/pem, net/http, net/mail, net/textproto, and net/url packages, as well as bug fixes to the compiler, the linker, and the debug/pe, net/http, os, and sync/atomic packages. See the Go 1.24.8 milestone on our issue tracker for details. go1.24.9 (released 2025-10-13) includes fixes to the crypto/x509 package. See the Go 1.24.9 milestone on our issue tracker for details. go1.24.10 (released 2025-11-05) includes fixes to the encoding/pem and net/url packages. See the Go 1.24.10 milestone on our issue tracker for details. go1.24.11 (released 2025-12-02) includes two security fixes to the crypto/x509 package, as well as bug fixes to the runtime. See the Go 1.24.11 milestone on our issue tracker for details. go1.24.12 (released 2026-01-15) includes security fixes to the go command, and the archive/zip, crypto/tls, and net/url packages, as well as bug fixes to the compiler, the runtime, and the crypto/tls and os packages. See the Go 1.24.12 milestone on our issue tracker for details. go1.24.13 (released 2026-02-04) includes security fixes to the go command and the crypto/tls package, as well as bug fixes to the crypto/x509 package. See the Go 1.24.13 milestone on our issue tracker for details. go1.23.0 (released 2024-08-13) Go 1.23.0 is a major release of Go. Read the Go 1.23 Release Notes for more information. Minor revisions go1.23.1 (released 2024-09-05) includes security fixes to the encoding/gob, go/build/constraint, and go/parser packages, as well as bug fixes to the compiler, the go command, the runtime, and the database/sql, go/types, os, runtime/trace, and unique packages. See the Go 1.23.1 milestone on our issue tracker for details. go1.23.2 (released 2024-10-01) includes fixes to the compiler, cgo, the runtime, and the maps, os, os/exec, time, and unique packages. See the Go 1.23.2 milestone on our issue tracker for details. go1.23.3 (released 2024-11-06) includes fixes to the linker, the runtime, and the net/http, os, and syscall packages. See the Go 1.23.3 milestone on our issue tracker for details. go1.23.4 (released 2024-12-03) includes fixes to the compiler, the runtime, the trace command, and the syscall package. See the Go 1.23.4 milestone on our issue tracker for details. go1.23.5 (released 2025-01-16) includes security fixes to the crypto/x509 and net/http packages, as well as bug fixes to the compiler, the runtime, and the net package. See the Go 1.23.5 milestone on our issue tracker for details. go1.23.6 (released 2025-02-04) includes security fixes to the crypto/elliptic package, as well as bug fixes to the compiler and the go command. See the Go 1.23.6 milestone on our issue tracker for details. go1.23.7 (released 2025-03-04) includes security fixes to the net/http package, as well as bug fixes to cgo, the compiler, and the reflect, runtime, and syscall packages. See the Go 1.23.7 milestone on our issue tracker for details. go1.23.8 (released 2025-04-01) includes security fixes to the net/http package, as well as bug fixes to the runtime and the go command. See the Go 1.23.8 milestone on our issue tracker for details. go1.23.9 (released 2025-05-06) includes fixes to the runtime and the linker. See the Go 1.23.9 milestone on our issue tracker for details. go1.23.10 (released 2025-06-05) includes security fixes to the net/http and os packages, as well as bug fixes to the linker. See the Go 1.23.10 milestone on our issue tracker for details. go1.23.11 (released 2025-07-08) includes security fixes to the go command, as well as bug fixes to the compiler, the linker, and the runtime. See the Go 1.23.11 milestone on our issue tracker for details. go1.23.12 (released 2025-08-06) includes security fixes to the database/sql and os/exec packages, as well as bug fixes to the runtime. See the Go 1.23.12 milestone on our issue tracker for details. go1.22.0 (released 2024-02-06) Go 1.22.0 is a major release of Go. Read the Go 1.22 Release Notes for more information. Minor revisions go1.22.1 (released 2024-03-05) includes security fixes to the crypto/x509, html/template, net/http, net/http/cookiejar, and net/mail packages, as well as bug fixes to the compiler, the go command, the runtime, the trace command, and the go/types and net/http packages. See the Go 1.22.1 milestone on our issue tracker for details. go1.22.2 (released 2024-04-03) includes a security fix to the net/http package, as well as bug fixes to the compiler, the go command, the linker, and the encoding/gob, go/types, net/http, and runtime/trace packages. See the Go 1.22.2 milestone on our issue tracker for details. go1.22.3 (released 2024-05-07) includes security fixes to the go command and the net package, as well as bug fixes to the compiler, the runtime, and the net/http package. See the Go 1.22.3 milestone on our issue tracker for details. go1.22.4 (released 2024-06-04) includes security fixes to the archive/zip and net/netip packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the os package. See the Go 1.22.4 milestone on our issue tracker for details. go1.22.5 (released 2024-07-02) includes security fixes to the net/http package, as well as bug fixes to the compiler, cgo, the go command, the linker, the runtime, and the crypto/tls, go/types, net, net/http, and os/exec packages. See the Go 1.22.5 milestone on our issue tracker for details. go1.22.6 (released 2024-08-06) includes fixes to the go command, the compiler, the linker, the trace command, the covdata command, and the bytes, go/types, and os/exec packages. See the Go 1.22.6 milestone on our issue tracker for details. go1.22.7 (released 2024-09-05) includes security fixes to the encoding/gob, go/build/constraint, and go/parser packages, as well as bug fixes to the fix command and the runtime. See the Go 1.22.7 milestone on our issue tracker for details. go1.22.8 (released 2024-10-01) includes fixes to cgo, and the maps and syscall packages. See the Go 1.22.8 milestone on our issue tracker for details. go1.22.9 (released 2024-11-06) includes fixes to the linker. See the Go 1.22.9 milestone on our issue tracker for details. go1.22.10 (released 2024-12-03) includes fixes to the runtime and the syscall package. See the Go 1.22.10 milestone on our issue tracker for details. go1.22.11 (released 2025-01-16) includes security fixes to the crypto/x509 and net/http packages, as well as bug fixes to the runtime. See the Go 1.22.11 milestone on our issue tracker for details. go1.22.12 (released 2025-02-04) includes security fixes to the crypto/elliptic package, as well as bug fixes to the compiler and the go command. See the Go 1.22.12 milestone on our issue tracker for details. go1.21.0 (released 2023-08-08) Go 1.21.0 is a major release of Go. Read the Go 1.21 Release Notes for more information. Minor revisions go1.21.1 (released 2023-09-06) includes four security fixes to the cmd/go, crypto/tls, and html/template packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the context, crypto/tls, encoding/gob, encoding/xml, go/types, net/http, os, and path/filepath packages. See the Go 1.21.1 milestone on our issue tracker for details. go1.21.2 (released 2023-10-05) includes one security fix to the cmd/go package, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the runtime/metrics package. See the Go 1.21.2 milestone on our issue tracker for details. go1.21.3 (released 2023-10-10) includes a security fix to the net/http package. See the Go 1.21.3 milestone on our issue tracker for details. go1.21.4 (released 2023-11-07) includes security fixes to the path/filepath package, as well as bug fixes to the linker, the runtime, the compiler, and the go/types, net/http, and runtime/cgo packages. See the Go 1.21.4 milestone on our issue tracker for details. go1.21.5 (released 2023-12-05) includes security fixes to the go command, and the net/http and path/filepath packages, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/rand, net, os, and syscall packages. See the Go 1.21.5 milestone on our issue tracker for details. go1.21.6 (released 2024-01-09) includes fixes to the compiler, the runtime, and the crypto/tls, maps, and runtime/pprof packages. See the Go 1.21.6 milestone on our issue tracker for details. go1.21.7 (released 2024-02-06) includes fixes to the compiler, the go command, the runtime, and the crypto/x509 package. See the Go 1.21.7 milestone on our issue tracker for details. go1.21.8 (released 2024-03-05) includes security fixes to the crypto/x509, html/template, net/http, net/http/cookiejar, and net/mail packages, as well as bug fixes to the go command and the runtime. See the Go 1.21.8 milestone on our issue tracker for details. go1.21.9 (released 2024-04-03) includes a security fix to the net/http package, as well as bug fixes to the linker, and the go/types and net/http packages. See the Go 1.21.9 milestone on our issue tracker for details. go1.21.10 (released 2024-05-07) includes security fixes to the go command, as well as bug fixes to the net/http package. See the Go 1.21.10 milestone on our issue tracker for details. go1.21.11 (released 2024-06-04) includes security fixes to the archive/zip and net/netip packages, as well as bug fixes to the compiler, the go command, the runtime, and the os package. See the Go 1.21.11 milestone on our issue tracker for details. go1.21.12 (released 2024-07-02) includes security fixes to the net/http package, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/x509, net/http, net/netip, and os packages. See the Go 1.21.12 milestone on our issue tracker for details. go1.21.13 (released 2024-08-06) includes fixes to the go command, the covdata command, and the bytes package. See the Go 1.21.13 milestone on our issue tracker for details. go1.20 (released 2023-02-01) Go 1.20 is a major release of Go. Read the Go 1.20 Release Notes for more information. Minor revisions go1.20.1 (released 2023-02-14) includes security fixes to the crypto/tls, mime/multipart, net/http, and path/filepath packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the time package. See the Go 1.20.1 milestone on our issue tracker for details. go1.20.2 (released 2023-03-07) includes a security fix to the crypto/elliptic package, as well as bug fixes to the compiler, the covdata command, the linker, the runtime, and the crypto/ecdh, crypto/rsa, crypto/x509, os, and syscall packages. See the Go 1.20.2 milestone on our issue tracker for details. go1.20.3 (released 2023-04-04) includes security fixes to the go/parser, html/template, mime/multipart, net/http, and net/textproto packages, as well as bug fixes to the compiler, the linker, the runtime, and the time package. See the Go 1.20.3 milestone on our issue tracker for details. go1.20.4 (released 2023-05-02) includes three security fixes to the html/template package, as well as bug fixes to the compiler, the runtime, and the crypto/subtle, crypto/tls, net/http, and syscall packages. See the Go 1.20.4 milestone on our issue tracker for details. go1.20.5 (released 2023-06-06) includes four security fixes to the cmd/go and runtime packages, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/rsa, net, and os packages. See the Go 1.20.5 milestone on our issue tracker for details. go1.20.6 (released 2023-07-11) includes a security fix to the net/http package, as well as bug fixes to the compiler, cgo, the cover tool, the go command, the runtime, and the crypto/ecdsa, go/build, go/printer, net/mail, and text/template packages. See the Go 1.20.6 milestone on our issue tracker for details. go1.20.7 (released 2023-08-01) includes a security fix to the crypto/tls package, as well as bug fixes to the assembler and the compiler. See the Go 1.20.7 milestone on our issue tracker for details. go1.20.8 (released 2023-09-06) includes two security fixes to the html/template package, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/tls, go/types, net/http, and path/filepath packages. See the Go 1.20.8 milestone on our issue tracker for details. go1.20.9 (released 2023-10-05) includes one security fix to the cmd/go package, as well as bug fixes to the go command and the linker. See the Go 1.20.9 milestone on our issue tracker for details. go1.20.10 (released 2023-10-10) includes a security fix to the net/http package. See the Go 1.20.10 milestone on our issue tracker for details. go1.20.11 (released 2023-11-07) includes security fixes to the path/filepath package, as well as bug fixes to the linker and the net/http package. See the Go 1.20.11 milestone on our issue tracker for details. go1.20.12 (released 2023-12-05) includes security fixes to the go command, and the net/http and path/filepath packages, as well as bug fixes to the compiler and the go command. See the Go 1.20.12 milestone on our issue tracker for details. go1.20.13 (released 2024-01-09) includes fixes to the runtime and the crypto/tls package. See the Go 1.20.13 milestone on our issue tracker for details. go1.20.14 (released 2024-02-06) includes fixes to the crypto/x509 package. See the Go 1.20.14 milestone on our issue tracker for details. go1.19 (released 2022-08-02) Go 1.19 is a major release of Go. Read the Go 1.19 Release Notes for more information. Minor revisions go1.19.1 (released 2022-09-06) includes security fixes to the net/http and net/url packages, as well as bug fixes to the compiler, the go command, the pprof command, the linker, the runtime, and the crypto/tls and crypto/x509 packages. See the Go 1.19.1 milestone on our issue tracker for details. go1.19.2 (released 2022-10-04) includes security fixes to the archive/tar, net/http/httputil, and regexp packages, as well as bug fixes to the compiler, the linker, the runtime, and the go/types package. See the Go 1.19.2 milestone on our issue tracker for details. go1.19.3 (released 2022-11-01) includes security fixes to the os/exec and syscall packages, as well as bug fixes to the compiler and the runtime. See the Go 1.19.3 milestone on our issue tracker for details. go1.19.4 (released 2022-12-06) includes security fixes to the net/http and os packages, as well as bug fixes to the compiler, the runtime, and the crypto/x509, os/exec, and sync/atomic packages. See the Go 1.19.4 milestone on our issue tracker for details. go1.19.5 (released 2023-01-10) includes fixes to the compiler, the linker, and the crypto/x509, net/http, sync/atomic, and syscall packages. See the Go 1.19.5 milestone on our issue tracker for details. go1.19.6 (released 2023-02-14) includes security fixes to the crypto/tls, mime/multipart, net/http, and path/filepath packages, as well as bug fixes to the go command, the linker, the runtime, and the crypto/x509, net/http, and time packages. See the Go 1.19.6 milestone on our issue tracker for details. go1.19.7 (released 2023-03-07) includes a security fix to the crypto/elliptic package, as well as bug fixes to the linker, the runtime, and the crypto/x509 and syscall packages. See the Go 1.19.7 milestone on our issue tracker for details. go1.19.8 (released 2023-04-04) includes security fixes to the go/parser, html/template, mime/multipart, net/http, and net/textproto packages, as well as bug fixes to the linker, the runtime, and the time package. See the Go 1.19.8 milestone on our issue tracker for details. go1.19.9 (released 2023-05-02) includes three security fixes to the html/template package, as well as bug fixes to the compiler, the runtime, and the crypto/tls and syscall packages. See the Go 1.19.9 milestone on our issue tracker for details. go1.19.10 (released 2023-06-06) includes four security fixes to the cmd/go and runtime packages, as well as bug fixes to the compiler, the go command, and the runtime. See the Go 1.19.10 milestone on our issue tracker for details. go1.19.11 (released 2023-07-11) includes a security fix to the net/http package, as well as bug fixes to cgo, the cover tool, the go command, the runtime, and the go/printer package. See the Go 1.19.11 milestone on our issue tracker for details. go1.19.12 (released 2023-08-01) includes a security fix to the crypto/tls package, as well as bug fixes to the assembler and the compiler. See the Go 1.19.12 milestone on our issue tracker for details. go1.19.13 (released 2023-09-06) includes fixes to the go command, and the crypto/tls and net/http packages. See the Go 1.19.13 milestone on our issue tracker for details. go1.18 (released 2022-03-15) Go 1.18 is a major release of Go. Read the Go 1.18 Release Notes for more information. Minor revisions go1.18.1 (released 2022-04-12) includes security fixes to the crypto/elliptic, crypto/x509, and encoding/pem packages, as well as bug fixes to the compiler, linker, runtime, the go command, vet, and the bytes, crypto/x509, and go/types packages. See the Go 1.18.1 milestone on our issue tracker for details. go1.18.2 (released 2022-05-10) includes security fixes to the syscall package, as well as bug fixes to the compiler, runtime, the go command, and the crypto/x509, go/types, net/http/httptest, reflect, and sync/atomic packages. See the Go 1.18.2 milestone on our issue tracker for details. go1.18.3 (released 2022-06-01) includes security fixes to the crypto/rand, crypto/tls, os/exec, and path/filepath packages, as well as bug fixes to the compiler, and the crypto/tls and text/template/parse packages. See the Go 1.18.3 milestone on our issue tracker for details. go1.18.4 (released 2022-07-12) includes security fixes to the compress/gzip, encoding/gob, encoding/xml, go/parser, io/fs, net/http, and path/filepath packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the runtime/metrics package. See the Go 1.18.4 milestone on our issue tracker for details. go1.18.5 (released 2022-08-01) includes security fixes to the encoding/gob and math/big packages, as well as bug fixes to the compiler, the go command, the runtime, and the testing package. See the Go 1.18.5 milestone on our issue tracker for details. go1.18.6 (released 2022-09-06) includes security fixes to the net/http package, as well as bug fixes to the compiler, the go command, the pprof command, the runtime, and the crypto/tls, encoding/xml, and net packages. See the Go 1.18.6 milestone on our issue tracker for details. go1.18.7 (released 2022-10-04) includes security fixes to the archive/tar, net/http/httputil, and regexp packages, as well as bug fixes to the compiler, the linker, and the go/types package. See the Go 1.18.7 milestone on our issue tracker for details. go1.18.8 (released 2022-11-01) includes security fixes to the os/exec and syscall packages, as well as bug fixes to the runtime. See the Go 1.18.8 milestone on our issue tracker for details. go1.18.9 (released 2022-12-06) includes security fixes to the net/http and os packages, as well as bug fixes to cgo, the compiler, the runtime, and the crypto/x509 and os/exec packages. See the Go 1.18.9 milestone on our issue tracker for details. go1.18.10 (released 2023-01-10) includes fixes to cgo, the compiler, the linker, and the crypto/x509, net/http, and syscall packages. See the Go 1.18.10 milestone on our issue tracker for details. go1.17 (released 2021-08-16) Go 1.17 is a major release of Go. Read the Go 1.17 Release Notes for more information. Minor revisions go1.17.1 (released 2021-09-09) includes a security fix to the archive/zip package, as well as bug fixes to the compiler, linker, the go command, and the crypto/rand, embed, go/types, html/template, and net/http packages. See the Go 1.17.1 milestone on our issue tracker for details. go1.17.2 (released 2021-10-07) includes security fixes to linker and the misc/wasm directory, as well as bug fixes to the compiler, runtime, the go command, and the text/template and time packages. See the Go 1.17.2 milestone on our issue tracker for details. go1.17.3 (released 2021-11-04) includes security fixes to the archive/zip and debug/macho packages, as well as bug fixes to the compiler, linker, runtime, the go command, the misc/wasm directory, and the net/http and syscall packages. See the Go 1.17.3 milestone on our issue tracker for details. go1.17.4 (released 2021-12-02) includes fixes to the compiler, linker, runtime, and the go/types, net/http, and time packages. See the Go 1.17.4 milestone on our issue tracker for details. go1.17.5 (released 2021-12-09) includes security fixes to the net/http and syscall packages. See the Go 1.17.5 milestone on our issue tracker for details. go1.17.6 (released 2022-01-06) includes fixes to the compiler, linker, runtime, and the crypto/x509, net/http, and reflect packages. See the Go 1.17.6 milestone on our issue tracker for details. go1.17.7 (released 2022-02-10) includes security fixes to the go command, and the crypto/elliptic and math/big packages, as well as bug fixes to the compiler, linker, runtime, the go command, and the debug/macho, debug/pe, and net/http/httptest packages. See the Go 1.17.7 milestone on our issue tracker for details. go1.17.8 (released 2022-03-03) includes a security fix to the regexp/syntax package, as well as bug fixes to the compiler, runtime, the go command, and the crypto/x509 and net packages. See the Go 1.17.8 milestone on our issue tracker for details. go1.17.9 (released 2022-04-12) includes security fixes to the crypto/elliptic and encoding/pem packages, as well as bug fixes to the linker and runtime. See the Go 1.17.9 milestone on our issue tracker for details. go1.17.10 (released 2022-05-10) includes security fixes to the syscall package, as well as bug fixes to the compiler, runtime, and the crypto/x509 and net/http/httptest packages. See the Go 1.17.10 milestone on our issue tracker for details. go1.17.11 (released 2022-06-01) includes security fixes to the crypto/rand, crypto/tls, os/exec, and path/filepath packages, as well as bug fixes to the crypto/tls package. See the Go 1.17.11 milestone on our issue tracker for details. go1.17.12 (released 2022-07-12) includes security fixes to the compress/gzip, encoding/gob, encoding/xml, go/parser, io/fs, net/http, and path/filepath packages, as well as bug fixes to the compiler, the go command, the runtime, and the runtime/metrics package. See the Go 1.17.12 milestone on our issue tracker for details. go1.17.13 (released 2022-08-01) includes security fixes to the encoding/gob and math/big packages, as well as bug fixes to the compiler and the runtime. See the Go 1.17.13 milestone on our issue tracker for details. go1.16 (released 2021-02-16) Go 1.16 is a major release of Go. Read the Go 1.16 Release Notes for more information. Minor revisions go1.16.1 (released 2021-03-10) includes security fixes to the archive/zip and encoding/xml packages. See the Go 1.16.1 milestone on our issue tracker for details. go1.16.2 (released 2021-03-11) includes fixes to cgo, the compiler, linker, the go command, and the syscall and time packages. See the Go 1.16.2 milestone on our issue tracker for details. go1.16.3 (released 2021-04-01) includes fixes to the compiler, linker, runtime, the go command, and the testing and time packages. See the Go 1.16.3 milestone on our issue tracker for details. go1.16.4 (released 2021-05-06) includes a security fix to the net/http package, as well as bug fixes to the compiler, runtime, and the archive/zip, syscall, and time packages. See the Go 1.16.4 milestone on our issue tracker for details. go1.16.5 (released 2021-06-03) includes security fixes to the archive/zip, math/big, net, and net/http/httputil packages, as well as bug fixes to the linker, the go command, and the net/http package. See the Go 1.16.5 milestone on our issue tracker for details. go1.16.6 (released 2021-07-12) includes a security fix to the crypto/tls package, as well as bug fixes to the compiler, and the net and net/http packages. See the Go 1.16.6 milestone on our issue tracker for details. go1.16.7 (released 2021-08-05) includes a security fix to the net/http/httputil package, as well as bug fixes to the compiler, linker, runtime, the go command, and the net/http package. See the Go 1.16.7 milestone on our issue tracker for details. go1.16.8 (released 2021-09-09) includes a security fix to the archive/zip package, as well as bug fixes to the archive/zip, go/internal/gccgoimporter, html/template, net/http, and runtime/pprof packages. See the Go 1.16.8 milestone on our issue tracker for details. go1.16.9 (released 2021-10-07) includes security fixes to linker and the misc/wasm directory, as well as bug fixes to runtime and the text/template package. See the Go 1.16.9 milestone on our issue tracker for details. go1.16.10 (released 2021-11-04) includes security fixes to the archive/zip and debug/macho packages, as well as bug fixes to the compiler, linker, runtime, the misc/wasm directory, and the net/http package. See the Go 1.16.10 milestone on our issue tracker for details. go1.16.11 (released 2021-12-02) includes fixes to the compiler, runtime, and the net/http, net/http/httptest, and time packages. See the Go 1.16.11 milestone on our issue tracker for details. go1.16.12 (released 2021-12-09) includes security fixes to the net/http and syscall packages. See the Go 1.16.12 milestone on our issue tracker for details. go1.16.13 (released 2022-01-06) includes fixes to the compiler, linker, runtime, and the net/http package. See the Go 1.16.13 milestone on our issue tracker for details. go1.16.14 (released 2022-02-10) includes security fixes to the go command, and the crypto/elliptic and math/big packages, as well as bug fixes to the compiler, linker, runtime, the go command, and the debug/macho, debug/pe, net/http/httptest, and testing packages. See the Go 1.16.14 milestone on our issue tracker for details. go1.16.15 (released 2022-03-03) includes a security fix to the regexp/syntax package, as well as bug fixes to the compiler, runtime, the go command, and the net package. See the Go 1.16.15 milestone on our issue tracker for details. go1.15 (released 2020-08-11) Go 1.15 is a major release of Go. Read the Go 1.15 Release Notes for more information. Minor revisions go1.15.1 (released 2020-09-01) includes security fixes to the net/http/cgi and net/http/fcgi packages. See the Go 1.15.1 milestone on our issue tracker for details. go1.15.2 (released 2020-09-09) includes fixes to the compiler, runtime, documentation, the go command, and the net/mail, os, sync, and testing packages. See the Go 1.15.2 milestone on our issue tracker for details. go1.15.3 (released 2020-10-14) includes fixes to cgo, the compiler, runtime, the go command, and the bytes, plugin, and testing packages. See the Go 1.15.3 milestone on our issue tracker for details. go1.15.4 (released 2020-11-05) includes fixes to cgo, the compiler, linker, runtime, and the compress/flate, net/http, reflect, and time packages. See the Go 1.15.4 milestone on our issue tracker for details. go1.15.5 (released 2020-11-12) includes security fixes to the go command and the math/big package. See the Go 1.15.5 milestone on our issue tracker for details. go1.15.6 (released 2020-12-03) includes fixes to the compiler, linker, runtime, the go command, and the io package. See the Go 1.15.6 milestone on our issue tracker for details. go1.15.7 (released 2021-01-19) includes security fixes to the go command and the crypto/elliptic package. See the Go 1.15.7 milestone on our issue tracker for details. go1.15.8 (released 2021-02-04) includes fixes to the compiler, linker, runtime, the go command, and the net/http package. See the Go 1.15.8 milestone on our issue tracker for details. go1.15.9 (released 2021-03-10) includes security fixes to the encoding/xml package. See the Go 1.15.9 milestone on our issue tracker for details. go1.15.10 (released 2021-03-11) includes fixes to the compiler, the go command, and the net/http, os, syscall, and time packages. See the Go 1.15.10 milestone on our issue tracker for details. go1.15.11 (released 2021-04-01) includes fixes to cgo, the compiler, linker, runtime, the go command, and the database/sql and net/http packages. See the Go 1.15.11 milestone on our issue tracker for details. go1.15.12 (released 2021-05-06) includes a security fix to the net/http package, as well as bug fixes to the compiler, runtime, and the archive/zip, syscall, and time packages. See the Go 1.15.12 milestone on our issue tracker for details. go1.15.13 (released 2021-06-03) includes security fixes to the archive/zip, math/big, net, and net/http/httputil packages, as well as bug fixes to the linker, the go command, and the math/big and net/http packages. See the Go 1.15.13 milestone on our issue tracker for details. go1.15.14 (released 2021-07-12) includes a security fix to the crypto/tls package, as well as bug fixes to the linker and the net package. See the Go 1.15.14 milestone on our issue tracker for details. go1.15.15 (released 2021-08-05) includes a security fix to the net/http/httputil package, as well as bug fixes to the compiler, runtime, the go command, and the net/http package. See the Go 1.15.15 milestone on our issue tracker for details. go1.14 (released 2020-02-25) Go 1.14 is a major release of Go. Read the Go 1.14 Release Notes for more information. Minor revisions go1.14.1 (released 2020-03-19) includes fixes to the go command, tools, and the runtime. See the Go 1.14.1 milestone on our issue tracker for details. go1.14.2 (released 2020-04-08) includes fixes to cgo, the go command, the runtime, and the os/exec and testing packages. See the Go 1.14.2 milestone on our issue tracker for details. go1.14.3 (released 2020-05-14) includes fixes to cgo, the compiler, the runtime, and the go/doc and math/big packages. See the Go 1.14.3 milestone on our issue tracker for details. go1.14.4 (released 2020-06-01) includes fixes to the go doc command, the runtime, and the encoding/json and os packages. See the Go 1.14.4 milestone on our issue tracker for details. go1.14.5 (released 2020-07-14) includes security fixes to the crypto/x509 and net/http packages. See the Go 1.14.5 milestone on our issue tracker for details. go1.14.6 (released 2020-07-16) includes fixes to the go command, the compiler, the linker, vet, and the database/sql, encoding/json, net/http, reflect, and testing packages. See the Go 1.14.6 milestone on our issue tracker for details. go1.14.7 (released 2020-08-06) includes security fixes to the encoding/binary package. See the Go 1.14.7 milestone on our issue tracker for details. go1.14.8 (released 2020-09-01) includes security fixes to the net/http/cgi and net/http/fcgi packages. See the Go 1.14.8 milestone on our issue tracker for details. go1.14.9 (released 2020-09-09) includes fixes to the compiler, linker, runtime, documentation, and the net/http and testing packages. See the Go 1.14.9 milestone on our issue tracker for details. go1.14.10 (released 2020-10-14) includes fixes to the compiler, runtime, and the plugin and testing packages. See the Go 1.14.10 milestone on our issue tracker for details. go1.14.11 (released 2020-11-05) includes fixes to the runtime, and the net/http and time packages. See the Go 1.14.11 milestone on our issue tracker for details. go1.14.12 (released 2020-11-12) includes security fixes to the go command and the math/big package. See the Go 1.14.12 milestone on our issue tracker for details. go1.14.13 (released 2020-12-03) includes fixes to the compiler, runtime, and the go command. See the Go 1.14.13 milestone on our issue tracker for details. go1.14.14 (released 2021-01-19) includes security fixes to the go command and the crypto/elliptic package. See the Go 1.14.14 milestone on our issue tracker for details. go1.14.15 (released 2021-02-04) includes fixes to the compiler, runtime, the go command, and the net/http package. See the Go 1.14.15 milestone on our issue tracker for details. go1.13 (released 2019-09-03) Go 1.13 is a major release of Go. Read the Go 1.13 Release Notes for more information. Minor revisions go1.13.1 (released 2019-09-25) includes security fixes to the net/http and net/textproto packages. See the Go 1.13.1 milestone on our issue tracker for details. go1.13.2 (released 2019-10-17) includes security fixes to the compiler and the crypto/dsa package. See the Go 1.13.2 milestone on our issue tracker for details. go1.13.3 (released 2019-10-17) includes fixes to the go command, the toolchain, the runtime, and the crypto/ecdsa, net, net/http, and syscall packages. See the Go 1.13.3 milestone on our issue tracker for details. go1.13.4 (released 2019-10-31) includes fixes to the net/http and syscall packages. It also fixes an issue on macOS 10.15 Catalina where the non-notarized installer and binaries were being rejected by Gatekeeper. See the Go 1.13.4 milestone on our issue tracker for details. go1.13.5 (released 2019-12-04) includes fixes to the go command, the runtime, the linker, and the net/http package. See the Go 1.13.5 milestone on our issue tracker for details. go1.13.6 (released 2020-01-09) includes fixes to the runtime and the net/http package. See the Go 1.13.6 milestone on our issue tracker for details. go1.13.7 (released 2020-01-28) includes two security fixes to the crypto/x509 package. See the Go 1.13.7 milestone on our issue tracker for details. go1.13.8 (released 2020-02-12) includes fixes to the runtime, and the crypto/x509 and net/http packages. See the Go 1.13.8 milestone on our issue tracker for details. go1.13.9 (released 2020-03-19) includes fixes to the go command, tools, the runtime, the toolchain, and the crypto/cypher package. See the Go 1.13.9 milestone on our issue tracker for details. go1.13.10 (released 2020-04-08) includes fixes to the go command, the runtime, and the os/exec and time packages. See the Go 1.13.10 milestone on our issue tracker for details. go1.13.11 (released 2020-05-14) includes fixes to the compiler. See the Go 1.13.11 milestone on our issue tracker for details. go1.13.12 (released 2020-06-01) includes fixes to the runtime, and the go/types and math/big packages. See the Go 1.13.12 milestone on our issue tracker for details. go1.13.13 (released 2020-07-14) includes security fixes to the crypto/x509 and net/http packages. See the Go 1.13.13 milestone on our issue tracker for details. go1.13.14 (released 2020-07-16) includes fixes to the compiler, vet, and the database/sql, net/http, and reflect packages. See the Go 1.13.14 milestone on our issue tracker for details. go1.13.15 (released 2020-08-06) includes security fixes to the encoding/binary package. See the Go 1.13.15 milestone on our issue tracker for details. go1.12 (released 2019-02-25) Go 1.12 is a major release of Go. Read the Go 1.12 Release Notes for more information. Minor revisions go1.12.1 (released 2019-03-14) includes fixes to cgo, the compiler, the go command, and the fmt, net/smtp, os, path/filepath, sync, and text/template packages. See the Go 1.12.1 milestone on our issue tracker for details. go1.12.2 (released 2019-04-05) includes security fixes to the runtime, as well as bug fixes to the compiler, the go command, and the doc, net, net/http/httputil, and os packages. See the Go 1.12.2 milestone on our issue tracker for details. go1.12.3 (released 2019-04-08) was accidentally released without its intended fix. It is identical to go1.12.2, except for its version number. The intended fix is in go1.12.4. go1.12.4 (released 2019-04-11) fixes an issue where using the prebuilt binary releases on older versions of GNU/Linux led to failures when linking programs that used cgo. Only Linux users who hit this issue need to update. go1.12.5 (released 2019-05-06) includes fixes to the compiler, the linker, the go command, the runtime, and the os package. See the Go 1.12.5 milestone on our issue tracker for details. go1.12.6 (released 2019-06-11) includes fixes to the compiler, the linker, the go command, and the crypto/x509, net/http, and os packages. See the Go 1.12.6 milestone on our issue tracker for details. go1.12.7 (released 2019-07-08) includes fixes to cgo, the compiler, and the linker. See the Go 1.12.7 milestone on our issue tracker for details. go1.12.8 (released 2019-08-13) includes security fixes to the net/http and net/url packages. See the Go 1.12.8 milestone on our issue tracker for details. go1.12.9 (released 2019-08-15) includes fixes to the linker, and the math/big and os packages. See the Go 1.12.9 milestone on our issue tracker for details. go1.12.10 (released 2019-09-25) includes security fixes to the net/http and net/textproto packages. See the Go 1.12.10 milestone on our issue tracker for details. go1.12.11 (released 2019-10-17) includes security fixes to the crypto/dsa package. See the Go 1.12.11 milestone on our issue tracker for details. go1.12.12 (released 2019-10-17) includes fixes to the go command, runtime, and the net and syscall packages. See the Go 1.12.12 milestone on our issue tracker for details. go1.12.13 (released 2019-10-31) fixes an issue on macOS 10.15 Catalina where the non-notarized installer and binaries were being rejected by Gatekeeper. Only macOS users who hit this issue need to update. go1.12.14 (released 2019-12-04) includes a fix to the runtime. See the Go 1.12.14 milestone on our issue tracker for details. go1.12.15 (released 2020-01-09) includes fixes to the runtime and the net/http package. See the Go 1.12.15 milestone on our issue tracker for details. go1.12.16 (released 2020-01-28) includes two security fixes to the crypto/x509 package. See the Go 1.12.16 milestone on our issue tracker for details. go1.12.17 (released 2020-02-12) includes a fix to the runtime. See the Go 1.12.17 milestone on our issue tracker for details. go1.11 (released 2018-08-24) Go 1.11 is a major release of Go. Read the Go 1.11 Release Notes for more information. Minor revisions go1.11.1 (released 2018-10-01) includes fixes to the compiler, documentation, go command, runtime, and the crypto/x509, encoding/json, go/types, net, net/http, and reflect packages. See the Go 1.11.1 milestone on our issue tracker for details. go1.11.2 (released 2018-11-02) includes fixes to the compiler, linker, documentation, go command, and the database/sql and go/types packages. See the Go 1.11.2 milestone on our issue tracker for details. go1.11.3 (released 2018-12-12) includes three security fixes to \"go get\" and the crypto/x509 package. See the Go 1.11.3 milestone on our issue tracker for details. go1.11.4 (released 2018-12-14) includes fixes to cgo, the compiler, linker, runtime, documentation, go command, and the go/types and net/http packages. It includes a fix to a bug introduced in Go 1.11.3 that broke go get for import path patterns containing \"...\". See the Go 1.11.4 milestone on our issue tracker for details. go1.11.5 (released 2019-01-23) includes a security fix to the crypto/elliptic package. See the Go 1.11.5 milestone on our issue tracker for details. go1.11.6 (released 2019-03-14) includes fixes to cgo, the compiler, linker, runtime, go command, and the crypto/x509, encoding/json, net, and net/url packages. See the Go 1.11.6 milestone on our issue tracker for details. go1.11.7 (released 2019-04-05) includes fixes to the runtime and the net package. See the Go 1.11.7 milestone on our issue tracker for details. go1.11.8 (released 2019-04-08) was accidentally released without its intended fix. It is identical to go1.11.7, except for its version number. The intended fix is in go1.11.9. go1.11.9 (released 2019-04-11) fixes an issue where using the prebuilt binary releases on older versions of GNU/Linux led to failures when linking programs that used cgo. Only Linux users who hit this issue need to update. go1.11.10 (released 2019-05-06) includes security fixes to the runtime, as well as bug fixes to the linker. See the Go 1.11.10 milestone on our issue tracker for details. go1.11.11 (released 2019-06-11) includes a fix to the crypto/x509 package. See the Go 1.11.11 milestone on our issue tracker for details. go1.11.12 (released 2019-07-08) includes fixes to the compiler and the linker. See the Go 1.11.12 milestone on our issue tracker for details. go1.11.13 (released 2019-08-13) includes security fixes to the net/http and net/url packages. See the Go 1.11.13 milestone on our issue tracker for details. go1.10 (released 2018-02-16) Go 1.10 is a major release of Go. Read the Go 1.10 Release Notes for more information. Minor revisions go1.10.1 (released 2018-03-28) includes security fixes to the go command, as well as bug fixes to the compiler, runtime, and the archive/zip, crypto/tls, crypto/x509, encoding/json, net, net/http, and net/http/pprof packages. See the Go 1.10.1 milestone on our issue tracker for details. go1.10.2 (released 2018-05-01) includes fixes to the compiler, linker, and go command. See the Go 1.10.2 milestone on our issue tracker for details. go1.10.3 (released 2018-06-05) includes fixes to the go command, and the crypto/tls, crypto/x509, and strings packages. In particular, it adds minimal support to the go command for the vgo transition. See the Go 1.10.3 milestone on our issue tracker for details. go1.10.4 (released 2018-08-24) includes fixes to the go command, linker, and the bytes, mime/multipart, net/http, and strings packages. See the Go 1.10.4 milestone on our issue tracker for details. go1.10.5 (released 2018-11-02) includes fixes to the go command, linker, runtime, and the database/sql package. See the Go 1.10.5 milestone on our issue tracker for details. go1.10.6 (released 2018-12-12) includes three security fixes to \"go get\" and the crypto/x509 package. It contains the same fixes as Go 1.11.3 and was released at the same time. See the Go 1.10.6 milestone on our issue tracker for details. go1.10.7 (released 2018-12-14) includes a fix to a bug introduced in Go 1.10.6 that broke go get for import path patterns containing \"...\". See the Go 1.10.7 milestone on our issue tracker for details. go1.10.8 (released 2019-01-23) includes a security fix to the crypto/elliptic package. See the Go 1.10.8 milestone on our issue tracker for details. go1.9 (released 2017-08-24) Go 1.9 is a major release of Go. Read the Go 1.9 Release Notes for more information. Minor revisions go1.9.1 (released 2017-10-04) includes two security fixes. See the Go 1.9.1 milestone on our issue tracker for details. go1.9.2 (released 2017-10-25) includes fixes to the compiler, linker, runtime, documentation, go command, and the crypto/x509, database/sql, log, and net/smtp packages. It includes a fix to a bug introduced in Go 1.9.1 that broke go get of non-Git repositories under certain conditions. See the Go 1.9.2 milestone on our issue tracker for details. go1.9.3 (released 2018-01-22) includes security fixes to the net/url package, as well as bug fixes to the compiler, runtime, and the database/sql, math/big, and net/http packages. See the Go 1.9.3 milestone on our issue tracker for details. go1.9.4 (released 2018-02-07) includes a security fix to \"go get\". See the Go 1.9.4 milestone on our issue tracker for details. go1.9.5 (released 2018-03-28) includes security fixes to the go command, as well as bug fixes to the compiler, go command, and the net/http/pprof package. See the Go 1.9.5 milestone on our issue tracker for details. go1.9.6 (released 2018-05-01) includes fixes to the compiler and go command. See the Go 1.9.6 milestone on our issue tracker for details. go1.9.7 (released 2018-06-05) includes fixes to the go command, and the crypto/x509 and strings packages. In particular, it adds minimal support to the go command for the vgo transition. See the Go 1.9.7 milestone on our issue tracker for details. go1.8 (released 2017-02-16) Go 1.8 is a major release of Go. Read the Go 1.8 Release Notes for more information. Minor revisions go1.8.1 (released 2017-04-07) includes fixes to the compiler, linker, runtime, documentation, go command and the crypto/tls, encoding/xml, image/png, net, net/http, reflect, text/template, and time packages. See the Go 1.8.1 milestone on our issue tracker for details. go1.8.2 (released 2017-05-23) includes a security fix to the crypto/elliptic package. See the Go 1.8.2 milestone on our issue tracker for details. go1.8.3 (released 2017-05-24) includes fixes to the compiler, runtime, documentation, and the database/sql package. See the Go 1.8.3 milestone on our issue tracker for details. go1.8.4 (released 2017-10-04) includes two security fixes. It contains the same fixes as Go 1.9.1 and was released at the same time. See the Go 1.8.4 milestone on our issue tracker for details. go1.8.5 (released 2017-10-25) includes fixes to the compiler, linker, runtime, documentation, go command, and the crypto/x509 and net/smtp packages. It includes a fix to a bug introduced in Go 1.8.4 that broke go get of non-Git repositories under certain conditions. See the Go 1.8.5 milestone on our issue tracker for details. go1.8.6 (released 2018-01-22) includes the same fix in math/big as Go 1.9.3 and was released at the same time. See the Go 1.8.6 milestone on our issue tracker for details. go1.8.7 (released 2018-02-07) includes a security fix to \"go get\". It contains the same fix as Go 1.9.4 and was released at the same time. See the Go 1.8.7 milestone on our issue tracker for details. go1.7 (released 2016-08-15) Go 1.7 is a major release of Go. Read the Go 1.7 Release Notes for more information. Minor revisions go1.7.1 (released 2016-09-07) includes fixes to the compiler, runtime, documentation, and the compress/flate, hash/crc32, io, net, net/http, path/filepath, reflect, and syscall packages. See the Go 1.7.1 milestone on our issue tracker for details. go1.7.2 should not be used. It was tagged but not fully released. The release was deferred due to a last minute bug report. Use go1.7.3 instead, and refer to the summary of changes below. go1.7.3 (released 2016-10-19) includes fixes to the compiler, runtime, and the crypto/cipher, crypto/tls, net/http, and strings packages. See the Go 1.7.3 milestone on our issue tracker for details. go1.7.4 (released 2016-12-01) includes two security fixes. See the Go 1.7.4 milestone on our issue tracker for details. go1.7.5 (released 2017-01-26) includes fixes to the compiler, runtime, and the crypto/x509 and time packages. See the Go 1.7.5 milestone on our issue tracker for details. go1.7.6 (released 2017-05-23) includes the same security fix as Go 1.8.2 and was released at the same time. See the Go 1.8.2 milestone on our issue tracker for details. go1.6 (released 2016-02-17) Go 1.6 is a major release of Go. Read the Go 1.6 Release Notes for more information. Minor revisions go1.6.1 (released 2016-04-12) includes two security fixes. See the Go 1.6.1 milestone on our issue tracker for details. go1.6.2 (released 2016-04-20) includes fixes to the compiler, runtime, tools, documentation, and the mime/multipart, net/http, and sort packages. See the Go 1.6.2 milestone on our issue tracker for details. go1.6.3 (released 2016-07-17) includes security fixes to the net/http/cgi package and net/http package when used in a CGI environment. See the Go 1.6.3 milestone on our issue tracker for details. go1.6.4 (released 2016-12-01) includes two security fixes. It contains the same fixes as Go 1.7.4 and was released at the same time. See the Go 1.7.4 milestone on our issue tracker for details. go1.5 (released 2015-08-19) Go 1.5 is a major release of Go. Read the Go 1.5 Release Notes for more information. Minor revisions go1.5.1 (released 2015-09-08) includes bug fixes to the compiler, assembler, and the fmt, net/textproto, net/http, and runtime packages. See the Go 1.5.1 milestone on our issue tracker for details. go1.5.2 (released 2015-12-02) includes bug fixes to the compiler, linker, and the mime/multipart, net, and runtime packages. See the Go 1.5.2 milestone on our issue tracker for details. go1.5.3 (released 2016-01-13) includes a security fix to the math/big package affecting the crypto/tls package. See the release announcement for details. go1.5.4 (released 2016-04-12) includes two security fixes. It contains the same fixes as Go 1.6.1 and was released at the same time. See the Go 1.6.1 milestone on our issue tracker for details. go1.4 (released 2014-12-10) Go 1.4 is a major release of Go. Read the Go 1.4 Release Notes for more information. Minor revisions go1.4.1 (released 2015-01-15) includes bug fixes to the linker and the log, syscall, and runtime packages. See the Go 1.4.1 milestone on our issue tracker for details. go1.4.2 (released 2015-02-17) includes security fixes to the compiler, and bug fixes to the go command, the compiler and linker, and the runtime, syscall, reflect, and math/big packages. See the Go 1.4.2 milestone on our issue tracker for details. go1.4.3 (released 2015-09-22) includes security fixes to the net/http package and bug fixes to the runtime package. See the Go 1.4.3 milestone on our issue tracker for details. go1.3 (released 2014-06-18) Go 1.3 is a major release of Go. Read the Go 1.3 Release Notes for more information. Minor revisions go1.3.1 (released 2014-08-13) includes bug fixes to the compiler and the runtime, net, and crypto/rsa packages. See the change history for details. go1.3.2 (released 2014-09-25) includes security fixes to the crypto/tls package and bug fixes to cgo. See the change history for details. go1.3.3 (released 2014-09-30) includes further bug fixes to cgo, the runtime package, and the nacl port. See the change history for details. go1.2 (released 2013-12-01) Go 1.2 is a major release of Go. Read the Go 1.2 Release Notes for more information. Minor revisions go1.2.1 (released 2014-03-02) includes bug fixes to the runtime, net, and database/sql packages. See the change history for details. go1.2.2 (released 2014-05-05) includes a security fix that affects the tour binary included in the binary distributions (thanks to Guillaume T). go1.1 (released 2013-05-13) Go 1.1 is a major release of Go. Read the Go 1.1 Release Notes for more information. Minor revisions go1.1.1 (released 2013-06-13) includes a security fix to the compiler and several bug fixes to the compiler and runtime. See the change history for details. go1.1.2 (released 2013-08-13) includes fixes to the gc compiler and cgo, and the bufio, runtime, syscall, and time packages. See the change history for details. If you use package syscall's Getrlimit and Setrlimit functions under Linux on the ARM or 386 architectures, please note change 11803043 that fixes issue 5949. go1 (released 2012-03-28) Go 1 is a major release of Go that will be stable in the long term. Read the Go 1 Release Notes for more information. It is intended that programs written for Go 1 will continue to compile and run correctly, unchanged, under future versions of Go 1. Read the Go 1 compatibility document for more about the future of Go 1. The go1 release corresponds to weekly.2012-03-27. Minor revisions go1.0.1 (released 2012-04-25) was issued to fix an escape analysis bug that can lead to memory corruption. It also includes several minor code and documentation fixes. go1.0.2 (released 2012-06-13) was issued to fix two bugs in the implementation of maps using struct or array 3695 and issue 3573. It also includes many minor code and documentation fixes. go1.0.3 (released 2012-09-21) includes minor code and documentation fixes. See the go1 release branch history for the complete list of changes. Older releases See the Pre-Go 1 Release History page for notes on earlier releases.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\ngit fetch --tags\ngit checkout goX.Y.Z\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.566Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":1,"totalLines":11,"estimatedTokens":14941}}52{"id":"doc-a_guide_to_the_go_garbage_collector_the_go_progr-5a935bf9","source":"documentation","title":"A Guide to the Go Garbage Collector - The Go Programming Language","url":"https://go.dev/doc/gc-guide","text":"go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\nf := new(myFile)\nf.fd = syscall.Open(...)\nruntime.AddCleanup(f, func(fd int) {\n\tsyscall.Close(f.fd) // Mistake: We reference f, so this cleanup won't run!\n}, f.fd)\n```\n\nExample:\n```text\nf := new(myFile)\nf.fd = syscall.Open(...)\nruntime.AddCleanup(f, func(f *myFile) {\n\tsyscall.Close(f.fd)\n}, f) // Mistake: We reference f, so this cleanup wouldn't ever run. This specific case also panics.\n```\n\nExample:\n```text\nf := new(myCycle)\nf.self = f // Mistake: f is reachable from f, so this finalizer would never run.\nruntime.SetFinalizer(f, func(f *myCycle) {\n\t...\n})\n```\n\nExample:\n```text\nf := new(myFile)\nf.fd = syscall.Open(...)\nruntime.SetFinalizer(f, func(_ *myFile) {\n\tsyscall.Close(f.fd) // Mistake: We reference the outer f, so this cleanup won't run!\n})\n```\n\nExample:\n```text\n// Mistake: reclaiming this linked list will take at least 10 GC cycles.\nnode := new(linkedListNode)\nfor range 10 {\n\ttmp := new(linkedListNode)\n\ttmp.next = node\n\tnode = tmp\n\truntime.SetFinalizer(node, func(node *linkedListNode) {\n\t\t...\n\t})\n}\n```\n\nExample:\n```text\n$ go build -gcflags=-m=3 [package]\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.641Z","totalSectionsIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":58,"estimatedTokens":310}}53{"id":"doc-canceling_in_progress_operations_the_go_programm-4c4d1d90","source":"documentation","title":"Canceling in-progress operations - The Go Programming Language","url":"https://go.dev/doc/database/cancel-operations","text":"Canceling in-progress operations You can manage in-progress operations by using Go context.Context. A Context is a standard Go data value that can report whether the overall operation it represents has been canceled and is no longer needed. By passing a context.Context across function calls and services in your application, those can stop working early and return an error when their processing is no longer needed. For more about Context, see Go Concurrency For example, you might want long-running operations, including database operations that are taking too long to complete. Propagate cancellation requests from elsewhere, such as when a client closes a connection. Many APIs for Go developers include methods that take a Context argument, making it easier for you to use Context throughout your application. Canceling database operations after a timeout You can use a Context to set a timeout or deadline after which an operation will be canceled. To derive a Context with a timeout or deadline, call context.WithTimeout or context.WithDeadline. Code in the following timeout example derives a Context and passes it into the sql.DB QueryContext method. func QueryWithTimeout(ctx context.Context) { // Create a Context with a timeout. queryCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() // Pass the timeout Context with a query. rows, err := db.QueryContext(queryCtx, \"SELECT * FROM album\") if err != nil { log.Fatal(err) } defer rows.Close() // Handle returned rows. } When one context is derived from an outer context, as queryCtx is derived from ctx in this example, if the outer context is canceled, then the derived context is automatically canceled as well. For example, in HTTP servers, the http.Request.Context method returns a context associated with the request. That context is canceled if the HTTP client disconnects or cancels the HTTP request (possible in HTTP/2). Passing an HTTP request’s context to QueryWithTimeout above would cause the database query to stop early either if the overall HTTP request was canceled or if the query took more than five seconds. defer a call to the cancel function that’s returned when you create a new Context with a timeout or deadline. This releases resources held by the new Context when the containing function exits. It also cancels queryCtx, but by the time the function returns, nothing should be using queryCtx anymore.\n\ngo.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay\n\nExample:\n```text\nfunc QueryWithTimeout(ctx context.Context) {\n    // Create a Context with a timeout.\n    queryCtx, cancel := context.WithTimeout(ctx, 5*time.Second)\n    defer cancel()\n\n    // Pass the timeout Context with a query.\n    rows, err := db.QueryContext(queryCtx, \"SELECT * FROM album\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer rows.Close()\n\n    // Handle returned rows.\n}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:17:45.641Z","totalSectionsIncluded":2,"totalCodeBlocksIncluded":1,"totalLines":23,"estimatedTokens":738}}54