From 754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 Mon Sep 17 00:00:00 2001 From: Craig Jennings Date: Sun, 7 Apr 2024 13:41:34 -0500 Subject: new repository --- devdocs/go/archive%2Ftar%2Findex.html | 299 +++ devdocs/go/archive%2Fzip%2Findex.html | 290 +++ devdocs/go/arena%2Findex.html | 8 + devdocs/go/bufio%2Findex.html | 318 +++ devdocs/go/builtin%2Findex.html | 147 ++ devdocs/go/bytes%2Findex.html | 650 +++++ devdocs/go/cmp%2Findex.html | 73 + devdocs/go/compress%2Fbzip2%2Findex.html | 17 + devdocs/go/compress%2Fflate%2Findex.html | 307 +++ devdocs/go/compress%2Fgzip%2Findex.html | 282 +++ devdocs/go/compress%2Flzw%2Findex.html | 54 + devdocs/go/compress%2Fzlib%2Findex.html | 95 + devdocs/go/container%2Fheap%2Findex.html | 171 ++ devdocs/go/container%2Flist%2Findex.html | 100 + devdocs/go/container%2Fring%2Findex.html | 199 ++ devdocs/go/context%2Findex.html | 381 +++ devdocs/go/crypto%2Faes%2Findex.html | 19 + devdocs/go/crypto%2Fboring%2Findex.html | 7 + devdocs/go/crypto%2Fcipher%2Findex.html | 463 ++++ devdocs/go/crypto%2Fdes%2Findex.html | 38 + devdocs/go/crypto%2Fdsa%2Findex.html | 50 + devdocs/go/crypto%2Fecdh%2Findex.html | 98 + devdocs/go/crypto%2Fecdsa%2Findex.html | 76 + devdocs/go/crypto%2Fed25519%2Findex.html | 90 + devdocs/go/crypto%2Felliptic%2Findex.html | 117 + devdocs/go/crypto%2Fhmac%2Findex.html | 23 + devdocs/go/crypto%2Findex.html | 106 + devdocs/go/crypto%2Fmd5%2Findex.html | 42 + devdocs/go/crypto%2Frand%2Findex.html | 32 + devdocs/go/crypto%2Frc4%2Findex.html | 30 + devdocs/go/crypto%2Frsa%2Findex.html | 295 +++ devdocs/go/crypto%2Fsha1%2Findex.html | 42 + devdocs/go/crypto%2Fsha256%2Findex.html | 45 + devdocs/go/crypto%2Fsha512%2Findex.html | 44 + devdocs/go/crypto%2Fsubtle%2Findex.html | 24 + devdocs/go/crypto%2Ftls%2Ffipsonly%2Findex.html | 9 + devdocs/go/crypto%2Ftls%2Findex.html | 1114 +++++++++ devdocs/go/crypto%2Fx509%2Findex.html | 785 ++++++ devdocs/go/crypto%2Fx509%2Fpkix%2Findex.html | 108 + devdocs/go/database%2Fsql%2Fdriver%2Findex.html | 403 ++++ devdocs/go/database%2Fsql%2Findex.html | 1151 +++++++++ devdocs/go/debug%2Fbuildinfo%2Findex.html | 19 + devdocs/go/debug%2Fdwarf%2Findex.html | 754 ++++++ devdocs/go/debug%2Felf%2Findex.html | 2116 +++++++++++++++++ devdocs/go/debug%2Fgosym%2Findex.html | 133 ++ devdocs/go/debug%2Fmacho%2Findex.html | 542 +++++ devdocs/go/debug%2Fpe%2Findex.html | 350 +++ devdocs/go/debug%2Fplan9obj%2Findex.html | 87 + devdocs/go/embed%2Findex.html | 102 + devdocs/go/encoding%2Fascii85%2Findex.html | 28 + devdocs/go/encoding%2Fasn1%2Findex.html | 130 + devdocs/go/encoding%2Fbase32%2Findex.html | 96 + devdocs/go/encoding%2Fbase64%2Findex.html | 114 + devdocs/go/encoding%2Fbinary%2Findex.html | 217 ++ devdocs/go/encoding%2Fcsv%2Findex.html | 239 ++ devdocs/go/encoding%2Fgob%2Findex.html | 374 +++ devdocs/go/encoding%2Fhex%2Findex.html | 106 + devdocs/go/encoding%2Findex.html | 33 + devdocs/go/encoding%2Fjson%2Findex.html | 640 +++++ devdocs/go/encoding%2Fpem%2Findex.html | 78 + devdocs/go/encoding%2Fxml%2Findex.html | 596 +++++ devdocs/go/errors%2Findex.html | 118 + devdocs/go/expvar%2Findex.html | 120 + devdocs/go/flag%2Findex.html | 452 ++++ devdocs/go/fmt%2Findex.html | 627 +++++ devdocs/go/go%2Fast%2Findex.html | 1031 ++++++++ devdocs/go/go%2Fbuild%2Fconstraint%2Findex.html | 88 + devdocs/go/go%2Fbuild%2Findex.html | 293 +++ devdocs/go/go%2Fconstant%2Findex.html | 290 +++ devdocs/go/go%2Fdoc%2Fcomment%2Findex.html | 256 ++ devdocs/go/go%2Fdoc%2Findex.html | 237 ++ devdocs/go/go%2Fformat%2Findex.html | 42 + devdocs/go/go%2Fimporter%2Findex.html | 22 + devdocs/go/go%2Fparser%2Findex.html | 68 + devdocs/go/go%2Fprinter%2Findex.html | 100 + devdocs/go/go%2Fscanner%2Findex.html | 111 + devdocs/go/go%2Ftoken%2Findex.html | 339 +++ devdocs/go/go%2Ftypes%2Findex.html | 1630 +++++++++++++ devdocs/go/go%2Fversion%2Findex.html | 23 + devdocs/go/hash%2Fadler32%2Findex.html | 23 + devdocs/go/hash%2Fcrc32%2Findex.html | 62 + devdocs/go/hash%2Fcrc64%2Findex.html | 30 + devdocs/go/hash%2Ffnv%2Findex.html | 23 + devdocs/go/hash%2Findex.html | 82 + devdocs/go/hash%2Fmaphash%2Findex.html | 106 + devdocs/go/html%2Findex.html | 23 + devdocs/go/html%2Ftemplate%2Findex.html | 773 ++++++ devdocs/go/image%2Fcolor%2Findex.html | 149 ++ devdocs/go/image%2Fcolor%2Fpalette%2Findex.html | 488 ++++ devdocs/go/image%2Fdraw%2Findex.html | 85 + devdocs/go/image%2Fgif%2Findex.html | 74 + devdocs/go/image%2Findex.html | 721 ++++++ devdocs/go/image%2Fjpeg%2Findex.html | 38 + devdocs/go/image%2Fpng%2Findex.html | 104 + devdocs/go/index | 1 + devdocs/go/index%2Fsuffixarray%2Findex.html | 50 + devdocs/go/index.html | 29 + devdocs/go/internal%2Fgoarch%2Findex.html | 33 + devdocs/go/internal%2Fgoos%2Findex.html | 10 + devdocs/go/io%2Ffs%2Findex.html | 256 ++ devdocs/go/io%2Findex.html | 461 ++++ devdocs/go/io%2Fioutil%2Findex.html | 147 ++ devdocs/go/iter%2Findex.html | 7 + devdocs/go/log%2Findex.html | 141 ++ devdocs/go/log%2Fslog%2Findex.html | 931 ++++++++ devdocs/go/log%2Fsyslog%2Findex.html | 109 + devdocs/go/maps%2Findex.html | 126 + devdocs/go/math%2Fbig%2Findex.html | 912 +++++++ devdocs/go/math%2Fbits%2Findex.html | 377 +++ devdocs/go/math%2Fcmplx%2Findex.html | 74 + devdocs/go/math%2Findex.html | 597 +++++ devdocs/go/math%2Frand%2Findex.html | 240 ++ devdocs/go/math%2Frand%2Fv2%2Findex.html | 278 +++ devdocs/go/metadata | 2 + devdocs/go/mime%2Findex.html | 153 ++ devdocs/go/mime%2Fmultipart%2Findex.html | 151 ++ devdocs/go/mime%2Fquotedprintable%2Findex.html | 55 + devdocs/go/net%2Fhttp%2Fcgi%2Findex.html | 48 + devdocs/go/net%2Fhttp%2Fcookiejar%2Findex.html | 106 + devdocs/go/net%2Fhttp%2Ffcgi%2Findex.html | 19 + devdocs/go/net%2Fhttp%2Fhttptest%2Findex.html | 200 ++ devdocs/go/net%2Fhttp%2Fhttptrace%2Findex.html | 167 ++ devdocs/go/net%2Fhttp%2Fhttputil%2Findex.html | 341 +++ devdocs/go/net%2Fhttp%2Findex.html | 2003 ++++++++++++++++ devdocs/go/net%2Fhttp%2Finternal%2Findex.html | 24 + devdocs/go/net%2Fhttp%2Fpprof%2Findex.html | 48 + devdocs/go/net%2Findex.html | 1610 +++++++++++++ devdocs/go/net%2Fmail%2Findex.html | 121 + devdocs/go/net%2Fnetip%2Findex.html | 260 ++ devdocs/go/net%2Frpc%2Findex.html | 218 ++ devdocs/go/net%2Frpc%2Fjsonrpc%2Findex.html | 20 + devdocs/go/net%2Fsmtp%2Findex.html | 168 ++ devdocs/go/net%2Ftextproto%2Findex.html | 213 ++ devdocs/go/net%2Furl%2Findex.html | 425 ++++ devdocs/go/os%2Fexec%2Findex.html | 413 ++++ devdocs/go/os%2Findex.html | 787 ++++++ devdocs/go/os%2Fsignal%2Findex.html | 127 + devdocs/go/os%2Fuser%2Findex.html | 79 + devdocs/go/path%2Ffilepath%2Findex.html | 305 +++ devdocs/go/path%2Findex.html | 132 ++ devdocs/go/plugin%2Findex.html | 60 + devdocs/go/reflect%2Findex.html | 870 +++++++ devdocs/go/regexp%2Findex.html | 501 ++++ devdocs/go/regexp%2Fsyntax%2Findex.html | 284 +++ devdocs/go/runtime%2Fasan%2Findex.html | 6 + devdocs/go/runtime%2Fcgo%2Findex.html | 96 + devdocs/go/runtime%2Fcoverage%2Findex.html | 20 + devdocs/go/runtime%2Fdebug%2Findex.html | 120 + devdocs/go/runtime%2Findex.html | 810 +++++++ devdocs/go/runtime%2Fmetrics%2Findex.html | 618 +++++ devdocs/go/runtime%2Fpprof%2Findex.html | 136 ++ devdocs/go/runtime%2Frace%2Findex.html | 11 + devdocs/go/runtime%2Ftrace%2Findex.html | 136 ++ devdocs/go/slices%2Findex.html | 277 +++ devdocs/go/sort%2Findex.html | 648 +++++ devdocs/go/strconv%2Findex.html | 449 ++++ devdocs/go/strings%2Findex.html | 488 ++++ devdocs/go/sync%2Fatomic%2Findex.html | 295 +++ devdocs/go/sync%2Findex.html | 290 +++ devdocs/go/syscall%2Findex.html | 2897 +++++++++++++++++++++++ devdocs/go/syscall%2Fjs%2Findex.html | 159 ++ devdocs/go/testing%2Ffstest%2Findex.html | 43 + devdocs/go/testing%2Findex.html | 661 ++++++ devdocs/go/testing%2Fiotest%2Findex.html | 39 + devdocs/go/testing%2Fquick%2Findex.html | 74 + devdocs/go/testing%2Fslogtest%2Findex.html | 42 + devdocs/go/text%2Fscanner%2Findex.html | 226 ++ devdocs/go/text%2Ftabwriter%2Findex.html | 134 ++ devdocs/go/text%2Ftemplate%2Findex.html | 640 +++++ devdocs/go/text%2Ftemplate%2Fparse%2Findex.html | 385 +++ devdocs/go/time%2Findex.html | 1035 ++++++++ devdocs/go/time%2Ftzdata%2Findex.html | 13 + devdocs/go/unicode%2Findex.html | 830 +++++++ devdocs/go/unicode%2Futf16%2Findex.html | 22 + devdocs/go/unicode%2Futf8%2Findex.html | 205 ++ devdocs/go/unsafe%2Findex.html | 120 + 176 files changed, 50598 insertions(+) create mode 100644 devdocs/go/archive%2Ftar%2Findex.html create mode 100644 devdocs/go/archive%2Fzip%2Findex.html create mode 100644 devdocs/go/arena%2Findex.html create mode 100644 devdocs/go/bufio%2Findex.html create mode 100644 devdocs/go/builtin%2Findex.html create mode 100644 devdocs/go/bytes%2Findex.html create mode 100644 devdocs/go/cmp%2Findex.html create mode 100644 devdocs/go/compress%2Fbzip2%2Findex.html create mode 100644 devdocs/go/compress%2Fflate%2Findex.html create mode 100644 devdocs/go/compress%2Fgzip%2Findex.html create mode 100644 devdocs/go/compress%2Flzw%2Findex.html create mode 100644 devdocs/go/compress%2Fzlib%2Findex.html create mode 100644 devdocs/go/container%2Fheap%2Findex.html create mode 100644 devdocs/go/container%2Flist%2Findex.html create mode 100644 devdocs/go/container%2Fring%2Findex.html create mode 100644 devdocs/go/context%2Findex.html create mode 100644 devdocs/go/crypto%2Faes%2Findex.html create mode 100644 devdocs/go/crypto%2Fboring%2Findex.html create mode 100644 devdocs/go/crypto%2Fcipher%2Findex.html create mode 100644 devdocs/go/crypto%2Fdes%2Findex.html create mode 100644 devdocs/go/crypto%2Fdsa%2Findex.html create mode 100644 devdocs/go/crypto%2Fecdh%2Findex.html create mode 100644 devdocs/go/crypto%2Fecdsa%2Findex.html create mode 100644 devdocs/go/crypto%2Fed25519%2Findex.html create mode 100644 devdocs/go/crypto%2Felliptic%2Findex.html create mode 100644 devdocs/go/crypto%2Fhmac%2Findex.html create mode 100644 devdocs/go/crypto%2Findex.html create mode 100644 devdocs/go/crypto%2Fmd5%2Findex.html create mode 100644 devdocs/go/crypto%2Frand%2Findex.html create mode 100644 devdocs/go/crypto%2Frc4%2Findex.html create mode 100644 devdocs/go/crypto%2Frsa%2Findex.html create mode 100644 devdocs/go/crypto%2Fsha1%2Findex.html create mode 100644 devdocs/go/crypto%2Fsha256%2Findex.html create mode 100644 devdocs/go/crypto%2Fsha512%2Findex.html create mode 100644 devdocs/go/crypto%2Fsubtle%2Findex.html create mode 100644 devdocs/go/crypto%2Ftls%2Ffipsonly%2Findex.html create mode 100644 devdocs/go/crypto%2Ftls%2Findex.html create mode 100644 devdocs/go/crypto%2Fx509%2Findex.html create mode 100644 devdocs/go/crypto%2Fx509%2Fpkix%2Findex.html create mode 100644 devdocs/go/database%2Fsql%2Fdriver%2Findex.html create mode 100644 devdocs/go/database%2Fsql%2Findex.html create mode 100644 devdocs/go/debug%2Fbuildinfo%2Findex.html create mode 100644 devdocs/go/debug%2Fdwarf%2Findex.html create mode 100644 devdocs/go/debug%2Felf%2Findex.html create mode 100644 devdocs/go/debug%2Fgosym%2Findex.html create mode 100644 devdocs/go/debug%2Fmacho%2Findex.html create mode 100644 devdocs/go/debug%2Fpe%2Findex.html create mode 100644 devdocs/go/debug%2Fplan9obj%2Findex.html create mode 100644 devdocs/go/embed%2Findex.html create mode 100644 devdocs/go/encoding%2Fascii85%2Findex.html create mode 100644 devdocs/go/encoding%2Fasn1%2Findex.html create mode 100644 devdocs/go/encoding%2Fbase32%2Findex.html create mode 100644 devdocs/go/encoding%2Fbase64%2Findex.html create mode 100644 devdocs/go/encoding%2Fbinary%2Findex.html create mode 100644 devdocs/go/encoding%2Fcsv%2Findex.html create mode 100644 devdocs/go/encoding%2Fgob%2Findex.html create mode 100644 devdocs/go/encoding%2Fhex%2Findex.html create mode 100644 devdocs/go/encoding%2Findex.html create mode 100644 devdocs/go/encoding%2Fjson%2Findex.html create mode 100644 devdocs/go/encoding%2Fpem%2Findex.html create mode 100644 devdocs/go/encoding%2Fxml%2Findex.html create mode 100644 devdocs/go/errors%2Findex.html create mode 100644 devdocs/go/expvar%2Findex.html create mode 100644 devdocs/go/flag%2Findex.html create mode 100644 devdocs/go/fmt%2Findex.html create mode 100644 devdocs/go/go%2Fast%2Findex.html create mode 100644 devdocs/go/go%2Fbuild%2Fconstraint%2Findex.html create mode 100644 devdocs/go/go%2Fbuild%2Findex.html create mode 100644 devdocs/go/go%2Fconstant%2Findex.html create mode 100644 devdocs/go/go%2Fdoc%2Fcomment%2Findex.html create mode 100644 devdocs/go/go%2Fdoc%2Findex.html create mode 100644 devdocs/go/go%2Fformat%2Findex.html create mode 100644 devdocs/go/go%2Fimporter%2Findex.html create mode 100644 devdocs/go/go%2Fparser%2Findex.html create mode 100644 devdocs/go/go%2Fprinter%2Findex.html create mode 100644 devdocs/go/go%2Fscanner%2Findex.html create mode 100644 devdocs/go/go%2Ftoken%2Findex.html create mode 100644 devdocs/go/go%2Ftypes%2Findex.html create mode 100644 devdocs/go/go%2Fversion%2Findex.html create mode 100644 devdocs/go/hash%2Fadler32%2Findex.html create mode 100644 devdocs/go/hash%2Fcrc32%2Findex.html create mode 100644 devdocs/go/hash%2Fcrc64%2Findex.html create mode 100644 devdocs/go/hash%2Ffnv%2Findex.html create mode 100644 devdocs/go/hash%2Findex.html create mode 100644 devdocs/go/hash%2Fmaphash%2Findex.html create mode 100644 devdocs/go/html%2Findex.html create mode 100644 devdocs/go/html%2Ftemplate%2Findex.html create mode 100644 devdocs/go/image%2Fcolor%2Findex.html create mode 100644 devdocs/go/image%2Fcolor%2Fpalette%2Findex.html create mode 100644 devdocs/go/image%2Fdraw%2Findex.html create mode 100644 devdocs/go/image%2Fgif%2Findex.html create mode 100644 devdocs/go/image%2Findex.html create mode 100644 devdocs/go/image%2Fjpeg%2Findex.html create mode 100644 devdocs/go/image%2Fpng%2Findex.html create mode 100644 devdocs/go/index create mode 100644 devdocs/go/index%2Fsuffixarray%2Findex.html create mode 100644 devdocs/go/index.html create mode 100644 devdocs/go/internal%2Fgoarch%2Findex.html create mode 100644 devdocs/go/internal%2Fgoos%2Findex.html create mode 100644 devdocs/go/io%2Ffs%2Findex.html create mode 100644 devdocs/go/io%2Findex.html create mode 100644 devdocs/go/io%2Fioutil%2Findex.html create mode 100644 devdocs/go/iter%2Findex.html create mode 100644 devdocs/go/log%2Findex.html create mode 100644 devdocs/go/log%2Fslog%2Findex.html create mode 100644 devdocs/go/log%2Fsyslog%2Findex.html create mode 100644 devdocs/go/maps%2Findex.html create mode 100644 devdocs/go/math%2Fbig%2Findex.html create mode 100644 devdocs/go/math%2Fbits%2Findex.html create mode 100644 devdocs/go/math%2Fcmplx%2Findex.html create mode 100644 devdocs/go/math%2Findex.html create mode 100644 devdocs/go/math%2Frand%2Findex.html create mode 100644 devdocs/go/math%2Frand%2Fv2%2Findex.html create mode 100644 devdocs/go/metadata create mode 100644 devdocs/go/mime%2Findex.html create mode 100644 devdocs/go/mime%2Fmultipart%2Findex.html create mode 100644 devdocs/go/mime%2Fquotedprintable%2Findex.html create mode 100644 devdocs/go/net%2Fhttp%2Fcgi%2Findex.html create mode 100644 devdocs/go/net%2Fhttp%2Fcookiejar%2Findex.html create mode 100644 devdocs/go/net%2Fhttp%2Ffcgi%2Findex.html create mode 100644 devdocs/go/net%2Fhttp%2Fhttptest%2Findex.html create mode 100644 devdocs/go/net%2Fhttp%2Fhttptrace%2Findex.html create mode 100644 devdocs/go/net%2Fhttp%2Fhttputil%2Findex.html create mode 100644 devdocs/go/net%2Fhttp%2Findex.html create mode 100644 devdocs/go/net%2Fhttp%2Finternal%2Findex.html create mode 100644 devdocs/go/net%2Fhttp%2Fpprof%2Findex.html create mode 100644 devdocs/go/net%2Findex.html create mode 100644 devdocs/go/net%2Fmail%2Findex.html create mode 100644 devdocs/go/net%2Fnetip%2Findex.html create mode 100644 devdocs/go/net%2Frpc%2Findex.html create mode 100644 devdocs/go/net%2Frpc%2Fjsonrpc%2Findex.html create mode 100644 devdocs/go/net%2Fsmtp%2Findex.html create mode 100644 devdocs/go/net%2Ftextproto%2Findex.html create mode 100644 devdocs/go/net%2Furl%2Findex.html create mode 100644 devdocs/go/os%2Fexec%2Findex.html create mode 100644 devdocs/go/os%2Findex.html create mode 100644 devdocs/go/os%2Fsignal%2Findex.html create mode 100644 devdocs/go/os%2Fuser%2Findex.html create mode 100644 devdocs/go/path%2Ffilepath%2Findex.html create mode 100644 devdocs/go/path%2Findex.html create mode 100644 devdocs/go/plugin%2Findex.html create mode 100644 devdocs/go/reflect%2Findex.html create mode 100644 devdocs/go/regexp%2Findex.html create mode 100644 devdocs/go/regexp%2Fsyntax%2Findex.html create mode 100644 devdocs/go/runtime%2Fasan%2Findex.html create mode 100644 devdocs/go/runtime%2Fcgo%2Findex.html create mode 100644 devdocs/go/runtime%2Fcoverage%2Findex.html create mode 100644 devdocs/go/runtime%2Fdebug%2Findex.html create mode 100644 devdocs/go/runtime%2Findex.html create mode 100644 devdocs/go/runtime%2Fmetrics%2Findex.html create mode 100644 devdocs/go/runtime%2Fpprof%2Findex.html create mode 100644 devdocs/go/runtime%2Frace%2Findex.html create mode 100644 devdocs/go/runtime%2Ftrace%2Findex.html create mode 100644 devdocs/go/slices%2Findex.html create mode 100644 devdocs/go/sort%2Findex.html create mode 100644 devdocs/go/strconv%2Findex.html create mode 100644 devdocs/go/strings%2Findex.html create mode 100644 devdocs/go/sync%2Fatomic%2Findex.html create mode 100644 devdocs/go/sync%2Findex.html create mode 100644 devdocs/go/syscall%2Findex.html create mode 100644 devdocs/go/syscall%2Fjs%2Findex.html create mode 100644 devdocs/go/testing%2Ffstest%2Findex.html create mode 100644 devdocs/go/testing%2Findex.html create mode 100644 devdocs/go/testing%2Fiotest%2Findex.html create mode 100644 devdocs/go/testing%2Fquick%2Findex.html create mode 100644 devdocs/go/testing%2Fslogtest%2Findex.html create mode 100644 devdocs/go/text%2Fscanner%2Findex.html create mode 100644 devdocs/go/text%2Ftabwriter%2Findex.html create mode 100644 devdocs/go/text%2Ftemplate%2Findex.html create mode 100644 devdocs/go/text%2Ftemplate%2Fparse%2Findex.html create mode 100644 devdocs/go/time%2Findex.html create mode 100644 devdocs/go/time%2Ftzdata%2Findex.html create mode 100644 devdocs/go/unicode%2Findex.html create mode 100644 devdocs/go/unicode%2Futf16%2Findex.html create mode 100644 devdocs/go/unicode%2Futf8%2Findex.html create mode 100644 devdocs/go/unsafe%2Findex.html (limited to 'devdocs/go') diff --git a/devdocs/go/archive%2Ftar%2Findex.html b/devdocs/go/archive%2Ftar%2Findex.html new file mode 100644 index 00000000..2c767046 --- /dev/null +++ b/devdocs/go/archive%2Ftar%2Findex.html @@ -0,0 +1,299 @@ +

Package tar

Overview

Package tar implements access to tar archives.

+

Tape archives (tar) are a file format for storing a sequence of files that can be read and written in a streaming manner. This package aims to cover most variations of the format, including those produced by GNU and BSD tar tools.

Example (Minimal) +

Code:

// Create and add some files to the archive.
+var buf bytes.Buffer
+tw := tar.NewWriter(&buf)
+var files = []struct {
+    Name, Body string
+}{
+    {"readme.txt", "This archive contains some text files."},
+    {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
+    {"todo.txt", "Get animal handling license."},
+}
+for _, file := range files {
+    hdr := &tar.Header{
+        Name: file.Name,
+        Mode: 0600,
+        Size: int64(len(file.Body)),
+    }
+    if err := tw.WriteHeader(hdr); err != nil {
+        log.Fatal(err)
+    }
+    if _, err := tw.Write([]byte(file.Body)); err != nil {
+        log.Fatal(err)
+    }
+}
+if err := tw.Close(); err != nil {
+    log.Fatal(err)
+}
+
+// Open and iterate through the files in the archive.
+tr := tar.NewReader(&buf)
+for {
+    hdr, err := tr.Next()
+    if err == io.EOF {
+        break // End of archive
+    }
+    if err != nil {
+        log.Fatal(err)
+    }
+    fmt.Printf("Contents of %s:\n", hdr.Name)
+    if _, err := io.Copy(os.Stdout, tr); err != nil {
+        log.Fatal(err)
+    }
+    fmt.Println()
+}
+
+

Output:

Contents of readme.txt:
+This archive contains some text files.
+Contents of gopher.txt:
+Gopher names:
+George
+Geoffrey
+Gonzo
+Contents of todo.txt:
+Get animal handling license.
+

Index

Examples

Package (Minimal)

Package files

common.go format.go reader.go stat_actime1.go stat_unix.go strconv.go writer.go

Constants

Type flags for Header.Typeflag.

+
const (
+    // Type '0' indicates a regular file.
+    TypeReg = '0'
+
+    // Deprecated: Use TypeReg instead.
+    TypeRegA = '\x00'
+
+    // Type '1' to '6' are header-only flags and may not have a data body.
+    TypeLink    = '1' // Hard link
+    TypeSymlink = '2' // Symbolic link
+    TypeChar    = '3' // Character device node
+    TypeBlock   = '4' // Block device node
+    TypeDir     = '5' // Directory
+    TypeFifo    = '6' // FIFO node
+
+    // Type '7' is reserved.
+    TypeCont = '7'
+
+    // Type 'x' is used by the PAX format to store key-value records that
+    // are only relevant to the next file.
+    // This package transparently handles these types.
+    TypeXHeader = 'x'
+
+    // Type 'g' is used by the PAX format to store key-value records that
+    // are relevant to all subsequent files.
+    // This package only supports parsing and composing such headers,
+    // but does not currently support persisting the global state across files.
+    TypeXGlobalHeader = 'g'
+
+    // Type 'S' indicates a sparse file in the GNU format.
+    TypeGNUSparse = 'S'
+
+    // Types 'L' and 'K' are used by the GNU format for a meta file
+    // used to store the path or link name for the next file.
+    // This package transparently handles these types.
+    TypeGNULongName = 'L'
+    TypeGNULongLink = 'K'
+)

Variables

var (
+    ErrHeader          = errors.New("archive/tar: invalid tar header")
+    ErrWriteTooLong    = errors.New("archive/tar: write too long")
+    ErrFieldTooLong    = errors.New("archive/tar: header field too long")
+    ErrWriteAfterClose = errors.New("archive/tar: write after close")
+    ErrInsecurePath    = errors.New("archive/tar: insecure file path")
+)

type Format 1.10

Format represents the tar archive format.

+

The original tar format was introduced in Unix V7. Since then, there have been multiple competing formats attempting to standardize or extend the V7 format to overcome its limitations. The most common formats are the USTAR, PAX, and GNU formats, each with their own advantages and limitations.

+

The following table captures the capabilities of each format:

+
                  |  USTAR |       PAX |       GNU
+------------------+--------+-----------+----------
+Name              |   256B | unlimited | unlimited
+Linkname          |   100B | unlimited | unlimited
+Size              | uint33 | unlimited |    uint89
+Mode              | uint21 |    uint21 |    uint57
+Uid/Gid           | uint21 | unlimited |    uint57
+Uname/Gname       |    32B | unlimited |       32B
+ModTime           | uint33 | unlimited |     int89
+AccessTime        |    n/a | unlimited |     int89
+ChangeTime        |    n/a | unlimited |     int89
+Devmajor/Devminor | uint21 |    uint21 |    uint57
+------------------+--------+-----------+----------
+string encoding   |  ASCII |     UTF-8 |    binary
+sub-second times  |     no |       yes |        no
+sparse files      |     no |       yes |       yes
+

The table's upper portion shows the Header fields, where each format reports the maximum number of bytes allowed for each string field and the integer type used to store each numeric field (where timestamps are stored as the number of seconds since the Unix epoch).

+

The table's lower portion shows specialized features of each format, such as supported string encodings, support for sub-second timestamps, or support for sparse files.

+

The Writer currently provides no support for sparse files.

+
type Format int

Constants to identify various tar formats.

+
const (
+
+    // FormatUnknown indicates that the format is unknown.
+    FormatUnknown Format
+
+    // FormatUSTAR represents the USTAR header format defined in POSIX.1-1988.
+    //
+    // While this format is compatible with most tar readers,
+    // the format has several limitations making it unsuitable for some usages.
+    // Most notably, it cannot support sparse files, files larger than 8GiB,
+    // filenames larger than 256 characters, and non-ASCII filenames.
+    //
+    // Reference:
+    //	http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_06
+    FormatUSTAR
+
+    // FormatPAX represents the PAX header format defined in POSIX.1-2001.
+    //
+    // PAX extends USTAR by writing a special file with Typeflag TypeXHeader
+    // preceding the original header. This file contains a set of key-value
+    // records, which are used to overcome USTAR's shortcomings, in addition to
+    // providing the ability to have sub-second resolution for timestamps.
+    //
+    // Some newer formats add their own extensions to PAX by defining their
+    // own keys and assigning certain semantic meaning to the associated values.
+    // For example, sparse file support in PAX is implemented using keys
+    // defined by the GNU manual (e.g., "GNU.sparse.map").
+    //
+    // Reference:
+    //	http://pubs.opengroup.org/onlinepubs/009695399/utilities/pax.html
+    FormatPAX
+
+    // FormatGNU represents the GNU header format.
+    //
+    // The GNU header format is older than the USTAR and PAX standards and
+    // is not compatible with them. The GNU format supports
+    // arbitrary file sizes, filenames of arbitrary encoding and length,
+    // sparse files, and other features.
+    //
+    // It is recommended that PAX be chosen over GNU unless the target
+    // application can only parse GNU formatted archives.
+    //
+    // Reference:
+    //	https://www.gnu.org/software/tar/manual/html_node/Standard.html
+    FormatGNU
+)

func (Format) String 1.10

func (f Format) String() string

A Header represents a single header in a tar archive. Some fields may not be populated.

+

For forward compatibility, users that retrieve a Header from Reader.Next, mutate it in some ways, and then pass it back to Writer.WriteHeader should do so by creating a new Header and copying the fields that they are interested in preserving.

+
type Header struct {
+    // Typeflag is the type of header entry.
+    // The zero value is automatically promoted to either TypeReg or TypeDir
+    // depending on the presence of a trailing slash in Name.
+    Typeflag byte
+
+    Name     string // Name of file entry
+    Linkname string // Target name of link (valid for TypeLink or TypeSymlink)
+
+    Size  int64  // Logical file size in bytes
+    Mode  int64  // Permission and mode bits
+    Uid   int    // User ID of owner
+    Gid   int    // Group ID of owner
+    Uname string // User name of owner
+    Gname string // Group name of owner
+
+    // If the Format is unspecified, then Writer.WriteHeader rounds ModTime
+    // to the nearest second and ignores the AccessTime and ChangeTime fields.
+    //
+    // To use AccessTime or ChangeTime, specify the Format as PAX or GNU.
+    // To use sub-second resolution, specify the Format as PAX.
+    ModTime    time.Time // Modification time
+    AccessTime time.Time // Access time (requires either PAX or GNU support)
+    ChangeTime time.Time // Change time (requires either PAX or GNU support)
+
+    Devmajor int64 // Major device number (valid for TypeChar or TypeBlock)
+    Devminor int64 // Minor device number (valid for TypeChar or TypeBlock)
+
+    // Xattrs stores extended attributes as PAX records under the
+    // "SCHILY.xattr." namespace.
+    //
+    // The following are semantically equivalent:
+    //  h.Xattrs[key] = value
+    //  h.PAXRecords["SCHILY.xattr."+key] = value
+    //
+    // When Writer.WriteHeader is called, the contents of Xattrs will take
+    // precedence over those in PAXRecords.
+    //
+    // Deprecated: Use PAXRecords instead.
+    Xattrs map[string]string // Go 1.3
+
+    // PAXRecords is a map of PAX extended header records.
+    //
+    // User-defined records should have keys of the following form:
+    //	VENDOR.keyword
+    // Where VENDOR is some namespace in all uppercase, and keyword may
+    // not contain the '=' character (e.g., "GOLANG.pkg.version").
+    // The key and value should be non-empty UTF-8 strings.
+    //
+    // When Writer.WriteHeader is called, PAX records derived from the
+    // other fields in Header take precedence over PAXRecords.
+    PAXRecords map[string]string // Go 1.10
+
+    // Format specifies the format of the tar header.
+    //
+    // This is set by Reader.Next as a best-effort guess at the format.
+    // Since the Reader liberally reads some non-compliant files,
+    // it is possible for this to be FormatUnknown.
+    //
+    // If the format is unspecified when Writer.WriteHeader is called,
+    // then it uses the first format (in the order of USTAR, PAX, GNU)
+    // capable of encoding this Header (see Format).
+    Format Format // Go 1.10
+}
+

func FileInfoHeader 1.1

func FileInfoHeader(fi fs.FileInfo, link string) (*Header, error)

FileInfoHeader creates a partially-populated Header from fi. If fi describes a symlink, FileInfoHeader records link as the link target. If fi describes a directory, a slash is appended to the name.

+

Since fs.FileInfo's Name method only returns the base name of the file it describes, it may be necessary to modify Header.Name to provide the full path name of the file.

+

func (*Header) FileInfo 1.1

func (h *Header) FileInfo() fs.FileInfo

FileInfo returns an fs.FileInfo for the Header.

+

type Reader

Reader provides sequential access to the contents of a tar archive. Reader.Next advances to the next file in the archive (including the first), and then Reader can be treated as an io.Reader to access the file's data.

+
type Reader struct {
+    // contains filtered or unexported fields
+}
+

func NewReader

func NewReader(r io.Reader) *Reader

NewReader creates a new Reader reading from r.

+

func (*Reader) Next

func (tr *Reader) Next() (*Header, error)

Next advances to the next entry in the tar archive. The Header.Size determines how many bytes can be read for the next file. Any remaining data in the current file is automatically discarded. At the end of the archive, Next returns the error io.EOF.

+

If Next encounters a non-local name (as defined by filepath.IsLocal) and the GODEBUG environment variable contains `tarinsecurepath=0`, Next returns the header with an ErrInsecurePath error. A future version of Go may introduce this behavior by default. Programs that want to accept non-local names can ignore the ErrInsecurePath error and use the returned header.

+

func (*Reader) Read

func (tr *Reader) Read(b []byte) (int, error)

Read reads from the current file in the tar archive. It returns (0, io.EOF) when it reaches the end of that file, until [Next] is called to advance to the next file.

+

If the current file is sparse, then the regions marked as a hole are read back as NUL-bytes.

+

Calling Read on special types like TypeLink, TypeSymlink, TypeChar, TypeBlock, TypeDir, and TypeFifo returns (0, io.EOF) regardless of what the [Header.Size] claims.

+

type Writer

Writer provides sequential writing of a tar archive. Writer.WriteHeader begins a new file with the provided Header, and then Writer can be treated as an io.Writer to supply that file's data.

+
type Writer struct {
+    // contains filtered or unexported fields
+}
+

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter creates a new Writer writing to w.

+

func (*Writer) AddFS 1.22

func (tw *Writer) AddFS(fsys fs.FS) error

AddFS adds the files from fs.FS to the archive. It walks the directory tree starting at the root of the filesystem adding each file to the tar archive while maintaining the directory structure.

+

func (*Writer) Close

func (tw *Writer) Close() error

Close closes the tar archive by flushing the padding, and writing the footer. If the current file (from a prior call to Writer.WriteHeader) is not fully written, then this returns an error.

+

func (*Writer) Flush

func (tw *Writer) Flush() error

Flush finishes writing the current file's block padding. The current file must be fully written before Flush can be called.

+

This is unnecessary as the next call to Writer.WriteHeader or Writer.Close will implicitly flush out the file's padding.

+

func (*Writer) Write

func (tw *Writer) Write(b []byte) (int, error)

Write writes to the current file in the tar archive. Write returns the error ErrWriteTooLong if more than Header.Size bytes are written after Writer.WriteHeader.

+

Calling Write on special types like TypeLink, TypeSymlink, TypeChar, TypeBlock, TypeDir, and TypeFifo returns (0, ErrWriteTooLong) regardless of what the [Header.Size] claims.

+

func (*Writer) WriteHeader

func (tw *Writer) WriteHeader(hdr *Header) error

WriteHeader writes hdr and prepares to accept the file's contents. The Header.Size determines how many bytes can be written for the next file. If the current file is not fully written, then this returns an error. This implicitly flushes any padding necessary before writing the header.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/archive/tar/ +

+
diff --git a/devdocs/go/archive%2Fzip%2Findex.html b/devdocs/go/archive%2Fzip%2Findex.html new file mode 100644 index 00000000..18031762 --- /dev/null +++ b/devdocs/go/archive%2Fzip%2Findex.html @@ -0,0 +1,290 @@ +

Package zip

Overview

Package zip provides support for reading and writing ZIP archives.

+

See the ZIP specification for details.

+

This package does not support disk spanning.

+

A note about ZIP64:

+

To be backwards compatible the FileHeader has both 32 and 64 bit Size fields. The 64 bit fields will always contain the correct value and for normal archives both fields will be the same. For files requiring the ZIP64 format the 32 bit fields will be 0xffffffff and the 64 bit fields must be used instead.

Index

Examples

Reader
Writer
Writer.RegisterCompressor

Package files

reader.go register.go struct.go writer.go

Constants

Compression methods.

+
const (
+    Store   uint16 = 0 // no compression
+    Deflate uint16 = 8 // DEFLATE compressed
+)

Variables

var (
+    ErrFormat       = errors.New("zip: not a valid zip file")
+    ErrAlgorithm    = errors.New("zip: unsupported compression algorithm")
+    ErrChecksum     = errors.New("zip: checksum error")
+    ErrInsecurePath = errors.New("zip: insecure file path")
+)

func RegisterCompressor 1.2

func RegisterCompressor(method uint16, comp Compressor)

RegisterCompressor registers custom compressors for a specified method ID. The common methods Store and Deflate are built in.

+

func RegisterDecompressor 1.2

func RegisterDecompressor(method uint16, dcomp Decompressor)

RegisterDecompressor allows custom decompressors for a specified method ID. The common methods Store and Deflate are built in.

+

type Compressor 1.2

A Compressor returns a new compressing writer, writing to w. The WriteCloser's Close method must be used to flush pending data to w. The Compressor itself must be safe to invoke from multiple goroutines simultaneously, but each returned writer will be used only by one goroutine at a time.

+
type Compressor func(w io.Writer) (io.WriteCloser, error)

type Decompressor 1.2

A Decompressor returns a new decompressing reader, reading from r. The io.ReadCloser's Close method must be used to release associated resources. The Decompressor itself must be safe to invoke from multiple goroutines simultaneously, but each returned reader will be used only by one goroutine at a time.

+
type Decompressor func(r io.Reader) io.ReadCloser

type File

A File is a single file in a ZIP archive. The file information is in the embedded FileHeader. The file content can be accessed by calling File.Open.

+
type File struct {
+    FileHeader
+    // contains filtered or unexported fields
+}
+

func (*File) DataOffset 1.2

func (f *File) DataOffset() (offset int64, err error)

DataOffset returns the offset of the file's possibly-compressed data, relative to the beginning of the zip file.

+

Most callers should instead use File.Open, which transparently decompresses data and verifies checksums.

+

func (*File) Open

func (f *File) Open() (io.ReadCloser, error)

Open returns a ReadCloser that provides access to the File's contents. Multiple files may be read concurrently.

+

func (*File) OpenRaw 1.17

func (f *File) OpenRaw() (io.Reader, error)

OpenRaw returns a Reader that provides access to the File's contents without decompression.

+

type FileHeader

FileHeader describes a file within a ZIP file. See the ZIP specification for details.

+
type FileHeader struct {
+    // Name is the name of the file.
+    //
+    // It must be a relative path, not start with a drive letter (such as "C:"),
+    // and must use forward slashes instead of back slashes. A trailing slash
+    // indicates that this file is a directory and should have no data.
+    Name string
+
+    // Comment is any arbitrary user-defined string shorter than 64KiB.
+    Comment string
+
+    // NonUTF8 indicates that Name and Comment are not encoded in UTF-8.
+    //
+    // By specification, the only other encoding permitted should be CP-437,
+    // but historically many ZIP readers interpret Name and Comment as whatever
+    // the system's local character encoding happens to be.
+    //
+    // This flag should only be set if the user intends to encode a non-portable
+    // ZIP file for a specific localized region. Otherwise, the Writer
+    // automatically sets the ZIP format's UTF-8 flag for valid UTF-8 strings.
+    NonUTF8 bool // Go 1.10
+
+    CreatorVersion uint16
+    ReaderVersion  uint16
+    Flags          uint16
+
+    // Method is the compression method. If zero, Store is used.
+    Method uint16
+
+    // Modified is the modified time of the file.
+    //
+    // When reading, an extended timestamp is preferred over the legacy MS-DOS
+    // date field, and the offset between the times is used as the timezone.
+    // If only the MS-DOS date is present, the timezone is assumed to be UTC.
+    //
+    // When writing, an extended timestamp (which is timezone-agnostic) is
+    // always emitted. The legacy MS-DOS date field is encoded according to the
+    // location of the Modified time.
+    Modified time.Time // Go 1.10
+
+    // ModifiedTime is an MS-DOS-encoded time.
+    //
+    // Deprecated: Use Modified instead.
+    ModifiedTime uint16
+
+    // ModifiedDate is an MS-DOS-encoded date.
+    //
+    // Deprecated: Use Modified instead.
+    ModifiedDate uint16
+
+    // CRC32 is the CRC32 checksum of the file content.
+    CRC32 uint32
+
+    // CompressedSize is the compressed size of the file in bytes.
+    // If either the uncompressed or compressed size of the file
+    // does not fit in 32 bits, CompressedSize is set to ^uint32(0).
+    //
+    // Deprecated: Use CompressedSize64 instead.
+    CompressedSize uint32
+
+    // UncompressedSize is the compressed size of the file in bytes.
+    // If either the uncompressed or compressed size of the file
+    // does not fit in 32 bits, CompressedSize is set to ^uint32(0).
+    //
+    // Deprecated: Use UncompressedSize64 instead.
+    UncompressedSize uint32
+
+    // CompressedSize64 is the compressed size of the file in bytes.
+    CompressedSize64 uint64 // Go 1.1
+
+    // UncompressedSize64 is the uncompressed size of the file in bytes.
+    UncompressedSize64 uint64 // Go 1.1
+
+    Extra         []byte
+    ExternalAttrs uint32 // Meaning depends on CreatorVersion
+}
+

func FileInfoHeader

func FileInfoHeader(fi fs.FileInfo) (*FileHeader, error)

FileInfoHeader creates a partially-populated FileHeader from an fs.FileInfo. Because fs.FileInfo's Name method returns only the base name of the file it describes, it may be necessary to modify the Name field of the returned header to provide the full path name of the file. If compression is desired, callers should set the FileHeader.Method field; it is unset by default.

+

func (*FileHeader) FileInfo

func (h *FileHeader) FileInfo() fs.FileInfo

FileInfo returns an fs.FileInfo for the FileHeader.

+

func (*FileHeader) ModTime

func (h *FileHeader) ModTime() time.Time

ModTime returns the modification time in UTC using the legacy [ModifiedDate] and [ModifiedTime] fields.

+

Deprecated: Use [Modified] instead.

+

func (*FileHeader) Mode

func (h *FileHeader) Mode() (mode fs.FileMode)

Mode returns the permission and mode bits for the FileHeader.

+

func (*FileHeader) SetModTime

func (h *FileHeader) SetModTime(t time.Time)

SetModTime sets the [Modified], [ModifiedTime], and [ModifiedDate] fields to the given time in UTC.

+

Deprecated: Use [Modified] instead.

+

func (*FileHeader) SetMode

func (h *FileHeader) SetMode(mode fs.FileMode)

SetMode changes the permission and mode bits for the FileHeader.

+

type ReadCloser

A ReadCloser is a Reader that must be closed when no longer needed.

+
type ReadCloser struct {
+    Reader
+    // contains filtered or unexported fields
+}
+

func OpenReader

func OpenReader(name string) (*ReadCloser, error)

OpenReader will open the Zip file specified by name and return a ReadCloser.

+

If any file inside the archive uses a non-local name (as defined by filepath.IsLocal) or a name containing backslashes and the GODEBUG environment variable contains `zipinsecurepath=0`, OpenReader returns the reader with an ErrInsecurePath error. A future version of Go may introduce this behavior by default. Programs that want to accept non-local names can ignore the ErrInsecurePath error and use the returned reader.

+

func (*ReadCloser) Close

func (rc *ReadCloser) Close() error

Close closes the Zip file, rendering it unusable for I/O.

+

type Reader

A Reader serves content from a ZIP archive.

+
type Reader struct {
+    File    []*File
+    Comment string
+    // contains filtered or unexported fields
+}
+

Example +

Code:

// Open a zip archive for reading.
+r, err := zip.OpenReader("testdata/readme.zip")
+if err != nil {
+    log.Fatal(err)
+}
+defer r.Close()
+
+// Iterate through the files in the archive,
+// printing some of their contents.
+for _, f := range r.File {
+    fmt.Printf("Contents of %s:\n", f.Name)
+    rc, err := f.Open()
+    if err != nil {
+        log.Fatal(err)
+    }
+    _, err = io.CopyN(os.Stdout, rc, 68)
+    if err != nil {
+        log.Fatal(err)
+    }
+    rc.Close()
+    fmt.Println()
+}
+

Output:

Contents of README:
+This is the source code repository for the Go programming language.
+

func NewReader

func NewReader(r io.ReaderAt, size int64) (*Reader, error)

NewReader returns a new Reader reading from r, which is assumed to have the given size in bytes.

+

If any file inside the archive uses a non-local name (as defined by filepath.IsLocal) or a name containing backslashes and the GODEBUG environment variable contains `zipinsecurepath=0`, NewReader returns the reader with an ErrInsecurePath error. A future version of Go may introduce this behavior by default. Programs that want to accept non-local names can ignore the ErrInsecurePath error and use the returned reader.

+

func (*Reader) Open 1.16

func (r *Reader) Open(name string) (fs.File, error)

Open opens the named file in the ZIP archive, using the semantics of fs.FS.Open: paths are always slash separated, with no leading / or ../ elements.

+

func (*Reader) RegisterDecompressor 1.6

func (r *Reader) RegisterDecompressor(method uint16, dcomp Decompressor)

RegisterDecompressor registers or overrides a custom decompressor for a specific method ID. If a decompressor for a given method is not found, Reader will default to looking up the decompressor at the package level.

+

type Writer

Writer implements a zip file writer.

+
type Writer struct {
+    // contains filtered or unexported fields
+}
+

Example +

Code:

+// Create a buffer to write our archive to.
+buf := new(bytes.Buffer)
+
+// Create a new zip archive.
+w := zip.NewWriter(buf)
+
+// Add some files to the archive.
+var files = []struct {
+    Name, Body string
+}{
+    {"readme.txt", "This archive contains some text files."},
+    {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
+    {"todo.txt", "Get animal handling licence.\nWrite more examples."},
+}
+for _, file := range files {
+    f, err := w.Create(file.Name)
+    if err != nil {
+        log.Fatal(err)
+    }
+    _, err = f.Write([]byte(file.Body))
+    if err != nil {
+        log.Fatal(err)
+    }
+}
+
+// Make sure to check the error on Close.
+err := w.Close()
+if err != nil {
+    log.Fatal(err)
+}
+

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter returns a new Writer writing a zip file to w.

+

func (*Writer) AddFS 1.22

func (w *Writer) AddFS(fsys fs.FS) error

AddFS adds the files from fs.FS to the archive. It walks the directory tree starting at the root of the filesystem adding each file to the zip using deflate while maintaining the directory structure.

+

func (*Writer) Close

func (w *Writer) Close() error

Close finishes writing the zip file by writing the central directory. It does not close the underlying writer.

+

func (*Writer) Copy 1.17

func (w *Writer) Copy(f *File) error

Copy copies the file f (obtained from a Reader) into w. It copies the raw form directly bypassing decompression, compression, and validation.

+

func (*Writer) Create

func (w *Writer) Create(name string) (io.Writer, error)

Create adds a file to the zip file using the provided name. It returns a Writer to which the file contents should be written. The file contents will be compressed using the Deflate method. The name must be a relative path: it must not start with a drive letter (e.g. C:) or leading slash, and only forward slashes are allowed. To create a directory instead of a file, add a trailing slash to the name. The file's contents must be written to the io.Writer before the next call to Writer.Create, Writer.CreateHeader, or Writer.Close.

+

func (*Writer) CreateHeader

func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error)

CreateHeader adds a file to the zip archive using the provided FileHeader for the file metadata. Writer takes ownership of fh and may mutate its fields. The caller must not modify fh after calling Writer.CreateHeader.

+

This returns a Writer to which the file contents should be written. The file's contents must be written to the io.Writer before the next call to Writer.Create, Writer.CreateHeader, Writer.CreateRaw, or Writer.Close.

+

func (*Writer) CreateRaw 1.17

func (w *Writer) CreateRaw(fh *FileHeader) (io.Writer, error)

CreateRaw adds a file to the zip archive using the provided FileHeader and returns a Writer to which the file contents should be written. The file's contents must be written to the io.Writer before the next call to Writer.Create, Writer.CreateHeader, Writer.CreateRaw, or Writer.Close.

+

In contrast to Writer.CreateHeader, the bytes passed to Writer are not compressed.

+

func (*Writer) Flush 1.4

func (w *Writer) Flush() error

Flush flushes any buffered data to the underlying writer. Calling Flush is not normally necessary; calling Close is sufficient.

+

func (*Writer) RegisterCompressor 1.6

func (w *Writer) RegisterCompressor(method uint16, comp Compressor)

RegisterCompressor registers or overrides a custom compressor for a specific method ID. If a compressor for a given method is not found, Writer will default to looking up the compressor at the package level.

Example +

Code:

+// Override the default Deflate compressor with a higher compression level.
+
+// Create a buffer to write our archive to.
+buf := new(bytes.Buffer)
+
+// Create a new zip archive.
+w := zip.NewWriter(buf)
+
+// Register a custom Deflate compressor.
+w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
+    return flate.NewWriter(out, flate.BestCompression)
+})
+
+// Proceed to add files to w.
+

func (*Writer) SetComment 1.10

func (w *Writer) SetComment(comment string) error

SetComment sets the end-of-central-directory comment field. It can only be called before Writer.Close.

+

func (*Writer) SetOffset 1.5

func (w *Writer) SetOffset(n int64)

SetOffset sets the offset of the beginning of the zip data within the underlying writer. It should be used when the zip data is appended to an existing file, such as a binary executable. It must be called before any data is written.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/archive/zip/ +

+
diff --git a/devdocs/go/arena%2Findex.html b/devdocs/go/arena%2Findex.html new file mode 100644 index 00000000..a1487901 --- /dev/null +++ b/devdocs/go/arena%2Findex.html @@ -0,0 +1,8 @@ +

Command arena

The arena package provides the ability to allocate memory for a collection of Go values and free that space manually all at once, safely. The purpose of this functionality is to improve efficiency: manually freeing memory before a garbage collection delays that cycle. Less frequent cycles means the CPU cost of the garbage collector is incurred less frequently.

+

This functionality in this package is mostly captured in the Arena type. Arenas allocate large chunks of memory for Go values, so they're likely to be inefficient for allocating only small amounts of small Go values. They're best used in bulk, on the order of MiB of memory allocated on each use.

+

Note that by allowing for this limited form of manual memory allocation that use-after-free bugs are possible with regular Go values. This package limits the impact of these use-after-free bugs by preventing reuse of freed memory regions until the garbage collector is able to determine that it is safe. Typically, a use-after-free bug will result in a fault and a helpful error message, but this package reserves the right to not force a fault on freed memory. That means a valid implementation of this package is to just allocate all memory the way the runtime normally would, and in fact, it reserves the right to occasionally do so for some Go values.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/arena/ +

+
diff --git a/devdocs/go/bufio%2Findex.html b/devdocs/go/bufio%2Findex.html new file mode 100644 index 00000000..415058a9 --- /dev/null +++ b/devdocs/go/bufio%2Findex.html @@ -0,0 +1,318 @@ +

Package bufio

Overview

Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.

Index

Examples

Scanner.Bytes
Scanner (Custom)
Scanner (EarlyStop)
Scanner (EmptyFinalToken)
Scanner (Lines)
Scanner (Words)
Writer
Writer.AvailableBuffer

Package files

bufio.go scan.go

Constants

const (
+    // MaxScanTokenSize is the maximum size used to buffer a token
+    // unless the user provides an explicit buffer with [Scanner.Buffer].
+    // The actual maximum token size may be smaller as the buffer
+    // may need to include, for instance, a newline.
+    MaxScanTokenSize = 64 * 1024
+)

Variables

var (
+    ErrInvalidUnreadByte = errors.New("bufio: invalid use of UnreadByte")
+    ErrInvalidUnreadRune = errors.New("bufio: invalid use of UnreadRune")
+    ErrBufferFull        = errors.New("bufio: buffer full")
+    ErrNegativeCount     = errors.New("bufio: negative count")
+)

Errors returned by Scanner.

+
var (
+    ErrTooLong         = errors.New("bufio.Scanner: token too long")
+    ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
+    ErrAdvanceTooFar   = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
+    ErrBadReadCount    = errors.New("bufio.Scanner: Read returned impossible count")
+)

ErrFinalToken is a special sentinel error value. It is intended to be returned by a Split function to indicate that the scanning should stop with no error. If the token being delivered with this error is not nil, the token is the last token.

+

The value is useful to stop processing early or when it is necessary to deliver a final empty token (which is different from a nil token). One could achieve the same behavior with a custom error value but providing one here is tidier. See the emptyFinalToken example for a use of this value.

+
var ErrFinalToken = errors.New("final token")

func ScanBytes 1.1

func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error)

ScanBytes is a split function for a Scanner that returns each byte as a token.

+

func ScanLines 1.1

func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error)

ScanLines is a split function for a Scanner that returns each line of text, stripped of any trailing end-of-line marker. The returned line may be empty. The end-of-line marker is one optional carriage return followed by one mandatory newline. In regular expression notation, it is `\r?\n`. The last non-empty line of input will be returned even if it has no newline.

+

func ScanRunes 1.1

func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error)

ScanRunes is a split function for a Scanner that returns each UTF-8-encoded rune as a token. The sequence of runes returned is equivalent to that from a range loop over the input as a string, which means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd". Because of the Scan interface, this makes it impossible for the client to distinguish correctly encoded replacement runes from encoding errors.

+

func ScanWords 1.1

func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error)

ScanWords is a split function for a Scanner that returns each space-separated word of text, with surrounding spaces deleted. It will never return an empty string. The definition of space is set by unicode.IsSpace.

+

type ReadWriter

ReadWriter stores pointers to a Reader and a Writer. It implements io.ReadWriter.

+
type ReadWriter struct {
+    *Reader
+    *Writer
+}
+

func NewReadWriter

func NewReadWriter(r *Reader, w *Writer) *ReadWriter

NewReadWriter allocates a new ReadWriter that dispatches to r and w.

+

type Reader

Reader implements buffering for an io.Reader object.

+
type Reader struct {
+    // contains filtered or unexported fields
+}
+

func NewReader

func NewReader(rd io.Reader) *Reader

NewReader returns a new Reader whose buffer has the default size.

+

func NewReaderSize

func NewReaderSize(rd io.Reader, size int) *Reader

NewReaderSize returns a new Reader whose buffer has at least the specified size. If the argument io.Reader is already a Reader with large enough size, it returns the underlying Reader.

+

func (*Reader) Buffered

func (b *Reader) Buffered() int

Buffered returns the number of bytes that can be read from the current buffer.

+

func (*Reader) Discard 1.5

func (b *Reader) Discard(n int) (discarded int, err error)

Discard skips the next n bytes, returning the number of bytes discarded.

+

If Discard skips fewer than n bytes, it also returns an error. If 0 <= n <= b.Buffered(), Discard is guaranteed to succeed without reading from the underlying io.Reader.

+

func (*Reader) Peek

func (b *Reader) Peek(n int) ([]byte, error)

Peek returns the next n bytes without advancing the reader. The bytes stop being valid at the next read call. If Peek returns fewer than n bytes, it also returns an error explaining why the read is short. The error is ErrBufferFull if n is larger than b's buffer size.

+

Calling Peek prevents a Reader.UnreadByte or Reader.UnreadRune call from succeeding until the next read operation.

+

func (*Reader) Read

func (b *Reader) Read(p []byte) (n int, err error)

Read reads data into p. It returns the number of bytes read into p. The bytes are taken from at most one Read on the underlying Reader, hence n may be less than len(p). To read exactly len(p) bytes, use io.ReadFull(b, p). If the underlying Reader can return a non-zero count with io.EOF, then this Read method can do so as well; see the io.Reader docs.

+

func (*Reader) ReadByte

func (b *Reader) ReadByte() (byte, error)

ReadByte reads and returns a single byte. If no byte is available, returns an error.

+

func (*Reader) ReadBytes

func (b *Reader) ReadBytes(delim byte) ([]byte, error)

ReadBytes reads until the first occurrence of delim in the input, returning a slice containing the data up to and including the delimiter. If ReadBytes encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadBytes returns err != nil if and only if the returned data does not end in delim. For simple uses, a Scanner may be more convenient.

+

func (*Reader) ReadLine

func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)

ReadLine is a low-level line-reading primitive. Most callers should use Reader.ReadBytes('\n') or Reader.ReadString('\n') instead or use a Scanner.

+

ReadLine tries to return a single line, not including the end-of-line bytes. If the line was too long for the buffer then isPrefix is set and the beginning of the line is returned. The rest of the line will be returned from future calls. isPrefix will be false when returning the last fragment of the line. The returned buffer is only valid until the next call to ReadLine. ReadLine either returns a non-nil line or it returns an error, never both.

+

The text returned from ReadLine does not include the line end ("\r\n" or "\n"). No indication or error is given if the input ends without a final line end. Calling Reader.UnreadByte after ReadLine will always unread the last byte read (possibly a character belonging to the line end) even if that byte is not part of the line returned by ReadLine.

+

func (*Reader) ReadRune

func (b *Reader) ReadRune() (r rune, size int, err error)

ReadRune reads a single UTF-8 encoded Unicode character and returns the rune and its size in bytes. If the encoded rune is invalid, it consumes one byte and returns unicode.ReplacementChar (U+FFFD) with a size of 1.

+

func (*Reader) ReadSlice

func (b *Reader) ReadSlice(delim byte) (line []byte, err error)

ReadSlice reads until the first occurrence of delim in the input, returning a slice pointing at the bytes in the buffer. The bytes stop being valid at the next read. If ReadSlice encounters an error before finding a delimiter, it returns all the data in the buffer and the error itself (often io.EOF). ReadSlice fails with error ErrBufferFull if the buffer fills without a delim. Because the data returned from ReadSlice will be overwritten by the next I/O operation, most clients should use Reader.ReadBytes or ReadString instead. ReadSlice returns err != nil if and only if line does not end in delim.

+

func (*Reader) ReadString

func (b *Reader) ReadString(delim byte) (string, error)

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim. For simple uses, a Scanner may be more convenient.

+

func (*Reader) Reset 1.2

func (b *Reader) Reset(r io.Reader)

Reset discards any buffered data, resets all state, and switches the buffered reader to read from r. Calling Reset on the zero value of Reader initializes the internal buffer to the default size. Calling b.Reset(b) (that is, resetting a Reader to itself) does nothing.

+

func (*Reader) Size 1.10

func (b *Reader) Size() int

Size returns the size of the underlying buffer in bytes.

+

func (*Reader) UnreadByte

func (b *Reader) UnreadByte() error

UnreadByte unreads the last byte. Only the most recently read byte can be unread.

+

UnreadByte returns an error if the most recent method called on the Reader was not a read operation. Notably, Reader.Peek, Reader.Discard, and Reader.WriteTo are not considered read operations.

+

func (*Reader) UnreadRune

func (b *Reader) UnreadRune() error

UnreadRune unreads the last rune. If the most recent method called on the Reader was not a Reader.ReadRune, Reader.UnreadRune returns an error. (In this regard it is stricter than Reader.UnreadByte, which will unread the last byte from any read operation.)

+

func (*Reader) WriteTo 1.1

func (b *Reader) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements io.WriterTo. This may make multiple calls to the Reader.Read method of the underlying Reader. If the underlying reader supports the Reader.WriteTo method, this calls the underlying Reader.WriteTo without buffering.

+

type Scanner 1.1

Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text. Successive calls to the Scanner.Scan method will step through the 'tokens' of a file, skipping the bytes between the tokens. The specification of a token is defined by a split function of type SplitFunc; the default split function breaks the input into lines with line termination stripped. Scanner.Split functions are defined in this package for scanning a file into lines, bytes, UTF-8-encoded runes, and space-delimited words. The client may instead provide a custom split function.

+

Scanning stops unrecoverably at EOF, the first I/O error, or a token too large to fit in the Scanner.Buffer. When a scan stops, the reader may have advanced arbitrarily far past the last token. Programs that need more control over error handling or large tokens, or must run sequential scans on a reader, should use bufio.Reader instead.

+
type Scanner struct {
+    // contains filtered or unexported fields
+}
+

Example (Custom) +

Use a Scanner with a custom split function (built by wrapping ScanWords) to validate 32-bit decimal input.

Code:

// An artificial input source.
+const input = "1234 5678 1234567901234567890"
+scanner := bufio.NewScanner(strings.NewReader(input))
+// Create a custom split function by wrapping the existing ScanWords function.
+split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
+    advance, token, err = bufio.ScanWords(data, atEOF)
+    if err == nil && token != nil {
+        _, err = strconv.ParseInt(string(token), 10, 32)
+    }
+    return
+}
+// Set the split function for the scanning operation.
+scanner.Split(split)
+// Validate the input
+for scanner.Scan() {
+    fmt.Printf("%s\n", scanner.Text())
+}
+
+if err := scanner.Err(); err != nil {
+    fmt.Printf("Invalid input: %s", err)
+}
+

Output:

1234
+5678
+Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range
+

Example (EarlyStop) +

Use a Scanner with a custom split function to parse a comma-separated list with an empty final value but stops at the token "STOP".

Code:

onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
+    i := bytes.IndexByte(data, ',')
+    if i == -1 {
+        if !atEOF {
+            return 0, nil, nil
+        }
+        // If we have reached the end, return the last token.
+        return 0, data, bufio.ErrFinalToken
+    }
+    // If the token is "STOP", stop the scanning and ignore the rest.
+    if string(data[:i]) == "STOP" {
+        return i + 1, nil, bufio.ErrFinalToken
+    }
+    // Otherwise, return the token before the comma.
+    return i + 1, data[:i], nil
+}
+const input = "1,2,STOP,4,"
+scanner := bufio.NewScanner(strings.NewReader(input))
+scanner.Split(onComma)
+for scanner.Scan() {
+    fmt.Printf("Got a token %q\n", scanner.Text())
+}
+if err := scanner.Err(); err != nil {
+    fmt.Fprintln(os.Stderr, "reading input:", err)
+}
+

Output:

Got a token "1"
+Got a token "2"
+

Example (EmptyFinalToken) +

Use a Scanner with a custom split function to parse a comma-separated list with an empty final value.

Code:

// Comma-separated list; last entry is empty.
+const input = "1,2,3,4,"
+scanner := bufio.NewScanner(strings.NewReader(input))
+// Define a split function that separates on commas.
+onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
+    for i := 0; i < len(data); i++ {
+        if data[i] == ',' {
+            return i + 1, data[:i], nil
+        }
+    }
+    if !atEOF {
+        return 0, nil, nil
+    }
+    // There is one final token to be delivered, which may be the empty string.
+    // Returning bufio.ErrFinalToken here tells Scan there are no more tokens after this
+    // but does not trigger an error to be returned from Scan itself.
+    return 0, data, bufio.ErrFinalToken
+}
+scanner.Split(onComma)
+// Scan.
+for scanner.Scan() {
+    fmt.Printf("%q ", scanner.Text())
+}
+if err := scanner.Err(); err != nil {
+    fmt.Fprintln(os.Stderr, "reading input:", err)
+}
+

Output:

"1" "2" "3" "4" ""
+

Example (Lines) +

The simplest use of a Scanner, to read standard input as a set of lines.

Code:

+scanner := bufio.NewScanner(os.Stdin)
+for scanner.Scan() {
+    fmt.Println(scanner.Text()) // Println will add back the final '\n'
+}
+if err := scanner.Err(); err != nil {
+    fmt.Fprintln(os.Stderr, "reading standard input:", err)
+}
+

Example (Words) +

Use a Scanner to implement a simple word-count utility by scanning the input as a sequence of space-delimited tokens.

Code:

// An artificial input source.
+const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
+scanner := bufio.NewScanner(strings.NewReader(input))
+// Set the split function for the scanning operation.
+scanner.Split(bufio.ScanWords)
+// Count the words.
+count := 0
+for scanner.Scan() {
+    count++
+}
+if err := scanner.Err(); err != nil {
+    fmt.Fprintln(os.Stderr, "reading input:", err)
+}
+fmt.Printf("%d\n", count)
+

Output:

15
+

func NewScanner 1.1

func NewScanner(r io.Reader) *Scanner

NewScanner returns a new Scanner to read from r. The split function defaults to ScanLines.

+

func (*Scanner) Buffer 1.6

func (s *Scanner) Buffer(buf []byte, max int)

Buffer sets the initial buffer to use when scanning and the maximum size of buffer that may be allocated during scanning. The maximum token size must be less than the larger of max and cap(buf). If max <= cap(buf), Scanner.Scan will use this buffer only and do no allocation.

+

By default, Scanner.Scan uses an internal buffer and sets the maximum token size to MaxScanTokenSize.

+

Buffer panics if it is called after scanning has started.

+

func (*Scanner) Bytes 1.1

func (s *Scanner) Bytes() []byte

Bytes returns the most recent token generated by a call to Scanner.Scan. The underlying array may point to data that will be overwritten by a subsequent call to Scan. It does no allocation.

Example +

Return the most recent call to Scan as a []byte.

Code:

scanner := bufio.NewScanner(strings.NewReader("gopher"))
+for scanner.Scan() {
+    fmt.Println(len(scanner.Bytes()) == 6)
+}
+if err := scanner.Err(); err != nil {
+    fmt.Fprintln(os.Stderr, "shouldn't see an error scanning a string")
+}
+

Output:

true
+

func (*Scanner) Err 1.1

func (s *Scanner) Err() error

Err returns the first non-EOF error that was encountered by the Scanner.

+

func (*Scanner) Scan 1.1

func (s *Scanner) Scan() bool

Scan advances the Scanner to the next token, which will then be available through the Scanner.Bytes or Scanner.Text method. It returns false when there are no more tokens, either by reaching the end of the input or an error. After Scan returns false, the Scanner.Err method will return any error that occurred during scanning, except that if it was io.EOF, Scanner.Err will return nil. Scan panics if the split function returns too many empty tokens without advancing the input. This is a common error mode for scanners.

+

func (*Scanner) Split 1.1

func (s *Scanner) Split(split SplitFunc)

Split sets the split function for the Scanner. The default split function is ScanLines.

+

Split panics if it is called after scanning has started.

+

func (*Scanner) Text 1.1

func (s *Scanner) Text() string

Text returns the most recent token generated by a call to Scanner.Scan as a newly allocated string holding its bytes.

+

type SplitFunc 1.1

SplitFunc is the signature of the split function used to tokenize the input. The arguments are an initial substring of the remaining unprocessed data and a flag, atEOF, that reports whether the Reader has no more data to give. The return values are the number of bytes to advance the input and the next token to return to the user, if any, plus an error, if any.

+

Scanning stops if the function returns an error, in which case some of the input may be discarded. If that error is ErrFinalToken, scanning stops with no error. A non-nil token delivered with ErrFinalToken will be the last token, and a nil token with ErrFinalToken immediately stops the scanning.

+

Otherwise, the Scanner advances the input. If the token is not nil, the Scanner returns it to the user. If the token is nil, the Scanner reads more data and continues scanning; if there is no more data--if atEOF was true--the Scanner returns. If the data does not yet hold a complete token, for instance if it has no newline while scanning lines, a SplitFunc can return (0, nil, nil) to signal the Scanner to read more data into the slice and try again with a longer slice starting at the same point in the input.

+

The function is never called with an empty data slice unless atEOF is true. If atEOF is true, however, data may be non-empty and, as always, holds unprocessed text.

+
type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)

type Writer

Writer implements buffering for an io.Writer object. If an error occurs writing to a Writer, no more data will be accepted and all subsequent writes, and Writer.Flush, will return the error. After all data has been written, the client should call the Writer.Flush method to guarantee all data has been forwarded to the underlying io.Writer.

+
type Writer struct {
+    // contains filtered or unexported fields
+}
+

Example +

Code:

w := bufio.NewWriter(os.Stdout)
+fmt.Fprint(w, "Hello, ")
+fmt.Fprint(w, "world!")
+w.Flush() // Don't forget to flush!
+

Output:

Hello, world!
+

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter returns a new Writer whose buffer has the default size. If the argument io.Writer is already a Writer with large enough buffer size, it returns the underlying Writer.

+

func NewWriterSize

func NewWriterSize(w io.Writer, size int) *Writer

NewWriterSize returns a new Writer whose buffer has at least the specified size. If the argument io.Writer is already a Writer with large enough size, it returns the underlying Writer.

+

func (*Writer) Available

func (b *Writer) Available() int

Available returns how many bytes are unused in the buffer.

+

func (*Writer) AvailableBuffer 1.18

func (b *Writer) AvailableBuffer() []byte

AvailableBuffer returns an empty buffer with b.Available() capacity. This buffer is intended to be appended to and passed to an immediately succeeding Writer.Write call. The buffer is only valid until the next write operation on b.

Example +

Code:

w := bufio.NewWriter(os.Stdout)
+for _, i := range []int64{1, 2, 3, 4} {
+    b := w.AvailableBuffer()
+    b = strconv.AppendInt(b, i, 10)
+    b = append(b, ' ')
+    w.Write(b)
+}
+w.Flush()
+

Output:

1 2 3 4
+

func (*Writer) Buffered

func (b *Writer) Buffered() int

Buffered returns the number of bytes that have been written into the current buffer.

+

func (*Writer) Flush

func (b *Writer) Flush() error

Flush writes any buffered data to the underlying io.Writer.

+

func (*Writer) ReadFrom 1.1

func (b *Writer) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom implements io.ReaderFrom. If the underlying writer supports the ReadFrom method, this calls the underlying ReadFrom. If there is buffered data and an underlying ReadFrom, this fills the buffer and writes it before calling ReadFrom.

+

func (*Writer) Reset 1.2

func (b *Writer) Reset(w io.Writer)

Reset discards any unflushed buffered data, clears any error, and resets b to write its output to w. Calling Reset on the zero value of Writer initializes the internal buffer to the default size. Calling w.Reset(w) (that is, resetting a Writer to itself) does nothing.

+

func (*Writer) Size 1.10

func (b *Writer) Size() int

Size returns the size of the underlying buffer in bytes.

+

func (*Writer) Write

func (b *Writer) Write(p []byte) (nn int, err error)

Write writes the contents of p into the buffer. It returns the number of bytes written. If nn < len(p), it also returns an error explaining why the write is short.

+

func (*Writer) WriteByte

func (b *Writer) WriteByte(c byte) error

WriteByte writes a single byte.

+

func (*Writer) WriteRune

func (b *Writer) WriteRune(r rune) (size int, err error)

WriteRune writes a single Unicode code point, returning the number of bytes written and any error.

+

func (*Writer) WriteString

func (b *Writer) WriteString(s string) (int, error)

WriteString writes a string. It returns the number of bytes written. If the count is less than len(s), it also returns an error explaining why the write is short.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/bufio/ +

+
diff --git a/devdocs/go/builtin%2Findex.html b/devdocs/go/builtin%2Findex.html new file mode 100644 index 00000000..55bc205d --- /dev/null +++ b/devdocs/go/builtin%2Findex.html @@ -0,0 +1,147 @@ +

Package builtin

Overview

Package builtin provides documentation for Go's predeclared identifiers. The items documented here are not actually in package builtin but their descriptions here allow godoc to present documentation for the language's special identifiers.

Index

Package files

builtin.go

Constants

true and false are the two untyped boolean values.

+
const (
+    true  = 0 == 0 // Untyped bool.
+    false = 0 != 0 // Untyped bool.
+)

iota is a predeclared identifier representing the untyped integer ordinal number of the current const specification in a (usually parenthesized) const declaration. It is zero-indexed.

+
const iota = 0 // Untyped int.
+

Variables

nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.

+
var nil Type // Type must be a pointer, channel, func, interface, map, or slice type
+

func append

func append(slice []Type, elems ...Type) []Type

The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:

+
slice = append(slice, elem1, elem2)
+slice = append(slice, anotherSlice...)
+

As a special case, it is legal to append a string to a byte slice, like this:

+
slice = append([]byte("hello "), "world"...)
+

func cap

func cap(v Type) int

The cap built-in function returns the capacity of v, according to its type:

+
Array: the number of elements in v (same as len(v)).
+Pointer to array: the number of elements in *v (same as len(v)).
+Slice: the maximum length the slice can reach when resliced;
+if v is nil, cap(v) is zero.
+Channel: the channel buffer capacity, in units of elements;
+if v is nil, cap(v) is zero.
+

For some arguments, such as a simple array expression, the result can be a constant. See the Go language specification's "Length and capacity" section for details.

+

func clear

func clear[T ~[]Type | ~map[Type]Type1](t T)

The clear built-in function clears maps and slices. For maps, clear deletes all entries, resulting in an empty map. For slices, clear sets all elements up to the length of the slice to the zero value of the respective element type. If the argument type is a type parameter, the type parameter's type set must contain only map or slice types, and clear performs the operation implied by the type argument.

+

func close

func close(c chan<- Type)

The close built-in function closes a channel, which must be either bidirectional or send-only. It should be executed only by the sender, never the receiver, and has the effect of shutting down the channel after the last sent value is received. After the last value has been received from a closed channel c, any receive from c will succeed without blocking, returning the zero value for the channel element. The form

+
x, ok := <-c
+

will also set ok to false for a closed and empty channel.

+

func complex

func complex(r, i FloatType) ComplexType

The complex built-in function constructs a complex value from two floating-point values. The real and imaginary parts must be of the same size, either float32 or float64 (or assignable to them), and the return value will be the corresponding complex type (complex64 for float32, complex128 for float64).

+

func copy

func copy(dst, src []Type) int

The copy built-in function copies elements from a source slice into a destination slice. (As a special case, it also will copy bytes from a string to a slice of bytes.) The source and destination may overlap. Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

+

func delete

func delete(m map[Type]Type1, key Type)

The delete built-in function deletes the element with the specified key (m[key]) from the map. If m is nil or there is no such element, delete is a no-op.

+

func imag

func imag(c ComplexType) FloatType

The imag built-in function returns the imaginary part of the complex number c. The return value will be floating point type corresponding to the type of c.

+

func len

func len(v Type) int

The len built-in function returns the length of v, according to its type:

+
Array: the number of elements in v.
+Pointer to array: the number of elements in *v (even if v is nil).
+Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
+String: the number of bytes in v.
+Channel: the number of elements queued (unread) in the channel buffer;
+         if v is nil, len(v) is zero.
+

For some arguments, such as a string literal or a simple array expression, the result can be a constant. See the Go language specification's "Length and capacity" section for details.

+

func make

func make(t Type, size ...IntegerType) Type

The make built-in function allocates and initializes an object of type slice, map, or chan (only). Like new, the first argument is a type, not a value. Unlike new, make's return type is the same as the type of its argument, not a pointer to it. The specification of the result depends on the type:

+
Slice: The size specifies the length. The capacity of the slice is
+equal to its length. A second integer argument may be provided to
+specify a different capacity; it must be no smaller than the
+length. For example, make([]int, 0, 10) allocates an underlying array
+of size 10 and returns a slice of length 0 and capacity 10 that is
+backed by this underlying array.
+Map: An empty map is allocated with enough space to hold the
+specified number of elements. The size may be omitted, in which case
+a small starting size is allocated.
+Channel: The channel's buffer is initialized with the specified
+buffer capacity. If zero, or the size is omitted, the channel is
+unbuffered.
+

func max

func max[T cmp.Ordered](x T, y ...T) T

The max built-in function returns the largest value of a fixed number of arguments of cmp.Ordered types. There must be at least one argument. If T is a floating-point type and any of the arguments are NaNs, max will return NaN.

+

func min

func min[T cmp.Ordered](x T, y ...T) T

The min built-in function returns the smallest value of a fixed number of arguments of cmp.Ordered types. There must be at least one argument. If T is a floating-point type and any of the arguments are NaNs, min will return NaN.

+

func new

func new(Type) *Type

The new built-in function allocates memory. The first argument is a type, not a value, and the value returned is a pointer to a newly allocated zero value of that type.

+

func panic

func panic(v any)

The panic built-in function stops normal execution of the current goroutine. When a function F calls panic, normal execution of F stops immediately. Any functions whose execution was deferred by F are run in the usual way, and then F returns to its caller. To the caller G, the invocation of F then behaves like a call to panic, terminating G's execution and running any deferred functions. This continues until all functions in the executing goroutine have stopped, in reverse order. At that point, the program is terminated with a non-zero exit code. This termination sequence is called panicking and can be controlled by the built-in function recover.

+

Starting in Go 1.21, calling panic with a nil interface value or an untyped nil causes a run-time error (a different panic). The GODEBUG setting panicnil=1 disables the run-time error.

+

func print

func print(args ...Type)

The print built-in function formats its arguments in an implementation-specific way and writes the result to standard error. Print is useful for bootstrapping and debugging; it is not guaranteed to stay in the language.

+

func println

func println(args ...Type)

The println built-in function formats its arguments in an implementation-specific way and writes the result to standard error. Spaces are always added between arguments and a newline is appended. Println is useful for bootstrapping and debugging; it is not guaranteed to stay in the language.

+

func real

func real(c ComplexType) FloatType

The real built-in function returns the real part of the complex number c. The return value will be floating point type corresponding to the type of c.

+

func recover

func recover() any

The recover built-in function allows a program to manage behavior of a panicking goroutine. Executing a call to recover inside a deferred function (but not any function called by it) stops the panicking sequence by restoring normal execution and retrieves the error value passed to the call of panic. If recover is called outside the deferred function it will not stop a panicking sequence. In this case, or when the goroutine is not panicking, recover returns nil.

+

Prior to Go 1.21, recover would also return nil if panic is called with a nil argument. See [panic] for details.

+

type ComplexType

ComplexType is here for the purposes of documentation only. It is a stand-in for either complex type: complex64 or complex128.

+
type ComplexType complex64

type FloatType

FloatType is here for the purposes of documentation only. It is a stand-in for either float type: float32 or float64.

+
type FloatType float32

type IntegerType

IntegerType is here for the purposes of documentation only. It is a stand-in for any integer type: int, uint, int8 etc.

+
type IntegerType int

type Type

Type is here for the purposes of documentation only. It is a stand-in for any Go type, but represents the same type for any given function invocation.

+
type Type int

type Type1

Type1 is here for the purposes of documentation only. It is a stand-in for any Go type, but represents the same type for any given function invocation.

+
type Type1 int

type any

any is an alias for interface{} and is equivalent to interface{} in all ways.

+
type any = interface{}

type bool

bool is the set of boolean values, true and false.

+
type bool bool

type byte

byte is an alias for uint8 and is equivalent to uint8 in all ways. It is used, by convention, to distinguish byte values from 8-bit unsigned integer values.

+
type byte = uint8

type comparable

comparable is an interface that is implemented by all comparable types (booleans, numbers, strings, pointers, channels, arrays of comparable types, structs whose fields are all comparable types). The comparable interface may only be used as a type parameter constraint, not as the type of a variable.

+
type comparable interface{ comparable }

type complex128

complex128 is the set of all complex numbers with float64 real and imaginary parts.

+
type complex128 complex128

type complex64

complex64 is the set of all complex numbers with float32 real and imaginary parts.

+
type complex64 complex64

type error

The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error.

+
type error interface {
+    Error() string
+}

type float32

float32 is the set of all IEEE-754 32-bit floating-point numbers.

+
type float32 float32

type float64

float64 is the set of all IEEE-754 64-bit floating-point numbers.

+
type float64 float64

type int

int is a signed integer type that is at least 32 bits in size. It is a distinct type, however, and not an alias for, say, int32.

+
type int int

type int16

int16 is the set of all signed 16-bit integers. Range: -32768 through 32767.

+
type int16 int16

type int32

int32 is the set of all signed 32-bit integers. Range: -2147483648 through 2147483647.

+
type int32 int32

type int64

int64 is the set of all signed 64-bit integers. Range: -9223372036854775808 through 9223372036854775807.

+
type int64 int64

type int8

int8 is the set of all signed 8-bit integers. Range: -128 through 127.

+
type int8 int8

type rune

rune is an alias for int32 and is equivalent to int32 in all ways. It is used, by convention, to distinguish character values from integer values.

+
type rune = int32

type string

string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. A string may be empty, but not nil. Values of string type are immutable.

+
type string string

type uint

uint is an unsigned integer type that is at least 32 bits in size. It is a distinct type, however, and not an alias for, say, uint32.

+
type uint uint

type uint16

uint16 is the set of all unsigned 16-bit integers. Range: 0 through 65535.

+
type uint16 uint16

type uint32

uint32 is the set of all unsigned 32-bit integers. Range: 0 through 4294967295.

+
type uint32 uint32

type uint64

uint64 is the set of all unsigned 64-bit integers. Range: 0 through 18446744073709551615.

+
type uint64 uint64

type uint8

uint8 is the set of all unsigned 8-bit integers. Range: 0 through 255.

+
type uint8 uint8

type uintptr

uintptr is an integer type that is large enough to hold the bit pattern of any pointer.

+
type uintptr uintptr
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/builtin/ +

+
diff --git a/devdocs/go/bytes%2Findex.html b/devdocs/go/bytes%2Findex.html new file mode 100644 index 00000000..08d37b2b --- /dev/null +++ b/devdocs/go/bytes%2Findex.html @@ -0,0 +1,650 @@ +

Package bytes

Overview

Package bytes implements functions for the manipulation of byte slices. It is analogous to the facilities of the strings package.

Index

Examples

Buffer
Buffer.AvailableBuffer
Buffer.Bytes
Buffer.Cap
Buffer.Grow
Buffer.Len
Buffer.Next
Buffer.Read
Buffer.ReadByte
Buffer (Reader)
Clone
Compare
Compare (Search)
Contains
ContainsAny
ContainsFunc
ContainsRune
Count
Cut
CutPrefix
CutSuffix
Equal
EqualFold
Fields
FieldsFunc
HasPrefix
HasSuffix
Index
IndexAny
IndexByte
IndexFunc
IndexRune
Join
LastIndex
LastIndexAny
LastIndexByte
LastIndexFunc
Map
Reader.Len
Repeat
Replace
ReplaceAll
Runes
Split
SplitAfter
SplitAfterN
SplitN
Title
ToLower
ToLowerSpecial
ToTitle
ToTitleSpecial
ToUpper
ToUpperSpecial
ToValidUTF8
Trim
TrimFunc
TrimLeft
TrimLeftFunc
TrimPrefix
TrimRight
TrimRightFunc
TrimSpace
TrimSuffix

Package files

buffer.go bytes.go reader.go

Constants

MinRead is the minimum slice size passed to a Read call by Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond what is required to hold the contents of r, ReadFrom will not grow the underlying buffer.

+
const MinRead = 512

Variables

ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer.

+
var ErrTooLarge = errors.New("bytes.Buffer: too large")

func Clone 1.20

func Clone(b []byte) []byte

Clone returns a copy of b[:len(b)]. The result may have additional unused capacity. Clone(nil) returns nil.

Example +

Code:

b := []byte("abc")
+clone := bytes.Clone(b)
+fmt.Printf("%s\n", clone)
+clone[0] = 'd'
+fmt.Printf("%s\n", b)
+fmt.Printf("%s\n", clone)
+

Output:

abc
+abc
+dbc
+

func Compare

func Compare(a, b []byte) int

Compare returns an integer comparing two byte slices lexicographically. The result will be 0 if a == b, -1 if a < b, and +1 if a > b. A nil argument is equivalent to an empty slice.

Example +

Code:

+// Interpret Compare's result by comparing it to zero.
+var a, b []byte
+if bytes.Compare(a, b) < 0 {
+    // a less b
+}
+if bytes.Compare(a, b) <= 0 {
+    // a less or equal b
+}
+if bytes.Compare(a, b) > 0 {
+    // a greater b
+}
+if bytes.Compare(a, b) >= 0 {
+    // a greater or equal b
+}
+
+// Prefer Equal to Compare for equality comparisons.
+if bytes.Equal(a, b) {
+    // a equal b
+}
+if !bytes.Equal(a, b) {
+    // a not equal b
+}
+

Code:

+// Binary search to find a matching byte slice.
+var needle []byte
+var haystack [][]byte // Assume sorted
+i := sort.Search(len(haystack), func(i int) bool {
+    // Return haystack[i] >= needle.
+    return bytes.Compare(haystack[i], needle) >= 0
+})
+if i < len(haystack) && bytes.Equal(haystack[i], needle) {
+    // Found it!
+}
+

func Contains

func Contains(b, subslice []byte) bool

Contains reports whether subslice is within b.

Example +

Code:

fmt.Println(bytes.Contains([]byte("seafood"), []byte("foo")))
+fmt.Println(bytes.Contains([]byte("seafood"), []byte("bar")))
+fmt.Println(bytes.Contains([]byte("seafood"), []byte("")))
+fmt.Println(bytes.Contains([]byte(""), []byte("")))
+

Output:

true
+false
+true
+true
+

func ContainsAny 1.7

func ContainsAny(b []byte, chars string) bool

ContainsAny reports whether any of the UTF-8-encoded code points in chars are within b.

Example +

Code:

fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "fÄo!"))
+fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "去是伟大的."))
+fmt.Println(bytes.ContainsAny([]byte("I like seafood."), ""))
+fmt.Println(bytes.ContainsAny([]byte(""), ""))
+

Output:

true
+true
+false
+false
+

func ContainsFunc 1.21

func ContainsFunc(b []byte, f func(rune) bool) bool

ContainsFunc reports whether any of the UTF-8-encoded code points r within b satisfy f(r).

Example +

Code:

f := func(r rune) bool {
+    return r >= 'a' && r <= 'z'
+}
+fmt.Println(bytes.ContainsFunc([]byte("HELLO"), f))
+fmt.Println(bytes.ContainsFunc([]byte("World"), f))
+

Output:

false
+true
+

func ContainsRune 1.7

func ContainsRune(b []byte, r rune) bool

ContainsRune reports whether the rune is contained in the UTF-8-encoded byte slice b.

Example +

Code:

fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'f'))
+fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'ö'))
+fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '大'))
+fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '!'))
+fmt.Println(bytes.ContainsRune([]byte(""), '@'))
+

Output:

true
+false
+true
+true
+false
+

func Count

func Count(s, sep []byte) int

Count counts the number of non-overlapping instances of sep in s. If sep is an empty slice, Count returns 1 + the number of UTF-8-encoded code points in s.

Example +

Code:

fmt.Println(bytes.Count([]byte("cheese"), []byte("e")))
+fmt.Println(bytes.Count([]byte("five"), []byte(""))) // before & after each rune
+

Output:

3
+5
+

func Cut 1.18

func Cut(s, sep []byte) (before, after []byte, found bool)

Cut slices s around the first instance of sep, returning the text before and after sep. The found result reports whether sep appears in s. If sep does not appear in s, cut returns s, nil, false.

+

Cut returns slices of the original slice s, not copies.

Example +

Code:

show := func(s, sep string) {
+    before, after, found := bytes.Cut([]byte(s), []byte(sep))
+    fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
+}
+show("Gopher", "Go")
+show("Gopher", "ph")
+show("Gopher", "er")
+show("Gopher", "Badger")
+

Output:

Cut("Gopher", "Go") = "", "pher", true
+Cut("Gopher", "ph") = "Go", "er", true
+Cut("Gopher", "er") = "Goph", "", true
+Cut("Gopher", "Badger") = "Gopher", "", false
+

func CutPrefix 1.20

func CutPrefix(s, prefix []byte) (after []byte, found bool)

CutPrefix returns s without the provided leading prefix byte slice and reports whether it found the prefix. If s doesn't start with prefix, CutPrefix returns s, false. If prefix is the empty byte slice, CutPrefix returns s, true.

+

CutPrefix returns slices of the original slice s, not copies.

Example +

Code:

show := func(s, sep string) {
+    after, found := bytes.CutPrefix([]byte(s), []byte(sep))
+    fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, sep, after, found)
+}
+show("Gopher", "Go")
+show("Gopher", "ph")
+

Output:

CutPrefix("Gopher", "Go") = "pher", true
+CutPrefix("Gopher", "ph") = "Gopher", false
+

func CutSuffix 1.20

func CutSuffix(s, suffix []byte) (before []byte, found bool)

CutSuffix returns s without the provided ending suffix byte slice and reports whether it found the suffix. If s doesn't end with suffix, CutSuffix returns s, false. If suffix is the empty byte slice, CutSuffix returns s, true.

+

CutSuffix returns slices of the original slice s, not copies.

Example +

Code:

show := func(s, sep string) {
+    before, found := bytes.CutSuffix([]byte(s), []byte(sep))
+    fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, sep, before, found)
+}
+show("Gopher", "Go")
+show("Gopher", "er")
+

Output:

CutSuffix("Gopher", "Go") = "Gopher", false
+CutSuffix("Gopher", "er") = "Goph", true
+

func Equal

func Equal(a, b []byte) bool

Equal reports whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice.

Example +

Code:

fmt.Println(bytes.Equal([]byte("Go"), []byte("Go")))
+fmt.Println(bytes.Equal([]byte("Go"), []byte("C++")))
+

Output:

true
+false
+

func EqualFold

func EqualFold(s, t []byte) bool

EqualFold reports whether s and t, interpreted as UTF-8 strings, are equal under simple Unicode case-folding, which is a more general form of case-insensitivity.

Example +

Code:

fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go")))
+

Output:

true
+

func Fields

func Fields(s []byte) [][]byte

Fields interprets s as a sequence of UTF-8-encoded code points. It splits the slice s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of subslices of s or an empty slice if s contains only white space.

Example +

Code:

fmt.Printf("Fields are: %q", bytes.Fields([]byte("  foo bar  baz   ")))
+

Output:

Fields are: ["foo" "bar" "baz"]
+

func FieldsFunc

func FieldsFunc(s []byte, f func(rune) bool) [][]byte

FieldsFunc interprets s as a sequence of UTF-8-encoded code points. It splits the slice s at each run of code points c satisfying f(c) and returns a slice of subslices of s. If all code points in s satisfy f(c), or len(s) == 0, an empty slice is returned.

+

FieldsFunc makes no guarantees about the order in which it calls f(c) and assumes that f always returns the same value for a given c.

Example +

Code:

f := func(c rune) bool {
+    return !unicode.IsLetter(c) && !unicode.IsNumber(c)
+}
+fmt.Printf("Fields are: %q", bytes.FieldsFunc([]byte("  foo1;bar2,baz3..."), f))
+

Output:

Fields are: ["foo1" "bar2" "baz3"]
+

func HasPrefix

func HasPrefix(s, prefix []byte) bool

HasPrefix reports whether the byte slice s begins with prefix.

Example +

Code:

fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
+fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
+fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
+

Output:

true
+false
+true
+

func HasSuffix

func HasSuffix(s, suffix []byte) bool

HasSuffix reports whether the byte slice s ends with suffix.

Example +

Code:

fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("go")))
+fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("O")))
+fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("Ami")))
+fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("")))
+

Output:

true
+false
+false
+true
+

func Index

func Index(s, sep []byte) int

Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.

Example +

Code:

fmt.Println(bytes.Index([]byte("chicken"), []byte("ken")))
+fmt.Println(bytes.Index([]byte("chicken"), []byte("dmr")))
+

Output:

4
+-1
+

func IndexAny

func IndexAny(s []byte, chars string) int

IndexAny interprets s as a sequence of UTF-8-encoded Unicode code points. It returns the byte index of the first occurrence in s of any of the Unicode code points in chars. It returns -1 if chars is empty or if there is no code point in common.

Example +

Code:

fmt.Println(bytes.IndexAny([]byte("chicken"), "aeiouy"))
+fmt.Println(bytes.IndexAny([]byte("crwth"), "aeiouy"))
+

Output:

2
+-1
+

func IndexByte

func IndexByte(b []byte, c byte) int

IndexByte returns the index of the first instance of c in b, or -1 if c is not present in b.

Example +

Code:

fmt.Println(bytes.IndexByte([]byte("chicken"), byte('k')))
+fmt.Println(bytes.IndexByte([]byte("chicken"), byte('g')))
+

Output:

4
+-1
+

func IndexFunc

func IndexFunc(s []byte, f func(r rune) bool) int

IndexFunc interprets s as a sequence of UTF-8-encoded code points. It returns the byte index in s of the first Unicode code point satisfying f(c), or -1 if none do.

Example +

Code:

f := func(c rune) bool {
+    return unicode.Is(unicode.Han, c)
+}
+fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f))
+fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f))
+

Output:

7
+-1
+

func IndexRune

func IndexRune(s []byte, r rune) int

IndexRune interprets s as a sequence of UTF-8-encoded code points. It returns the byte index of the first occurrence in s of the given rune. It returns -1 if rune is not present in s. If r is utf8.RuneError, it returns the first instance of any invalid UTF-8 byte sequence.

Example +

Code:

fmt.Println(bytes.IndexRune([]byte("chicken"), 'k'))
+fmt.Println(bytes.IndexRune([]byte("chicken"), 'd'))
+

Output:

4
+-1
+

func Join

func Join(s [][]byte, sep []byte) []byte

Join concatenates the elements of s to create a new byte slice. The separator sep is placed between elements in the resulting slice.

Example +

Code:

s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")}
+fmt.Printf("%s", bytes.Join(s, []byte(", ")))
+

Output:

foo, bar, baz
+

func LastIndex

func LastIndex(s, sep []byte) int

LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s.

Example +

Code:

fmt.Println(bytes.Index([]byte("go gopher"), []byte("go")))
+fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("go")))
+fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("rodent")))
+

Output:

0
+3
+-1
+

func LastIndexAny

func LastIndexAny(s []byte, chars string) int

LastIndexAny interprets s as a sequence of UTF-8-encoded Unicode code points. It returns the byte index of the last occurrence in s of any of the Unicode code points in chars. It returns -1 if chars is empty or if there is no code point in common.

Example +

Code:

fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "MüQp"))
+fmt.Println(bytes.LastIndexAny([]byte("go 地鼠"), "地大"))
+fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "z,!."))
+

Output:

5
+3
+-1
+

func LastIndexByte 1.5

func LastIndexByte(s []byte, c byte) int

LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s.

Example +

Code:

fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('g')))
+fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('r')))
+fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('z')))
+

Output:

3
+8
+-1
+

func LastIndexFunc

func LastIndexFunc(s []byte, f func(r rune) bool) int

LastIndexFunc interprets s as a sequence of UTF-8-encoded code points. It returns the byte index in s of the last Unicode code point satisfying f(c), or -1 if none do.

Example +

Code:

fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsLetter))
+fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsPunct))
+fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsNumber))
+

Output:

8
+9
+-1
+

func Map

func Map(mapping func(r rune) rune, s []byte) []byte

Map returns a copy of the byte slice s with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the byte slice with no replacement. The characters in s and the output are interpreted as UTF-8-encoded code points.

Example +

Code:

rot13 := func(r rune) rune {
+    switch {
+    case r >= 'A' && r <= 'Z':
+        return 'A' + (r-'A'+13)%26
+    case r >= 'a' && r <= 'z':
+        return 'a' + (r-'a'+13)%26
+    }
+    return r
+}
+fmt.Printf("%s\n", bytes.Map(rot13, []byte("'Twas brillig and the slithy gopher...")))
+

Output:

'Gjnf oevyyvt naq gur fyvgul tbcure...
+

func Repeat

func Repeat(b []byte, count int) []byte

Repeat returns a new byte slice consisting of count copies of b.

+

It panics if count is negative or if the result of (len(b) * count) overflows.

Example +

Code:

fmt.Printf("ba%s", bytes.Repeat([]byte("na"), 2))
+

Output:

banana
+

func Replace

func Replace(s, old, new []byte, n int) []byte

Replace returns a copy of the slice s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the slice and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune slice. If n < 0, there is no limit on the number of replacements.

Example +

Code:

fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("k"), []byte("ky"), 2))
+fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("oink"), []byte("moo"), -1))
+

Output:

oinky oinky oink
+moo moo moo
+

func ReplaceAll 1.12

func ReplaceAll(s, old, new []byte) []byte

ReplaceAll returns a copy of the slice s with all non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the slice and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune slice.

Example +

Code:

fmt.Printf("%s\n", bytes.ReplaceAll([]byte("oink oink oink"), []byte("oink"), []byte("moo")))
+

Output:

moo moo moo
+

func Runes

func Runes(s []byte) []rune

Runes interprets s as a sequence of UTF-8-encoded code points. It returns a slice of runes (Unicode code points) equivalent to s.

Example +

Code:

rs := bytes.Runes([]byte("go gopher"))
+for _, r := range rs {
+    fmt.Printf("%#U\n", r)
+}
+

Output:

U+0067 'g'
+U+006F 'o'
+U+0020 ' '
+U+0067 'g'
+U+006F 'o'
+U+0070 'p'
+U+0068 'h'
+U+0065 'e'
+U+0072 'r'
+

func Split

func Split(s, sep []byte) [][]byte

Split slices s into all subslices separated by sep and returns a slice of the subslices between those separators. If sep is empty, Split splits after each UTF-8 sequence. It is equivalent to SplitN with a count of -1.

+

To split around the first instance of a separator, see Cut.

Example +

Code:

fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(",")))
+fmt.Printf("%q\n", bytes.Split([]byte("a man a plan a canal panama"), []byte("a ")))
+fmt.Printf("%q\n", bytes.Split([]byte(" xyz "), []byte("")))
+fmt.Printf("%q\n", bytes.Split([]byte(""), []byte("Bernardo O'Higgins")))
+

Output:

["a" "b" "c"]
+["" "man " "plan " "canal panama"]
+[" " "x" "y" "z" " "]
+[""]
+

func SplitAfter

func SplitAfter(s, sep []byte) [][]byte

SplitAfter slices s into all subslices after each instance of sep and returns a slice of those subslices. If sep is empty, SplitAfter splits after each UTF-8 sequence. It is equivalent to SplitAfterN with a count of -1.

Example +

Code:

fmt.Printf("%q\n", bytes.SplitAfter([]byte("a,b,c"), []byte(",")))
+

Output:

["a," "b," "c"]
+

func SplitAfterN

func SplitAfterN(s, sep []byte, n int) [][]byte

SplitAfterN slices s into subslices after each instance of sep and returns a slice of those subslices. If sep is empty, SplitAfterN splits after each UTF-8 sequence. The count determines the number of subslices to return:

+
n > 0: at most n subslices; the last subslice will be the unsplit remainder.
+n == 0: the result is nil (zero subslices)
+n < 0: all subslices
+

Example +

Code:

fmt.Printf("%q\n", bytes.SplitAfterN([]byte("a,b,c"), []byte(","), 2))
+

Output:

["a," "b,c"]
+

func SplitN

func SplitN(s, sep []byte, n int) [][]byte

SplitN slices s into subslices separated by sep and returns a slice of the subslices between those separators. If sep is empty, SplitN splits after each UTF-8 sequence. The count determines the number of subslices to return:

+
n > 0: at most n subslices; the last subslice will be the unsplit remainder.
+n == 0: the result is nil (zero subslices)
+n < 0: all subslices
+

To split around the first instance of a separator, see Cut.

Example +

Code:

fmt.Printf("%q\n", bytes.SplitN([]byte("a,b,c"), []byte(","), 2))
+z := bytes.SplitN([]byte("a,b,c"), []byte(","), 0)
+fmt.Printf("%q (nil = %v)\n", z, z == nil)
+

Output:

["a" "b,c"]
+[] (nil = true)
+

func Title

func Title(s []byte) []byte

Title treats s as UTF-8-encoded bytes and returns a copy with all Unicode letters that begin words mapped to their title case.

+

Deprecated: The rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.

Example +

Code:

fmt.Printf("%s", bytes.Title([]byte("her royal highness")))
+

Output:

Her Royal Highness
+

func ToLower

func ToLower(s []byte) []byte

ToLower returns a copy of the byte slice s with all Unicode letters mapped to their lower case.

Example +

Code:

fmt.Printf("%s", bytes.ToLower([]byte("Gopher")))
+

Output:

gopher
+

func ToLowerSpecial

func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte

ToLowerSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their lower case, giving priority to the special casing rules.

Example +

Code:

str := []byte("AHOJ VÝVOJÁRİ GOLANG")
+totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str)
+fmt.Println("Original : " + string(str))
+fmt.Println("ToLower : " + string(totitle))
+

Output:

Original : AHOJ VÝVOJÁRİ GOLANG
+ToLower : ahoj vývojári golang
+

func ToTitle

func ToTitle(s []byte) []byte

ToTitle treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their title case.

Example +

Code:

fmt.Printf("%s\n", bytes.ToTitle([]byte("loud noises")))
+fmt.Printf("%s\n", bytes.ToTitle([]byte("хлеб")))
+

Output:

LOUD NOISES
+ХЛЕБ
+

func ToTitleSpecial

func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte

ToTitleSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their title case, giving priority to the special casing rules.

Example +

Code:

str := []byte("ahoj vývojári golang")
+totitle := bytes.ToTitleSpecial(unicode.AzeriCase, str)
+fmt.Println("Original : " + string(str))
+fmt.Println("ToTitle : " + string(totitle))
+

Output:

Original : ahoj vývojári golang
+ToTitle : AHOJ VÝVOJÁRİ GOLANG
+

func ToUpper

func ToUpper(s []byte) []byte

ToUpper returns a copy of the byte slice s with all Unicode letters mapped to their upper case.

Example +

Code:

fmt.Printf("%s", bytes.ToUpper([]byte("Gopher")))
+

Output:

GOPHER
+

func ToUpperSpecial

func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte

ToUpperSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their upper case, giving priority to the special casing rules.

Example +

Code:

str := []byte("ahoj vývojári golang")
+totitle := bytes.ToUpperSpecial(unicode.AzeriCase, str)
+fmt.Println("Original : " + string(str))
+fmt.Println("ToUpper : " + string(totitle))
+

Output:

Original : ahoj vývojári golang
+ToUpper : AHOJ VÝVOJÁRİ GOLANG
+

func ToValidUTF8 1.13

func ToValidUTF8(s, replacement []byte) []byte

ToValidUTF8 treats s as UTF-8-encoded bytes and returns a copy with each run of bytes representing invalid UTF-8 replaced with the bytes in replacement, which may be empty.

Example +

Code:

fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("abc"), []byte("\uFFFD")))
+fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("a\xffb\xC0\xAFc\xff"), []byte("")))
+fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("\xed\xa0\x80"), []byte("abc")))
+

Output:

abc
+abc
+abc
+

func Trim

func Trim(s []byte, cutset string) []byte

Trim returns a subslice of s by slicing off all leading and trailing UTF-8-encoded code points contained in cutset.

Example +

Code:

fmt.Printf("[%q]", bytes.Trim([]byte(" !!! Achtung! Achtung! !!! "), "! "))
+

Output:

["Achtung! Achtung"]
+

func TrimFunc

func TrimFunc(s []byte, f func(r rune) bool) []byte

TrimFunc returns a subslice of s by slicing off all leading and trailing UTF-8-encoded code points c that satisfy f(c).

Example +

Code:

fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsLetter)))
+fmt.Println(string(bytes.TrimFunc([]byte("\"go-gopher!\""), unicode.IsLetter)))
+fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsPunct)))
+fmt.Println(string(bytes.TrimFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
+

Output:

-gopher!
+"go-gopher!"
+go-gopher
+go-gopher!
+

func TrimLeft

func TrimLeft(s []byte, cutset string) []byte

TrimLeft returns a subslice of s by slicing off all leading UTF-8-encoded code points contained in cutset.

Example +

Code:

fmt.Print(string(bytes.TrimLeft([]byte("453gopher8257"), "0123456789")))
+

Output:

gopher8257
+

func TrimLeftFunc

func TrimLeftFunc(s []byte, f func(r rune) bool) []byte

TrimLeftFunc treats s as UTF-8-encoded bytes and returns a subslice of s by slicing off all leading UTF-8-encoded code points c that satisfy f(c).

Example +

Code:

fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher"), unicode.IsLetter)))
+fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher!"), unicode.IsPunct)))
+fmt.Println(string(bytes.TrimLeftFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
+

Output:

-gopher
+go-gopher!
+go-gopher!567
+

func TrimPrefix 1.1

func TrimPrefix(s, prefix []byte) []byte

TrimPrefix returns s without the provided leading prefix string. If s doesn't start with prefix, s is returned unchanged.

Example +

Code:

var b = []byte("Goodbye,, world!")
+b = bytes.TrimPrefix(b, []byte("Goodbye,"))
+b = bytes.TrimPrefix(b, []byte("See ya,"))
+fmt.Printf("Hello%s", b)
+

Output:

Hello, world!
+

func TrimRight

func TrimRight(s []byte, cutset string) []byte

TrimRight returns a subslice of s by slicing off all trailing UTF-8-encoded code points that are contained in cutset.

Example +

Code:

fmt.Print(string(bytes.TrimRight([]byte("453gopher8257"), "0123456789")))
+

Output:

453gopher
+

func TrimRightFunc

func TrimRightFunc(s []byte, f func(r rune) bool) []byte

TrimRightFunc returns a subslice of s by slicing off all trailing UTF-8-encoded code points c that satisfy f(c).

Example +

Code:

fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher"), unicode.IsLetter)))
+fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher!"), unicode.IsPunct)))
+fmt.Println(string(bytes.TrimRightFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
+

Output:

go-
+go-gopher
+1234go-gopher!
+

func TrimSpace

func TrimSpace(s []byte) []byte

TrimSpace returns a subslice of s by slicing off all leading and trailing white space, as defined by Unicode.

Example +

Code:

fmt.Printf("%s", bytes.TrimSpace([]byte(" \t\n a lone gopher \n\t\r\n")))
+

Output:

a lone gopher
+

func TrimSuffix 1.1

func TrimSuffix(s, suffix []byte) []byte

TrimSuffix returns s without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.

Example +

Code:

var b = []byte("Hello, goodbye, etc!")
+b = bytes.TrimSuffix(b, []byte("goodbye, etc!"))
+b = bytes.TrimSuffix(b, []byte("gopher"))
+b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...)
+os.Stdout.Write(b)
+

Output:

Hello, world!
+

type Buffer

A Buffer is a variable-sized buffer of bytes with Buffer.Read and Buffer.Write methods. The zero value for Buffer is an empty buffer ready to use.

+
type Buffer struct {
+    // contains filtered or unexported fields
+}
+

Example +

Code:

var b bytes.Buffer // A Buffer needs no initialization.
+b.Write([]byte("Hello "))
+fmt.Fprintf(&b, "world!")
+b.WriteTo(os.Stdout)
+

Output:

Hello world!
+

Example (Reader) +

Code:

// A Buffer can turn a string or a []byte into an io.Reader.
+buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==")
+dec := base64.NewDecoder(base64.StdEncoding, buf)
+io.Copy(os.Stdout, dec)
+

Output:

Gophers rule!
+

func NewBuffer

func NewBuffer(buf []byte) *Buffer

NewBuffer creates and initializes a new Buffer using buf as its initial contents. The new Buffer takes ownership of buf, and the caller should not use buf after this call. NewBuffer is intended to prepare a Buffer to read existing data. It can also be used to set the initial size of the internal buffer for writing. To do that, buf should have the desired capacity but a length of zero.

+

In most cases, new(Buffer) (or just declaring a Buffer variable) is sufficient to initialize a Buffer.

+

func NewBufferString

func NewBufferString(s string) *Buffer

NewBufferString creates and initializes a new Buffer using string s as its initial contents. It is intended to prepare a buffer to read an existing string.

+

In most cases, new(Buffer) (or just declaring a Buffer variable) is sufficient to initialize a Buffer.

+

func (*Buffer) Available 1.21

func (b *Buffer) Available() int

Available returns how many bytes are unused in the buffer.

+

func (*Buffer) AvailableBuffer 1.21

func (b *Buffer) AvailableBuffer() []byte

AvailableBuffer returns an empty buffer with b.Available() capacity. This buffer is intended to be appended to and passed to an immediately succeeding Buffer.Write call. The buffer is only valid until the next write operation on b.

Example +

Code:

var buf bytes.Buffer
+for i := 0; i < 4; i++ {
+    b := buf.AvailableBuffer()
+    b = strconv.AppendInt(b, int64(i), 10)
+    b = append(b, ' ')
+    buf.Write(b)
+}
+os.Stdout.Write(buf.Bytes())
+

Output:

0 1 2 3
+

func (*Buffer) Bytes

func (b *Buffer) Bytes() []byte

Bytes returns a slice of length b.Len() holding the unread portion of the buffer. The slice is valid for use only until the next buffer modification (that is, only until the next call to a method like Buffer.Read, Buffer.Write, Buffer.Reset, or Buffer.Truncate). The slice aliases the buffer content at least until the next buffer modification, so immediate changes to the slice will affect the result of future reads.

Example +

Code:

buf := bytes.Buffer{}
+buf.Write([]byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'})
+os.Stdout.Write(buf.Bytes())
+

Output:

hello world
+

func (*Buffer) Cap 1.5

func (b *Buffer) Cap() int

Cap returns the capacity of the buffer's underlying byte slice, that is, the total space allocated for the buffer's data.

Example +

Code:

buf1 := bytes.NewBuffer(make([]byte, 10))
+buf2 := bytes.NewBuffer(make([]byte, 0, 10))
+fmt.Println(buf1.Cap())
+fmt.Println(buf2.Cap())
+

Output:

10
+10
+

func (*Buffer) Grow 1.1

func (b *Buffer) Grow(n int)

Grow grows the buffer's capacity, if necessary, to guarantee space for another n bytes. After Grow(n), at least n bytes can be written to the buffer without another allocation. If n is negative, Grow will panic. If the buffer can't grow it will panic with ErrTooLarge.

Example +

Code:

var b bytes.Buffer
+b.Grow(64)
+bb := b.Bytes()
+b.Write([]byte("64 bytes or fewer"))
+fmt.Printf("%q", bb[:b.Len()])
+

Output:

"64 bytes or fewer"
+

func (*Buffer) Len

func (b *Buffer) Len() int

Len returns the number of bytes of the unread portion of the buffer; b.Len() == len(b.Bytes()).

Example +

Code:

var b bytes.Buffer
+b.Grow(64)
+b.Write([]byte("abcde"))
+fmt.Printf("%d", b.Len())
+

Output:

5
+

func (*Buffer) Next

func (b *Buffer) Next(n int) []byte

Next returns a slice containing the next n bytes from the buffer, advancing the buffer as if the bytes had been returned by Buffer.Read. If there are fewer than n bytes in the buffer, Next returns the entire buffer. The slice is only valid until the next call to a read or write method.

Example +

Code:

var b bytes.Buffer
+b.Grow(64)
+b.Write([]byte("abcde"))
+fmt.Printf("%s\n", b.Next(2))
+fmt.Printf("%s\n", b.Next(2))
+fmt.Printf("%s", b.Next(2))
+

Output:

ab
+cd
+e
+

func (*Buffer) Read

func (b *Buffer) Read(p []byte) (n int, err error)

Read reads the next len(p) bytes from the buffer or until the buffer is drained. The return value n is the number of bytes read. If the buffer has no data to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.

Example +

Code:

+var b bytes.Buffer
+b.Grow(64)
+b.Write([]byte("abcde"))
+rdbuf := make([]byte, 1)
+n, err := b.Read(rdbuf)
+if err != nil {
+    panic(err)
+}
+fmt.Println(n)
+fmt.Println(b.String())
+fmt.Println(string(rdbuf))
+// Output
+// 1
+// bcde
+// a
+

func (*Buffer) ReadByte

func (b *Buffer) ReadByte() (byte, error)

ReadByte reads and returns the next byte from the buffer. If no byte is available, it returns error io.EOF.

Example +

Code:

+var b bytes.Buffer
+b.Grow(64)
+b.Write([]byte("abcde"))
+c, err := b.ReadByte()
+if err != nil {
+    panic(err)
+}
+fmt.Println(c)
+fmt.Println(b.String())
+// Output
+// 97
+// bcde
+

func (*Buffer) ReadBytes

func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)

ReadBytes reads until the first occurrence of delim in the input, returning a slice containing the data up to and including the delimiter. If ReadBytes encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadBytes returns err != nil if and only if the returned data does not end in delim.

+

func (*Buffer) ReadFrom

func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom reads data from r until EOF and appends it to the buffer, growing the buffer as needed. The return value n is the number of bytes read. Any error except io.EOF encountered during the read is also returned. If the buffer becomes too large, ReadFrom will panic with ErrTooLarge.

+

func (*Buffer) ReadRune

func (b *Buffer) ReadRune() (r rune, size int, err error)

ReadRune reads and returns the next UTF-8-encoded Unicode code point from the buffer. If no bytes are available, the error returned is io.EOF. If the bytes are an erroneous UTF-8 encoding, it consumes one byte and returns U+FFFD, 1.

+

func (*Buffer) ReadString

func (b *Buffer) ReadString(delim byte) (line string, err error)

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim.

+

func (*Buffer) Reset

func (b *Buffer) Reset()

Reset resets the buffer to be empty, but it retains the underlying storage for use by future writes. Reset is the same as Buffer.Truncate(0).

+

func (*Buffer) String

func (b *Buffer) String() string

String returns the contents of the unread portion of the buffer as a string. If the Buffer is a nil pointer, it returns "<nil>".

+

To build strings more efficiently, see the strings.Builder type.

+

func (*Buffer) Truncate

func (b *Buffer) Truncate(n int)

Truncate discards all but the first n unread bytes from the buffer but continues to use the same allocated storage. It panics if n is negative or greater than the length of the buffer.

+

func (*Buffer) UnreadByte

func (b *Buffer) UnreadByte() error

UnreadByte unreads the last byte returned by the most recent successful read operation that read at least one byte. If a write has happened since the last read, if the last read returned an error, or if the read read zero bytes, UnreadByte returns an error.

+

func (*Buffer) UnreadRune

func (b *Buffer) UnreadRune() error

UnreadRune unreads the last rune returned by Buffer.ReadRune. If the most recent read or write operation on the buffer was not a successful Buffer.ReadRune, UnreadRune returns an error. (In this regard it is stricter than Buffer.UnreadByte, which will unread the last byte from any read operation.)

+

func (*Buffer) Write

func (b *Buffer) Write(p []byte) (n int, err error)

Write appends the contents of p to the buffer, growing the buffer as needed. The return value n is the length of p; err is always nil. If the buffer becomes too large, Write will panic with ErrTooLarge.

+

func (*Buffer) WriteByte

func (b *Buffer) WriteByte(c byte) error

WriteByte appends the byte c to the buffer, growing the buffer as needed. The returned error is always nil, but is included to match bufio.Writer's WriteByte. If the buffer becomes too large, WriteByte will panic with ErrTooLarge.

+

func (*Buffer) WriteRune

func (b *Buffer) WriteRune(r rune) (n int, err error)

WriteRune appends the UTF-8 encoding of Unicode code point r to the buffer, returning its length and an error, which is always nil but is included to match bufio.Writer's WriteRune. The buffer is grown as needed; if it becomes too large, WriteRune will panic with ErrTooLarge.

+

func (*Buffer) WriteString

func (b *Buffer) WriteString(s string) (n int, err error)

WriteString appends the contents of s to the buffer, growing the buffer as needed. The return value n is the length of s; err is always nil. If the buffer becomes too large, WriteString will panic with ErrTooLarge.

+

func (*Buffer) WriteTo

func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes data to w until the buffer is drained or an error occurs. The return value n is the number of bytes written; it always fits into an int, but it is int64 to match the io.WriterTo interface. Any error encountered during the write is also returned.

+

type Reader

A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker, io.ByteScanner, and io.RuneScanner interfaces by reading from a byte slice. Unlike a Buffer, a Reader is read-only and supports seeking. The zero value for Reader operates like a Reader of an empty slice.

+
type Reader struct {
+    // contains filtered or unexported fields
+}
+

func NewReader

func NewReader(b []byte) *Reader

NewReader returns a new [Reader.Reader] reading from b.

+

func (*Reader) Len

func (r *Reader) Len() int

Len returns the number of bytes of the unread portion of the slice.

Example +

Code:

fmt.Println(bytes.NewReader([]byte("Hi!")).Len())
+fmt.Println(bytes.NewReader([]byte("こんにちは!")).Len())
+

Output:

3
+16
+

func (*Reader) Read

func (r *Reader) Read(b []byte) (n int, err error)

Read implements the io.Reader interface.

+

func (*Reader) ReadAt

func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)

ReadAt implements the io.ReaderAt interface.

+

func (*Reader) ReadByte

func (r *Reader) ReadByte() (byte, error)

ReadByte implements the io.ByteReader interface.

+

func (*Reader) ReadRune

func (r *Reader) ReadRune() (ch rune, size int, err error)

ReadRune implements the io.RuneReader interface.

+

func (*Reader) Reset 1.7

func (r *Reader) Reset(b []byte)

Reset resets the [Reader.Reader] to be reading from b.

+

func (*Reader) Seek

func (r *Reader) Seek(offset int64, whence int) (int64, error)

Seek implements the io.Seeker interface.

+

func (*Reader) Size 1.5

func (r *Reader) Size() int64

Size returns the original length of the underlying byte slice. Size is the number of bytes available for reading via Reader.ReadAt. The result is unaffected by any method calls except Reader.Reset.

+

func (*Reader) UnreadByte

func (r *Reader) UnreadByte() error

UnreadByte complements Reader.ReadByte in implementing the io.ByteScanner interface.

+

func (*Reader) UnreadRune

func (r *Reader) UnreadRune() error

UnreadRune complements Reader.ReadRune in implementing the io.RuneScanner interface.

+

func (*Reader) WriteTo 1.1

func (r *Reader) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements the io.WriterTo interface.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/bytes/ +

+
diff --git a/devdocs/go/cmp%2Findex.html b/devdocs/go/cmp%2Findex.html new file mode 100644 index 00000000..d13c7f2c --- /dev/null +++ b/devdocs/go/cmp%2Findex.html @@ -0,0 +1,73 @@ +

Package cmp

Overview

Package cmp provides types and functions related to comparing ordered values.

Index

Examples

Or
Or (Sort)

Package files

cmp.go

func Compare

func Compare[T Ordered](x, y T) int

Compare returns

+
-1 if x is less than y,
+ 0 if x equals y,
++1 if x is greater than y.
+

For floating-point types, a NaN is considered less than any non-NaN, a NaN is considered equal to a NaN, and -0.0 is equal to 0.0.

+

func Less

func Less[T Ordered](x, y T) bool

Less reports whether x is less than y. For floating-point types, a NaN is considered less than any non-NaN, and -0.0 is not less than (is equal to) 0.0.

+

func Or

func Or[T comparable](vals ...T) T

Or returns the first of its arguments that is not equal to the zero value. If no argument is non-zero, it returns the zero value.

Example +

Code:

// Suppose we have some user input
+// that may or may not be an empty string
+userInput1 := ""
+userInput2 := "some text"
+
+fmt.Println(cmp.Or(userInput1, "default"))
+fmt.Println(cmp.Or(userInput2, "default"))
+fmt.Println(cmp.Or(userInput1, userInput2, "default"))
+

Output:

default
+some text
+some text
+

Example (Sort) +

Code:

type Order struct {
+    Product  string
+    Customer string
+    Price    float64
+}
+orders := []Order{
+    {"foo", "alice", 1.00},
+    {"bar", "bob", 3.00},
+    {"baz", "carol", 4.00},
+    {"foo", "alice", 2.00},
+    {"bar", "carol", 1.00},
+    {"foo", "bob", 4.00},
+}
+// Sort by customer first, product second, and last by higher price
+slices.SortFunc(orders, func(a, b Order) int {
+    return cmp.Or(
+        cmp.Compare(a.Customer, b.Customer),
+        cmp.Compare(a.Product, b.Product),
+        cmp.Compare(b.Price, a.Price),
+    )
+})
+for _, order := range orders {
+    fmt.Printf("%s %s %.2f\n", order.Product, order.Customer, order.Price)
+}
+
+

Output:

foo alice 2.00
+foo alice 1.00
+bar bob 3.00
+foo bob 4.00
+bar carol 1.00
+baz carol 4.00
+

type Ordered 1.21

Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >. If future releases of Go add new ordered types, this constraint will be modified to include them.

+

Note that floating-point types may contain NaN ("not-a-number") values. An operator such as == or < will always report false when comparing a NaN value with any other value, NaN or not. See the Compare function for a consistent way to compare NaN values.

+
type Ordered interface {
+    ~int | ~int8 | ~int16 | ~int32 | ~int64 |
+        ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
+        ~float32 | ~float64 |
+        ~string
+}
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/cmp/ +

+
diff --git a/devdocs/go/compress%2Fbzip2%2Findex.html b/devdocs/go/compress%2Fbzip2%2Findex.html new file mode 100644 index 00000000..523f71cb --- /dev/null +++ b/devdocs/go/compress%2Fbzip2%2Findex.html @@ -0,0 +1,17 @@ +

Package bzip2

Overview

Package bzip2 implements bzip2 decompression.

Index

Package files

bit_reader.go bzip2.go huffman.go move_to_front.go

func NewReader

func NewReader(r io.Reader) io.Reader

NewReader returns an io.Reader which decompresses bzip2 data from r. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r.

+

type StructuralError

A StructuralError is returned when the bzip2 data is found to be syntactically invalid.

+
type StructuralError string

func (StructuralError) Error

func (s StructuralError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/compress/bzip2/ +

+
diff --git a/devdocs/go/compress%2Fflate%2Findex.html b/devdocs/go/compress%2Fflate%2Findex.html new file mode 100644 index 00000000..88631066 --- /dev/null +++ b/devdocs/go/compress%2Fflate%2Findex.html @@ -0,0 +1,307 @@ +

Package flate

Overview

Package flate implements the DEFLATE compressed data format, described in RFC 1951. The gzip and zlib packages implement access to DEFLATE-based file formats.

Example (Dictionary) +

A preset dictionary can be used to improve the compression ratio. The downside to using a dictionary is that the compressor and decompressor must agree in advance what dictionary to use.

Code:

// The dictionary is a string of bytes. When compressing some input data,
+// the compressor will attempt to substitute substrings with matches found
+// in the dictionary. As such, the dictionary should only contain substrings
+// that are expected to be found in the actual data stream.
+const dict = `<?xml version="1.0"?>` + `<book>` + `<data>` + `<meta name="` + `" content="`
+
+// The data to compress should (but is not required to) contain frequent
+// substrings that match those in the dictionary.
+const data = `<?xml version="1.0"?>
+<book>
+    <meta name="title" content="The Go Programming Language"/>
+    <meta name="authors" content="Alan Donovan and Brian Kernighan"/>
+    <meta name="published" content="2015-10-26"/>
+    <meta name="isbn" content="978-0134190440"/>
+    <data>...</data>
+</book>
+`
+
+var b bytes.Buffer
+
+// Compress the data using the specially crafted dictionary.
+zw, err := flate.NewWriterDict(&b, flate.DefaultCompression, []byte(dict))
+if err != nil {
+    log.Fatal(err)
+}
+if _, err := io.Copy(zw, strings.NewReader(data)); err != nil {
+    log.Fatal(err)
+}
+if err := zw.Close(); err != nil {
+    log.Fatal(err)
+}
+
+// The decompressor must use the same dictionary as the compressor.
+// Otherwise, the input may appear as corrupted.
+fmt.Println("Decompressed output using the dictionary:")
+zr := flate.NewReaderDict(bytes.NewReader(b.Bytes()), []byte(dict))
+if _, err := io.Copy(os.Stdout, zr); err != nil {
+    log.Fatal(err)
+}
+if err := zr.Close(); err != nil {
+    log.Fatal(err)
+}
+
+fmt.Println()
+
+// Substitute all of the bytes in the dictionary with a '#' to visually
+// demonstrate the approximate effectiveness of using a preset dictionary.
+fmt.Println("Substrings matched by the dictionary are marked with #:")
+hashDict := []byte(dict)
+for i := range hashDict {
+    hashDict[i] = '#'
+}
+zr = flate.NewReaderDict(&b, hashDict)
+if _, err := io.Copy(os.Stdout, zr); err != nil {
+    log.Fatal(err)
+}
+if err := zr.Close(); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

Decompressed output using the dictionary:
+<?xml version="1.0"?>
+<book>
+	<meta name="title" content="The Go Programming Language"/>
+	<meta name="authors" content="Alan Donovan and Brian Kernighan"/>
+	<meta name="published" content="2015-10-26"/>
+	<meta name="isbn" content="978-0134190440"/>
+	<data>...</data>
+</book>
+
+Substrings matched by the dictionary are marked with #:
+#####################
+######
+	############title###########The Go Programming Language"/#
+	############authors###########Alan Donovan and Brian Kernighan"/#
+	############published###########2015-10-26"/#
+	############isbn###########978-0134190440"/#
+	######...</#####
+</#####
+

Example (Reset) +

In performance critical applications, Reset can be used to discard the current compressor or decompressor state and reinitialize them quickly by taking advantage of previously allocated memory.

Code:

proverbs := []string{
+    "Don't communicate by sharing memory, share memory by communicating.\n",
+    "Concurrency is not parallelism.\n",
+    "The bigger the interface, the weaker the abstraction.\n",
+    "Documentation is for users.\n",
+}
+
+var r strings.Reader
+var b bytes.Buffer
+buf := make([]byte, 32<<10)
+
+zw, err := flate.NewWriter(nil, flate.DefaultCompression)
+if err != nil {
+    log.Fatal(err)
+}
+zr := flate.NewReader(nil)
+
+for _, s := range proverbs {
+    r.Reset(s)
+    b.Reset()
+
+    // Reset the compressor and encode from some input stream.
+    zw.Reset(&b)
+    if _, err := io.CopyBuffer(zw, &r, buf); err != nil {
+        log.Fatal(err)
+    }
+    if err := zw.Close(); err != nil {
+        log.Fatal(err)
+    }
+
+    // Reset the decompressor and decode to some output stream.
+    if err := zr.(flate.Resetter).Reset(&b, nil); err != nil {
+        log.Fatal(err)
+    }
+    if _, err := io.CopyBuffer(os.Stdout, zr, buf); err != nil {
+        log.Fatal(err)
+    }
+    if err := zr.Close(); err != nil {
+        log.Fatal(err)
+    }
+}
+
+

Output:

Don't communicate by sharing memory, share memory by communicating.
+Concurrency is not parallelism.
+The bigger the interface, the weaker the abstraction.
+Documentation is for users.
+

Example (Synchronization) +

DEFLATE is suitable for transmitting compressed data across the network.

Code:

var wg sync.WaitGroup
+defer wg.Wait()
+
+// Use io.Pipe to simulate a network connection.
+// A real network application should take care to properly close the
+// underlying connection.
+rp, wp := io.Pipe()
+
+// Start a goroutine to act as the transmitter.
+wg.Add(1)
+go func() {
+    defer wg.Done()
+
+    zw, err := flate.NewWriter(wp, flate.BestSpeed)
+    if err != nil {
+        log.Fatal(err)
+    }
+
+    b := make([]byte, 256)
+    for _, m := range strings.Fields("A long time ago in a galaxy far, far away...") {
+        // We use a simple framing format where the first byte is the
+        // message length, followed the message itself.
+        b[0] = uint8(copy(b[1:], m))
+
+        if _, err := zw.Write(b[:1+len(m)]); err != nil {
+            log.Fatal(err)
+        }
+
+        // Flush ensures that the receiver can read all data sent so far.
+        if err := zw.Flush(); err != nil {
+            log.Fatal(err)
+        }
+    }
+
+    if err := zw.Close(); err != nil {
+        log.Fatal(err)
+    }
+}()
+
+// Start a goroutine to act as the receiver.
+wg.Add(1)
+go func() {
+    defer wg.Done()
+
+    zr := flate.NewReader(rp)
+
+    b := make([]byte, 256)
+    for {
+        // Read the message length.
+        // This is guaranteed to return for every corresponding
+        // Flush and Close on the transmitter side.
+        if _, err := io.ReadFull(zr, b[:1]); err != nil {
+            if err == io.EOF {
+                break // The transmitter closed the stream
+            }
+            log.Fatal(err)
+        }
+
+        // Read the message content.
+        n := int(b[0])
+        if _, err := io.ReadFull(zr, b[:n]); err != nil {
+            log.Fatal(err)
+        }
+
+        fmt.Printf("Received %d bytes: %s\n", n, b[:n])
+    }
+    fmt.Println()
+
+    if err := zr.Close(); err != nil {
+        log.Fatal(err)
+    }
+}()
+
+

Output:

Received 1 bytes: A
+Received 4 bytes: long
+Received 4 bytes: time
+Received 3 bytes: ago
+Received 2 bytes: in
+Received 1 bytes: a
+Received 6 bytes: galaxy
+Received 4 bytes: far,
+Received 3 bytes: far
+Received 7 bytes: away...
+

Index

Examples

Package (Dictionary)
Package (Reset)
Package (Synchronization)

Package files

deflate.go deflatefast.go dict_decoder.go huffman_bit_writer.go huffman_code.go inflate.go token.go

Constants

const (
+    NoCompression      = 0
+    BestSpeed          = 1
+    BestCompression    = 9
+    DefaultCompression = -1
+
+    // HuffmanOnly disables Lempel-Ziv match searching and only performs Huffman
+    // entropy encoding. This mode is useful in compressing data that has
+    // already been compressed with an LZ style algorithm (e.g. Snappy or LZ4)
+    // that lacks an entropy encoder. Compression gains are achieved when
+    // certain bytes in the input stream occur more frequently than others.
+    //
+    // Note that HuffmanOnly produces a compressed output that is
+    // RFC 1951 compliant. That is, any valid DEFLATE decompressor will
+    // continue to be able to decompress this output.
+    HuffmanOnly = -2
+)

func NewReader

func NewReader(r io.Reader) io.ReadCloser

NewReader returns a new ReadCloser that can be used to read the uncompressed version of r. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r. The reader returns io.EOF after the final block in the DEFLATE stream has been encountered. Any trailing data after the final block is ignored.

+

The io.ReadCloser returned by NewReader also implements Resetter.

+

func NewReaderDict

func NewReaderDict(r io.Reader, dict []byte) io.ReadCloser

NewReaderDict is like NewReader but initializes the reader with a preset dictionary. The returned Reader behaves as if the uncompressed data stream started with the given dictionary, which has already been read. NewReaderDict is typically used to read data compressed by NewWriterDict.

+

The ReadCloser returned by NewReaderDict also implements Resetter.

+

type CorruptInputError

A CorruptInputError reports the presence of corrupt input at a given offset.

+
type CorruptInputError int64

func (CorruptInputError) Error

func (e CorruptInputError) Error() string

type InternalError

An InternalError reports an error in the flate code itself.

+
type InternalError string

func (InternalError) Error

func (e InternalError) Error() string

type ReadError

A ReadError reports an error encountered while reading input.

+

Deprecated: No longer returned.

+
type ReadError struct {
+    Offset int64 // byte offset where error occurred
+    Err    error // error returned by underlying Read
+}
+

func (*ReadError) Error

func (e *ReadError) Error() string

type Reader

The actual read interface needed by NewReader. If the passed in io.Reader does not also have ReadByte, the NewReader will introduce its own buffering.

+
type Reader interface {
+    io.Reader
+    io.ByteReader
+}

type Resetter 1.4

Resetter resets a ReadCloser returned by NewReader or NewReaderDict to switch to a new underlying Reader. This permits reusing a ReadCloser instead of allocating a new one.

+
type Resetter interface {
+    // Reset discards any buffered data and resets the Resetter as if it was
+    // newly initialized with the given reader.
+    Reset(r io.Reader, dict []byte) error
+}

type WriteError

A WriteError reports an error encountered while writing output.

+

Deprecated: No longer returned.

+
type WriteError struct {
+    Offset int64 // byte offset where error occurred
+    Err    error // error returned by underlying Write
+}
+

func (*WriteError) Error

func (e *WriteError) Error() string

type Writer

A Writer takes data written to it and writes the compressed form of that data to an underlying writer (see NewWriter).

+
type Writer struct {
+    // contains filtered or unexported fields
+}
+

func NewWriter

func NewWriter(w io.Writer, level int) (*Writer, error)

NewWriter returns a new Writer compressing data at the given level. Following zlib, levels range from 1 (BestSpeed) to 9 (BestCompression); higher levels typically run slower but compress more. Level 0 (NoCompression) does not attempt any compression; it only adds the necessary DEFLATE framing. Level -1 (DefaultCompression) uses the default compression level. Level -2 (HuffmanOnly) will use Huffman compression only, giving a very fast compression for all types of input, but sacrificing considerable compression efficiency.

+

If level is in the range [-2, 9] then the error returned will be nil. Otherwise the error returned will be non-nil.

+

func NewWriterDict

func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error)

NewWriterDict is like NewWriter but initializes the new Writer with a preset dictionary. The returned Writer behaves as if the dictionary had been written to it without producing any compressed output. The compressed data written to w can only be decompressed by a Reader initialized with the same dictionary.

+

func (*Writer) Close

func (w *Writer) Close() error

Close flushes and closes the writer.

+

func (*Writer) Flush

func (w *Writer) Flush() error

Flush flushes any pending data to the underlying writer. It is useful mainly in compressed network protocols, to ensure that a remote reader has enough data to reconstruct a packet. Flush does not return until the data has been written. Calling Flush when there is no pending data still causes the Writer to emit a sync marker of at least 4 bytes. If the underlying writer returns an error, Flush returns that error.

+

In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.

+

func (*Writer) Reset 1.2

func (w *Writer) Reset(dst io.Writer)

Reset discards the writer's state and makes it equivalent to the result of NewWriter or NewWriterDict called with dst and w's level and dictionary.

+

func (*Writer) Write

func (w *Writer) Write(data []byte) (n int, err error)

Write writes data to w, which will eventually write the compressed form of data to its underlying writer.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/compress/flate/ +

+
diff --git a/devdocs/go/compress%2Fgzip%2Findex.html b/devdocs/go/compress%2Fgzip%2Findex.html new file mode 100644 index 00000000..6a4d0d8b --- /dev/null +++ b/devdocs/go/compress%2Fgzip%2Findex.html @@ -0,0 +1,282 @@ +

Package gzip

Overview

Package gzip implements reading and writing of gzip format compressed files, as specified in RFC 1952.

Example (CompressingReader) +

Code:

// This is an example of writing a compressing reader.
+// This can be useful for an HTTP client body, as shown.
+
+const testdata = "the data to be compressed"
+
+// This HTTP handler is just for testing purposes.
+handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
+    zr, err := gzip.NewReader(req.Body)
+    if err != nil {
+        log.Fatal(err)
+    }
+
+    // Just output the data for the example.
+    if _, err := io.Copy(os.Stdout, zr); err != nil {
+        log.Fatal(err)
+    }
+})
+ts := httptest.NewServer(handler)
+defer ts.Close()
+
+// The remainder is the example code.
+
+// The data we want to compress, as an io.Reader
+dataReader := strings.NewReader(testdata)
+
+// bodyReader is the body of the HTTP request, as an io.Reader.
+// httpWriter is the body of the HTTP request, as an io.Writer.
+bodyReader, httpWriter := io.Pipe()
+
+// Make sure that bodyReader is always closed, so that the
+// goroutine below will always exit.
+defer bodyReader.Close()
+
+// gzipWriter compresses data to httpWriter.
+gzipWriter := gzip.NewWriter(httpWriter)
+
+// errch collects any errors from the writing goroutine.
+errch := make(chan error, 1)
+
+go func() {
+    defer close(errch)
+    sentErr := false
+    sendErr := func(err error) {
+        if !sentErr {
+            errch <- err
+            sentErr = true
+        }
+    }
+
+    // Copy our data to gzipWriter, which compresses it to
+    // gzipWriter, which feeds it to bodyReader.
+    if _, err := io.Copy(gzipWriter, dataReader); err != nil && err != io.ErrClosedPipe {
+        sendErr(err)
+    }
+    if err := gzipWriter.Close(); err != nil && err != io.ErrClosedPipe {
+        sendErr(err)
+    }
+    if err := httpWriter.Close(); err != nil && err != io.ErrClosedPipe {
+        sendErr(err)
+    }
+}()
+
+// Send an HTTP request to the test server.
+req, err := http.NewRequest("PUT", ts.URL, bodyReader)
+if err != nil {
+    log.Fatal(err)
+}
+
+// Note that passing req to http.Client.Do promises that it
+// will close the body, in this case bodyReader.
+resp, err := ts.Client().Do(req)
+if err != nil {
+    log.Fatal(err)
+}
+
+// Check whether there was an error compressing the data.
+if err := <-errch; err != nil {
+    log.Fatal(err)
+}
+
+// For this example we don't care about the response.
+resp.Body.Close()
+
+

Output:

the data to be compressed
+

Example (WriterReader) +

Code:

var buf bytes.Buffer
+zw := gzip.NewWriter(&buf)
+
+// Setting the Header fields is optional.
+zw.Name = "a-new-hope.txt"
+zw.Comment = "an epic space opera by George Lucas"
+zw.ModTime = time.Date(1977, time.May, 25, 0, 0, 0, 0, time.UTC)
+
+_, err := zw.Write([]byte("A long time ago in a galaxy far, far away..."))
+if err != nil {
+    log.Fatal(err)
+}
+
+if err := zw.Close(); err != nil {
+    log.Fatal(err)
+}
+
+zr, err := gzip.NewReader(&buf)
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("Name: %s\nComment: %s\nModTime: %s\n\n", zr.Name, zr.Comment, zr.ModTime.UTC())
+
+if _, err := io.Copy(os.Stdout, zr); err != nil {
+    log.Fatal(err)
+}
+
+if err := zr.Close(); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

Name: a-new-hope.txt
+Comment: an epic space opera by George Lucas
+ModTime: 1977-05-25 00:00:00 +0000 UTC
+
+A long time ago in a galaxy far, far away...
+

Index

Examples

Reader.Multistream
Package (CompressingReader)
Package (WriterReader)

Package files

gunzip.go gzip.go

Constants

These constants are copied from the flate package, so that code that imports "compress/gzip" does not also have to import "compress/flate".

+
const (
+    NoCompression      = flate.NoCompression
+    BestSpeed          = flate.BestSpeed
+    BestCompression    = flate.BestCompression
+    DefaultCompression = flate.DefaultCompression
+    HuffmanOnly        = flate.HuffmanOnly
+)

Variables

var (
+    // ErrChecksum is returned when reading GZIP data that has an invalid checksum.
+    ErrChecksum = errors.New("gzip: invalid checksum")
+    // ErrHeader is returned when reading GZIP data that has an invalid header.
+    ErrHeader = errors.New("gzip: invalid header")
+)

The gzip file stores a header giving metadata about the compressed file. That header is exposed as the fields of the Writer and Reader structs.

+

Strings must be UTF-8 encoded and may only contain Unicode code points U+0001 through U+00FF, due to limitations of the GZIP file format.

+
type Header struct {
+    Comment string    // comment
+    Extra   []byte    // "extra data"
+    ModTime time.Time // modification time
+    Name    string    // file name
+    OS      byte      // operating system type
+}
+

type Reader

A Reader is an io.Reader that can be read to retrieve uncompressed data from a gzip-format compressed file.

+

In general, a gzip file can be a concatenation of gzip files, each with its own header. Reads from the Reader return the concatenation of the uncompressed data of each. Only the first header is recorded in the Reader fields.

+

Gzip files store a length and checksum of the uncompressed data. The Reader will return an ErrChecksum when Reader.Read reaches the end of the uncompressed data if it does not have the expected length or checksum. Clients should treat data returned by Reader.Read as tentative until they receive the io.EOF marking the end of the data.

+
type Reader struct {
+    Header // valid after NewReader or Reader.Reset
+    // contains filtered or unexported fields
+}
+

func NewReader

func NewReader(r io.Reader) (*Reader, error)

NewReader creates a new Reader reading the given reader. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r.

+

It is the caller's responsibility to call Close on the Reader when done.

+

The [Reader.Header] fields will be valid in the Reader returned.

+

func (*Reader) Close

func (z *Reader) Close() error

Close closes the Reader. It does not close the underlying io.Reader. In order for the GZIP checksum to be verified, the reader must be fully consumed until the io.EOF.

+

func (*Reader) Multistream 1.4

func (z *Reader) Multistream(ok bool)

Multistream controls whether the reader supports multistream files.

+

If enabled (the default), the Reader expects the input to be a sequence of individually gzipped data streams, each with its own header and trailer, ending at EOF. The effect is that the concatenation of a sequence of gzipped files is treated as equivalent to the gzip of the concatenation of the sequence. This is standard behavior for gzip readers.

+

Calling Multistream(false) disables this behavior; disabling the behavior can be useful when reading file formats that distinguish individual gzip data streams or mix gzip data streams with other data streams. In this mode, when the Reader reaches the end of the data stream, Reader.Read returns io.EOF. The underlying reader must implement io.ByteReader in order to be left positioned just after the gzip stream. To start the next stream, call z.Reset(r) followed by z.Multistream(false). If there is no next stream, z.Reset(r) will return io.EOF.

Example +

Code:

var buf bytes.Buffer
+zw := gzip.NewWriter(&buf)
+
+var files = []struct {
+    name    string
+    comment string
+    modTime time.Time
+    data    string
+}{
+    {"file-1.txt", "file-header-1", time.Date(2006, time.February, 1, 3, 4, 5, 0, time.UTC), "Hello Gophers - 1"},
+    {"file-2.txt", "file-header-2", time.Date(2007, time.March, 2, 4, 5, 6, 1, time.UTC), "Hello Gophers - 2"},
+}
+
+for _, file := range files {
+    zw.Name = file.name
+    zw.Comment = file.comment
+    zw.ModTime = file.modTime
+
+    if _, err := zw.Write([]byte(file.data)); err != nil {
+        log.Fatal(err)
+    }
+
+    if err := zw.Close(); err != nil {
+        log.Fatal(err)
+    }
+
+    zw.Reset(&buf)
+}
+
+zr, err := gzip.NewReader(&buf)
+if err != nil {
+    log.Fatal(err)
+}
+
+for {
+    zr.Multistream(false)
+    fmt.Printf("Name: %s\nComment: %s\nModTime: %s\n\n", zr.Name, zr.Comment, zr.ModTime.UTC())
+
+    if _, err := io.Copy(os.Stdout, zr); err != nil {
+        log.Fatal(err)
+    }
+
+    fmt.Print("\n\n")
+
+    err = zr.Reset(&buf)
+    if err == io.EOF {
+        break
+    }
+    if err != nil {
+        log.Fatal(err)
+    }
+}
+
+if err := zr.Close(); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

Name: file-1.txt
+Comment: file-header-1
+ModTime: 2006-02-01 03:04:05 +0000 UTC
+
+Hello Gophers - 1
+
+Name: file-2.txt
+Comment: file-header-2
+ModTime: 2007-03-02 04:05:06 +0000 UTC
+
+Hello Gophers - 2
+

func (*Reader) Read

func (z *Reader) Read(p []byte) (n int, err error)

Read implements io.Reader, reading uncompressed bytes from its underlying Reader.

+

func (*Reader) Reset 1.3

func (z *Reader) Reset(r io.Reader) error

Reset discards the Reader z's state and makes it equivalent to the result of its original state from NewReader, but reading from r instead. This permits reusing a Reader rather than allocating a new one.

+

type Writer

A Writer is an io.WriteCloser. Writes to a Writer are compressed and written to w.

+
type Writer struct {
+    Header // written at first call to Write, Flush, or Close
+    // contains filtered or unexported fields
+}
+

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter returns a new Writer. Writes to the returned writer are compressed and written to w.

+

It is the caller's responsibility to call Close on the Writer when done. Writes may be buffered and not flushed until Close.

+

Callers that wish to set the fields in Writer.Header must do so before the first call to Write, Flush, or Close.

+

func NewWriterLevel

func NewWriterLevel(w io.Writer, level int) (*Writer, error)

NewWriterLevel is like NewWriter but specifies the compression level instead of assuming DefaultCompression.

+

The compression level can be DefaultCompression, NoCompression, HuffmanOnly or any integer value between BestSpeed and BestCompression inclusive. The error returned will be nil if the level is valid.

+

func (*Writer) Close

func (z *Writer) Close() error

Close closes the Writer by flushing any unwritten data to the underlying io.Writer and writing the GZIP footer. It does not close the underlying io.Writer.

+

func (*Writer) Flush 1.1

func (z *Writer) Flush() error

Flush flushes any pending compressed data to the underlying writer.

+

It is useful mainly in compressed network protocols, to ensure that a remote reader has enough data to reconstruct a packet. Flush does not return until the data has been written. If the underlying writer returns an error, Flush returns that error.

+

In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.

+

func (*Writer) Reset 1.2

func (z *Writer) Reset(w io.Writer)

Reset discards the Writer z's state and makes it equivalent to the result of its original state from NewWriter or NewWriterLevel, but writing to w instead. This permits reusing a Writer rather than allocating a new one.

+

func (*Writer) Write

func (z *Writer) Write(p []byte) (int, error)

Write writes a compressed form of p to the underlying io.Writer. The compressed bytes are not necessarily flushed until the Writer is closed.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/compress/gzip/ +

+
diff --git a/devdocs/go/compress%2Flzw%2Findex.html b/devdocs/go/compress%2Flzw%2Findex.html new file mode 100644 index 00000000..fd2df20e --- /dev/null +++ b/devdocs/go/compress%2Flzw%2Findex.html @@ -0,0 +1,54 @@ +

Package lzw

Overview

Package lzw implements the Lempel-Ziv-Welch compressed data format, described in T. A. Welch, “A Technique for High-Performance Data Compression”, Computer, 17(6) (June 1984), pp 8-19.

+

In particular, it implements LZW as used by the GIF and PDF file formats, which means variable-width codes up to 12 bits and the first two non-literal codes are a clear code and an EOF code.

+

The TIFF file format uses a similar but incompatible version of the LZW algorithm. See the golang.org/x/image/tiff/lzw package for an implementation.

Index

Package files

reader.go writer.go

func NewReader

func NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser

NewReader creates a new io.ReadCloser. Reads from the returned io.ReadCloser read and decompress data from r. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r. It is the caller's responsibility to call Close on the ReadCloser when finished reading. The number of bits to use for literal codes, litWidth, must be in the range [2,8] and is typically 8. It must equal the litWidth used during compression.

+

It is guaranteed that the underlying type of the returned io.ReadCloser is a *Reader.

+

func NewWriter

func NewWriter(w io.Writer, order Order, litWidth int) io.WriteCloser

NewWriter creates a new io.WriteCloser. Writes to the returned io.WriteCloser are compressed and written to w. It is the caller's responsibility to call Close on the WriteCloser when finished writing. The number of bits to use for literal codes, litWidth, must be in the range [2,8] and is typically 8. Input bytes must be less than 1<<litWidth.

+

It is guaranteed that the underlying type of the returned io.WriteCloser is a *Writer.

+

type Order

Order specifies the bit ordering in an LZW data stream.

+
type Order int
const (
+    // LSB means Least Significant Bits first, as used in the GIF file format.
+    LSB Order = iota
+    // MSB means Most Significant Bits first, as used in the TIFF and PDF
+    // file formats.
+    MSB
+)

type Reader 1.17

Reader is an io.Reader which can be used to read compressed data in the LZW format.

+
type Reader struct {
+    // contains filtered or unexported fields
+}
+

func (*Reader) Close 1.17

func (r *Reader) Close() error

Close closes the Reader and returns an error for any future read operation. It does not close the underlying io.Reader.

+

func (*Reader) Read 1.17

func (r *Reader) Read(b []byte) (int, error)

Read implements io.Reader, reading uncompressed bytes from its underlying Reader.

+

func (*Reader) Reset 1.17

func (r *Reader) Reset(src io.Reader, order Order, litWidth int)

Reset clears the Reader's state and allows it to be reused again as a new Reader.

+

type Writer 1.17

Writer is an LZW compressor. It writes the compressed form of the data to an underlying writer (see NewWriter).

+
type Writer struct {
+    // contains filtered or unexported fields
+}
+

func (*Writer) Close 1.17

func (w *Writer) Close() error

Close closes the Writer, flushing any pending output. It does not close w's underlying writer.

+

func (*Writer) Reset 1.17

func (w *Writer) Reset(dst io.Writer, order Order, litWidth int)

Reset clears the Writer's state and allows it to be reused again as a new Writer.

+

func (*Writer) Write 1.17

func (w *Writer) Write(p []byte) (n int, err error)

Write writes a compressed representation of p to w's underlying writer.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/compress/lzw/ +

+
diff --git a/devdocs/go/compress%2Fzlib%2Findex.html b/devdocs/go/compress%2Fzlib%2Findex.html new file mode 100644 index 00000000..393ad89d --- /dev/null +++ b/devdocs/go/compress%2Fzlib%2Findex.html @@ -0,0 +1,95 @@ +

Package zlib

Overview

Package zlib implements reading and writing of zlib format compressed data, as specified in RFC 1950.

+

The implementation provides filters that uncompress during reading and compress during writing. For example, to write compressed data to a buffer:

+
var b bytes.Buffer
+w := zlib.NewWriter(&b)
+w.Write([]byte("hello, world\n"))
+w.Close()
+

and to read that data back:

+
r, err := zlib.NewReader(&b)
+io.Copy(os.Stdout, r)
+r.Close()
+

Index

Examples

NewReader
NewWriter

Package files

reader.go writer.go

Constants

These constants are copied from the flate package, so that code that imports "compress/zlib" does not also have to import "compress/flate".

+
const (
+    NoCompression      = flate.NoCompression
+    BestSpeed          = flate.BestSpeed
+    BestCompression    = flate.BestCompression
+    DefaultCompression = flate.DefaultCompression
+    HuffmanOnly        = flate.HuffmanOnly
+)

Variables

var (
+    // ErrChecksum is returned when reading ZLIB data that has an invalid checksum.
+    ErrChecksum = errors.New("zlib: invalid checksum")
+    // ErrDictionary is returned when reading ZLIB data that has an invalid dictionary.
+    ErrDictionary = errors.New("zlib: invalid dictionary")
+    // ErrHeader is returned when reading ZLIB data that has an invalid header.
+    ErrHeader = errors.New("zlib: invalid header")
+)

func NewReader

func NewReader(r io.Reader) (io.ReadCloser, error)

NewReader creates a new ReadCloser. Reads from the returned ReadCloser read and decompress data from r. If r does not implement io.ByteReader, the decompressor may read more data than necessary from r. It is the caller's responsibility to call Close on the ReadCloser when done.

+

The io.ReadCloser returned by NewReader also implements Resetter.

Example +

Code:

buff := []byte{120, 156, 202, 72, 205, 201, 201, 215, 81, 40, 207,
+    47, 202, 73, 225, 2, 4, 0, 0, 255, 255, 33, 231, 4, 147}
+b := bytes.NewReader(buff)
+
+r, err := zlib.NewReader(b)
+if err != nil {
+    panic(err)
+}
+io.Copy(os.Stdout, r)
+

Output:

hello, world
+

func NewReaderDict

func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, error)

NewReaderDict is like NewReader but uses a preset dictionary. NewReaderDict ignores the dictionary if the compressed data does not refer to it. If the compressed data refers to a different dictionary, NewReaderDict returns ErrDictionary.

+

The ReadCloser returned by NewReaderDict also implements Resetter.

+

type Resetter 1.4

Resetter resets a ReadCloser returned by NewReader or NewReaderDict to switch to a new underlying Reader. This permits reusing a ReadCloser instead of allocating a new one.

+
type Resetter interface {
+    // Reset discards any buffered data and resets the Resetter as if it was
+    // newly initialized with the given reader.
+    Reset(r io.Reader, dict []byte) error
+}

type Writer

A Writer takes data written to it and writes the compressed form of that data to an underlying writer (see NewWriter).

+
type Writer struct {
+    // contains filtered or unexported fields
+}
+

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter creates a new Writer. Writes to the returned Writer are compressed and written to w.

+

It is the caller's responsibility to call Close on the Writer when done. Writes may be buffered and not flushed until Close.

Example +

Code:

var b bytes.Buffer
+
+w := zlib.NewWriter(&b)
+w.Write([]byte("hello, world\n"))
+w.Close()
+fmt.Println(b.Bytes())
+

Output:

[120 156 202 72 205 201 201 215 81 40 207 47 202 73 225 2 4 0 0 255 255 33 231 4 147]
+

func NewWriterLevel

func NewWriterLevel(w io.Writer, level int) (*Writer, error)

NewWriterLevel is like NewWriter but specifies the compression level instead of assuming DefaultCompression.

+

The compression level can be DefaultCompression, NoCompression, HuffmanOnly or any integer value between BestSpeed and BestCompression inclusive. The error returned will be nil if the level is valid.

+

func NewWriterLevelDict

func NewWriterLevelDict(w io.Writer, level int, dict []byte) (*Writer, error)

NewWriterLevelDict is like NewWriterLevel but specifies a dictionary to compress with.

+

The dictionary may be nil. If not, its contents should not be modified until the Writer is closed.

+

func (*Writer) Close

func (z *Writer) Close() error

Close closes the Writer, flushing any unwritten data to the underlying io.Writer, but does not close the underlying io.Writer.

+

func (*Writer) Flush

func (z *Writer) Flush() error

Flush flushes the Writer to its underlying io.Writer.

+

func (*Writer) Reset 1.2

func (z *Writer) Reset(w io.Writer)

Reset clears the state of the Writer z such that it is equivalent to its initial state from NewWriterLevel or NewWriterLevelDict, but instead writing to w.

+

func (*Writer) Write

func (z *Writer) Write(p []byte) (n int, err error)

Write writes a compressed form of p to the underlying io.Writer. The compressed bytes are not necessarily flushed until the Writer is closed or explicitly flushed.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/compress/zlib/ +

+
diff --git a/devdocs/go/container%2Fheap%2Findex.html b/devdocs/go/container%2Fheap%2Findex.html new file mode 100644 index 00000000..8c236281 --- /dev/null +++ b/devdocs/go/container%2Fheap%2Findex.html @@ -0,0 +1,171 @@ +

Package heap

Overview

Package heap provides heap operations for any type that implements heap.Interface. A heap is a tree with the property that each node is the minimum-valued node in its subtree.

+

The minimum element in the tree is the root, at index 0.

+

A heap is a common way to implement a priority queue. To build a priority queue, implement the Heap interface with the (negative) priority as the ordering for the Less method, so Push adds items while Pop removes the highest-priority item from the queue. The Examples include such an implementation; the file example_pq_test.go has the complete source.

Example (IntHeap) +

This example inserts several ints into an IntHeap, checks the minimum, and removes them in order of priority.

Code:

// This example demonstrates an integer heap built using the heap interface.
+package heap_test
+
+import (
+    "container/heap"
+    "fmt"
+)
+
+// An IntHeap is a min-heap of ints.
+type IntHeap []int
+
+func (h IntHeap) Len() int           { return len(h) }
+func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
+func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
+
+func (h *IntHeap) Push(x any) {
+    // Push and Pop use pointer receivers because they modify the slice's length,
+    // not just its contents.
+    *h = append(*h, x.(int))
+}
+
+func (h *IntHeap) Pop() any {
+    old := *h
+    n := len(old)
+    x := old[n-1]
+    *h = old[0 : n-1]
+    return x
+}
+
+// This example inserts several ints into an IntHeap, checks the minimum,
+// and removes them in order of priority.
+func Example_intHeap() {
+    h := &IntHeap{2, 1, 5}
+    heap.Init(h)
+    heap.Push(h, 3)
+    fmt.Printf("minimum: %d\n", (*h)[0])
+    for h.Len() > 0 {
+        fmt.Printf("%d ", heap.Pop(h))
+    }
+    // Output:
+    // minimum: 1
+    // 1 2 3 5
+}
+

Example (PriorityQueue) +

This example creates a PriorityQueue with some items, adds and manipulates an item, and then removes the items in priority order.

Code:

// This example demonstrates a priority queue built using the heap interface.
+package heap_test
+
+import (
+    "container/heap"
+    "fmt"
+)
+
+// An Item is something we manage in a priority queue.
+type Item struct {
+    value    string // The value of the item; arbitrary.
+    priority int    // The priority of the item in the queue.
+    // The index is needed by update and is maintained by the heap.Interface methods.
+    index int // The index of the item in the heap.
+}
+
+// A PriorityQueue implements heap.Interface and holds Items.
+type PriorityQueue []*Item
+
+func (pq PriorityQueue) Len() int { return len(pq) }
+
+func (pq PriorityQueue) Less(i, j int) bool {
+    // We want Pop to give us the highest, not lowest, priority so we use greater than here.
+    return pq[i].priority > pq[j].priority
+}
+
+func (pq PriorityQueue) Swap(i, j int) {
+    pq[i], pq[j] = pq[j], pq[i]
+    pq[i].index = i
+    pq[j].index = j
+}
+
+func (pq *PriorityQueue) Push(x any) {
+    n := len(*pq)
+    item := x.(*Item)
+    item.index = n
+    *pq = append(*pq, item)
+}
+
+func (pq *PriorityQueue) Pop() any {
+    old := *pq
+    n := len(old)
+    item := old[n-1]
+    old[n-1] = nil  // avoid memory leak
+    item.index = -1 // for safety
+    *pq = old[0 : n-1]
+    return item
+}
+
+// update modifies the priority and value of an Item in the queue.
+func (pq *PriorityQueue) update(item *Item, value string, priority int) {
+    item.value = value
+    item.priority = priority
+    heap.Fix(pq, item.index)
+}
+
+// This example creates a PriorityQueue with some items, adds and manipulates an item,
+// and then removes the items in priority order.
+func Example_priorityQueue() {
+    // Some items and their priorities.
+    items := map[string]int{
+        "banana": 3, "apple": 2, "pear": 4,
+    }
+
+    // Create a priority queue, put the items in it, and
+    // establish the priority queue (heap) invariants.
+    pq := make(PriorityQueue, len(items))
+    i := 0
+    for value, priority := range items {
+        pq[i] = &Item{
+            value:    value,
+            priority: priority,
+            index:    i,
+        }
+        i++
+    }
+    heap.Init(&pq)
+
+    // Insert a new item and then modify its priority.
+    item := &Item{
+        value:    "orange",
+        priority: 1,
+    }
+    heap.Push(&pq, item)
+    pq.update(item, item.value, 5)
+
+    // Take the items out; they arrive in decreasing priority order.
+    for pq.Len() > 0 {
+        item := heap.Pop(&pq).(*Item)
+        fmt.Printf("%.2d:%s ", item.priority, item.value)
+    }
+    // Output:
+    // 05:orange 04:pear 03:banana 02:apple
+}
+

Index

Examples

Package (IntHeap)
Package (PriorityQueue)

Package files

heap.go

func Fix 1.2

func Fix(h Interface, i int)

Fix re-establishes the heap ordering after the element at index i has changed its value. Changing the value of the element at index i and then calling Fix is equivalent to, but less expensive than, calling Remove(h, i) followed by a Push of the new value. The complexity is O(log n) where n = h.Len().

+

func Init

func Init(h Interface)

Init establishes the heap invariants required by the other routines in this package. Init is idempotent with respect to the heap invariants and may be called whenever the heap invariants may have been invalidated. The complexity is O(n) where n = h.Len().

+

func Pop

func Pop(h Interface) any

Pop removes and returns the minimum element (according to Less) from the heap. The complexity is O(log n) where n = h.Len(). Pop is equivalent to Remove(h, 0).

+

func Push

func Push(h Interface, x any)

Push pushes the element x onto the heap. The complexity is O(log n) where n = h.Len().

+

func Remove

func Remove(h Interface, i int) any

Remove removes and returns the element at index i from the heap. The complexity is O(log n) where n = h.Len().

+

type Interface

The Interface type describes the requirements for a type using the routines in this package. Any type that implements it may be used as a min-heap with the following invariants (established after Init has been called or if the data is empty or sorted):

+
!h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len()
+

Note that Push and Pop in this interface are for package heap's implementation to call. To add and remove things from the heap, use heap.Push and heap.Pop.

+
type Interface interface {
+    sort.Interface
+    Push(x any) // add x as element Len()
+    Pop() any   // remove and return element Len() - 1.
+}
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/container/heap/ +

+
diff --git a/devdocs/go/container%2Flist%2Findex.html b/devdocs/go/container%2Flist%2Findex.html new file mode 100644 index 00000000..ba081a0e --- /dev/null +++ b/devdocs/go/container%2Flist%2Findex.html @@ -0,0 +1,100 @@ +

Package list

Overview

Package list implements a doubly linked list.

+

To iterate over a list (where l is a *List):

+
for e := l.Front(); e != nil; e = e.Next() {
+	// do something with e.Value
+}
+

Example +

Code:

// Create a new list and put some numbers in it.
+l := list.New()
+e4 := l.PushBack(4)
+e1 := l.PushFront(1)
+l.InsertBefore(3, e4)
+l.InsertAfter(2, e1)
+
+// Iterate through list and print its contents.
+for e := l.Front(); e != nil; e = e.Next() {
+    fmt.Println(e.Value)
+}
+
+

Output:

1
+2
+3
+4
+

Index

Examples

Package

Package files

list.go

type Element

Element is an element of a linked list.

+
type Element struct {
+
+    // The value stored with this element.
+    Value any
+    // contains filtered or unexported fields
+}
+

func (*Element) Next

func (e *Element) Next() *Element

Next returns the next list element or nil.

+

func (*Element) Prev

func (e *Element) Prev() *Element

Prev returns the previous list element or nil.

+

type List

List represents a doubly linked list. The zero value for List is an empty list ready to use.

+
type List struct {
+    // contains filtered or unexported fields
+}
+

func New

func New() *List

New returns an initialized list.

+

func (*List) Back

func (l *List) Back() *Element

Back returns the last element of list l or nil if the list is empty.

+

func (*List) Front

func (l *List) Front() *Element

Front returns the first element of list l or nil if the list is empty.

+

func (*List) Init

func (l *List) Init() *List

Init initializes or clears list l.

+

func (*List) InsertAfter

func (l *List) InsertAfter(v any, mark *Element) *Element

InsertAfter inserts a new element e with value v immediately after mark and returns e. If mark is not an element of l, the list is not modified. The mark must not be nil.

+

func (*List) InsertBefore

func (l *List) InsertBefore(v any, mark *Element) *Element

InsertBefore inserts a new element e with value v immediately before mark and returns e. If mark is not an element of l, the list is not modified. The mark must not be nil.

+

func (*List) Len

func (l *List) Len() int

Len returns the number of elements of list l. The complexity is O(1).

+

func (*List) MoveAfter 1.2

func (l *List) MoveAfter(e, mark *Element)

MoveAfter moves element e to its new position after mark. If e or mark is not an element of l, or e == mark, the list is not modified. The element and mark must not be nil.

+

func (*List) MoveBefore 1.2

func (l *List) MoveBefore(e, mark *Element)

MoveBefore moves element e to its new position before mark. If e or mark is not an element of l, or e == mark, the list is not modified. The element and mark must not be nil.

+

func (*List) MoveToBack

func (l *List) MoveToBack(e *Element)

MoveToBack moves element e to the back of list l. If e is not an element of l, the list is not modified. The element must not be nil.

+

func (*List) MoveToFront

func (l *List) MoveToFront(e *Element)

MoveToFront moves element e to the front of list l. If e is not an element of l, the list is not modified. The element must not be nil.

+

func (*List) PushBack

func (l *List) PushBack(v any) *Element

PushBack inserts a new element e with value v at the back of list l and returns e.

+

func (*List) PushBackList

func (l *List) PushBackList(other *List)

PushBackList inserts a copy of another list at the back of list l. The lists l and other may be the same. They must not be nil.

+

func (*List) PushFront

func (l *List) PushFront(v any) *Element

PushFront inserts a new element e with value v at the front of list l and returns e.

+

func (*List) PushFrontList

func (l *List) PushFrontList(other *List)

PushFrontList inserts a copy of another list at the front of list l. The lists l and other may be the same. They must not be nil.

+

func (*List) Remove

func (l *List) Remove(e *Element) any

Remove removes e from l if e is an element of list l. It returns the element value e.Value. The element must not be nil.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/container/list/ +

+
diff --git a/devdocs/go/container%2Fring%2Findex.html b/devdocs/go/container%2Fring%2Findex.html new file mode 100644 index 00000000..6abf62b0 --- /dev/null +++ b/devdocs/go/container%2Fring%2Findex.html @@ -0,0 +1,199 @@ +

Package ring

Overview

Package ring implements operations on circular lists.

Index

Examples

Ring.Do
Ring.Len
Ring.Link
Ring.Move
Ring.Next
Ring.Prev
Ring.Unlink

Package files

ring.go

type Ring

A Ring is an element of a circular list, or ring. Rings do not have a beginning or end; a pointer to any ring element serves as reference to the entire ring. Empty rings are represented as nil Ring pointers. The zero value for a Ring is a one-element ring with a nil Value.

+
type Ring struct {
+    Value any // for use by client; untouched by this library
+    // contains filtered or unexported fields
+}
+

func New

func New(n int) *Ring

New creates a ring of n elements.

+

func (*Ring) Do

func (r *Ring) Do(f func(any))

Do calls function f on each element of the ring, in forward order. The behavior of Do is undefined if f changes *r.

Example +

Code:

// Create a new ring of size 5
+r := ring.New(5)
+
+// Get the length of the ring
+n := r.Len()
+
+// Initialize the ring with some integer values
+for i := 0; i < n; i++ {
+    r.Value = i
+    r = r.Next()
+}
+
+// Iterate through the ring and print its contents
+r.Do(func(p any) {
+    fmt.Println(p.(int))
+})
+
+

Output:

0
+1
+2
+3
+4
+

func (*Ring) Len

func (r *Ring) Len() int

Len computes the number of elements in ring r. It executes in time proportional to the number of elements.

Example +

Code:

// Create a new ring of size 4
+r := ring.New(4)
+
+// Print out its length
+fmt.Println(r.Len())
+
+

Output:

4
+
func (r *Ring) Link(s *Ring) *Ring

Link connects ring r with ring s such that r.Next() becomes s and returns the original value for r.Next(). r must not be empty.

+

If r and s point to the same ring, linking them removes the elements between r and s from the ring. The removed elements form a subring and the result is a reference to that subring (if no elements were removed, the result is still the original value for r.Next(), and not nil).

+

If r and s point to different rings, linking them creates a single ring with the elements of s inserted after r. The result points to the element following the last element of s after insertion.

Code:

// Create two rings, r and s, of size 2
+r := ring.New(2)
+s := ring.New(2)
+
+// Get the length of the ring
+lr := r.Len()
+ls := s.Len()
+
+// Initialize r with 0s
+for i := 0; i < lr; i++ {
+    r.Value = 0
+    r = r.Next()
+}
+
+// Initialize s with 1s
+for j := 0; j < ls; j++ {
+    s.Value = 1
+    s = s.Next()
+}
+
+// Link ring r and ring s
+rs := r.Link(s)
+
+// Iterate through the combined ring and print its contents
+rs.Do(func(p any) {
+    fmt.Println(p.(int))
+})
+
+

Output:

0
+0
+1
+1
+

func (*Ring) Move

func (r *Ring) Move(n int) *Ring

Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0) in the ring and returns that ring element. r must not be empty.

Example +

Code:

// Create a new ring of size 5
+r := ring.New(5)
+
+// Get the length of the ring
+n := r.Len()
+
+// Initialize the ring with some integer values
+for i := 0; i < n; i++ {
+    r.Value = i
+    r = r.Next()
+}
+
+// Move the pointer forward by three steps
+r = r.Move(3)
+
+// Iterate through the ring and print its contents
+r.Do(func(p any) {
+    fmt.Println(p.(int))
+})
+
+

Output:

3
+4
+0
+1
+2
+

func (*Ring) Next

func (r *Ring) Next() *Ring

Next returns the next ring element. r must not be empty.

Example +

Code:

// Create a new ring of size 5
+r := ring.New(5)
+
+// Get the length of the ring
+n := r.Len()
+
+// Initialize the ring with some integer values
+for i := 0; i < n; i++ {
+    r.Value = i
+    r = r.Next()
+}
+
+// Iterate through the ring and print its contents
+for j := 0; j < n; j++ {
+    fmt.Println(r.Value)
+    r = r.Next()
+}
+
+

Output:

0
+1
+2
+3
+4
+

func (*Ring) Prev

func (r *Ring) Prev() *Ring

Prev returns the previous ring element. r must not be empty.

Example +

Code:

// Create a new ring of size 5
+r := ring.New(5)
+
+// Get the length of the ring
+n := r.Len()
+
+// Initialize the ring with some integer values
+for i := 0; i < n; i++ {
+    r.Value = i
+    r = r.Next()
+}
+
+// Iterate through the ring backwards and print its contents
+for j := 0; j < n; j++ {
+    r = r.Prev()
+    fmt.Println(r.Value)
+}
+
+

Output:

4
+3
+2
+1
+0
+
func (r *Ring) Unlink(n int) *Ring

Unlink removes n % r.Len() elements from the ring r, starting at r.Next(). If n % r.Len() == 0, r remains unchanged. The result is the removed subring. r must not be empty.

Code:

// Create a new ring of size 6
+r := ring.New(6)
+
+// Get the length of the ring
+n := r.Len()
+
+// Initialize the ring with some integer values
+for i := 0; i < n; i++ {
+    r.Value = i
+    r = r.Next()
+}
+
+// Unlink three elements from r, starting from r.Next()
+r.Unlink(3)
+
+// Iterate through the remaining ring and print its contents
+r.Do(func(p any) {
+    fmt.Println(p.(int))
+})
+
+

Output:

0
+4
+5
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/container/ring/ +

+
diff --git a/devdocs/go/context%2Findex.html b/devdocs/go/context%2Findex.html new file mode 100644 index 00000000..62f03ee1 --- /dev/null +++ b/devdocs/go/context%2Findex.html @@ -0,0 +1,381 @@ +

Package context

Overview

Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.

+

Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context. The chain of function calls between them must propagate the Context, optionally replacing it with a derived Context created using WithCancel, WithDeadline, WithTimeout, or WithValue. When a Context is canceled, all Contexts derived from it are also canceled.

+

The WithCancel, WithDeadline, and WithTimeout functions take a Context (the parent) and return a derived Context (the child) and a CancelFunc. Calling the CancelFunc cancels the child and its children, removes the parent's reference to the child, and stops any associated timers. Failing to call the CancelFunc leaks the child and its children until the parent is canceled or the timer fires. The go vet tool checks that CancelFuncs are used on all control-flow paths.

+

The WithCancelCause function returns a CancelCauseFunc, which takes an error and records it as the cancellation cause. Calling Cause on the canceled context or any of its children retrieves the cause. If no cause is specified, Cause(ctx) returns the same value as ctx.Err().

+

Programs that use Contexts should follow these rules to keep interfaces consistent across packages and enable static analysis tools to check context propagation:

+

Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx:

+
func DoSomething(ctx context.Context, arg Arg) error {
+	// ... use ctx ...
+}
+

Do not pass a nil Context, even if a function permits it. Pass context.TODO if you are unsure about which Context to use.

+

Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.

+

The same Context may be passed to functions running in different goroutines; Contexts are safe for simultaneous use by multiple goroutines.

+

See https://blog.golang.org/context for example code for a server that uses Contexts.

Index

Examples

AfterFunc (Cond)
AfterFunc (Connection)
AfterFunc (Merge)
WithCancel
WithDeadline
WithTimeout
WithValue

Package files

context.go

Variables

Canceled is the error returned by [Context.Err] when the context is canceled.

+
var Canceled = errors.New("context canceled")

DeadlineExceeded is the error returned by [Context.Err] when the context's deadline passes.

+
var DeadlineExceeded error = deadlineExceededError{}

func AfterFunc 1.21

func AfterFunc(ctx Context, f func()) (stop func() bool)

AfterFunc arranges to call f in its own goroutine after ctx is done (cancelled or timed out). If ctx is already done, AfterFunc calls f immediately in its own goroutine.

+

Multiple calls to AfterFunc on a context operate independently; one does not replace another.

+

Calling the returned stop function stops the association of ctx with f. It returns true if the call stopped f from being run. If stop returns false, either the context is done and f has been started in its own goroutine; or f was already stopped. The stop function does not wait for f to complete before returning. If the caller needs to know whether f is completed, it must coordinate with f explicitly.

+

If ctx has a "AfterFunc(func()) func() bool" method, AfterFunc will use it to schedule the call.

Example (Cond) +

This example uses AfterFunc to define a function which waits on a sync.Cond, stopping the wait when a context is canceled.

Code:

waitOnCond := func(ctx context.Context, cond *sync.Cond, conditionMet func() bool) error {
+    stopf := context.AfterFunc(ctx, func() {
+        // We need to acquire cond.L here to be sure that the Broadcast
+        // below won't occur before the call to Wait, which would result
+        // in a missed signal (and deadlock).
+        cond.L.Lock()
+        defer cond.L.Unlock()
+
+        // If multiple goroutines are waiting on cond simultaneously,
+        // we need to make sure we wake up exactly this one.
+        // That means that we need to Broadcast to all of the goroutines,
+        // which will wake them all up.
+        //
+        // If there are N concurrent calls to waitOnCond, each of the goroutines
+        // will spuriously wake up O(N) other goroutines that aren't ready yet,
+        // so this will cause the overall CPU cost to be O(N²).
+        cond.Broadcast()
+    })
+    defer stopf()
+
+    // Since the wakeups are using Broadcast instead of Signal, this call to
+    // Wait may unblock due to some other goroutine's context becoming done,
+    // so to be sure that ctx is actually done we need to check it in a loop.
+    for !conditionMet() {
+        cond.Wait()
+        if ctx.Err() != nil {
+            return ctx.Err()
+        }
+    }
+
+    return nil
+}
+
+cond := sync.NewCond(new(sync.Mutex))
+
+var wg sync.WaitGroup
+for i := 0; i < 4; i++ {
+    wg.Add(1)
+    go func() {
+        defer wg.Done()
+
+        ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
+        defer cancel()
+
+        cond.L.Lock()
+        defer cond.L.Unlock()
+
+        err := waitOnCond(ctx, cond, func() bool { return false })
+        fmt.Println(err)
+    }()
+}
+wg.Wait()
+
+

Output:

context deadline exceeded
+context deadline exceeded
+context deadline exceeded
+context deadline exceeded
+

Example (Connection) +

This example uses AfterFunc to define a function which reads from a net.Conn, stopping the read when a context is canceled.

Code:

readFromConn := func(ctx context.Context, conn net.Conn, b []byte) (n int, err error) {
+    stopc := make(chan struct{})
+    stop := context.AfterFunc(ctx, func() {
+        conn.SetReadDeadline(time.Now())
+        close(stopc)
+    })
+    n, err = conn.Read(b)
+    if !stop() {
+        // The AfterFunc was started.
+        // Wait for it to complete, and reset the Conn's deadline.
+        <-stopc
+        conn.SetReadDeadline(time.Time{})
+        return n, ctx.Err()
+    }
+    return n, err
+}
+
+listener, err := net.Listen("tcp", ":0")
+if err != nil {
+    fmt.Println(err)
+    return
+}
+defer listener.Close()
+
+conn, err := net.Dial(listener.Addr().Network(), listener.Addr().String())
+if err != nil {
+    fmt.Println(err)
+    return
+}
+defer conn.Close()
+
+ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
+defer cancel()
+
+b := make([]byte, 1024)
+_, err = readFromConn(ctx, conn, b)
+fmt.Println(err)
+
+

Output:

context deadline exceeded
+

Example (Merge) +

This example uses AfterFunc to define a function which combines the cancellation signals of two Contexts.

Code:

// mergeCancel returns a context that contains the values of ctx,
+// and which is canceled when either ctx or cancelCtx is canceled.
+mergeCancel := func(ctx, cancelCtx context.Context) (context.Context, context.CancelFunc) {
+    ctx, cancel := context.WithCancelCause(ctx)
+    stop := context.AfterFunc(cancelCtx, func() {
+        cancel(context.Cause(cancelCtx))
+    })
+    return ctx, func() {
+        stop()
+        cancel(context.Canceled)
+    }
+}
+
+ctx1, cancel1 := context.WithCancelCause(context.Background())
+defer cancel1(errors.New("ctx1 canceled"))
+
+ctx2, cancel2 := context.WithCancelCause(context.Background())
+
+mergedCtx, mergedCancel := mergeCancel(ctx1, ctx2)
+defer mergedCancel()
+
+cancel2(errors.New("ctx2 canceled"))
+<-mergedCtx.Done()
+fmt.Println(context.Cause(mergedCtx))
+
+

Output:

ctx2 canceled
+

func Cause 1.20

func Cause(c Context) error

Cause returns a non-nil error explaining why c was canceled. The first cancellation of c or one of its parents sets the cause. If that cancellation happened via a call to CancelCauseFunc(err), then Cause returns err. Otherwise Cause(c) returns the same value as c.Err(). Cause returns nil if c has not been canceled yet.

+

func WithCancel 1.7

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)

WithCancel returns a copy of parent with a new Done channel. The returned context's Done channel is closed when the returned cancel function is called or when the parent context's Done channel is closed, whichever happens first.

+

Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.

Example +

This example demonstrates the use of a cancelable context to prevent a goroutine leak. By the end of the example function, the goroutine started by gen will return without leaking.

Code:

// gen generates integers in a separate goroutine and
+// sends them to the returned channel.
+// The callers of gen need to cancel the context once
+// they are done consuming generated integers not to leak
+// the internal goroutine started by gen.
+gen := func(ctx context.Context) <-chan int {
+    dst := make(chan int)
+    n := 1
+    go func() {
+        for {
+            select {
+            case <-ctx.Done():
+                return // returning not to leak the goroutine
+            case dst <- n:
+                n++
+            }
+        }
+    }()
+    return dst
+}
+
+ctx, cancel := context.WithCancel(context.Background())
+defer cancel() // cancel when we are finished consuming integers
+
+for n := range gen(ctx) {
+    fmt.Println(n)
+    if n == 5 {
+        break
+    }
+}
+

Output:

1
+2
+3
+4
+5
+

func WithCancelCause 1.20

func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)

WithCancelCause behaves like WithCancel but returns a CancelCauseFunc instead of a CancelFunc. Calling cancel with a non-nil error (the "cause") records that error in ctx; it can then be retrieved using Cause(ctx). Calling cancel with nil sets the cause to Canceled.

+

Example use:

+
ctx, cancel := context.WithCancelCause(parent)
+cancel(myError)
+ctx.Err() // returns context.Canceled
+context.Cause(ctx) // returns myError
+

func WithDeadline 1.7

func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)

WithDeadline returns a copy of the parent context with the deadline adjusted to be no later than d. If the parent's deadline is already earlier than d, WithDeadline(parent, d) is semantically equivalent to parent. The returned [Context.Done] channel is closed when the deadline expires, when the returned cancel function is called, or when the parent context's Done channel is closed, whichever happens first.

+

Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.

Example +

This example passes a context with an arbitrary deadline to tell a blocking function that it should abandon its work as soon as it gets to it.

Code:

d := time.Now().Add(shortDuration)
+ctx, cancel := context.WithDeadline(context.Background(), d)
+
+// Even though ctx will be expired, it is good practice to call its
+// cancellation function in any case. Failure to do so may keep the
+// context and its parent alive longer than necessary.
+defer cancel()
+
+select {
+case <-neverReady:
+    fmt.Println("ready")
+case <-ctx.Done():
+    fmt.Println(ctx.Err())
+}
+
+

Output:

context deadline exceeded
+

func WithDeadlineCause 1.21

func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc)

WithDeadlineCause behaves like WithDeadline but also sets the cause of the returned Context when the deadline is exceeded. The returned CancelFunc does not set the cause.

+

func WithTimeout 1.7

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).

+

Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete:

+
func slowOperationWithTimeout(ctx context.Context) (Result, error) {
+	ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
+	defer cancel()  // releases resources if slowOperation completes before timeout elapses
+	return slowOperation(ctx)
+}
+

Example +

This example passes a context with a timeout to tell a blocking function that it should abandon its work after the timeout elapses.

Code:

// Pass a context with a timeout to tell a blocking function that it
+// should abandon its work after the timeout elapses.
+ctx, cancel := context.WithTimeout(context.Background(), shortDuration)
+defer cancel()
+
+select {
+case <-neverReady:
+    fmt.Println("ready")
+case <-ctx.Done():
+    fmt.Println(ctx.Err()) // prints "context deadline exceeded"
+}
+
+

Output:

context deadline exceeded
+

func WithTimeoutCause 1.21

func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)

WithTimeoutCause behaves like WithTimeout but also sets the cause of the returned Context when the timeout expires. The returned CancelFunc does not set the cause.

+

type CancelCauseFunc 1.20

A CancelCauseFunc behaves like a CancelFunc but additionally sets the cancellation cause. This cause can be retrieved by calling Cause on the canceled Context or on any of its derived Contexts.

+

If the context has already been canceled, CancelCauseFunc does not set the cause. For example, if childContext is derived from parentContext:

+
type CancelCauseFunc func(cause error)

type CancelFunc 1.7

A CancelFunc tells an operation to abandon its work. A CancelFunc does not wait for the work to stop. A CancelFunc may be called by multiple goroutines simultaneously. After the first call, subsequent calls to a CancelFunc do nothing.

+
type CancelFunc func()

type Context 1.7

A Context carries a deadline, a cancellation signal, and other values across API boundaries.

+

Context's methods may be called by multiple goroutines simultaneously.

+
type Context interface {
+    // Deadline returns the time when work done on behalf of this context
+    // should be canceled. Deadline returns ok==false when no deadline is
+    // set. Successive calls to Deadline return the same results.
+    Deadline() (deadline time.Time, ok bool)
+
+    // Done returns a channel that's closed when work done on behalf of this
+    // context should be canceled. Done may return nil if this context can
+    // never be canceled. Successive calls to Done return the same value.
+    // The close of the Done channel may happen asynchronously,
+    // after the cancel function returns.
+    //
+    // WithCancel arranges for Done to be closed when cancel is called;
+    // WithDeadline arranges for Done to be closed when the deadline
+    // expires; WithTimeout arranges for Done to be closed when the timeout
+    // elapses.
+    //
+    // Done is provided for use in select statements:
+    //
+    //  // Stream generates values with DoSomething and sends them to out
+    //  // until DoSomething returns an error or ctx.Done is closed.
+    //  func Stream(ctx context.Context, out chan<- Value) error {
+    //  	for {
+    //  		v, err := DoSomething(ctx)
+    //  		if err != nil {
+    //  			return err
+    //  		}
+    //  		select {
+    //  		case <-ctx.Done():
+    //  			return ctx.Err()
+    //  		case out <- v:
+    //  		}
+    //  	}
+    //  }
+    //
+    // See https://blog.golang.org/pipelines for more examples of how to use
+    // a Done channel for cancellation.
+    Done() <-chan struct{}
+
+    // If Done is not yet closed, Err returns nil.
+    // If Done is closed, Err returns a non-nil error explaining why:
+    // Canceled if the context was canceled
+    // or DeadlineExceeded if the context's deadline passed.
+    // After Err returns a non-nil error, successive calls to Err return the same error.
+    Err() error
+
+    // Value returns the value associated with this context for key, or nil
+    // if no value is associated with key. Successive calls to Value with
+    // the same key returns the same result.
+    //
+    // Use context values only for request-scoped data that transits
+    // processes and API boundaries, not for passing optional parameters to
+    // functions.
+    //
+    // A key identifies a specific value in a Context. Functions that wish
+    // to store values in Context typically allocate a key in a global
+    // variable then use that key as the argument to context.WithValue and
+    // Context.Value. A key can be any type that supports equality;
+    // packages should define keys as an unexported type to avoid
+    // collisions.
+    //
+    // Packages that define a Context key should provide type-safe accessors
+    // for the values stored using that key:
+    //
+    // 	// Package user defines a User type that's stored in Contexts.
+    // 	package user
+    //
+    // 	import "context"
+    //
+    // 	// User is the type of value stored in the Contexts.
+    // 	type User struct {...}
+    //
+    // 	// key is an unexported type for keys defined in this package.
+    // 	// This prevents collisions with keys defined in other packages.
+    // 	type key int
+    //
+    // 	// userKey is the key for user.User values in Contexts. It is
+    // 	// unexported; clients use user.NewContext and user.FromContext
+    // 	// instead of using this key directly.
+    // 	var userKey key
+    //
+    // 	// NewContext returns a new Context that carries value u.
+    // 	func NewContext(ctx context.Context, u *User) context.Context {
+    // 		return context.WithValue(ctx, userKey, u)
+    // 	}
+    //
+    // 	// FromContext returns the User value stored in ctx, if any.
+    // 	func FromContext(ctx context.Context) (*User, bool) {
+    // 		u, ok := ctx.Value(userKey).(*User)
+    // 		return u, ok
+    // 	}
+    Value(key any) any
+}

func Background 1.7

func Background() Context

Background returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline. It is typically used by the main function, initialization, and tests, and as the top-level Context for incoming requests.

+

func TODO 1.7

func TODO() Context

TODO returns a non-nil, empty Context. Code should use context.TODO when it's unclear which Context to use or it is not yet available (because the surrounding function has not yet been extended to accept a Context parameter).

+

func WithValue 1.7

func WithValue(parent Context, key, val any) Context

WithValue returns a copy of parent in which the value associated with key is val.

+

Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.

+

The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys. To avoid allocating when assigning to an interface{}, context keys often have concrete type struct{}. Alternatively, exported context key variables' static type should be a pointer or interface.

Example +

This example demonstrates how a value can be passed to the context and also how to retrieve it if it exists.

Code:

type favContextKey string
+
+f := func(ctx context.Context, k favContextKey) {
+    if v := ctx.Value(k); v != nil {
+        fmt.Println("found value:", v)
+        return
+    }
+    fmt.Println("key not found:", k)
+}
+
+k := favContextKey("language")
+ctx := context.WithValue(context.Background(), k, "Go")
+
+f(ctx, k)
+f(ctx, favContextKey("color"))
+
+

Output:

found value: Go
+key not found: color
+

func WithoutCancel 1.21

func WithoutCancel(parent Context) Context

WithoutCancel returns a copy of parent that is not canceled when parent is canceled. The returned context returns no Deadline or Err, and its Done channel is nil. Calling Cause on the returned context returns nil.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/context/ +

+
diff --git a/devdocs/go/crypto%2Faes%2Findex.html b/devdocs/go/crypto%2Faes%2Findex.html new file mode 100644 index 00000000..24507c43 --- /dev/null +++ b/devdocs/go/crypto%2Faes%2Findex.html @@ -0,0 +1,19 @@ +

Package aes

Overview

Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.

+

The AES operations in this package are not implemented using constant-time algorithms. An exception is when running on systems with enabled hardware support for AES that makes these operations constant-time. Examples include amd64 systems using AES-NI extensions and s390x systems using Message-Security-Assist extensions. On such systems, when the result of NewCipher is passed to cipher.NewGCM, the GHASH operation used by GCM is also constant-time.

Index

Package files

aes_gcm.go block.go cipher.go cipher_asm.go const.go modes.go

Constants

The AES block size in bytes.

+
const BlockSize = 16

func NewCipher

func NewCipher(key []byte) (cipher.Block, error)

NewCipher creates and returns a new cipher.Block. The key argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

+

type KeySizeError

type KeySizeError int

func (KeySizeError) Error

func (k KeySizeError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/aes/ +

+
diff --git a/devdocs/go/crypto%2Fboring%2Findex.html b/devdocs/go/crypto%2Fboring%2Findex.html new file mode 100644 index 00000000..ba809331 --- /dev/null +++ b/devdocs/go/crypto%2Fboring%2Findex.html @@ -0,0 +1,7 @@ +

Command boring

Package boring exposes functions that are only available when building with Go+BoringCrypto. This package is available on all targets as long as the Go+BoringCrypto toolchain is used. Use the Enabled function to determine whether the BoringCrypto core is actually in use.

+

Any time the Go+BoringCrypto toolchain is used, the "boringcrypto" build tag is satisfied, so that applications can tag files that use this package.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/boring/ +

+
diff --git a/devdocs/go/crypto%2Fcipher%2Findex.html b/devdocs/go/crypto%2Fcipher%2Findex.html new file mode 100644 index 00000000..4abc775c --- /dev/null +++ b/devdocs/go/crypto%2Fcipher%2Findex.html @@ -0,0 +1,463 @@ +

Package cipher

Overview

Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations. See https://csrc.nist.gov/groups/ST/toolkit/BCM/current_modes.html and NIST Special Publication 800-38A.

Index

Examples

NewCBCDecrypter
NewCBCEncrypter
NewCFBDecrypter
NewCFBEncrypter
NewCTR
NewGCM (Decrypt)
NewGCM (Encrypt)
NewOFB
StreamReader
StreamWriter

Package files

cbc.go cfb.go cipher.go ctr.go gcm.go io.go ofb.go

type AEAD 1.2

AEAD is a cipher mode providing authenticated encryption with associated data. For a description of the methodology, see https://en.wikipedia.org/wiki/Authenticated_encryption.

+
type AEAD interface {
+    // NonceSize returns the size of the nonce that must be passed to Seal
+    // and Open.
+    NonceSize() int
+
+    // Overhead returns the maximum difference between the lengths of a
+    // plaintext and its ciphertext.
+    Overhead() int
+
+    // Seal encrypts and authenticates plaintext, authenticates the
+    // additional data and appends the result to dst, returning the updated
+    // slice. The nonce must be NonceSize() bytes long and unique for all
+    // time, for a given key.
+    //
+    // To reuse plaintext's storage for the encrypted output, use plaintext[:0]
+    // as dst. Otherwise, the remaining capacity of dst must not overlap plaintext.
+    Seal(dst, nonce, plaintext, additionalData []byte) []byte
+
+    // Open decrypts and authenticates ciphertext, authenticates the
+    // additional data and, if successful, appends the resulting plaintext
+    // to dst, returning the updated slice. The nonce must be NonceSize()
+    // bytes long and both it and the additional data must match the
+    // value passed to Seal.
+    //
+    // To reuse ciphertext's storage for the decrypted output, use ciphertext[:0]
+    // as dst. Otherwise, the remaining capacity of dst must not overlap plaintext.
+    //
+    // Even if the function fails, the contents of dst, up to its capacity,
+    // may be overwritten.
+    Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
+}

func NewGCM 1.2

func NewGCM(cipher Block) (AEAD, error)

NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode with the standard nonce length.

+

In general, the GHASH operation performed by this implementation of GCM is not constant-time. An exception is when the underlying Block was created by aes.NewCipher on systems with hardware support for AES. See the crypto/aes package documentation for details.

Example (Decrypt) +

Code:

// Load your secret key from a safe place and reuse it across multiple
+// Seal/Open calls. (Obviously don't use this example key for anything
+// real.) If you want to convert a passphrase to a key, use a suitable
+// package like bcrypt or scrypt.
+// When decoded the key should be 16 bytes (AES-128) or 32 (AES-256).
+key, _ := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
+ciphertext, _ := hex.DecodeString("c3aaa29f002ca75870806e44086700f62ce4d43e902b3888e23ceff797a7a471")
+nonce, _ := hex.DecodeString("64a9433eae7ccceee2fc0eda")
+
+block, err := aes.NewCipher(key)
+if err != nil {
+    panic(err.Error())
+}
+
+aesgcm, err := cipher.NewGCM(block)
+if err != nil {
+    panic(err.Error())
+}
+
+plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
+if err != nil {
+    panic(err.Error())
+}
+
+fmt.Printf("%s\n", plaintext)
+

Output:

exampleplaintext
+

Example (Encrypt) +

Code:

+// Load your secret key from a safe place and reuse it across multiple
+// Seal/Open calls. (Obviously don't use this example key for anything
+// real.) If you want to convert a passphrase to a key, use a suitable
+// package like bcrypt or scrypt.
+// When decoded the key should be 16 bytes (AES-128) or 32 (AES-256).
+key, _ := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
+plaintext := []byte("exampleplaintext")
+
+block, err := aes.NewCipher(key)
+if err != nil {
+    panic(err.Error())
+}
+
+// Never use more than 2^32 random nonces with a given key because of the risk of a repeat.
+nonce := make([]byte, 12)
+if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
+    panic(err.Error())
+}
+
+aesgcm, err := cipher.NewGCM(block)
+if err != nil {
+    panic(err.Error())
+}
+
+ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
+fmt.Printf("%x\n", ciphertext)
+

func NewGCMWithNonceSize 1.5

func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error)

NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois Counter Mode, which accepts nonces of the given length. The length must not be zero.

+

Only use this function if you require compatibility with an existing cryptosystem that uses non-standard nonce lengths. All other users should use NewGCM, which is faster and more resistant to misuse.

+

func NewGCMWithTagSize 1.11

func NewGCMWithTagSize(cipher Block, tagSize int) (AEAD, error)

NewGCMWithTagSize returns the given 128-bit, block cipher wrapped in Galois Counter Mode, which generates tags with the given length.

+

Tag sizes between 12 and 16 bytes are allowed.

+

Only use this function if you require compatibility with an existing cryptosystem that uses non-standard tag lengths. All other users should use NewGCM, which is more resistant to misuse.

+

type Block

A Block represents an implementation of block cipher using a given key. It provides the capability to encrypt or decrypt individual blocks. The mode implementations extend that capability to streams of blocks.

+
type Block interface {
+    // BlockSize returns the cipher's block size.
+    BlockSize() int
+
+    // Encrypt encrypts the first block in src into dst.
+    // Dst and src must overlap entirely or not at all.
+    Encrypt(dst, src []byte)
+
+    // Decrypt decrypts the first block in src into dst.
+    // Dst and src must overlap entirely or not at all.
+    Decrypt(dst, src []byte)
+}

type BlockMode

A BlockMode represents a block cipher running in a block-based mode (CBC, ECB etc).

+
type BlockMode interface {
+    // BlockSize returns the mode's block size.
+    BlockSize() int
+
+    // CryptBlocks encrypts or decrypts a number of blocks. The length of
+    // src must be a multiple of the block size. Dst and src must overlap
+    // entirely or not at all.
+    //
+    // If len(dst) < len(src), CryptBlocks should panic. It is acceptable
+    // to pass a dst bigger than src, and in that case, CryptBlocks will
+    // only update dst[:len(src)] and will not touch the rest of dst.
+    //
+    // Multiple calls to CryptBlocks behave as if the concatenation of
+    // the src buffers was passed in a single run. That is, BlockMode
+    // maintains state and does not reset at each CryptBlocks call.
+    CryptBlocks(dst, src []byte)
+}

func NewCBCDecrypter

func NewCBCDecrypter(b Block, iv []byte) BlockMode

NewCBCDecrypter returns a BlockMode which decrypts in cipher block chaining mode, using the given Block. The length of iv must be the same as the Block's block size and must match the iv used to encrypt the data.

Example +

Code:

// Load your secret key from a safe place and reuse it across multiple
+// NewCipher calls. (Obviously don't use this example key for anything
+// real.) If you want to convert a passphrase to a key, use a suitable
+// package like bcrypt or scrypt.
+key, _ := hex.DecodeString("6368616e676520746869732070617373")
+ciphertext, _ := hex.DecodeString("73c86d43a9d700a253a96c85b0f6b03ac9792e0e757f869cca306bd3cba1c62b")
+
+block, err := aes.NewCipher(key)
+if err != nil {
+    panic(err)
+}
+
+// The IV needs to be unique, but not secure. Therefore it's common to
+// include it at the beginning of the ciphertext.
+if len(ciphertext) < aes.BlockSize {
+    panic("ciphertext too short")
+}
+iv := ciphertext[:aes.BlockSize]
+ciphertext = ciphertext[aes.BlockSize:]
+
+// CBC mode always works in whole blocks.
+if len(ciphertext)%aes.BlockSize != 0 {
+    panic("ciphertext is not a multiple of the block size")
+}
+
+mode := cipher.NewCBCDecrypter(block, iv)
+
+// CryptBlocks can work in-place if the two arguments are the same.
+mode.CryptBlocks(ciphertext, ciphertext)
+
+// If the original plaintext lengths are not a multiple of the block
+// size, padding would have to be added when encrypting, which would be
+// removed at this point. For an example, see
+// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. However, it's
+// critical to note that ciphertexts must be authenticated (i.e. by
+// using crypto/hmac) before being decrypted in order to avoid creating
+// a padding oracle.
+
+fmt.Printf("%s\n", ciphertext)
+

Output:

exampleplaintext
+

func NewCBCEncrypter

func NewCBCEncrypter(b Block, iv []byte) BlockMode

NewCBCEncrypter returns a BlockMode which encrypts in cipher block chaining mode, using the given Block. The length of iv must be the same as the Block's block size.

Example +

Code:

+// Load your secret key from a safe place and reuse it across multiple
+// NewCipher calls. (Obviously don't use this example key for anything
+// real.) If you want to convert a passphrase to a key, use a suitable
+// package like bcrypt or scrypt.
+key, _ := hex.DecodeString("6368616e676520746869732070617373")
+plaintext := []byte("exampleplaintext")
+
+// CBC mode works on blocks so plaintexts may need to be padded to the
+// next whole block. For an example of such padding, see
+// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. Here we'll
+// assume that the plaintext is already of the correct length.
+if len(plaintext)%aes.BlockSize != 0 {
+    panic("plaintext is not a multiple of the block size")
+}
+
+block, err := aes.NewCipher(key)
+if err != nil {
+    panic(err)
+}
+
+// The IV needs to be unique, but not secure. Therefore it's common to
+// include it at the beginning of the ciphertext.
+ciphertext := make([]byte, aes.BlockSize+len(plaintext))
+iv := ciphertext[:aes.BlockSize]
+if _, err := io.ReadFull(rand.Reader, iv); err != nil {
+    panic(err)
+}
+
+mode := cipher.NewCBCEncrypter(block, iv)
+mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
+
+// It's important to remember that ciphertexts must be authenticated
+// (i.e. by using crypto/hmac) as well as being encrypted in order to
+// be secure.
+
+fmt.Printf("%x\n", ciphertext)
+

type Stream

A Stream represents a stream cipher.

+
type Stream interface {
+    // XORKeyStream XORs each byte in the given slice with a byte from the
+    // cipher's key stream. Dst and src must overlap entirely or not at all.
+    //
+    // If len(dst) < len(src), XORKeyStream should panic. It is acceptable
+    // to pass a dst bigger than src, and in that case, XORKeyStream will
+    // only update dst[:len(src)] and will not touch the rest of dst.
+    //
+    // Multiple calls to XORKeyStream behave as if the concatenation of
+    // the src buffers was passed in a single run. That is, Stream
+    // maintains state and does not reset at each XORKeyStream call.
+    XORKeyStream(dst, src []byte)
+}

func NewCFBDecrypter

func NewCFBDecrypter(block Block, iv []byte) Stream

NewCFBDecrypter returns a Stream which decrypts with cipher feedback mode, using the given Block. The iv must be the same length as the Block's block size.

Example +

Code:

// Load your secret key from a safe place and reuse it across multiple
+// NewCipher calls. (Obviously don't use this example key for anything
+// real.) If you want to convert a passphrase to a key, use a suitable
+// package like bcrypt or scrypt.
+key, _ := hex.DecodeString("6368616e676520746869732070617373")
+ciphertext, _ := hex.DecodeString("7dd015f06bec7f1b8f6559dad89f4131da62261786845100056b353194ad")
+
+block, err := aes.NewCipher(key)
+if err != nil {
+    panic(err)
+}
+
+// The IV needs to be unique, but not secure. Therefore it's common to
+// include it at the beginning of the ciphertext.
+if len(ciphertext) < aes.BlockSize {
+    panic("ciphertext too short")
+}
+iv := ciphertext[:aes.BlockSize]
+ciphertext = ciphertext[aes.BlockSize:]
+
+stream := cipher.NewCFBDecrypter(block, iv)
+
+// XORKeyStream can work in-place if the two arguments are the same.
+stream.XORKeyStream(ciphertext, ciphertext)
+fmt.Printf("%s", ciphertext)
+

Output:

some plaintext
+

func NewCFBEncrypter

func NewCFBEncrypter(block Block, iv []byte) Stream

NewCFBEncrypter returns a Stream which encrypts with cipher feedback mode, using the given Block. The iv must be the same length as the Block's block size.

Example +

Code:

+// Load your secret key from a safe place and reuse it across multiple
+// NewCipher calls. (Obviously don't use this example key for anything
+// real.) If you want to convert a passphrase to a key, use a suitable
+// package like bcrypt or scrypt.
+key, _ := hex.DecodeString("6368616e676520746869732070617373")
+plaintext := []byte("some plaintext")
+
+block, err := aes.NewCipher(key)
+if err != nil {
+    panic(err)
+}
+
+// The IV needs to be unique, but not secure. Therefore it's common to
+// include it at the beginning of the ciphertext.
+ciphertext := make([]byte, aes.BlockSize+len(plaintext))
+iv := ciphertext[:aes.BlockSize]
+if _, err := io.ReadFull(rand.Reader, iv); err != nil {
+    panic(err)
+}
+
+stream := cipher.NewCFBEncrypter(block, iv)
+stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
+
+// It's important to remember that ciphertexts must be authenticated
+// (i.e. by using crypto/hmac) as well as being encrypted in order to
+// be secure.
+fmt.Printf("%x\n", ciphertext)
+

func NewCTR

func NewCTR(block Block, iv []byte) Stream

NewCTR returns a Stream which encrypts/decrypts using the given Block in counter mode. The length of iv must be the same as the Block's block size.

Example +

Code:

// Load your secret key from a safe place and reuse it across multiple
+// NewCipher calls. (Obviously don't use this example key for anything
+// real.) If you want to convert a passphrase to a key, use a suitable
+// package like bcrypt or scrypt.
+key, _ := hex.DecodeString("6368616e676520746869732070617373")
+plaintext := []byte("some plaintext")
+
+block, err := aes.NewCipher(key)
+if err != nil {
+    panic(err)
+}
+
+// The IV needs to be unique, but not secure. Therefore it's common to
+// include it at the beginning of the ciphertext.
+ciphertext := make([]byte, aes.BlockSize+len(plaintext))
+iv := ciphertext[:aes.BlockSize]
+if _, err := io.ReadFull(rand.Reader, iv); err != nil {
+    panic(err)
+}
+
+stream := cipher.NewCTR(block, iv)
+stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
+
+// It's important to remember that ciphertexts must be authenticated
+// (i.e. by using crypto/hmac) as well as being encrypted in order to
+// be secure.
+
+// CTR mode is the same for both encryption and decryption, so we can
+// also decrypt that ciphertext with NewCTR.
+
+plaintext2 := make([]byte, len(plaintext))
+stream = cipher.NewCTR(block, iv)
+stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:])
+
+fmt.Printf("%s\n", plaintext2)
+

Output:

some plaintext
+

func NewOFB

func NewOFB(b Block, iv []byte) Stream

NewOFB returns a Stream that encrypts or decrypts using the block cipher b in output feedback mode. The initialization vector iv's length must be equal to b's block size.

Example +

Code:

// Load your secret key from a safe place and reuse it across multiple
+// NewCipher calls. (Obviously don't use this example key for anything
+// real.) If you want to convert a passphrase to a key, use a suitable
+// package like bcrypt or scrypt.
+key, _ := hex.DecodeString("6368616e676520746869732070617373")
+plaintext := []byte("some plaintext")
+
+block, err := aes.NewCipher(key)
+if err != nil {
+    panic(err)
+}
+
+// The IV needs to be unique, but not secure. Therefore it's common to
+// include it at the beginning of the ciphertext.
+ciphertext := make([]byte, aes.BlockSize+len(plaintext))
+iv := ciphertext[:aes.BlockSize]
+if _, err := io.ReadFull(rand.Reader, iv); err != nil {
+    panic(err)
+}
+
+stream := cipher.NewOFB(block, iv)
+stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
+
+// It's important to remember that ciphertexts must be authenticated
+// (i.e. by using crypto/hmac) as well as being encrypted in order to
+// be secure.
+
+// OFB mode is the same for both encryption and decryption, so we can
+// also decrypt that ciphertext with NewOFB.
+
+plaintext2 := make([]byte, len(plaintext))
+stream = cipher.NewOFB(block, iv)
+stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:])
+
+fmt.Printf("%s\n", plaintext2)
+

Output:

some plaintext
+

type StreamReader

StreamReader wraps a Stream into an io.Reader. It calls XORKeyStream to process each slice of data which passes through.

+
type StreamReader struct {
+    S Stream
+    R io.Reader
+}
+

Example +

Code:

// Load your secret key from a safe place and reuse it across multiple
+// NewCipher calls. (Obviously don't use this example key for anything
+// real.) If you want to convert a passphrase to a key, use a suitable
+// package like bcrypt or scrypt.
+key, _ := hex.DecodeString("6368616e676520746869732070617373")
+
+encrypted, _ := hex.DecodeString("cf0495cc6f75dafc23948538e79904a9")
+bReader := bytes.NewReader(encrypted)
+
+block, err := aes.NewCipher(key)
+if err != nil {
+    panic(err)
+}
+
+// If the key is unique for each ciphertext, then it's ok to use a zero
+// IV.
+var iv [aes.BlockSize]byte
+stream := cipher.NewOFB(block, iv[:])
+
+reader := &cipher.StreamReader{S: stream, R: bReader}
+// Copy the input to the output stream, decrypting as we go.
+if _, err := io.Copy(os.Stdout, reader); err != nil {
+    panic(err)
+}
+
+// Note that this example is simplistic in that it omits any
+// authentication of the encrypted data. If you were actually to use
+// StreamReader in this manner, an attacker could flip arbitrary bits in
+// the output.
+
+

Output:

some secret text
+

func (StreamReader) Read

func (r StreamReader) Read(dst []byte) (n int, err error)

type StreamWriter

StreamWriter wraps a Stream into an io.Writer. It calls XORKeyStream to process each slice of data which passes through. If any StreamWriter.Write call returns short then the StreamWriter is out of sync and must be discarded. A StreamWriter has no internal buffering; StreamWriter.Close does not need to be called to flush write data.

+
type StreamWriter struct {
+    S   Stream
+    W   io.Writer
+    Err error // unused
+}
+

Example +

Code:

// Load your secret key from a safe place and reuse it across multiple
+// NewCipher calls. (Obviously don't use this example key for anything
+// real.) If you want to convert a passphrase to a key, use a suitable
+// package like bcrypt or scrypt.
+key, _ := hex.DecodeString("6368616e676520746869732070617373")
+
+bReader := bytes.NewReader([]byte("some secret text"))
+
+block, err := aes.NewCipher(key)
+if err != nil {
+    panic(err)
+}
+
+// If the key is unique for each ciphertext, then it's ok to use a zero
+// IV.
+var iv [aes.BlockSize]byte
+stream := cipher.NewOFB(block, iv[:])
+
+var out bytes.Buffer
+
+writer := &cipher.StreamWriter{S: stream, W: &out}
+// Copy the input to the output buffer, encrypting as we go.
+if _, err := io.Copy(writer, bReader); err != nil {
+    panic(err)
+}
+
+// Note that this example is simplistic in that it omits any
+// authentication of the encrypted data. If you were actually to use
+// StreamReader in this manner, an attacker could flip arbitrary bits in
+// the decrypted result.
+
+fmt.Printf("%x\n", out.Bytes())
+

Output:

cf0495cc6f75dafc23948538e79904a9
+

func (StreamWriter) Close

func (w StreamWriter) Close() error

Close closes the underlying Writer and returns its Close return value, if the Writer is also an io.Closer. Otherwise it returns nil.

+

func (StreamWriter) Write

func (w StreamWriter) Write(src []byte) (n int, err error)
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/cipher/ +

+
diff --git a/devdocs/go/crypto%2Fdes%2Findex.html b/devdocs/go/crypto%2Fdes%2Findex.html new file mode 100644 index 00000000..1a7845ae --- /dev/null +++ b/devdocs/go/crypto%2Fdes%2Findex.html @@ -0,0 +1,38 @@ +

Package des

Overview

Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3.

+

DES is cryptographically broken and should not be used for secure applications.

Index

Examples

NewTripleDESCipher

Package files

block.go cipher.go const.go

Constants

The DES block size in bytes.

+
const BlockSize = 8

func NewCipher

func NewCipher(key []byte) (cipher.Block, error)

NewCipher creates and returns a new cipher.Block.

+

func NewTripleDESCipher

func NewTripleDESCipher(key []byte) (cipher.Block, error)

NewTripleDESCipher creates and returns a new cipher.Block.

Example +

Code:

+// NewTripleDESCipher can also be used when EDE2 is required by
+// duplicating the first 8 bytes of the 16-byte key.
+ede2Key := []byte("example key 1234")
+
+var tripleDESKey []byte
+tripleDESKey = append(tripleDESKey, ede2Key[:16]...)
+tripleDESKey = append(tripleDESKey, ede2Key[:8]...)
+
+_, err := des.NewTripleDESCipher(tripleDESKey)
+if err != nil {
+    panic(err)
+}
+
+// See crypto/cipher for how to use a cipher.Block for encryption and
+// decryption.
+

type KeySizeError

type KeySizeError int

func (KeySizeError) Error

func (k KeySizeError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/des/ +

+
diff --git a/devdocs/go/crypto%2Fdsa%2Findex.html b/devdocs/go/crypto%2Fdsa%2Findex.html new file mode 100644 index 00000000..2be6caf1 --- /dev/null +++ b/devdocs/go/crypto%2Fdsa%2Findex.html @@ -0,0 +1,50 @@ +

Package dsa

Overview

Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.

+

The DSA operations in this package are not implemented using constant-time algorithms.

+

Deprecated: DSA is a legacy algorithm, and modern alternatives such as Ed25519 (implemented by package crypto/ed25519) should be used instead. Keys with 1024-bit moduli (L1024N160 parameters) are cryptographically weak, while bigger keys are not widely supported. Note that FIPS 186-5 no longer approves DSA for signature generation.

Index

Package files

dsa.go

Variables

ErrInvalidPublicKey results when a public key is not usable by this code. FIPS is quite strict about the format of DSA keys, but other code may be less so. Thus, when using keys which may have been generated by other code, this error must be handled.

+
var ErrInvalidPublicKey = errors.New("crypto/dsa: invalid public key")

func GenerateKey

func GenerateKey(priv *PrivateKey, rand io.Reader) error

GenerateKey generates a public&private key pair. The Parameters of the PrivateKey must already be valid (see GenerateParameters).

+

func GenerateParameters

func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) error

GenerateParameters puts a random, valid set of DSA parameters into params. This function can take many seconds, even on fast machines.

+

func Sign

func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)

Sign signs an arbitrary length hash (which should be the result of hashing a larger message) using the private key, priv. It returns the signature as a pair of integers. The security of the private key depends on the entropy of rand.

+

Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated to the byte-length of the subgroup. This function does not perform that truncation itself.

+

Be aware that calling Sign with an attacker-controlled PrivateKey may require an arbitrary amount of CPU.

+

func Verify

func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool

Verify verifies the signature in r, s of hash using the public key, pub. It reports whether the signature is valid.

+

Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated to the byte-length of the subgroup. This function does not perform that truncation itself.

+

type ParameterSizes

ParameterSizes is an enumeration of the acceptable bit lengths of the primes in a set of DSA parameters. See FIPS 186-3, section 4.2.

+
type ParameterSizes int
const (
+    L1024N160 ParameterSizes = iota
+    L2048N224
+    L2048N256
+    L3072N256
+)

type Parameters

Parameters represents the domain parameters for a key. These parameters can be shared across many keys. The bit length of Q must be a multiple of 8.

+
type Parameters struct {
+    P, Q, G *big.Int
+}
+

type PrivateKey

PrivateKey represents a DSA private key.

+
type PrivateKey struct {
+    PublicKey
+    X *big.Int
+}
+

type PublicKey

PublicKey represents a DSA public key.

+
type PublicKey struct {
+    Parameters
+    Y *big.Int
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/dsa/ +

+
diff --git a/devdocs/go/crypto%2Fecdh%2Findex.html b/devdocs/go/crypto%2Fecdh%2Findex.html new file mode 100644 index 00000000..162cc854 --- /dev/null +++ b/devdocs/go/crypto%2Fecdh%2Findex.html @@ -0,0 +1,98 @@ +

Package ecdh

Overview

Package ecdh implements Elliptic Curve Diffie-Hellman over NIST curves and Curve25519.

Index

Package files

ecdh.go nist.go x25519.go

type Curve 1.20

type Curve interface {
+    // GenerateKey generates a random PrivateKey.
+    //
+    // Most applications should use [crypto/rand.Reader] as rand. Note that the
+    // returned key does not depend deterministically on the bytes read from rand,
+    // and may change between calls and/or between versions.
+    GenerateKey(rand io.Reader) (*PrivateKey, error)
+
+    // NewPrivateKey checks that key is valid and returns a PrivateKey.
+    //
+    // For NIST curves, this follows SEC 1, Version 2.0, Section 2.3.6, which
+    // amounts to decoding the bytes as a fixed length big endian integer and
+    // checking that the result is lower than the order of the curve. The zero
+    // private key is also rejected, as the encoding of the corresponding public
+    // key would be irregular.
+    //
+    // For X25519, this only checks the scalar length.
+    NewPrivateKey(key []byte) (*PrivateKey, error)
+
+    // NewPublicKey checks that key is valid and returns a PublicKey.
+    //
+    // For NIST curves, this decodes an uncompressed point according to SEC 1,
+    // Version 2.0, Section 2.3.4. Compressed encodings and the point at
+    // infinity are rejected.
+    //
+    // For X25519, this only checks the u-coordinate length. Adversarially
+    // selected public keys can cause ECDH to return an error.
+    NewPublicKey(key []byte) (*PublicKey, error)
+    // contains filtered or unexported methods
+}

func P256 1.20

func P256() Curve

P256 returns a Curve which implements NIST P-256 (FIPS 186-3, section D.2.3), also known as secp256r1 or prime256v1.

+

Multiple invocations of this function will return the same value, which can be used for equality checks and switch statements.

+

func P384 1.20

func P384() Curve

P384 returns a Curve which implements NIST P-384 (FIPS 186-3, section D.2.4), also known as secp384r1.

+

Multiple invocations of this function will return the same value, which can be used for equality checks and switch statements.

+

func P521 1.20

func P521() Curve

P521 returns a Curve which implements NIST P-521 (FIPS 186-3, section D.2.5), also known as secp521r1.

+

Multiple invocations of this function will return the same value, which can be used for equality checks and switch statements.

+

func X25519 1.20

func X25519() Curve

X25519 returns a Curve which implements the X25519 function over Curve25519 (RFC 7748, Section 5).

+

Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

+

type PrivateKey 1.20

PrivateKey is an ECDH private key, usually kept secret.

+

These keys can be parsed with crypto/x509.ParsePKCS8PrivateKey and encoded with crypto/x509.MarshalPKCS8PrivateKey. For NIST curves, they then need to be converted with crypto/ecdsa.PrivateKey.ECDH after parsing.

+
type PrivateKey struct {
+    // contains filtered or unexported fields
+}
+

func (*PrivateKey) Bytes 1.20

func (k *PrivateKey) Bytes() []byte

Bytes returns a copy of the encoding of the private key.

+

func (*PrivateKey) Curve 1.20

func (k *PrivateKey) Curve() Curve

func (*PrivateKey) ECDH 1.20

func (k *PrivateKey) ECDH(remote *PublicKey) ([]byte, error)

ECDH performs an ECDH exchange and returns the shared secret. The PrivateKey and PublicKey must use the same curve.

+

For NIST curves, this performs ECDH as specified in SEC 1, Version 2.0, Section 3.3.1, and returns the x-coordinate encoded according to SEC 1, Version 2.0, Section 2.3.5. The result is never the point at infinity.

+

For X25519, this performs ECDH as specified in RFC 7748, Section 6.1. If the result is the all-zero value, ECDH returns an error.

+

func (*PrivateKey) Equal 1.20

func (k *PrivateKey) Equal(x crypto.PrivateKey) bool

Equal returns whether x represents the same private key as k.

+

Note that there can be equivalent private keys with different encodings which would return false from this check but behave the same way as inputs to [ECDH].

+

This check is performed in constant time as long as the key types and their curve match.

+

func (*PrivateKey) Public 1.20

func (k *PrivateKey) Public() crypto.PublicKey

Public implements the implicit interface of all standard library private keys. See the docs of crypto.PrivateKey.

+

func (*PrivateKey) PublicKey 1.20

func (k *PrivateKey) PublicKey() *PublicKey

type PublicKey 1.20

PublicKey is an ECDH public key, usually a peer's ECDH share sent over the wire.

+

These keys can be parsed with crypto/x509.ParsePKIXPublicKey and encoded with crypto/x509.MarshalPKIXPublicKey. For NIST curves, they then need to be converted with crypto/ecdsa.PublicKey.ECDH after parsing.

+
type PublicKey struct {
+    // contains filtered or unexported fields
+}
+

func (*PublicKey) Bytes 1.20

func (k *PublicKey) Bytes() []byte

Bytes returns a copy of the encoding of the public key.

+

func (*PublicKey) Curve 1.20

func (k *PublicKey) Curve() Curve

func (*PublicKey) Equal 1.20

func (k *PublicKey) Equal(x crypto.PublicKey) bool

Equal returns whether x represents the same public key as k.

+

Note that there can be equivalent public keys with different encodings which would return false from this check but behave the same way as inputs to ECDH.

+

This check is performed in constant time as long as the key types and their curve match.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/ecdh/ +

+
diff --git a/devdocs/go/crypto%2Fecdsa%2Findex.html b/devdocs/go/crypto%2Fecdsa%2Findex.html new file mode 100644 index 00000000..712672fb --- /dev/null +++ b/devdocs/go/crypto%2Fecdsa%2Findex.html @@ -0,0 +1,76 @@ +

Package ecdsa

Overview

Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-4 and SEC 1, Version 2.0.

+

Signatures generated by this package are not deterministic, but entropy is mixed with the private key and the message, achieving the same level of security in case of randomness source failure.

Example +

Code:

+privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+if err != nil {
+    panic(err)
+}
+
+msg := "hello, world"
+hash := sha256.Sum256([]byte(msg))
+
+sig, err := ecdsa.SignASN1(rand.Reader, privateKey, hash[:])
+if err != nil {
+    panic(err)
+}
+fmt.Printf("signature: %x\n", sig)
+
+valid := ecdsa.VerifyASN1(&privateKey.PublicKey, hash[:], sig)
+fmt.Println("signature verified:", valid)
+

Index

Examples

Package

Package files

ecdsa.go ecdsa_legacy.go ecdsa_noasm.go notboring.go

func Sign

func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)

Sign signs a hash (which should be the result of hashing a larger message) using the private key, priv. If the hash is longer than the bit-length of the private key's curve order, the hash will be truncated to that length. It returns the signature as a pair of integers. Most applications should use SignASN1 instead of dealing directly with r, s.

+

func SignASN1 1.15

func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error)

SignASN1 signs a hash (which should be the result of hashing a larger message) using the private key, priv. If the hash is longer than the bit-length of the private key's curve order, the hash will be truncated to that length. It returns the ASN.1 encoded signature.

+

The signature is randomized. Most applications should use crypto/rand.Reader as rand. Note that the returned signature does not depend deterministically on the bytes read from rand, and may change between calls and/or between versions.

+

func Verify

func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool

Verify verifies the signature in r, s of hash using the public key, pub. Its return value records whether the signature is valid. Most applications should use VerifyASN1 instead of dealing directly with r, s.

+

func VerifyASN1 1.15

func VerifyASN1(pub *PublicKey, hash, sig []byte) bool

VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the public key, pub. Its return value records whether the signature is valid.

+

type PrivateKey

PrivateKey represents an ECDSA private key.

+
type PrivateKey struct {
+    PublicKey
+    D *big.Int
+}
+

func GenerateKey

func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error)

GenerateKey generates a new ECDSA private key for the specified curve.

+

Most applications should use crypto/rand.Reader as rand. Note that the returned key does not depend deterministically on the bytes read from rand, and may change between calls and/or between versions.

+

func (*PrivateKey) ECDH 1.20

func (k *PrivateKey) ECDH() (*ecdh.PrivateKey, error)

ECDH returns k as a ecdh.PrivateKey. It returns an error if the key is invalid according to the definition of ecdh.Curve.NewPrivateKey, or if the Curve is not supported by crypto/ecdh.

+

func (*PrivateKey) Equal 1.15

func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool

Equal reports whether priv and x have the same value.

+

See PublicKey.Equal for details on how Curve is compared.

+

func (*PrivateKey) Public 1.4

func (priv *PrivateKey) Public() crypto.PublicKey

Public returns the public key corresponding to priv.

+

func (*PrivateKey) Sign 1.4

func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)

Sign signs digest with priv, reading randomness from rand. The opts argument is not currently used but, in keeping with the crypto.Signer interface, should be the hash function used to digest the message.

+

This method implements crypto.Signer, which is an interface to support keys where the private part is kept in, for example, a hardware module. Common uses can use the SignASN1 function in this package directly.

+

type PublicKey

PublicKey represents an ECDSA public key.

+
type PublicKey struct {
+    elliptic.Curve
+    X, Y *big.Int
+}
+

func (*PublicKey) ECDH 1.20

func (k *PublicKey) ECDH() (*ecdh.PublicKey, error)

ECDH returns k as a ecdh.PublicKey. It returns an error if the key is invalid according to the definition of ecdh.Curve.NewPublicKey, or if the Curve is not supported by crypto/ecdh.

+

func (*PublicKey) Equal 1.15

func (pub *PublicKey) Equal(x crypto.PublicKey) bool

Equal reports whether pub and x have the same value.

+

Two keys are only considered to have the same value if they have the same Curve value. Note that for example elliptic.P256 and elliptic.P256().Params() are different values, as the latter is a generic not constant time implementation.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/ecdsa/ +

+
diff --git a/devdocs/go/crypto%2Fed25519%2Findex.html b/devdocs/go/crypto%2Fed25519%2Findex.html new file mode 100644 index 00000000..0a2ce4fa --- /dev/null +++ b/devdocs/go/crypto%2Fed25519%2Findex.html @@ -0,0 +1,90 @@ +

Package ed25519

Overview

Package ed25519 implements the Ed25519 signature algorithm. See https://ed25519.cr.yp.to/.

+

These functions are also compatible with the “Ed25519” function defined in RFC 8032. However, unlike RFC 8032's formulation, this package's private key representation includes a public key suffix to make multiple signing operations with the same key more efficient. This package refers to the RFC 8032 private key as the “seed”.

Example (Ed25519ctx) +

Code:

+pub, priv, err := GenerateKey(nil)
+if err != nil {
+    log.Fatal(err)
+}
+
+msg := []byte("The quick brown fox jumps over the lazy dog")
+
+sig, err := priv.Sign(nil, msg, &Options{
+    Context: "Example_ed25519ctx",
+})
+if err != nil {
+    log.Fatal(err)
+}
+
+if err := VerifyWithOptions(pub, msg, sig, &Options{
+    Context: "Example_ed25519ctx",
+}); err != nil {
+    log.Fatal("invalid signature")
+}
+

Index

Examples

Package (Ed25519ctx)

Package files

ed25519.go

Constants

const (
+    // PublicKeySize is the size, in bytes, of public keys as used in this package.
+    PublicKeySize = 32
+    // PrivateKeySize is the size, in bytes, of private keys as used in this package.
+    PrivateKeySize = 64
+    // SignatureSize is the size, in bytes, of signatures generated and verified by this package.
+    SignatureSize = 64
+    // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032.
+    SeedSize = 32
+)

func GenerateKey 1.13

func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error)

GenerateKey generates a public/private key pair using entropy from rand. If rand is nil, crypto/rand.Reader will be used.

+

The output of this function is deterministic, and equivalent to reading SeedSize bytes from rand, and passing them to NewKeyFromSeed.

+

func Sign 1.13

func Sign(privateKey PrivateKey, message []byte) []byte

Sign signs the message with privateKey and returns a signature. It will panic if len(privateKey) is not PrivateKeySize.

+

func Verify 1.13

func Verify(publicKey PublicKey, message, sig []byte) bool

Verify reports whether sig is a valid signature of message by publicKey. It will panic if len(publicKey) is not PublicKeySize.

+

func VerifyWithOptions 1.20

func VerifyWithOptions(publicKey PublicKey, message, sig []byte, opts *Options) error

VerifyWithOptions reports whether sig is a valid signature of message by publicKey. A valid signature is indicated by returning a nil error. It will panic if len(publicKey) is not PublicKeySize.

+

If opts.Hash is crypto.SHA512, the pre-hashed variant Ed25519ph is used and message is expected to be a SHA-512 hash, otherwise opts.Hash must be crypto.Hash(0) and the message must not be hashed, as Ed25519 performs two passes over messages to be signed.

+

type Options 1.20

Options can be used with PrivateKey.Sign or VerifyWithOptions to select Ed25519 variants.

+
type Options struct {
+    // Hash can be zero for regular Ed25519, or crypto.SHA512 for Ed25519ph.
+    Hash crypto.Hash
+
+    // Context, if not empty, selects Ed25519ctx or provides the context string
+    // for Ed25519ph. It can be at most 255 bytes in length.
+    Context string
+}
+

func (*Options) HashFunc 1.20

func (o *Options) HashFunc() crypto.Hash

HashFunc returns o.Hash.

+

type PrivateKey 1.13

PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer.

+
type PrivateKey []byte

func NewKeyFromSeed 1.13

func NewKeyFromSeed(seed []byte) PrivateKey

NewKeyFromSeed calculates a private key from a seed. It will panic if len(seed) is not SeedSize. This function is provided for interoperability with RFC 8032. RFC 8032's private keys correspond to seeds in this package.

+

func (PrivateKey) Equal 1.15

func (priv PrivateKey) Equal(x crypto.PrivateKey) bool

Equal reports whether priv and x have the same value.

+

func (PrivateKey) Public 1.13

func (priv PrivateKey) Public() crypto.PublicKey

Public returns the PublicKey corresponding to priv.

+

func (PrivateKey) Seed 1.13

func (priv PrivateKey) Seed() []byte

Seed returns the private key seed corresponding to priv. It is provided for interoperability with RFC 8032. RFC 8032's private keys correspond to seeds in this package.

+

func (PrivateKey) Sign 1.13

func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error)

Sign signs the given message with priv. rand is ignored and can be nil.

+

If opts.HashFunc() is crypto.SHA512, the pre-hashed variant Ed25519ph is used and message is expected to be a SHA-512 hash, otherwise opts.HashFunc() must be crypto.Hash(0) and the message must not be hashed, as Ed25519 performs two passes over messages to be signed.

+

A value of type Options can be used as opts, or crypto.Hash(0) or crypto.SHA512 directly to select plain Ed25519 or Ed25519ph, respectively.

+

type PublicKey 1.13

PublicKey is the type of Ed25519 public keys.

+
type PublicKey []byte

func (PublicKey) Equal 1.15

func (pub PublicKey) Equal(x crypto.PublicKey) bool

Equal reports whether pub and x have the same value.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/ed25519/ +

+
diff --git a/devdocs/go/crypto%2Felliptic%2Findex.html b/devdocs/go/crypto%2Felliptic%2Findex.html new file mode 100644 index 00000000..496c473a --- /dev/null +++ b/devdocs/go/crypto%2Felliptic%2Findex.html @@ -0,0 +1,117 @@ +

Package elliptic

Overview

Package elliptic implements the standard NIST P-224, P-256, P-384, and P-521 elliptic curves over prime fields.

+

Direct use of this package is deprecated, beyond the P224, P256, P384, and P521 values necessary to use crypto/ecdsa. Most other uses should migrate to the more efficient and safer crypto/ecdh, or to third-party modules for lower-level functionality.

Index

Package files

elliptic.go nistec.go nistec_p256.go params.go

func GenerateKey

func GenerateKey(curve Curve, rand io.Reader) (priv []byte, x, y *big.Int, err error)

GenerateKey returns a public/private key pair. The private key is generated using the given reader, which must return random data.

+

Deprecated: for ECDH, use the GenerateKey methods of the crypto/ecdh package; for ECDSA, use the GenerateKey function of the crypto/ecdsa package.

+

func Marshal

func Marshal(curve Curve, x, y *big.Int) []byte

Marshal converts a point on the curve into the uncompressed form specified in SEC 1, Version 2.0, Section 2.3.3. If the point is not on the curve (or is the conventional point at infinity), the behavior is undefined.

+

Deprecated: for ECDH, use the crypto/ecdh package. This function returns an encoding equivalent to that of PublicKey.Bytes in crypto/ecdh.

+

func MarshalCompressed 1.15

func MarshalCompressed(curve Curve, x, y *big.Int) []byte

MarshalCompressed converts a point on the curve into the compressed form specified in SEC 1, Version 2.0, Section 2.3.3. If the point is not on the curve (or is the conventional point at infinity), the behavior is undefined.

+

func Unmarshal

func Unmarshal(curve Curve, data []byte) (x, y *big.Int)

Unmarshal converts a point, serialized by Marshal, into an x, y pair. It is an error if the point is not in uncompressed form, is not on the curve, or is the point at infinity. On error, x = nil.

+

Deprecated: for ECDH, use the crypto/ecdh package. This function accepts an encoding equivalent to that of the NewPublicKey methods in crypto/ecdh.

+

func UnmarshalCompressed 1.15

func UnmarshalCompressed(curve Curve, data []byte) (x, y *big.Int)

UnmarshalCompressed converts a point, serialized by MarshalCompressed, into an x, y pair. It is an error if the point is not in compressed form, is not on the curve, or is the point at infinity. On error, x = nil.

+

type Curve

A Curve represents a short-form Weierstrass curve with a=-3.

+

The behavior of Add, Double, and ScalarMult when the input is not a point on the curve is undefined.

+

Note that the conventional point at infinity (0, 0) is not considered on the curve, although it can be returned by Add, Double, ScalarMult, or ScalarBaseMult (but not the Unmarshal or UnmarshalCompressed functions).

+

Using Curve implementations besides those returned by P224, P256, P384, and P521 is deprecated.

+
type Curve interface {
+    // Params returns the parameters for the curve.
+    Params() *CurveParams
+
+    // IsOnCurve reports whether the given (x,y) lies on the curve.
+    //
+    // Deprecated: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
+    // package. The NewPublicKey methods of NIST curves in crypto/ecdh accept
+    // the same encoding as the Unmarshal function, and perform on-curve checks.
+    IsOnCurve(x, y *big.Int) bool
+
+    // Add returns the sum of (x1,y1) and (x2,y2).
+    //
+    // Deprecated: this is a low-level unsafe API.
+    Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int)
+
+    // Double returns 2*(x,y).
+    //
+    // Deprecated: this is a low-level unsafe API.
+    Double(x1, y1 *big.Int) (x, y *big.Int)
+
+    // ScalarMult returns k*(x,y) where k is an integer in big-endian form.
+    //
+    // Deprecated: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
+    // package. Most uses of ScalarMult can be replaced by a call to the ECDH
+    // methods of NIST curves in crypto/ecdh.
+    ScalarMult(x1, y1 *big.Int, k []byte) (x, y *big.Int)
+
+    // ScalarBaseMult returns k*G, where G is the base point of the group
+    // and k is an integer in big-endian form.
+    //
+    // Deprecated: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
+    // package. Most uses of ScalarBaseMult can be replaced by a call to the
+    // PrivateKey.PublicKey method in crypto/ecdh.
+    ScalarBaseMult(k []byte) (x, y *big.Int)
+}

func P224

func P224() Curve

P224 returns a Curve which implements NIST P-224 (FIPS 186-3, section D.2.2), also known as secp224r1. The CurveParams.Name of this Curve is "P-224".

+

Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

+

The cryptographic operations are implemented using constant-time algorithms.

+

func P256

func P256() Curve

P256 returns a Curve which implements NIST P-256 (FIPS 186-3, section D.2.3), also known as secp256r1 or prime256v1. The CurveParams.Name of this Curve is "P-256".

+

Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

+

The cryptographic operations are implemented using constant-time algorithms.

+

func P384

func P384() Curve

P384 returns a Curve which implements NIST P-384 (FIPS 186-3, section D.2.4), also known as secp384r1. The CurveParams.Name of this Curve is "P-384".

+

Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

+

The cryptographic operations are implemented using constant-time algorithms.

+

func P521

func P521() Curve

P521 returns a Curve which implements NIST P-521 (FIPS 186-3, section D.2.5), also known as secp521r1. The CurveParams.Name of this Curve is "P-521".

+

Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

+

The cryptographic operations are implemented using constant-time algorithms.

+

type CurveParams

CurveParams contains the parameters of an elliptic curve and also provides a generic, non-constant time implementation of Curve.

+

The generic Curve implementation is deprecated, and using custom curves (those not returned by P224, P256, P384, and P521) is not guaranteed to provide any security property.

+
type CurveParams struct {
+    P       *big.Int // the order of the underlying field
+    N       *big.Int // the order of the base point
+    B       *big.Int // the constant of the curve equation
+    Gx, Gy  *big.Int // (x,y) of the base point
+    BitSize int      // the size of the underlying field
+    Name    string   // the canonical name of the curve; added in Go 1.5
+}
+

func (*CurveParams) Add

func (curve *CurveParams) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int)

Add implements [Curve.Add].

+

Deprecated: the CurveParams methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224, P256, P384, or P521.

+

func (*CurveParams) Double

func (curve *CurveParams) Double(x1, y1 *big.Int) (*big.Int, *big.Int)

Double implements [Curve.Double].

+

Deprecated: the [CurveParams】 methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224, P256, P384, or P521.

+

func (*CurveParams) IsOnCurve

func (curve *CurveParams) IsOnCurve(x, y *big.Int) bool

IsOnCurve implements [Curve.IsOnCurve].

+

Deprecated: the CurveParams methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224, P256, P384, or P521.

+

func (*CurveParams) Params

func (curve *CurveParams) Params() *CurveParams

func (*CurveParams) ScalarBaseMult

func (curve *CurveParams) ScalarBaseMult(k []byte) (*big.Int, *big.Int)

ScalarBaseMult implements [Curve.ScalarBaseMult].

+

Deprecated: the CurveParams methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224, P256, P384, or P521.

+

func (*CurveParams) ScalarMult

func (curve *CurveParams) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int)

ScalarMult implements [Curve.ScalarMult].

+

Deprecated: the CurveParams methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224, P256, P384, or P521.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/elliptic/ +

+
diff --git a/devdocs/go/crypto%2Fhmac%2Findex.html b/devdocs/go/crypto%2Fhmac%2Findex.html new file mode 100644 index 00000000..e08e7719 --- /dev/null +++ b/devdocs/go/crypto%2Fhmac%2Findex.html @@ -0,0 +1,23 @@ +

Package hmac

Overview

Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198. An HMAC is a cryptographic hash that uses a key to sign a message. The receiver verifies the hash by recomputing it using the same key.

+

Receivers should be careful to use Equal to compare MACs in order to avoid timing side-channels:

+
// ValidMAC reports whether messageMAC is a valid HMAC tag for message.
+func ValidMAC(message, messageMAC, key []byte) bool {
+	mac := hmac.New(sha256.New, key)
+	mac.Write(message)
+	expectedMAC := mac.Sum(nil)
+	return hmac.Equal(messageMAC, expectedMAC)
+}
+

Index

Package files

hmac.go

func Equal 1.1

func Equal(mac1, mac2 []byte) bool

Equal compares two MACs for equality without leaking timing information.

+

func New

func New(h func() hash.Hash, key []byte) hash.Hash

New returns a new HMAC hash using the given hash.Hash type and key. New functions like sha256.New from crypto/sha256 can be used as h. h must return a new Hash every time it is called. Note that unlike other hash implementations in the standard library, the returned Hash does not implement encoding.BinaryMarshaler or encoding.BinaryUnmarshaler.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/hmac/ +

+
diff --git a/devdocs/go/crypto%2Findex.html b/devdocs/go/crypto%2Findex.html new file mode 100644 index 00000000..40f5c02a --- /dev/null +++ b/devdocs/go/crypto%2Findex.html @@ -0,0 +1,106 @@ +

Package crypto

Overview

Package crypto collects common cryptographic constants.

Index

Package files

crypto.go

func RegisterHash

func RegisterHash(h Hash, f func() hash.Hash)

RegisterHash registers a function that returns a new instance of the given hash function. This is intended to be called from the init function in packages that implement hash functions.

+

type Decrypter 1.5

Decrypter is an interface for an opaque private key that can be used for asymmetric decryption operations. An example would be an RSA key kept in a hardware module.

+
type Decrypter interface {
+    // Public returns the public key corresponding to the opaque,
+    // private key.
+    Public() PublicKey
+
+    // Decrypt decrypts msg. The opts argument should be appropriate for
+    // the primitive used. See the documentation in each implementation for
+    // details.
+    Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error)
+}

type DecrypterOpts 1.5

type DecrypterOpts any

type Hash

Hash identifies a cryptographic hash function that is implemented in another package.

+
type Hash uint
const (
+    MD4         Hash = 1 + iota // import golang.org/x/crypto/md4
+    MD5                         // import crypto/md5
+    SHA1                        // import crypto/sha1
+    SHA224                      // import crypto/sha256
+    SHA256                      // import crypto/sha256
+    SHA384                      // import crypto/sha512
+    SHA512                      // import crypto/sha512
+    MD5SHA1                     // no implementation; MD5+SHA1 used for TLS RSA
+    RIPEMD160                   // import golang.org/x/crypto/ripemd160
+    SHA3_224                    // import golang.org/x/crypto/sha3
+    SHA3_256                    // import golang.org/x/crypto/sha3
+    SHA3_384                    // import golang.org/x/crypto/sha3
+    SHA3_512                    // import golang.org/x/crypto/sha3
+    SHA512_224                  // import crypto/sha512
+    SHA512_256                  // import crypto/sha512
+    BLAKE2s_256                 // import golang.org/x/crypto/blake2s
+    BLAKE2b_256                 // import golang.org/x/crypto/blake2b
+    BLAKE2b_384                 // import golang.org/x/crypto/blake2b
+    BLAKE2b_512                 // import golang.org/x/crypto/blake2b
+
+)

func (Hash) Available

func (h Hash) Available() bool

Available reports whether the given hash function is linked into the binary.

+

func (Hash) HashFunc 1.4

func (h Hash) HashFunc() Hash

HashFunc simply returns the value of h so that Hash implements SignerOpts.

+

func (Hash) New

func (h Hash) New() hash.Hash

New returns a new hash.Hash calculating the given hash function. New panics if the hash function is not linked into the binary.

+

func (Hash) Size

func (h Hash) Size() int

Size returns the length, in bytes, of a digest resulting from the given hash function. It doesn't require that the hash function in question be linked into the program.

+

func (Hash) String 1.15

func (h Hash) String() string

type PrivateKey

PrivateKey represents a private key using an unspecified algorithm.

+

Although this type is an empty interface for backwards compatibility reasons, all private key types in the standard library implement the following interface

+
interface{
+    Public() crypto.PublicKey
+    Equal(x crypto.PrivateKey) bool
+}
+

as well as purpose-specific interfaces such as Signer and Decrypter, which can be used for increased type safety within applications.

+
type PrivateKey any

type PublicKey 1.2

PublicKey represents a public key using an unspecified algorithm.

+

Although this type is an empty interface for backwards compatibility reasons, all public key types in the standard library implement the following interface

+
interface{
+    Equal(x crypto.PublicKey) bool
+}
+

which can be used for increased type safety within applications.

+
type PublicKey any

type Signer 1.4

Signer is an interface for an opaque private key that can be used for signing operations. For example, an RSA key kept in a hardware module.

+
type Signer interface {
+    // Public returns the public key corresponding to the opaque,
+    // private key.
+    Public() PublicKey
+
+    // Sign signs digest with the private key, possibly using entropy from
+    // rand. For an RSA key, the resulting signature should be either a
+    // PKCS #1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA
+    // key, it should be a DER-serialised, ASN.1 signature structure.
+    //
+    // Hash implements the SignerOpts interface and, in most cases, one can
+    // simply pass in the hash function used as opts. Sign may also attempt
+    // to type assert opts to other types in order to obtain algorithm
+    // specific values. See the documentation in each package for details.
+    //
+    // Note that when a signature of a hash of a larger message is needed,
+    // the caller is responsible for hashing the larger message and passing
+    // the hash (as digest) and the hash function (as opts) to Sign.
+    Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error)
+}

type SignerOpts 1.4

SignerOpts contains options for signing with a Signer.

+
type SignerOpts interface {
+    // HashFunc returns an identifier for the hash function used to produce
+    // the message passed to Signer.Sign, or else zero to indicate that no
+    // hashing was done.
+    HashFunc() Hash
+}

Subdirectories

Name Synopsis
..
aes Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.
boring Package boring exposes functions that are only available when building with Go+BoringCrypto.
cipher Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations.
des Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3.
dsa Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.
ecdh Package ecdh implements Elliptic Curve Diffie-Hellman over NIST curves and Curve25519.
ecdsa Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-4 and SEC 1, Version 2.0.
ed25519 Package ed25519 implements the Ed25519 signature algorithm.
elliptic Package elliptic implements the standard NIST P-224, P-256, P-384, and P-521 elliptic curves over prime fields.
hmac Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198.
md5 Package md5 implements the MD5 hash algorithm as defined in RFC 1321.
rand Package rand implements a cryptographically secure random number generator.
rc4 Package rc4 implements RC4 encryption, as defined in Bruce Schneier's Applied Cryptography.
rsa Package rsa implements RSA encryption as specified in PKCS #1 and RFC 8017.
sha1 Package sha1 implements the SHA-1 hash algorithm as defined in RFC 3174.
sha256 Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.
sha512 Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.
subtle Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.
tls Package tls partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.
fipsonly Package fipsonly restricts all TLS configuration to FIPS-approved settings.
x509 Package x509 implements a subset of the X.509 standard.
pkix Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/ +

+
diff --git a/devdocs/go/crypto%2Fmd5%2Findex.html b/devdocs/go/crypto%2Fmd5%2Findex.html new file mode 100644 index 00000000..a41a5b8d --- /dev/null +++ b/devdocs/go/crypto%2Fmd5%2Findex.html @@ -0,0 +1,42 @@ +

Package md5

Overview

Package md5 implements the MD5 hash algorithm as defined in RFC 1321.

+

MD5 is cryptographically broken and should not be used for secure applications.

Index

Examples

New
New (File)
Sum

Package files

md5.go md5block.go md5block_decl.go

Constants

The blocksize of MD5 in bytes.

+
const BlockSize = 64

The size of an MD5 checksum in bytes.

+
const Size = 16

func New

func New() hash.Hash

New returns a new hash.Hash computing the MD5 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

Example +

Code:

h := md5.New()
+io.WriteString(h, "The fog is getting thicker!")
+io.WriteString(h, "And Leon's getting laaarger!")
+fmt.Printf("%x", h.Sum(nil))
+

Output:

e2c569be17396eca2a2e3c11578123ed
+

Example (File) +

Code:

+f, err := os.Open("file.txt")
+if err != nil {
+    log.Fatal(err)
+}
+defer f.Close()
+
+h := md5.New()
+if _, err := io.Copy(h, f); err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%x", h.Sum(nil))
+

func Sum 1.2

func Sum(data []byte) [Size]byte

Sum returns the MD5 checksum of the data.

Example +

Code:

data := []byte("These pretzels are making me thirsty.")
+fmt.Printf("%x", md5.Sum(data))
+

Output:

b0804ec967f48520697662a204f5fe72
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/md5/ +

+
diff --git a/devdocs/go/crypto%2Frand%2Findex.html b/devdocs/go/crypto%2Frand%2Findex.html new file mode 100644 index 00000000..0ffd3e5b --- /dev/null +++ b/devdocs/go/crypto%2Frand%2Findex.html @@ -0,0 +1,32 @@ +

Package rand

Overview

Package rand implements a cryptographically secure random number generator.

Index

Examples

Read

Package files

rand.go rand_getrandom.go rand_unix.go util.go

Variables

Reader is a global, shared instance of a cryptographically secure random number generator.

+

On Linux, FreeBSD, Dragonfly, NetBSD and Solaris, Reader uses getrandom(2) if available, /dev/urandom otherwise. On OpenBSD and macOS, Reader uses getentropy(2). On other Unix-like systems, Reader reads from /dev/urandom. On Windows systems, Reader uses the ProcessPrng API. On JS/Wasm, Reader uses the Web Crypto API. On WASIP1/Wasm, Reader uses random_get from wasi_snapshot_preview1.

+
var Reader io.Reader

func Int

func Int(rand io.Reader, max *big.Int) (n *big.Int, err error)

Int returns a uniform random value in [0, max). It panics if max <= 0.

+

func Prime

func Prime(rand io.Reader, bits int) (*big.Int, error)

Prime returns a number of the given bit length that is prime with high probability. Prime will return error for any error returned by rand.Read or if bits < 2.

+

func Read

func Read(b []byte) (n int, err error)

Read is a helper function that calls Reader.Read using io.ReadFull. On return, n == len(b) if and only if err == nil.

Example +

This example reads 10 cryptographically secure pseudorandom numbers from rand.Reader and writes them to a byte slice.

Code:

c := 10
+b := make([]byte, c)
+_, err := rand.Read(b)
+if err != nil {
+    fmt.Println("error:", err)
+    return
+}
+// The slice should now contain random bytes instead of only zeroes.
+fmt.Println(bytes.Equal(b, make([]byte, c)))
+
+

Output:

false
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/rand/ +

+
diff --git a/devdocs/go/crypto%2Frc4%2Findex.html b/devdocs/go/crypto%2Frc4%2Findex.html new file mode 100644 index 00000000..51f33835 --- /dev/null +++ b/devdocs/go/crypto%2Frc4%2Findex.html @@ -0,0 +1,30 @@ +

Package rc4

Overview

Package rc4 implements RC4 encryption, as defined in Bruce Schneier's Applied Cryptography.

+

RC4 is cryptographically broken and should not be used for secure applications.

Index

Package files

rc4.go

type Cipher

A Cipher is an instance of RC4 using a particular key.

+
type Cipher struct {
+    // contains filtered or unexported fields
+}
+

func NewCipher

func NewCipher(key []byte) (*Cipher, error)

NewCipher creates and returns a new Cipher. The key argument should be the RC4 key, at least 1 byte and at most 256 bytes.

+

func (*Cipher) Reset

func (c *Cipher) Reset()

Reset zeros the key data and makes the Cipher unusable.

+

Deprecated: Reset can't guarantee that the key will be entirely removed from the process's memory.

+

func (*Cipher) XORKeyStream

func (c *Cipher) XORKeyStream(dst, src []byte)

XORKeyStream sets dst to the result of XORing src with the key stream. Dst and src must overlap entirely or not at all.

+

type KeySizeError

type KeySizeError int

func (KeySizeError) Error

func (k KeySizeError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/rc4/ +

+
diff --git a/devdocs/go/crypto%2Frsa%2Findex.html b/devdocs/go/crypto%2Frsa%2Findex.html new file mode 100644 index 00000000..6bfdc892 --- /dev/null +++ b/devdocs/go/crypto%2Frsa%2Findex.html @@ -0,0 +1,295 @@ +

Package rsa

Overview

Package rsa implements RSA encryption as specified in PKCS #1 and RFC 8017.

+

RSA is a single, fundamental operation that is used in this package to implement either public-key encryption or public-key signatures.

+

The original specification for encryption and signatures with RSA is PKCS #1 and the terms "RSA encryption" and "RSA signatures" by default refer to PKCS #1 version 1.5. However, that specification has flaws and new designs should use version 2, usually called by just OAEP and PSS, where possible.

+

Two sets of interfaces are included in this package. When a more abstract interface isn't necessary, there are functions for encrypting/decrypting with v1.5/OAEP and signing/verifying with v1.5/PSS. If one needs to abstract over the public key primitive, the PrivateKey type implements the Decrypter and Signer interfaces from the crypto package.

+

Operations in this package are implemented using constant-time algorithms, except for GenerateKey, PrivateKey.Precompute, and PrivateKey.Validate. Every other operation only leaks the bit size of the involved values, which all depend on the selected key size.

Index

Examples

DecryptOAEP
DecryptPKCS1v15SessionKey
EncryptOAEP
SignPKCS1v15
VerifyPKCS1v15

Package files

notboring.go pkcs1v15.go pss.go rsa.go

Constants

const (
+    // PSSSaltLengthAuto causes the salt in a PSS signature to be as large
+    // as possible when signing, and to be auto-detected when verifying.
+    PSSSaltLengthAuto = 0
+    // PSSSaltLengthEqualsHash causes the salt length to equal the length
+    // of the hash used in the signature.
+    PSSSaltLengthEqualsHash = -1
+)

Variables

ErrDecryption represents a failure to decrypt a message. It is deliberately vague to avoid adaptive attacks.

+
var ErrDecryption = errors.New("crypto/rsa: decryption error")

ErrMessageTooLong is returned when attempting to encrypt or sign a message which is too large for the size of the key. When using SignPSS, this can also be returned if the size of the salt is too large.

+
var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA key size")

ErrVerification represents a failure to verify a signature. It is deliberately vague to avoid adaptive attacks.

+
var ErrVerification = errors.New("crypto/rsa: verification error")

func DecryptOAEP

func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error)

DecryptOAEP decrypts ciphertext using RSA-OAEP.

+

OAEP is parameterised by a hash function that is used as a random oracle. Encryption and decryption of a given message must use the same hash function and sha256.New() is a reasonable choice.

+

The random parameter is legacy and ignored, and it can be nil.

+

The label parameter must match the value given when encrypting. See EncryptOAEP for details.

Example +

Code:

+ciphertext, _ := hex.DecodeString("4d1ee10e8f286390258c51a5e80802844c3e6358ad6690b7285218a7c7ed7fc3a4c7b950fbd04d4b0239cc060dcc7065ca6f84c1756deb71ca5685cadbb82be025e16449b905c568a19c088a1abfad54bf7ecc67a7df39943ec511091a34c0f2348d04e058fcff4d55644de3cd1d580791d4524b92f3e91695582e6e340a1c50b6c6d78e80b4e42c5b4d45e479b492de42bbd39cc642ebb80226bb5200020d501b24a37bcc2ec7f34e596b4fd6b063de4858dbf5a4e3dd18e262eda0ec2d19dbd8e890d672b63d368768360b20c0b6b8592a438fa275e5fa7f60bef0dd39673fd3989cc54d2cb80c08fcd19dacbc265ee1c6014616b0e04ea0328c2a04e73460")
+label := []byte("orders")
+
+plaintext, err := rsa.DecryptOAEP(sha256.New(), nil, test2048Key, ciphertext, label)
+if err != nil {
+    fmt.Fprintf(os.Stderr, "Error from decryption: %s\n", err)
+    return
+}
+
+fmt.Printf("Plaintext: %s\n", plaintext)
+
+// Remember that encryption only provides confidentiality. The
+// ciphertext should be signed before authenticity is assumed and, even
+// then, consider that messages might be reordered.
+

func DecryptPKCS1v15

func DecryptPKCS1v15(random io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error)

DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS #1 v1.5. The random parameter is legacy and ignored, and it can be nil.

+

Note that whether this function returns an error or not discloses secret information. If an attacker can cause this function to run repeatedly and learn whether each instance returned an error then they can decrypt and forge signatures as if they had the private key. See DecryptPKCS1v15SessionKey for a way of solving this problem.

+

func DecryptPKCS1v15SessionKey

func DecryptPKCS1v15SessionKey(random io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) error

DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS #1 v1.5. The random parameter is legacy and ignored, and it can be nil.

+

DecryptPKCS1v15SessionKey returns an error if the ciphertext is the wrong length or if the ciphertext is greater than the public modulus. Otherwise, no error is returned. If the padding is valid, the resulting plaintext message is copied into key. Otherwise, key is unchanged. These alternatives occur in constant time. It is intended that the user of this function generate a random session key beforehand and continue the protocol with the resulting value.

+

Note that if the session key is too small then it may be possible for an attacker to brute-force it. If they can do that then they can learn whether a random value was used (because it'll be different for the same ciphertext) and thus whether the padding was correct. This also defeats the point of this function. Using at least a 16-byte key will protect against this attack.

+

This method implements protections against Bleichenbacher chosen ciphertext attacks [0] described in RFC 3218 Section 2.3.2 [1]. While these protections make a Bleichenbacher attack significantly more difficult, the protections are only effective if the rest of the protocol which uses DecryptPKCS1v15SessionKey is designed with these considerations in mind. In particular, if any subsequent operations which use the decrypted session key leak any information about the key (e.g. whether it is a static or random key) then the mitigations are defeated. This method must be used extremely carefully, and typically should only be used when absolutely necessary for compatibility with an existing protocol (such as TLS) that is designed with these properties in mind.

+

Example +

RSA is able to encrypt only a very limited amount of data. In order to encrypt reasonable amounts of data a hybrid scheme is commonly used: RSA is used to encrypt a key for a symmetric primitive like AES-GCM. Before encrypting, data is “padded” by embedding it in a known structure. This is done for a number of reasons, but the most obvious is to ensure that the value is large enough that the exponentiation is larger than the modulus. (Otherwise it could be decrypted with a square-root.) In these designs, when using PKCS #1 v1.5, it's vitally important to avoid disclosing whether the received RSA message was well-formed (that is, whether the result of decrypting is a correctly padded message) because this leaks secret information. DecryptPKCS1v15SessionKey is designed for this situation and copies the decrypted, symmetric key (if well-formed) in constant-time over a buffer that contains a random key. Thus, if the RSA result isn't well-formed, the implementation uses a random key in constant time.

Code:

+// The hybrid scheme should use at least a 16-byte symmetric key. Here
+// we read the random key that will be used if the RSA decryption isn't
+// well-formed.
+key := make([]byte, 32)
+if _, err := rand.Read(key); err != nil {
+    panic("RNG failure")
+}
+
+rsaCiphertext, _ := hex.DecodeString("aabbccddeeff")
+
+if err := rsa.DecryptPKCS1v15SessionKey(nil, rsaPrivateKey, rsaCiphertext, key); err != nil {
+    // Any errors that result will be “public” – meaning that they
+    // can be determined without any secret information. (For
+    // instance, if the length of key is impossible given the RSA
+    // public key.)
+    fmt.Fprintf(os.Stderr, "Error from RSA decryption: %s\n", err)
+    return
+}
+
+// Given the resulting key, a symmetric scheme can be used to decrypt a
+// larger ciphertext.
+block, err := aes.NewCipher(key)
+if err != nil {
+    panic("aes.NewCipher failed: " + err.Error())
+}
+
+// Since the key is random, using a fixed nonce is acceptable as the
+// (key, nonce) pair will still be unique, as required.
+var zeroNonce [12]byte
+aead, err := cipher.NewGCM(block)
+if err != nil {
+    panic("cipher.NewGCM failed: " + err.Error())
+}
+ciphertext, _ := hex.DecodeString("00112233445566")
+plaintext, err := aead.Open(nil, zeroNonce[:], ciphertext, nil)
+if err != nil {
+    // The RSA ciphertext was badly formed; the decryption will
+    // fail here because the AES-GCM key will be incorrect.
+    fmt.Fprintf(os.Stderr, "Error decrypting: %s\n", err)
+    return
+}
+
+fmt.Printf("Plaintext: %s\n", plaintext)
+

func EncryptOAEP

func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error)

EncryptOAEP encrypts the given message with RSA-OAEP.

+

OAEP is parameterised by a hash function that is used as a random oracle. Encryption and decryption of a given message must use the same hash function and sha256.New() is a reasonable choice.

+

The random parameter is used as a source of entropy to ensure that encrypting the same message twice doesn't result in the same ciphertext. Most applications should use crypto/rand.Reader as random.

+

The label parameter may contain arbitrary data that will not be encrypted, but which gives important context to the message. For example, if a given public key is used to encrypt two types of messages then distinct label values could be used to ensure that a ciphertext for one purpose cannot be used for another by an attacker. If not required it can be empty.

+

The message must be no longer than the length of the public modulus minus twice the hash length, minus a further 2.

Example +

Code:

+secretMessage := []byte("send reinforcements, we're going to advance")
+label := []byte("orders")
+
+// crypto/rand.Reader is a good source of entropy for randomizing the
+// encryption function.
+rng := rand.Reader
+
+ciphertext, err := rsa.EncryptOAEP(sha256.New(), rng, &test2048Key.PublicKey, secretMessage, label)
+if err != nil {
+    fmt.Fprintf(os.Stderr, "Error from encryption: %s\n", err)
+    return
+}
+
+// Since encryption is a randomized function, ciphertext will be
+// different each time.
+fmt.Printf("Ciphertext: %x\n", ciphertext)
+

func EncryptPKCS1v15

func EncryptPKCS1v15(random io.Reader, pub *PublicKey, msg []byte) ([]byte, error)

EncryptPKCS1v15 encrypts the given message with RSA and the padding scheme from PKCS #1 v1.5. The message must be no longer than the length of the public modulus minus 11 bytes.

+

The random parameter is used as a source of entropy to ensure that encrypting the same message twice doesn't result in the same ciphertext. Most applications should use crypto/rand.Reader as random. Note that the returned ciphertext does not depend deterministically on the bytes read from random, and may change between calls and/or between versions.

+

WARNING: use of this function to encrypt plaintexts other than session keys is dangerous. Use RSA OAEP in new protocols.

+

func SignPKCS1v15

func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error)

SignPKCS1v15 calculates the signature of hashed using RSASSA-PKCS1-V1_5-SIGN from RSA PKCS #1 v1.5. Note that hashed must be the result of hashing the input message using the given hash function. If hash is zero, hashed is signed directly. This isn't advisable except for interoperability.

+

The random parameter is legacy and ignored, and it can be nil.

+

This function is deterministic. Thus, if the set of possible messages is small, an attacker may be able to build a map from messages to signatures and identify the signed messages. As ever, signatures provide authenticity, not confidentiality.

Example +

Code:

+message := []byte("message to be signed")
+
+// Only small messages can be signed directly; thus the hash of a
+// message, rather than the message itself, is signed. This requires
+// that the hash function be collision resistant. SHA-256 is the
+// least-strong hash function that should be used for this at the time
+// of writing (2016).
+hashed := sha256.Sum256(message)
+
+signature, err := rsa.SignPKCS1v15(nil, rsaPrivateKey, crypto.SHA256, hashed[:])
+if err != nil {
+    fmt.Fprintf(os.Stderr, "Error from signing: %s\n", err)
+    return
+}
+
+fmt.Printf("Signature: %x\n", signature)
+

func SignPSS 1.2

func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, digest []byte, opts *PSSOptions) ([]byte, error)

SignPSS calculates the signature of digest using PSS.

+

digest must be the result of hashing the input message using the given hash function. The opts argument may be nil, in which case sensible defaults are used. If opts.Hash is set, it overrides hash.

+

The signature is randomized depending on the message, key, and salt size, using bytes from rand. Most applications should use crypto/rand.Reader as rand.

+

func VerifyPKCS1v15

func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error

VerifyPKCS1v15 verifies an RSA PKCS #1 v1.5 signature. hashed is the result of hashing the input message using the given hash function and sig is the signature. A valid signature is indicated by returning a nil error. If hash is zero then hashed is used directly. This isn't advisable except for interoperability.

Example +

Code:

+message := []byte("message to be signed")
+signature, _ := hex.DecodeString("ad2766728615cc7a746cc553916380ca7bfa4f8983b990913bc69eb0556539a350ff0f8fe65ddfd3ebe91fe1c299c2fac135bc8c61e26be44ee259f2f80c1530")
+
+// Only small messages can be signed directly; thus the hash of a
+// message, rather than the message itself, is signed. This requires
+// that the hash function be collision resistant. SHA-256 is the
+// least-strong hash function that should be used for this at the time
+// of writing (2016).
+hashed := sha256.Sum256(message)
+
+err := rsa.VerifyPKCS1v15(&rsaPrivateKey.PublicKey, crypto.SHA256, hashed[:], signature)
+if err != nil {
+    fmt.Fprintf(os.Stderr, "Error from verification: %s\n", err)
+    return
+}
+
+// signature is a valid signature of message from the public key.
+

func VerifyPSS 1.2

func VerifyPSS(pub *PublicKey, hash crypto.Hash, digest []byte, sig []byte, opts *PSSOptions) error

VerifyPSS verifies a PSS signature.

+

A valid signature is indicated by returning a nil error. digest must be the result of hashing the input message using the given hash function. The opts argument may be nil, in which case sensible defaults are used. opts.Hash is ignored.

+

type CRTValue

CRTValue contains the precomputed Chinese remainder theorem values.

+
type CRTValue struct {
+    Exp   *big.Int // D mod (prime-1).
+    Coeff *big.Int // R·Coeff ≡ 1 mod Prime.
+    R     *big.Int // product of primes prior to this (inc p and q).
+}
+

type OAEPOptions 1.5

OAEPOptions is an interface for passing options to OAEP decryption using the crypto.Decrypter interface.

+
type OAEPOptions struct {
+    // Hash is the hash function that will be used when generating the mask.
+    Hash crypto.Hash
+
+    // MGFHash is the hash function used for MGF1.
+    // If zero, Hash is used instead.
+    MGFHash crypto.Hash // Go 1.20
+
+    // Label is an arbitrary byte string that must be equal to the value
+    // used when encrypting.
+    Label []byte
+}
+

type PKCS1v15DecryptOptions 1.5

PKCS1v15DecryptOptions is for passing options to PKCS #1 v1.5 decryption using the crypto.Decrypter interface.

+
type PKCS1v15DecryptOptions struct {
+    // SessionKeyLen is the length of the session key that is being
+    // decrypted. If not zero, then a padding error during decryption will
+    // cause a random plaintext of this length to be returned rather than
+    // an error. These alternatives happen in constant time.
+    SessionKeyLen int
+}
+

type PSSOptions 1.2

PSSOptions contains options for creating and verifying PSS signatures.

+
type PSSOptions struct {
+    // SaltLength controls the length of the salt used in the PSS signature. It
+    // can either be a positive number of bytes, or one of the special
+    // PSSSaltLength constants.
+    SaltLength int
+
+    // Hash is the hash function used to generate the message digest. If not
+    // zero, it overrides the hash function passed to SignPSS. It's required
+    // when using PrivateKey.Sign.
+    Hash crypto.Hash // Go 1.4
+}
+

func (*PSSOptions) HashFunc 1.4

func (opts *PSSOptions) HashFunc() crypto.Hash

HashFunc returns opts.Hash so that PSSOptions implements crypto.SignerOpts.

+

type PrecomputedValues

type PrecomputedValues struct {
+    Dp, Dq *big.Int // D mod (P-1) (or mod Q-1)
+    Qinv   *big.Int // Q^-1 mod P
+
+    // CRTValues is used for the 3rd and subsequent primes. Due to a
+    // historical accident, the CRT for the first two primes is handled
+    // differently in PKCS #1 and interoperability is sufficiently
+    // important that we mirror this.
+    //
+    // Deprecated: These values are still filled in by Precompute for
+    // backwards compatibility but are not used. Multi-prime RSA is very rare,
+    // and is implemented by this package without CRT optimizations to limit
+    // complexity.
+    CRTValues []CRTValue
+    // contains filtered or unexported fields
+}
+

type PrivateKey

A PrivateKey represents an RSA key

+
type PrivateKey struct {
+    PublicKey            // public part.
+    D         *big.Int   // private exponent
+    Primes    []*big.Int // prime factors of N, has >= 2 elements.
+
+    // Precomputed contains precomputed values that speed up RSA operations,
+    // if available. It must be generated by calling PrivateKey.Precompute and
+    // must not be modified.
+    Precomputed PrecomputedValues
+}
+

func GenerateKey

func GenerateKey(random io.Reader, bits int) (*PrivateKey, error)

GenerateKey generates a random RSA private key of the given bit size.

+

Most applications should use crypto/rand.Reader as rand. Note that the returned key does not depend deterministically on the bytes read from rand, and may change between calls and/or between versions.

+

func GenerateMultiPrimeKey

func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error)

GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit size and the given random source.

+

Table 1 in "On the Security of Multi-prime RSA" suggests maximum numbers of primes for a given bit size.

+

Although the public keys are compatible (actually, indistinguishable) from the 2-prime case, the private keys are not. Thus it may not be possible to export multi-prime private keys in certain formats or to subsequently import them into other code.

+

This package does not implement CRT optimizations for multi-prime RSA, so the keys with more than two primes will have worse performance.

+

Deprecated: The use of this function with a number of primes different from two is not recommended for the above security, compatibility, and performance reasons. Use GenerateKey instead.

+

func (*PrivateKey) Decrypt 1.5

func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error)

Decrypt decrypts ciphertext with priv. If opts is nil or of type *PKCS1v15DecryptOptions then PKCS #1 v1.5 decryption is performed. Otherwise opts must have type *OAEPOptions and OAEP decryption is done.

+

func (*PrivateKey) Equal 1.15

func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool

Equal reports whether priv and x have equivalent values. It ignores Precomputed values.

+

func (*PrivateKey) Precompute

func (priv *PrivateKey) Precompute()

Precompute performs some calculations that speed up private key operations in the future.

+

func (*PrivateKey) Public 1.4

func (priv *PrivateKey) Public() crypto.PublicKey

Public returns the public key corresponding to priv.

+

func (*PrivateKey) Sign 1.4

func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)

Sign signs digest with priv, reading randomness from rand. If opts is a *PSSOptions then the PSS algorithm will be used, otherwise PKCS #1 v1.5 will be used. digest must be the result of hashing the input message using opts.HashFunc().

+

This method implements crypto.Signer, which is an interface to support keys where the private part is kept in, for example, a hardware module. Common uses should use the Sign* functions in this package directly.

+

func (*PrivateKey) Validate

func (priv *PrivateKey) Validate() error

Validate performs basic sanity checks on the key. It returns nil if the key is valid, or else an error describing a problem.

+

type PublicKey

A PublicKey represents the public part of an RSA key.

+

The value of the modulus N is considered secret by this library and protected from leaking through timing side-channels. However, neither the value of the exponent E nor the precise bit size of N are similarly protected.

+
type PublicKey struct {
+    N *big.Int // modulus
+    E int      // public exponent
+}
+

func (*PublicKey) Equal 1.15

func (pub *PublicKey) Equal(x crypto.PublicKey) bool

Equal reports whether pub and x have the same value.

+

func (*PublicKey) Size 1.11

func (pub *PublicKey) Size() int

Size returns the modulus size in bytes. Raw signatures and ciphertexts for or by this public key will have the same size.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/rsa/ +

+
diff --git a/devdocs/go/crypto%2Fsha1%2Findex.html b/devdocs/go/crypto%2Fsha1%2Findex.html new file mode 100644 index 00000000..0173cd7a --- /dev/null +++ b/devdocs/go/crypto%2Fsha1%2Findex.html @@ -0,0 +1,42 @@ +

Package sha1

Overview

Package sha1 implements the SHA-1 hash algorithm as defined in RFC 3174.

+

SHA-1 is cryptographically broken and should not be used for secure applications.

Index

Examples

New
New (File)
Sum

Package files

sha1.go sha1block.go sha1block_amd64.go

Constants

The blocksize of SHA-1 in bytes.

+
const BlockSize = 64

The size of a SHA-1 checksum in bytes.

+
const Size = 20

func New

func New() hash.Hash

New returns a new hash.Hash computing the SHA1 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

Example +

Code:

h := sha1.New()
+io.WriteString(h, "His money is twice tainted:")
+io.WriteString(h, " 'taint yours and 'taint mine.")
+fmt.Printf("% x", h.Sum(nil))
+

Output:

59 7f 6a 54 00 10 f9 4c 15 d7 18 06 a9 9a 2c 87 10 e7 47 bd
+

Example (File) +

Code:

+f, err := os.Open("file.txt")
+if err != nil {
+    log.Fatal(err)
+}
+defer f.Close()
+
+h := sha1.New()
+if _, err := io.Copy(h, f); err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("% x", h.Sum(nil))
+

func Sum 1.2

func Sum(data []byte) [Size]byte

Sum returns the SHA-1 checksum of the data.

Example +

Code:

data := []byte("This page intentionally left blank.")
+fmt.Printf("% x", sha1.Sum(data))
+

Output:

af 06 49 23 bb f2 30 15 96 aa c4 c2 73 ba 32 17 8e bc 4a 96
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/sha1/ +

+
diff --git a/devdocs/go/crypto%2Fsha256%2Findex.html b/devdocs/go/crypto%2Fsha256%2Findex.html new file mode 100644 index 00000000..a11414b2 --- /dev/null +++ b/devdocs/go/crypto%2Fsha256%2Findex.html @@ -0,0 +1,45 @@ +

Package sha256

Overview

Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.

Index

Examples

New
New (File)
Sum256

Package files

sha256.go sha256block.go sha256block_amd64.go sha256block_decl.go

Constants

The blocksize of SHA256 and SHA224 in bytes.

+
const BlockSize = 64

The size of a SHA256 checksum in bytes.

+
const Size = 32

The size of a SHA224 checksum in bytes.

+
const Size224 = 28

func New

func New() hash.Hash

New returns a new hash.Hash computing the SHA256 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

Example +

Code:

h := sha256.New()
+h.Write([]byte("hello world\n"))
+fmt.Printf("%x", h.Sum(nil))
+

Output:

a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447
+

Example (File) +

Code:

+f, err := os.Open("file.txt")
+if err != nil {
+    log.Fatal(err)
+}
+defer f.Close()
+
+h := sha256.New()
+if _, err := io.Copy(h, f); err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%x", h.Sum(nil))
+

func New224

func New224() hash.Hash

New224 returns a new hash.Hash computing the SHA224 checksum.

+

func Sum224 1.2

func Sum224(data []byte) [Size224]byte

Sum224 returns the SHA224 checksum of the data.

+

func Sum256 1.2

func Sum256(data []byte) [Size]byte

Sum256 returns the SHA256 checksum of the data.

Example +

Code:

sum := sha256.Sum256([]byte("hello world\n"))
+fmt.Printf("%x", sum)
+

Output:

a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/sha256/ +

+
diff --git a/devdocs/go/crypto%2Fsha512%2Findex.html b/devdocs/go/crypto%2Fsha512%2Findex.html new file mode 100644 index 00000000..8d8cd3d6 --- /dev/null +++ b/devdocs/go/crypto%2Fsha512%2Findex.html @@ -0,0 +1,44 @@ +

Package sha512

Overview

Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.

+

All the hash.Hash implementations returned by this package also implement encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

Index

Package files

sha512.go sha512block.go sha512block_amd64.go

Constants

const (
+    // Size is the size, in bytes, of a SHA-512 checksum.
+    Size = 64
+
+    // Size224 is the size, in bytes, of a SHA-512/224 checksum.
+    Size224 = 28
+
+    // Size256 is the size, in bytes, of a SHA-512/256 checksum.
+    Size256 = 32
+
+    // Size384 is the size, in bytes, of a SHA-384 checksum.
+    Size384 = 48
+
+    // BlockSize is the block size, in bytes, of the SHA-512/224,
+    // SHA-512/256, SHA-384 and SHA-512 hash functions.
+    BlockSize = 128
+)

func New

func New() hash.Hash

New returns a new hash.Hash computing the SHA-512 checksum.

+

func New384

func New384() hash.Hash

New384 returns a new hash.Hash computing the SHA-384 checksum.

+

func New512_224 1.5

func New512_224() hash.Hash

New512_224 returns a new hash.Hash computing the SHA-512/224 checksum.

+

func New512_256 1.5

func New512_256() hash.Hash

New512_256 returns a new hash.Hash computing the SHA-512/256 checksum.

+

func Sum384 1.2

func Sum384(data []byte) [Size384]byte

Sum384 returns the SHA384 checksum of the data.

+

func Sum512 1.2

func Sum512(data []byte) [Size]byte

Sum512 returns the SHA512 checksum of the data.

+

func Sum512_224 1.5

func Sum512_224(data []byte) [Size224]byte

Sum512_224 returns the Sum512/224 checksum of the data.

+

func Sum512_256 1.5

func Sum512_256(data []byte) [Size256]byte

Sum512_256 returns the Sum512/256 checksum of the data.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/sha512/ +

+
diff --git a/devdocs/go/crypto%2Fsubtle%2Findex.html b/devdocs/go/crypto%2Fsubtle%2Findex.html new file mode 100644 index 00000000..505d1b0f --- /dev/null +++ b/devdocs/go/crypto%2Fsubtle%2Findex.html @@ -0,0 +1,24 @@ +

Package subtle

Overview

Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.

Index

Package files

constant_time.go xor.go xor_amd64.go

func ConstantTimeByteEq

func ConstantTimeByteEq(x, y uint8) int

ConstantTimeByteEq returns 1 if x == y and 0 otherwise.

+

func ConstantTimeCompare

func ConstantTimeCompare(x, y []byte) int

ConstantTimeCompare returns 1 if the two slices, x and y, have equal contents and 0 otherwise. The time taken is a function of the length of the slices and is independent of the contents. If the lengths of x and y do not match it returns 0 immediately.

+

func ConstantTimeCopy

func ConstantTimeCopy(v int, x, y []byte)

ConstantTimeCopy copies the contents of y into x (a slice of equal length) if v == 1. If v == 0, x is left unchanged. Its behavior is undefined if v takes any other value.

+

func ConstantTimeEq

func ConstantTimeEq(x, y int32) int

ConstantTimeEq returns 1 if x == y and 0 otherwise.

+

func ConstantTimeLessOrEq 1.2

func ConstantTimeLessOrEq(x, y int) int

ConstantTimeLessOrEq returns 1 if x <= y and 0 otherwise. Its behavior is undefined if x or y are negative or > 2**31 - 1.

+

func ConstantTimeSelect

func ConstantTimeSelect(v, x, y int) int

ConstantTimeSelect returns x if v == 1 and y if v == 0. Its behavior is undefined if v takes any other value.

+

func XORBytes 1.20

func XORBytes(dst, x, y []byte) int

XORBytes sets dst[i] = x[i] ^ y[i] for all i < n = min(len(x), len(y)), returning n, the number of bytes written to dst. If dst does not have length at least n, XORBytes panics without writing anything to dst.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/subtle/ +

+
diff --git a/devdocs/go/crypto%2Ftls%2Ffipsonly%2Findex.html b/devdocs/go/crypto%2Ftls%2Ffipsonly%2Findex.html new file mode 100644 index 00000000..7d3cb98e --- /dev/null +++ b/devdocs/go/crypto%2Ftls%2Ffipsonly%2Findex.html @@ -0,0 +1,9 @@ +

Command fipsonly

Package fipsonly restricts all TLS configuration to FIPS-approved settings.

+

The effect is triggered by importing the package anywhere in a program, as in:

+
import _ "crypto/tls/fipsonly"
+

This package only exists when using Go compiled with GOEXPERIMENT=boringcrypto.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/tls/fipsonly/ +

+
diff --git a/devdocs/go/crypto%2Ftls%2Findex.html b/devdocs/go/crypto%2Ftls%2Findex.html new file mode 100644 index 00000000..ed0df528 --- /dev/null +++ b/devdocs/go/crypto%2Ftls%2Findex.html @@ -0,0 +1,1114 @@ +

Package tls

Overview

Package tls partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.

Index

Examples

Config (KeyLogWriter)
Config (VerifyConnection)
Dial
LoadX509KeyPair
X509KeyPair
X509KeyPair (HttpServer)

Package files

alert.go auth.go cache.go cipher_suites.go common.go common_string.go conn.go handshake_client.go handshake_client_tls13.go handshake_messages.go handshake_server.go handshake_server_tls13.go key_agreement.go key_schedule.go notboring.go prf.go quic.go ticket.go tls.go

Constants

A list of cipher suite IDs that are, or have been, implemented by this package.

+

See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

+
const (
+    // TLS 1.0 - 1.2 cipher suites.
+    TLS_RSA_WITH_RC4_128_SHA                      uint16 = 0x0005
+    TLS_RSA_WITH_3DES_EDE_CBC_SHA                 uint16 = 0x000a
+    TLS_RSA_WITH_AES_128_CBC_SHA                  uint16 = 0x002f
+    TLS_RSA_WITH_AES_256_CBC_SHA                  uint16 = 0x0035
+    TLS_RSA_WITH_AES_128_CBC_SHA256               uint16 = 0x003c
+    TLS_RSA_WITH_AES_128_GCM_SHA256               uint16 = 0x009c
+    TLS_RSA_WITH_AES_256_GCM_SHA384               uint16 = 0x009d
+    TLS_ECDHE_ECDSA_WITH_RC4_128_SHA              uint16 = 0xc007
+    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA          uint16 = 0xc009
+    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA          uint16 = 0xc00a
+    TLS_ECDHE_RSA_WITH_RC4_128_SHA                uint16 = 0xc011
+    TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0xc012
+    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA            uint16 = 0xc013
+    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA            uint16 = 0xc014
+    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256       uint16 = 0xc023
+    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256         uint16 = 0xc027
+    TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0xc02f
+    TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256       uint16 = 0xc02b
+    TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384         uint16 = 0xc030
+    TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384       uint16 = 0xc02c
+    TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   uint16 = 0xcca8
+    TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca9
+
+    // TLS 1.3 cipher suites.
+    TLS_AES_128_GCM_SHA256       uint16 = 0x1301
+    TLS_AES_256_GCM_SHA384       uint16 = 0x1302
+    TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303
+
+    // TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator
+    // that the client is doing version fallback. See RFC 7507.
+    TLS_FALLBACK_SCSV uint16 = 0x5600
+
+    // Legacy names for the corresponding cipher suites with the correct _SHA256
+    // suffix, retained for backward compatibility.
+    TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305   = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
+    TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
+)
const (
+    VersionTLS10 = 0x0301
+    VersionTLS11 = 0x0302
+    VersionTLS12 = 0x0303
+    VersionTLS13 = 0x0304
+
+    // Deprecated: SSLv3 is cryptographically broken, and is no longer
+    // supported by this package. See golang.org/issue/32716.
+    VersionSSL30 = 0x0300
+)
const (
+    QUICEncryptionLevelInitial = QUICEncryptionLevel(iota)
+    QUICEncryptionLevelEarly
+    QUICEncryptionLevelHandshake
+    QUICEncryptionLevelApplication
+)

func CipherSuiteName 1.14

func CipherSuiteName(id uint16) string

CipherSuiteName returns the standard name for the passed cipher suite ID (e.g. "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"), or a fallback representation of the ID value if the cipher suite is not implemented by this package.

+

func Listen

func Listen(network, laddr string, config *Config) (net.Listener, error)

Listen creates a TLS listener accepting connections on the given network address using net.Listen. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.

+

func NewListener

func NewListener(inner net.Listener, config *Config) net.Listener

NewListener creates a Listener which accepts connections from an inner Listener and wraps each connection with Server. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.

+

func VersionName 1.21

func VersionName(version uint16) string

VersionName returns the name for the provided TLS version number (e.g. "TLS 1.3"), or a fallback representation of the value if the version is not implemented by this package.

+

type AlertError 1.21

An AlertError is a TLS alert.

+

When using a QUIC transport, QUICConn methods will return an error which wraps AlertError rather than sending a TLS alert.

+
type AlertError uint8

func (AlertError) Error 1.21

func (e AlertError) Error() string

type Certificate

A Certificate is a chain of one or more certificates, leaf first.

+
type Certificate struct {
+    Certificate [][]byte
+    // PrivateKey contains the private key corresponding to the public key in
+    // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
+    // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
+    // an RSA PublicKey.
+    PrivateKey crypto.PrivateKey
+    // SupportedSignatureAlgorithms is an optional list restricting what
+    // signature algorithms the PrivateKey can be used for.
+    SupportedSignatureAlgorithms []SignatureScheme // Go 1.14
+    // OCSPStaple contains an optional OCSP response which will be served
+    // to clients that request it.
+    OCSPStaple []byte
+    // SignedCertificateTimestamps contains an optional list of Signed
+    // Certificate Timestamps which will be served to clients that request it.
+    SignedCertificateTimestamps [][]byte // Go 1.5
+    // Leaf is the parsed form of the leaf certificate, which may be initialized
+    // using x509.ParseCertificate to reduce per-handshake processing. If nil,
+    // the leaf certificate will be parsed as needed.
+    Leaf *x509.Certificate
+}
+

func LoadX509KeyPair

func LoadX509KeyPair(certFile, keyFile string) (Certificate, error)

LoadX509KeyPair reads and parses a public/private key pair from a pair of files. The files must contain PEM encoded data. The certificate file may contain intermediate certificates following the leaf certificate to form a certificate chain. On successful return, Certificate.Leaf will be nil because the parsed form of the certificate is not retained.

Example +

Code:

+cert, err := tls.LoadX509KeyPair("testdata/example-cert.pem", "testdata/example-key.pem")
+if err != nil {
+    log.Fatal(err)
+}
+cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
+listener, err := tls.Listen("tcp", ":2000", cfg)
+if err != nil {
+    log.Fatal(err)
+}
+_ = listener
+

func X509KeyPair

func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error)

X509KeyPair parses a public/private key pair from a pair of PEM encoded data. On successful return, Certificate.Leaf will be nil because the parsed form of the certificate is not retained.

Example +

Code:

+certPem := []byte(`-----BEGIN CERTIFICATE-----
+MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAw
+DgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlow
+EjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d
+7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B
+5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggr
+BgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1
+NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/l
+Wf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc
+6MF9+Yw1Yy0t
+-----END CERTIFICATE-----`)
+keyPem := []byte(`-----BEGIN EC PRIVATE KEY-----
+MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49
+AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8q
+EKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==
+-----END EC PRIVATE KEY-----`)
+cert, err := tls.X509KeyPair(certPem, keyPem)
+if err != nil {
+    log.Fatal(err)
+}
+cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
+listener, err := tls.Listen("tcp", ":2000", cfg)
+if err != nil {
+    log.Fatal(err)
+}
+_ = listener
+

Example (HttpServer) +

Code:

+certPem := []byte(`-----BEGIN CERTIFICATE-----
+MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAw
+DgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlow
+EjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d
+7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B
+5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggr
+BgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1
+NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/l
+Wf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc
+6MF9+Yw1Yy0t
+-----END CERTIFICATE-----`)
+keyPem := []byte(`-----BEGIN EC PRIVATE KEY-----
+MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49
+AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8q
+EKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==
+-----END EC PRIVATE KEY-----`)
+cert, err := tls.X509KeyPair(certPem, keyPem)
+if err != nil {
+    log.Fatal(err)
+}
+cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
+srv := &http.Server{
+    TLSConfig:    cfg,
+    ReadTimeout:  time.Minute,
+    WriteTimeout: time.Minute,
+}
+log.Fatal(srv.ListenAndServeTLS("", ""))
+

type CertificateRequestInfo 1.8

CertificateRequestInfo contains information from a server's CertificateRequest message, which is used to demand a certificate and proof of control from a client.

+
type CertificateRequestInfo struct {
+    // AcceptableCAs contains zero or more, DER-encoded, X.501
+    // Distinguished Names. These are the names of root or intermediate CAs
+    // that the server wishes the returned certificate to be signed by. An
+    // empty slice indicates that the server has no preference.
+    AcceptableCAs [][]byte
+
+    // SignatureSchemes lists the signature schemes that the server is
+    // willing to verify.
+    SignatureSchemes []SignatureScheme
+
+    // Version is the TLS version that was negotiated for this connection.
+    Version uint16 // Go 1.14
+    // contains filtered or unexported fields
+}
+

func (*CertificateRequestInfo) Context 1.17

func (c *CertificateRequestInfo) Context() context.Context

Context returns the context of the handshake that is in progress. This context is a child of the context passed to HandshakeContext, if any, and is canceled when the handshake concludes.

+

func (*CertificateRequestInfo) SupportsCertificate 1.14

func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error

SupportsCertificate returns nil if the provided certificate is supported by the server that sent the CertificateRequest. Otherwise, it returns an error describing the reason for the incompatibility.

+

type CertificateVerificationError 1.20

CertificateVerificationError is returned when certificate verification fails during the handshake.

+
type CertificateVerificationError struct {
+    // UnverifiedCertificates and its contents should not be modified.
+    UnverifiedCertificates []*x509.Certificate
+    Err                    error
+}
+

func (*CertificateVerificationError) Error 1.20

func (e *CertificateVerificationError) Error() string

func (*CertificateVerificationError) Unwrap 1.20

func (e *CertificateVerificationError) Unwrap() error

type CipherSuite 1.14

CipherSuite is a TLS cipher suite. Note that most functions in this package accept and expose cipher suite IDs instead of this type.

+
type CipherSuite struct {
+    ID   uint16
+    Name string
+
+    // Supported versions is the list of TLS protocol versions that can
+    // negotiate this cipher suite.
+    SupportedVersions []uint16
+
+    // Insecure is true if the cipher suite has known security issues
+    // due to its primitives, design, or implementation.
+    Insecure bool
+}
+

func CipherSuites 1.14

func CipherSuites() []*CipherSuite

CipherSuites returns a list of cipher suites currently implemented by this package, excluding those with security issues, which are returned by InsecureCipherSuites.

+

The list is sorted by ID. Note that the default cipher suites selected by this package might depend on logic that can't be captured by a static list, and might not match those returned by this function.

+

func InsecureCipherSuites 1.14

func InsecureCipherSuites() []*CipherSuite

InsecureCipherSuites returns a list of cipher suites currently implemented by this package and which have security issues.

+

Most applications should not use the cipher suites in this list, and should only use those returned by CipherSuites.

+

type ClientAuthType

ClientAuthType declares the policy the server will follow for TLS Client Authentication.

+
type ClientAuthType int
const (
+    // NoClientCert indicates that no client certificate should be requested
+    // during the handshake, and if any certificates are sent they will not
+    // be verified.
+    NoClientCert ClientAuthType = iota
+    // RequestClientCert indicates that a client certificate should be requested
+    // during the handshake, but does not require that the client send any
+    // certificates.
+    RequestClientCert
+    // RequireAnyClientCert indicates that a client certificate should be requested
+    // during the handshake, and that at least one certificate is required to be
+    // sent by the client, but that certificate is not required to be valid.
+    RequireAnyClientCert
+    // VerifyClientCertIfGiven indicates that a client certificate should be requested
+    // during the handshake, but does not require that the client sends a
+    // certificate. If the client does send a certificate it is required to be
+    // valid.
+    VerifyClientCertIfGiven
+    // RequireAndVerifyClientCert indicates that a client certificate should be requested
+    // during the handshake, and that at least one valid certificate is required
+    // to be sent by the client.
+    RequireAndVerifyClientCert
+)

func (ClientAuthType) String 1.15

func (i ClientAuthType) String() string

type ClientHelloInfo 1.4

ClientHelloInfo contains information from a ClientHello message in order to guide application logic in the GetCertificate and GetConfigForClient callbacks.

+
type ClientHelloInfo struct {
+    // CipherSuites lists the CipherSuites supported by the client (e.g.
+    // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
+    CipherSuites []uint16
+
+    // ServerName indicates the name of the server requested by the client
+    // in order to support virtual hosting. ServerName is only set if the
+    // client is using SNI (see RFC 4366, Section 3.1).
+    ServerName string
+
+    // SupportedCurves lists the elliptic curves supported by the client.
+    // SupportedCurves is set only if the Supported Elliptic Curves
+    // Extension is being used (see RFC 4492, Section 5.1.1).
+    SupportedCurves []CurveID
+
+    // SupportedPoints lists the point formats supported by the client.
+    // SupportedPoints is set only if the Supported Point Formats Extension
+    // is being used (see RFC 4492, Section 5.1.2).
+    SupportedPoints []uint8
+
+    // SignatureSchemes lists the signature and hash schemes that the client
+    // is willing to verify. SignatureSchemes is set only if the Signature
+    // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
+    SignatureSchemes []SignatureScheme // Go 1.8
+
+    // SupportedProtos lists the application protocols supported by the client.
+    // SupportedProtos is set only if the Application-Layer Protocol
+    // Negotiation Extension is being used (see RFC 7301, Section 3.1).
+    //
+    // Servers can select a protocol by setting Config.NextProtos in a
+    // GetConfigForClient return value.
+    SupportedProtos []string // Go 1.8
+
+    // SupportedVersions lists the TLS versions supported by the client.
+    // For TLS versions less than 1.3, this is extrapolated from the max
+    // version advertised by the client, so values other than the greatest
+    // might be rejected if used.
+    SupportedVersions []uint16 // Go 1.8
+
+    // Conn is the underlying net.Conn for the connection. Do not read
+    // from, or write to, this connection; that will cause the TLS
+    // connection to fail.
+    Conn net.Conn // Go 1.8
+    // contains filtered or unexported fields
+}
+

func (*ClientHelloInfo) Context 1.17

func (c *ClientHelloInfo) Context() context.Context

Context returns the context of the handshake that is in progress. This context is a child of the context passed to HandshakeContext, if any, and is canceled when the handshake concludes.

+

func (*ClientHelloInfo) SupportsCertificate 1.14

func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error

SupportsCertificate returns nil if the provided certificate is supported by the client that sent the ClientHello. Otherwise, it returns an error describing the reason for the incompatibility.

+

If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate callback, this method will take into account the associated Config. Note that if GetConfigForClient returns a different Config, the change can't be accounted for by this method.

+

This function will call x509.ParseCertificate unless c.Leaf is set, which can incur a significant performance cost.

+

type ClientSessionCache 1.3

ClientSessionCache is a cache of ClientSessionState objects that can be used by a client to resume a TLS session with a given server. ClientSessionCache implementations should expect to be called concurrently from different goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which are supported via this interface.

+
type ClientSessionCache interface {
+    // Get searches for a ClientSessionState associated with the given key.
+    // On return, ok is true if one was found.
+    Get(sessionKey string) (session *ClientSessionState, ok bool)
+
+    // Put adds the ClientSessionState to the cache with the given key. It might
+    // get called multiple times in a connection if a TLS 1.3 server provides
+    // more than one session ticket. If called with a nil *ClientSessionState,
+    // it should remove the cache entry.
+    Put(sessionKey string, cs *ClientSessionState)
+}

func NewLRUClientSessionCache 1.3

func NewLRUClientSessionCache(capacity int) ClientSessionCache

NewLRUClientSessionCache returns a ClientSessionCache with the given capacity that uses an LRU strategy. If capacity is < 1, a default capacity is used instead.

+

type ClientSessionState 1.3

ClientSessionState contains the state needed by a client to resume a previous TLS session.

+
type ClientSessionState struct {
+    // contains filtered or unexported fields
+}
+

func NewResumptionState 1.21

func NewResumptionState(ticket []byte, state *SessionState) (*ClientSessionState, error)

NewResumptionState returns a state value that can be returned by [ClientSessionCache.Get] to resume a previous session.

+

state needs to be returned by ParseSessionState, and the ticket and session state must have been returned by ClientSessionState.ResumptionState.

+

func (*ClientSessionState) ResumptionState 1.21

func (cs *ClientSessionState) ResumptionState() (ticket []byte, state *SessionState, err error)

ResumptionState returns the session ticket sent by the server (also known as the session's identity) and the state necessary to resume this session.

+

It can be called by [ClientSessionCache.Put] to serialize (with SessionState.Bytes) and store the session.

+

type Config

A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified. A Config may be reused; the tls package will also not modify it.

+
type Config struct {
+    // Rand provides the source of entropy for nonces and RSA blinding.
+    // If Rand is nil, TLS uses the cryptographic random reader in package
+    // crypto/rand.
+    // The Reader must be safe for use by multiple goroutines.
+    Rand io.Reader
+
+    // Time returns the current time as the number of seconds since the epoch.
+    // If Time is nil, TLS uses time.Now.
+    Time func() time.Time
+
+    // Certificates contains one or more certificate chains to present to the
+    // other side of the connection. The first certificate compatible with the
+    // peer's requirements is selected automatically.
+    //
+    // Server configurations must set one of Certificates, GetCertificate or
+    // GetConfigForClient. Clients doing client-authentication may set either
+    // Certificates or GetClientCertificate.
+    //
+    // Note: if there are multiple Certificates, and they don't have the
+    // optional field Leaf set, certificate selection will incur a significant
+    // per-handshake performance cost.
+    Certificates []Certificate
+
+    // NameToCertificate maps from a certificate name to an element of
+    // Certificates. Note that a certificate name can be of the form
+    // '*.example.com' and so doesn't have to be a domain name as such.
+    //
+    // Deprecated: NameToCertificate only allows associating a single
+    // certificate with a given name. Leave this field nil to let the library
+    // select the first compatible chain from Certificates.
+    NameToCertificate map[string]*Certificate
+
+    // GetCertificate returns a Certificate based on the given
+    // ClientHelloInfo. It will only be called if the client supplies SNI
+    // information or if Certificates is empty.
+    //
+    // If GetCertificate is nil or returns nil, then the certificate is
+    // retrieved from NameToCertificate. If NameToCertificate is nil, the
+    // best element of Certificates will be used.
+    //
+    // Once a Certificate is returned it should not be modified.
+    GetCertificate func(*ClientHelloInfo) (*Certificate, error) // Go 1.4
+
+    // GetClientCertificate, if not nil, is called when a server requests a
+    // certificate from a client. If set, the contents of Certificates will
+    // be ignored.
+    //
+    // If GetClientCertificate returns an error, the handshake will be
+    // aborted and that error will be returned. Otherwise
+    // GetClientCertificate must return a non-nil Certificate. If
+    // Certificate.Certificate is empty then no certificate will be sent to
+    // the server. If this is unacceptable to the server then it may abort
+    // the handshake.
+    //
+    // GetClientCertificate may be called multiple times for the same
+    // connection if renegotiation occurs or if TLS 1.3 is in use.
+    //
+    // Once a Certificate is returned it should not be modified.
+    GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error) // Go 1.8
+
+    // GetConfigForClient, if not nil, is called after a ClientHello is
+    // received from a client. It may return a non-nil Config in order to
+    // change the Config that will be used to handle this connection. If
+    // the returned Config is nil, the original Config will be used. The
+    // Config returned by this callback may not be subsequently modified.
+    //
+    // If GetConfigForClient is nil, the Config passed to Server() will be
+    // used for all connections.
+    //
+    // If SessionTicketKey was explicitly set on the returned Config, or if
+    // SetSessionTicketKeys was called on the returned Config, those keys will
+    // be used. Otherwise, the original Config keys will be used (and possibly
+    // rotated if they are automatically managed).
+    GetConfigForClient func(*ClientHelloInfo) (*Config, error) // Go 1.8
+
+    // VerifyPeerCertificate, if not nil, is called after normal
+    // certificate verification by either a TLS client or server. It
+    // receives the raw ASN.1 certificates provided by the peer and also
+    // any verified chains that normal processing found. If it returns a
+    // non-nil error, the handshake is aborted and that error results.
+    //
+    // If normal verification fails then the handshake will abort before
+    // considering this callback. If normal verification is disabled (on the
+    // client when InsecureSkipVerify is set, or on a server when ClientAuth is
+    // RequestClientCert or RequireAnyClientCert), then this callback will be
+    // considered but the verifiedChains argument will always be nil. When
+    // ClientAuth is NoClientCert, this callback is not called on the server.
+    // rawCerts may be empty on the server if ClientAuth is RequestClientCert or
+    // VerifyClientCertIfGiven.
+    //
+    // This callback is not invoked on resumed connections, as certificates are
+    // not re-verified on resumption.
+    //
+    // verifiedChains and its contents should not be modified.
+    VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error // Go 1.8
+
+    // VerifyConnection, if not nil, is called after normal certificate
+    // verification and after VerifyPeerCertificate by either a TLS client
+    // or server. If it returns a non-nil error, the handshake is aborted
+    // and that error results.
+    //
+    // If normal verification fails then the handshake will abort before
+    // considering this callback. This callback will run for all connections,
+    // including resumptions, regardless of InsecureSkipVerify or ClientAuth
+    // settings.
+    VerifyConnection func(ConnectionState) error // Go 1.15
+
+    // RootCAs defines the set of root certificate authorities
+    // that clients use when verifying server certificates.
+    // If RootCAs is nil, TLS uses the host's root CA set.
+    RootCAs *x509.CertPool
+
+    // NextProtos is a list of supported application level protocols, in
+    // order of preference. If both peers support ALPN, the selected
+    // protocol will be one from this list, and the connection will fail
+    // if there is no mutually supported protocol. If NextProtos is empty
+    // or the peer doesn't support ALPN, the connection will succeed and
+    // ConnectionState.NegotiatedProtocol will be empty.
+    NextProtos []string
+
+    // ServerName is used to verify the hostname on the returned
+    // certificates unless InsecureSkipVerify is given. It is also included
+    // in the client's handshake to support virtual hosting unless it is
+    // an IP address.
+    ServerName string
+
+    // ClientAuth determines the server's policy for
+    // TLS Client Authentication. The default is NoClientCert.
+    ClientAuth ClientAuthType
+
+    // ClientCAs defines the set of root certificate authorities
+    // that servers use if required to verify a client certificate
+    // by the policy in ClientAuth.
+    ClientCAs *x509.CertPool
+
+    // InsecureSkipVerify controls whether a client verifies the server's
+    // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
+    // accepts any certificate presented by the server and any host name in that
+    // certificate. In this mode, TLS is susceptible to machine-in-the-middle
+    // attacks unless custom verification is used. This should be used only for
+    // testing or in combination with VerifyConnection or VerifyPeerCertificate.
+    InsecureSkipVerify bool
+
+    // CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
+    // the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
+    //
+    // If CipherSuites is nil, a safe default list is used. The default cipher
+    // suites might change over time. In Go 1.22 RSA key exchange based cipher
+    // suites were removed from the default list, but can be re-added with the
+    // GODEBUG setting tlsrsakex=1.
+    CipherSuites []uint16
+
+    // PreferServerCipherSuites is a legacy field and has no effect.
+    //
+    // It used to control whether the server would follow the client's or the
+    // server's preference. Servers now select the best mutually supported
+    // cipher suite based on logic that takes into account inferred client
+    // hardware, server hardware, and security.
+    //
+    // Deprecated: PreferServerCipherSuites is ignored.
+    PreferServerCipherSuites bool // Go 1.1
+
+    // SessionTicketsDisabled may be set to true to disable session ticket and
+    // PSK (resumption) support. Note that on clients, session ticket support is
+    // also disabled if ClientSessionCache is nil.
+    SessionTicketsDisabled bool // Go 1.1
+
+    // SessionTicketKey is used by TLS servers to provide session resumption.
+    // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
+    // with random data before the first server handshake.
+    //
+    // Deprecated: if this field is left at zero, session ticket keys will be
+    // automatically rotated every day and dropped after seven days. For
+    // customizing the rotation schedule or synchronizing servers that are
+    // terminating connections for the same host, use SetSessionTicketKeys.
+    SessionTicketKey [32]byte // Go 1.1
+
+    // ClientSessionCache is a cache of ClientSessionState entries for TLS
+    // session resumption. It is only used by clients.
+    ClientSessionCache ClientSessionCache // Go 1.3
+
+    // UnwrapSession is called on the server to turn a ticket/identity
+    // previously produced by [WrapSession] into a usable session.
+    //
+    // UnwrapSession will usually either decrypt a session state in the ticket
+    // (for example with [Config.EncryptTicket]), or use the ticket as a handle
+    // to recover a previously stored state. It must use [ParseSessionState] to
+    // deserialize the session state.
+    //
+    // If UnwrapSession returns an error, the connection is terminated. If it
+    // returns (nil, nil), the session is ignored. crypto/tls may still choose
+    // not to resume the returned session.
+    UnwrapSession func(identity []byte, cs ConnectionState) (*SessionState, error) // Go 1.21
+
+    // WrapSession is called on the server to produce a session ticket/identity.
+    //
+    // WrapSession must serialize the session state with [SessionState.Bytes].
+    // It may then encrypt the serialized state (for example with
+    // [Config.DecryptTicket]) and use it as the ticket, or store the state and
+    // return a handle for it.
+    //
+    // If WrapSession returns an error, the connection is terminated.
+    //
+    // Warning: the return value will be exposed on the wire and to clients in
+    // plaintext. The application is in charge of encrypting and authenticating
+    // it (and rotating keys) or returning high-entropy identifiers. Failing to
+    // do so correctly can compromise current, previous, and future connections
+    // depending on the protocol version.
+    WrapSession func(ConnectionState, *SessionState) ([]byte, error) // Go 1.21
+
+    // MinVersion contains the minimum TLS version that is acceptable.
+    //
+    // By default, TLS 1.2 is currently used as the minimum. TLS 1.0 is the
+    // minimum supported by this package.
+    //
+    // The server-side default can be reverted to TLS 1.0 by including the value
+    // "tls10server=1" in the GODEBUG environment variable.
+    MinVersion uint16 // Go 1.2
+
+    // MaxVersion contains the maximum TLS version that is acceptable.
+    //
+    // By default, the maximum version supported by this package is used,
+    // which is currently TLS 1.3.
+    MaxVersion uint16 // Go 1.2
+
+    // CurvePreferences contains the elliptic curves that will be used in
+    // an ECDHE handshake, in preference order. If empty, the default will
+    // be used. The client will use the first preference as the type for
+    // its key share in TLS 1.3. This may change in the future.
+    CurvePreferences []CurveID // Go 1.3
+
+    // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
+    // When true, the largest possible TLS record size is always used. When
+    // false, the size of TLS records may be adjusted in an attempt to
+    // improve latency.
+    DynamicRecordSizingDisabled bool // Go 1.7
+
+    // Renegotiation controls what types of renegotiation are supported.
+    // The default, none, is correct for the vast majority of applications.
+    Renegotiation RenegotiationSupport // Go 1.7
+
+    // KeyLogWriter optionally specifies a destination for TLS master secrets
+    // in NSS key log format that can be used to allow external programs
+    // such as Wireshark to decrypt TLS connections.
+    // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
+    // Use of KeyLogWriter compromises security and should only be
+    // used for debugging.
+    KeyLogWriter io.Writer // Go 1.8
+    // contains filtered or unexported fields
+}
+

Example (KeyLogWriter) +

Code:

+// Debugging TLS applications by decrypting a network traffic capture.
+
+// WARNING: Use of KeyLogWriter compromises security and should only be
+// used for debugging.
+
+// Dummy test HTTP server for the example with insecure random so output is
+// reproducible.
+server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
+server.TLS = &tls.Config{
+    Rand: zeroSource{}, // for example only; don't do this.
+}
+server.StartTLS()
+defer server.Close()
+
+// Typically the log would go to an open file:
+// w, err := os.OpenFile("tls-secrets.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
+w := os.Stdout
+
+client := &http.Client{
+    Transport: &http.Transport{
+        TLSClientConfig: &tls.Config{
+            KeyLogWriter: w,
+
+            Rand:               zeroSource{}, // for reproducible output; don't do this.
+            InsecureSkipVerify: true,         // test server certificate is not trusted.
+        },
+    },
+}
+resp, err := client.Get(server.URL)
+if err != nil {
+    log.Fatalf("Failed to get URL: %v", err)
+}
+resp.Body.Close()
+
+// The resulting file can be used with Wireshark to decrypt the TLS
+// connection by setting (Pre)-Master-Secret log filename in SSL Protocol
+// preferences.
+

Example (VerifyConnection) +

Code:

+// VerifyConnection can be used to replace and customize connection
+// verification. This example shows a VerifyConnection implementation that
+// will be approximately equivalent to what crypto/tls does normally to
+// verify the peer's certificate.
+
+// Client side configuration.
+_ = &tls.Config{
+    // Set InsecureSkipVerify to skip the default validation we are
+    // replacing. This will not disable VerifyConnection.
+    InsecureSkipVerify: true,
+    VerifyConnection: func(cs tls.ConnectionState) error {
+        opts := x509.VerifyOptions{
+            DNSName:       cs.ServerName,
+            Intermediates: x509.NewCertPool(),
+        }
+        for _, cert := range cs.PeerCertificates[1:] {
+            opts.Intermediates.AddCert(cert)
+        }
+        _, err := cs.PeerCertificates[0].Verify(opts)
+        return err
+    },
+}
+
+// Server side configuration.
+_ = &tls.Config{
+    // Require client certificates (or VerifyConnection will run anyway and
+    // panic accessing cs.PeerCertificates[0]) but don't verify them with the
+    // default verifier. This will not disable VerifyConnection.
+    ClientAuth: tls.RequireAnyClientCert,
+    VerifyConnection: func(cs tls.ConnectionState) error {
+        opts := x509.VerifyOptions{
+            DNSName:       cs.ServerName,
+            Intermediates: x509.NewCertPool(),
+            KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
+        }
+        for _, cert := range cs.PeerCertificates[1:] {
+            opts.Intermediates.AddCert(cert)
+        }
+        _, err := cs.PeerCertificates[0].Verify(opts)
+        return err
+    },
+}
+
+// Note that when certificates are not handled by the default verifier
+// ConnectionState.VerifiedChains will be nil.
+

func (*Config) BuildNameToCertificate

func (c *Config) BuildNameToCertificate()

BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate from the CommonName and SubjectAlternateName fields of each of the leaf certificates.

+

Deprecated: NameToCertificate only allows associating a single certificate with a given name. Leave that field nil to let the library select the first compatible chain from Certificates.

+

func (*Config) Clone 1.8

func (c *Config) Clone() *Config

Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is being used concurrently by a TLS client or server.

+

func (*Config) DecryptTicket 1.21

func (c *Config) DecryptTicket(identity []byte, cs ConnectionState) (*SessionState, error)

DecryptTicket decrypts a ticket encrypted by Config.EncryptTicket. It can be used as a [Config.UnwrapSession] implementation.

+

If the ticket can't be decrypted or parsed, DecryptTicket returns (nil, nil).

+

func (*Config) EncryptTicket 1.21

func (c *Config) EncryptTicket(cs ConnectionState, ss *SessionState) ([]byte, error)

EncryptTicket encrypts a ticket with the Config's configured (or default) session ticket keys. It can be used as a [Config.WrapSession] implementation.

+

func (*Config) SetSessionTicketKeys 1.5

func (c *Config) SetSessionTicketKeys(keys [][32]byte)

SetSessionTicketKeys updates the session ticket keys for a server.

+

The first key will be used when creating new tickets, while all keys can be used for decrypting tickets. It is safe to call this function while the server is running in order to rotate the session ticket keys. The function will panic if keys is empty.

+

Calling this function will turn off automatic session ticket key rotation.

+

If multiple servers are terminating connections for the same host they should all have the same session ticket keys. If the session ticket keys leaks, previously recorded and future TLS connections using those keys might be compromised.

+

type Conn

A Conn represents a secured connection. It implements the net.Conn interface.

+
type Conn struct {
+    // contains filtered or unexported fields
+}
+

func Client

func Client(conn net.Conn, config *Config) *Conn

Client returns a new TLS client side connection using conn as the underlying transport. The config cannot be nil: users must set either ServerName or InsecureSkipVerify in the config.

+

func Dial

func Dial(network, addr string, config *Config) (*Conn, error)

Dial connects to the given network address using net.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Dial interprets a nil configuration as equivalent to the zero configuration; see the documentation of Config for the defaults.

Example +

Code:

+// Connecting with a custom root-certificate set.
+
+const rootPEM = `
+-- GlobalSign Root R2, valid until Dec 15, 2021
+-----BEGIN CERTIFICATE-----
+MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4G
+A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNp
+Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1
+MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEG
+A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI
+hvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPL
+v4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8
+eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklq
+tTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd
+C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pa
+zq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCB
+mTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IH
+V2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5n
+bG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG
+3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs
+J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO
+291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavS
+ot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd
+AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7
+TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg==
+-----END CERTIFICATE-----`
+
+// First, create the set of root certificates. For this example we only
+// have one. It's also possible to omit this in order to use the
+// default root set of the current operating system.
+roots := x509.NewCertPool()
+ok := roots.AppendCertsFromPEM([]byte(rootPEM))
+if !ok {
+    panic("failed to parse root certificate")
+}
+
+conn, err := tls.Dial("tcp", "mail.google.com:443", &tls.Config{
+    RootCAs: roots,
+})
+if err != nil {
+    panic("failed to connect: " + err.Error())
+}
+conn.Close()
+

func DialWithDialer 1.3

func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error)

DialWithDialer connects to the given network address using dialer.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Any timeout or deadline given in the dialer apply to connection and TLS handshake as a whole.

+

DialWithDialer interprets a nil configuration as equivalent to the zero configuration; see the documentation of Config for the defaults.

+

DialWithDialer uses context.Background internally; to specify the context, use Dialer.DialContext with NetDialer set to the desired dialer.

+

func Server

func Server(conn net.Conn, config *Config) *Conn

Server returns a new TLS server side connection using conn as the underlying transport. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.

+

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection.

+

func (*Conn) CloseWrite 1.8

func (c *Conn) CloseWrite() error

CloseWrite shuts down the writing side of the connection. It should only be called once the handshake has completed and does not call CloseWrite on the underlying connection. Most callers should just use Conn.Close.

+

func (*Conn) ConnectionState

func (c *Conn) ConnectionState() ConnectionState

ConnectionState returns basic TLS details about the connection.

+

func (*Conn) Handshake

func (c *Conn) Handshake() error

Handshake runs the client or server handshake protocol if it has not yet been run.

+

Most uses of this package need not call Handshake explicitly: the first Conn.Read or Conn.Write will call it automatically.

+

For control over canceling or setting a timeout on a handshake, use Conn.HandshakeContext or the Dialer's DialContext method instead.

+

In order to avoid denial of service attacks, the maximum RSA key size allowed in certificates sent by either the TLS server or client is limited to 8192 bits. This limit can be overridden by setting tlsmaxrsasize in the GODEBUG environment variable (e.g. GODEBUG=tlsmaxrsasize=4096).

+

func (*Conn) HandshakeContext 1.17

func (c *Conn) HandshakeContext(ctx context.Context) error

HandshakeContext runs the client or server handshake protocol if it has not yet been run.

+

The provided Context must be non-nil. If the context is canceled before the handshake is complete, the handshake is interrupted and an error is returned. Once the handshake has completed, cancellation of the context will not affect the connection.

+

Most uses of this package need not call HandshakeContext explicitly: the first Conn.Read or Conn.Write will call it automatically.

+

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local network address.

+

func (*Conn) NetConn 1.18

func (c *Conn) NetConn() net.Conn

NetConn returns the underlying connection that is wrapped by c. Note that writing to or reading from this connection directly will corrupt the TLS session.

+

func (*Conn) OCSPResponse

func (c *Conn) OCSPResponse() []byte

OCSPResponse returns the stapled OCSP response from the TLS server, if any. (Only valid for client connections.)

+

func (*Conn) Read

func (c *Conn) Read(b []byte) (int, error)

Read reads data from the connection.

+

As Read calls Conn.Handshake, in order to prevent indefinite blocking a deadline must be set for both Read and Conn.Write before Read is called when the handshake has not yet completed. See Conn.SetDeadline, Conn.SetReadDeadline, and Conn.SetWriteDeadline.

+

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

+

func (*Conn) SetDeadline

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the connection. A zero value for t means Conn.Read and Conn.Write will not time out. After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.

+

func (*Conn) SetReadDeadline

func (c *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline on the underlying connection. A zero value for t means Conn.Read will not time out.

+

func (*Conn) SetWriteDeadline

func (c *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline on the underlying connection. A zero value for t means Conn.Write will not time out. After a Conn.Write has timed out, the TLS state is corrupt and all future writes will return the same error.

+

func (*Conn) VerifyHostname

func (c *Conn) VerifyHostname(host string) error

VerifyHostname checks that the peer certificate chain is valid for connecting to host. If so, it returns nil; if not, it returns an error describing the problem.

+

func (*Conn) Write

func (c *Conn) Write(b []byte) (int, error)

Write writes data to the connection.

+

As Write calls Conn.Handshake, in order to prevent indefinite blocking a deadline must be set for both Conn.Read and Write before Write is called when the handshake has not yet completed. See Conn.SetDeadline, Conn.SetReadDeadline, and Conn.SetWriteDeadline.

+

type ConnectionState

ConnectionState records basic TLS details about the connection.

+
type ConnectionState struct {
+    // Version is the TLS version used by the connection (e.g. VersionTLS12).
+    Version uint16 // Go 1.3
+
+    // HandshakeComplete is true if the handshake has concluded.
+    HandshakeComplete bool
+
+    // DidResume is true if this connection was successfully resumed from a
+    // previous session with a session ticket or similar mechanism.
+    DidResume bool // Go 1.1
+
+    // CipherSuite is the cipher suite negotiated for the connection (e.g.
+    // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
+    CipherSuite uint16
+
+    // NegotiatedProtocol is the application protocol negotiated with ALPN.
+    NegotiatedProtocol string
+
+    // NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
+    //
+    // Deprecated: this value is always true.
+    NegotiatedProtocolIsMutual bool
+
+    // ServerName is the value of the Server Name Indication extension sent by
+    // the client. It's available both on the server and on the client side.
+    ServerName string
+
+    // PeerCertificates are the parsed certificates sent by the peer, in the
+    // order in which they were sent. The first element is the leaf certificate
+    // that the connection is verified against.
+    //
+    // On the client side, it can't be empty. On the server side, it can be
+    // empty if Config.ClientAuth is not RequireAnyClientCert or
+    // RequireAndVerifyClientCert.
+    //
+    // PeerCertificates and its contents should not be modified.
+    PeerCertificates []*x509.Certificate
+
+    // VerifiedChains is a list of one or more chains where the first element is
+    // PeerCertificates[0] and the last element is from Config.RootCAs (on the
+    // client side) or Config.ClientCAs (on the server side).
+    //
+    // On the client side, it's set if Config.InsecureSkipVerify is false. On
+    // the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
+    // (and the peer provided a certificate) or RequireAndVerifyClientCert.
+    //
+    // VerifiedChains and its contents should not be modified.
+    VerifiedChains [][]*x509.Certificate
+
+    // SignedCertificateTimestamps is a list of SCTs provided by the peer
+    // through the TLS handshake for the leaf certificate, if any.
+    SignedCertificateTimestamps [][]byte // Go 1.5
+
+    // OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
+    // response provided by the peer for the leaf certificate, if any.
+    OCSPResponse []byte // Go 1.5
+
+    // TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
+    // Section 3). This value will be nil for TLS 1.3 connections and for
+    // resumed connections that don't support Extended Master Secret (RFC 7627).
+    TLSUnique []byte // Go 1.4
+    // contains filtered or unexported fields
+}
+

func (*ConnectionState) ExportKeyingMaterial 1.11

func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error)

ExportKeyingMaterial returns length bytes of exported key material in a new slice as defined in RFC 5705. If context is nil, it is not used as part of the seed. If the connection was set to allow renegotiation via Config.Renegotiation, or if the connections supports neither TLS 1.3 nor Extended Master Secret, this function will return an error.

+

Exporting key material without Extended Master Secret or TLS 1.3 was disabled in Go 1.22 due to security issues (see the Security Considerations sections of RFC 5705 and RFC 7627), but can be re-enabled with the GODEBUG setting tlsunsafeekm=1.

+

type CurveID 1.3

CurveID is the type of a TLS identifier for an elliptic curve. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.

+

In TLS 1.3, this type is called NamedGroup, but at this time this library only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.

+
type CurveID uint16
const (
+    CurveP256 CurveID = 23
+    CurveP384 CurveID = 24
+    CurveP521 CurveID = 25
+    X25519    CurveID = 29
+)

func (CurveID) String 1.15

func (i CurveID) String() string

type Dialer 1.15

Dialer dials TLS connections given a configuration and a Dialer for the underlying connection.

+
type Dialer struct {
+    // NetDialer is the optional dialer to use for the TLS connections'
+    // underlying TCP connections.
+    // A nil NetDialer is equivalent to the net.Dialer zero value.
+    NetDialer *net.Dialer
+
+    // Config is the TLS configuration to use for new connections.
+    // A nil configuration is equivalent to the zero
+    // configuration; see the documentation of Config for the
+    // defaults.
+    Config *Config
+}
+

func (*Dialer) Dial 1.15

func (d *Dialer) Dial(network, addr string) (net.Conn, error)

Dial connects to the given network address and initiates a TLS handshake, returning the resulting TLS connection.

+

The returned Conn, if any, will always be of type *Conn.

+

Dial uses context.Background internally; to specify the context, use Dialer.DialContext.

+

func (*Dialer) DialContext 1.15

func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error)

DialContext connects to the given network address and initiates a TLS handshake, returning the resulting TLS connection.

+

The provided Context must be non-nil. If the context expires before the connection is complete, an error is returned. Once successfully connected, any expiration of the context will not affect the connection.

+

The returned Conn, if any, will always be of type *Conn.

+

type QUICConfig 1.21

A QUICConfig configures a QUICConn.

+
type QUICConfig struct {
+    TLSConfig *Config
+}
+

type QUICConn 1.21

A QUICConn represents a connection which uses a QUIC implementation as the underlying transport as described in RFC 9001.

+

Methods of QUICConn are not safe for concurrent use.

+
type QUICConn struct {
+    // contains filtered or unexported fields
+}
+

func QUICClient 1.21

func QUICClient(config *QUICConfig) *QUICConn

QUICClient returns a new TLS client side connection using QUICTransport as the underlying transport. The config cannot be nil.

+

The config's MinVersion must be at least TLS 1.3.

+

func QUICServer 1.21

func QUICServer(config *QUICConfig) *QUICConn

QUICServer returns a new TLS server side connection using QUICTransport as the underlying transport. The config cannot be nil.

+

The config's MinVersion must be at least TLS 1.3.

+

func (*QUICConn) Close 1.21

func (q *QUICConn) Close() error

Close closes the connection and stops any in-progress handshake.

+

func (*QUICConn) ConnectionState 1.21

func (q *QUICConn) ConnectionState() ConnectionState

ConnectionState returns basic TLS details about the connection.

+

func (*QUICConn) HandleData 1.21

func (q *QUICConn) HandleData(level QUICEncryptionLevel, data []byte) error

HandleData handles handshake bytes received from the peer. It may produce connection events, which may be read with QUICConn.NextEvent.

+

func (*QUICConn) NextEvent 1.21

func (q *QUICConn) NextEvent() QUICEvent

NextEvent returns the next event occurring on the connection. It returns an event with a Kind of QUICNoEvent when no events are available.

+

func (*QUICConn) SendSessionTicket 1.21

func (q *QUICConn) SendSessionTicket(opts QUICSessionTicketOptions) error

SendSessionTicket sends a session ticket to the client. It produces connection events, which may be read with QUICConn.NextEvent. Currently, it can only be called once.

+

func (*QUICConn) SetTransportParameters 1.21

func (q *QUICConn) SetTransportParameters(params []byte)

SetTransportParameters sets the transport parameters to send to the peer.

+

Server connections may delay setting the transport parameters until after receiving the client's transport parameters. See QUICTransportParametersRequired.

+

func (*QUICConn) Start 1.21

func (q *QUICConn) Start(ctx context.Context) error

Start starts the client or server handshake protocol. It may produce connection events, which may be read with QUICConn.NextEvent.

+

Start must be called at most once.

+

type QUICEncryptionLevel 1.21

QUICEncryptionLevel represents a QUIC encryption level used to transmit handshake messages.

+
type QUICEncryptionLevel int

func (QUICEncryptionLevel) String 1.21

func (l QUICEncryptionLevel) String() string

type QUICEvent 1.21

A QUICEvent is an event occurring on a QUIC connection.

+

The type of event is specified by the Kind field. The contents of the other fields are kind-specific.

+
type QUICEvent struct {
+    Kind QUICEventKind
+
+    // Set for QUICSetReadSecret, QUICSetWriteSecret, and QUICWriteData.
+    Level QUICEncryptionLevel
+
+    // Set for QUICTransportParameters, QUICSetReadSecret, QUICSetWriteSecret, and QUICWriteData.
+    // The contents are owned by crypto/tls, and are valid until the next NextEvent call.
+    Data []byte
+
+    // Set for QUICSetReadSecret and QUICSetWriteSecret.
+    Suite uint16
+}
+

type QUICEventKind 1.21

A QUICEventKind is a type of operation on a QUIC connection.

+
type QUICEventKind int
const (
+    // QUICNoEvent indicates that there are no events available.
+    QUICNoEvent QUICEventKind = iota
+
+    // QUICSetReadSecret and QUICSetWriteSecret provide the read and write
+    // secrets for a given encryption level.
+    // QUICEvent.Level, QUICEvent.Data, and QUICEvent.Suite are set.
+    //
+    // Secrets for the Initial encryption level are derived from the initial
+    // destination connection ID, and are not provided by the QUICConn.
+    QUICSetReadSecret
+    QUICSetWriteSecret
+
+    // QUICWriteData provides data to send to the peer in CRYPTO frames.
+    // QUICEvent.Data is set.
+    QUICWriteData
+
+    // QUICTransportParameters provides the peer's QUIC transport parameters.
+    // QUICEvent.Data is set.
+    QUICTransportParameters
+
+    // QUICTransportParametersRequired indicates that the caller must provide
+    // QUIC transport parameters to send to the peer. The caller should set
+    // the transport parameters with QUICConn.SetTransportParameters and call
+    // QUICConn.NextEvent again.
+    //
+    // If transport parameters are set before calling QUICConn.Start, the
+    // connection will never generate a QUICTransportParametersRequired event.
+    QUICTransportParametersRequired
+
+    // QUICRejectedEarlyData indicates that the server rejected 0-RTT data even
+    // if we offered it. It's returned before QUICEncryptionLevelApplication
+    // keys are returned.
+    QUICRejectedEarlyData
+
+    // QUICHandshakeDone indicates that the TLS handshake has completed.
+    QUICHandshakeDone
+)

type QUICSessionTicketOptions 1.21

type QUICSessionTicketOptions struct {
+    // EarlyData specifies whether the ticket may be used for 0-RTT.
+    EarlyData bool
+}
+

type RecordHeaderError 1.6

RecordHeaderError is returned when a TLS record header is invalid.

+
type RecordHeaderError struct {
+    // Msg contains a human readable string that describes the error.
+    Msg string
+    // RecordHeader contains the five bytes of TLS record header that
+    // triggered the error.
+    RecordHeader [5]byte
+    // Conn provides the underlying net.Conn in the case that a client
+    // sent an initial handshake that didn't look like TLS.
+    // It is nil if there's already been a handshake or a TLS alert has
+    // been written to the connection.
+    Conn net.Conn // Go 1.12
+}
+

func (RecordHeaderError) Error 1.6

func (e RecordHeaderError) Error() string

type RenegotiationSupport 1.7

RenegotiationSupport enumerates the different levels of support for TLS renegotiation. TLS renegotiation is the act of performing subsequent handshakes on a connection after the first. This significantly complicates the state machine and has been the source of numerous, subtle security issues. Initiating a renegotiation is not supported, but support for accepting renegotiation requests may be enabled.

+

Even when enabled, the server may not change its identity between handshakes (i.e. the leaf certificate must be the same). Additionally, concurrent handshake and application data flow is not permitted so renegotiation can only be used with protocols that synchronise with the renegotiation, such as HTTPS.

+

Renegotiation is not defined in TLS 1.3.

+
type RenegotiationSupport int
const (
+    // RenegotiateNever disables renegotiation.
+    RenegotiateNever RenegotiationSupport = iota
+
+    // RenegotiateOnceAsClient allows a remote server to request
+    // renegotiation once per connection.
+    RenegotiateOnceAsClient
+
+    // RenegotiateFreelyAsClient allows a remote server to repeatedly
+    // request renegotiation.
+    RenegotiateFreelyAsClient
+)

type SessionState 1.21

A SessionState is a resumable session.

+
type SessionState struct {
+
+    // Extra is ignored by crypto/tls, but is encoded by [SessionState.Bytes]
+    // and parsed by [ParseSessionState].
+    //
+    // This allows [Config.UnwrapSession]/[Config.WrapSession] and
+    // [ClientSessionCache] implementations to store and retrieve additional
+    // data alongside this session.
+    //
+    // To allow different layers in a protocol stack to share this field,
+    // applications must only append to it, not replace it, and must use entries
+    // that can be recognized even if out of order (for example, by starting
+    // with an id and version prefix).
+    Extra [][]byte
+
+    // EarlyData indicates whether the ticket can be used for 0-RTT in a QUIC
+    // connection. The application may set this to false if it is true to
+    // decline to offer 0-RTT even if supported.
+    EarlyData bool
+    // contains filtered or unexported fields
+}
+

func ParseSessionState 1.21

func ParseSessionState(data []byte) (*SessionState, error)

ParseSessionState parses a SessionState encoded by SessionState.Bytes.

+

func (*SessionState) Bytes 1.21

func (s *SessionState) Bytes() ([]byte, error)

Bytes encodes the session, including any private fields, so that it can be parsed by ParseSessionState. The encoding contains secret values critical to the security of future and possibly past sessions.

+

The specific encoding should be considered opaque and may change incompatibly between Go versions.

+

type SignatureScheme 1.8

SignatureScheme identifies a signature algorithm supported by TLS. See RFC 8446, Section 4.2.3.

+
type SignatureScheme uint16
const (
+    // RSASSA-PKCS1-v1_5 algorithms.
+    PKCS1WithSHA256 SignatureScheme = 0x0401
+    PKCS1WithSHA384 SignatureScheme = 0x0501
+    PKCS1WithSHA512 SignatureScheme = 0x0601
+
+    // RSASSA-PSS algorithms with public key OID rsaEncryption.
+    PSSWithSHA256 SignatureScheme = 0x0804
+    PSSWithSHA384 SignatureScheme = 0x0805
+    PSSWithSHA512 SignatureScheme = 0x0806
+
+    // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
+    ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
+    ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
+    ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
+
+    // EdDSA algorithms.
+    Ed25519 SignatureScheme = 0x0807
+
+    // Legacy signature and hash algorithms for TLS 1.2.
+    PKCS1WithSHA1 SignatureScheme = 0x0201
+    ECDSAWithSHA1 SignatureScheme = 0x0203
+)

func (SignatureScheme) String 1.15

func (i SignatureScheme) String() string

Bugs

Subdirectories

Name Synopsis
..
fipsonly Package fipsonly restricts all TLS configuration to FIPS-approved settings.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/tls/ +

+
diff --git a/devdocs/go/crypto%2Fx509%2Findex.html b/devdocs/go/crypto%2Fx509%2Findex.html new file mode 100644 index 00000000..92829477 --- /dev/null +++ b/devdocs/go/crypto%2Fx509%2Findex.html @@ -0,0 +1,785 @@ +

Package x509

Overview

Package x509 implements a subset of the X.509 standard.

+

It allows parsing and generating certificates, certificate signing requests, certificate revocation lists, and encoded public and private keys. It provides a certificate verifier, complete with a chain builder.

+

The package targets the X.509 technical profile defined by the IETF (RFC 2459/3280/5280), and as further restricted by the CA/Browser Forum Baseline Requirements. There is minimal support for features outside of these profiles, as the primary goal of the package is to provide compatibility with the publicly trusted TLS certificate ecosystem and its policies and constraints.

+

On macOS and Windows, certificate verification is handled by system APIs, but the package aims to apply consistent validation rules across operating systems.

Index

Examples

Certificate.Verify
ParsePKIXPublicKey

Package files

cert_pool.go notboring.go oid.go parser.go pem_decrypt.go pkcs1.go pkcs8.go root.go root_linux.go root_unix.go sec1.go verify.go x509.go

Variables

ErrUnsupportedAlgorithm results from attempting to perform an operation that involves algorithms that are not currently implemented.

+
var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")

IncorrectPasswordError is returned when an incorrect password is detected.

+
var IncorrectPasswordError = errors.New("x509: decryption password incorrect")

func CreateCertificate

func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error)

CreateCertificate creates a new X.509 v3 certificate based on a template. The following members of template are currently used:

+

The certificate is signed by parent. If parent is equal to template then the certificate is self-signed. The parameter pub is the public key of the certificate to be generated and priv is the private key of the signer.

+

The returned slice is the certificate in DER encoding.

+

The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and ed25519.PublicKey. pub must be a supported key type, and priv must be a crypto.Signer with a supported public key.

+

The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any, unless the resulting certificate is self-signed. Otherwise the value from template will be used.

+

If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId will be generated from the hash of the public key.

+

The PolicyIdentifier and Policies fields are both used to marshal certificate policy OIDs. By default, only the PolicyIdentifier is marshaled, but if the GODEBUG setting "x509usepolicies" has the value "1", the Policies field will be marshalled instead of the PolicyIdentifier field. The Policies field can be used to marshal policy OIDs which have components that are larger than 31 bits.

+

func CreateCertificateRequest 1.3

func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error)

CreateCertificateRequest creates a new certificate request based on a template. The following members of template are used:

+

priv is the private key to sign the CSR with, and the corresponding public key will be included in the CSR. It must implement crypto.Signer and its Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or ed25519.PrivateKey satisfies this.)

+

The returned slice is the certificate request in DER encoding.

+

func CreateRevocationList 1.15

func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error)

CreateRevocationList creates a new X.509 v2 Certificate Revocation List, according to RFC 5280, based on template.

+

The CRL is signed by priv which should be the private key associated with the public key in the issuer certificate.

+

The issuer may not be nil, and the crlSign bit must be set in KeyUsage in order to use it as a CRL issuer.

+

The issuer distinguished name CRL field and authority key identifier extension are populated using the issuer certificate. issuer must have SubjectKeyId set.

+

func DecryptPEMBlock 1.1

func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)

DecryptPEMBlock takes a PEM block encrypted according to RFC 1423 and the password used to encrypt it and returns a slice of decrypted DER encoded bytes. It inspects the DEK-Info header to determine the algorithm used for decryption. If no DEK-Info header is present, an error is returned. If an incorrect password is detected an IncorrectPasswordError is returned. Because of deficiencies in the format, it's not always possible to detect an incorrect password. In these cases no error will be returned but the decrypted DER bytes will be random noise.

+

Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.

+

func EncryptPEMBlock 1.1

func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)

EncryptPEMBlock returns a PEM block of the specified type holding the given DER encoded data encrypted with the specified algorithm and password according to RFC 1423.

+

Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.

+

func IsEncryptedPEMBlock 1.1

func IsEncryptedPEMBlock(b *pem.Block) bool

IsEncryptedPEMBlock returns whether the PEM block is password encrypted according to RFC 1423.

+

Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.

+

func MarshalECPrivateKey 1.2

func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error)

MarshalECPrivateKey converts an EC private key to SEC 1, ASN.1 DER form.

+

This kind of key is commonly encoded in PEM blocks of type "EC PRIVATE KEY". For a more flexible key format which is not EC specific, use MarshalPKCS8PrivateKey.

+

func MarshalPKCS1PrivateKey

func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte

MarshalPKCS1PrivateKey converts an RSA private key to PKCS #1, ASN.1 DER form.

+

This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY". For a more flexible key format which is not RSA specific, use MarshalPKCS8PrivateKey.

+

func MarshalPKCS1PublicKey 1.10

func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte

MarshalPKCS1PublicKey converts an RSA public key to PKCS #1, ASN.1 DER form.

+

This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".

+

func MarshalPKCS8PrivateKey 1.10

func MarshalPKCS8PrivateKey(key any) ([]byte, error)

MarshalPKCS8PrivateKey converts a private key to PKCS #8, ASN.1 DER form.

+

The following key types are currently supported: *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey (not a pointer), and *ecdh.PrivateKey. Unsupported key types result in an error.

+

This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".

+

func MarshalPKIXPublicKey

func MarshalPKIXPublicKey(pub any) ([]byte, error)

MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form. The encoded public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).

+

The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey (not a pointer), and *ecdh.PublicKey. Unsupported key types result in an error.

+

This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".

+

func ParseCRL

func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error)

ParseCRL parses a CRL from the given bytes. It's often the case that PEM encoded CRLs will appear where they should be DER encoded, so this function will transparently handle PEM encoding as long as there isn't any leading garbage.

+

Deprecated: Use ParseRevocationList instead.

+

func ParseDERCRL

func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error)

ParseDERCRL parses a DER encoded CRL from the given bytes.

+

Deprecated: Use ParseRevocationList instead.

+

func ParseECPrivateKey 1.1

func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)

ParseECPrivateKey parses an EC private key in SEC 1, ASN.1 DER form.

+

This kind of key is commonly encoded in PEM blocks of type "EC PRIVATE KEY".

+

func ParsePKCS1PrivateKey

func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)

ParsePKCS1PrivateKey parses an RSA private key in PKCS #1, ASN.1 DER form.

+

This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY".

+

func ParsePKCS1PublicKey 1.10

func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error)

ParsePKCS1PublicKey parses an RSA public key in PKCS #1, ASN.1 DER form.

+

This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".

+

func ParsePKCS8PrivateKey

func ParsePKCS8PrivateKey(der []byte) (key any, err error)

ParsePKCS8PrivateKey parses an unencrypted private key in PKCS #8, ASN.1 DER form.

+

It returns a *rsa.PrivateKey, an *ecdsa.PrivateKey, an ed25519.PrivateKey (not a pointer), or an *ecdh.PrivateKey (for X25519). More types might be supported in the future.

+

This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".

+

func ParsePKIXPublicKey

func ParsePKIXPublicKey(derBytes []byte) (pub any, err error)

ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. The encoded public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).

+

It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey (not a pointer), or *ecdh.PublicKey (for X25519). More types might be supported in the future.

+

This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".

Example +

Code:

+const pubPEM = `
+-----BEGIN PUBLIC KEY-----
+MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlRuRnThUjU8/prwYxbty
+WPT9pURI3lbsKMiB6Fn/VHOKE13p4D8xgOCADpdRagdT6n4etr9atzDKUSvpMtR3
+CP5noNc97WiNCggBjVWhs7szEe8ugyqF23XwpHQ6uV1LKH50m92MbOWfCtjU9p/x
+qhNpQQ1AZhqNy5Gevap5k8XzRmjSldNAFZMY7Yv3Gi+nyCwGwpVtBUwhuLzgNFK/
+yDtw2WcWmUU7NuC8Q6MWvPebxVtCfVp/iQU6q60yyt6aGOBkhAX0LpKAEhKidixY
+nP9PNVBvxgu3XZ4P36gZV6+ummKdBVnc3NqwBLu5+CcdRdusmHPHd5pHf4/38Z3/
+6qU2a/fPvWzceVTEgZ47QjFMTCTmCwNt29cvi7zZeQzjtwQgn4ipN9NibRH/Ax/q
+TbIzHfrJ1xa2RteWSdFjwtxi9C20HUkjXSeI4YlzQMH0fPX6KCE7aVePTOnB69I/
+a9/q96DiXZajwlpq3wFctrs1oXqBp5DVrCIj8hU2wNgB7LtQ1mCtsYz//heai0K9
+PhE4X6hiE0YmeAZjR0uHl8M/5aW9xCoJ72+12kKpWAa0SFRWLy6FejNYCYpkupVJ
+yecLk/4L1W0l6jQQZnWErXZYe0PNFcmwGXy1Rep83kfBRNKRy5tvocalLlwXLdUk
+AIU+2GKjyT3iMuzZxxFxPFMCAwEAAQ==
+-----END PUBLIC KEY-----`
+
+block, _ := pem.Decode([]byte(pubPEM))
+if block == nil {
+    panic("failed to parse PEM block containing the public key")
+}
+
+pub, err := x509.ParsePKIXPublicKey(block.Bytes)
+if err != nil {
+    panic("failed to parse DER encoded public key: " + err.Error())
+}
+
+switch pub := pub.(type) {
+case *rsa.PublicKey:
+    fmt.Println("pub is of type RSA:", pub)
+case *dsa.PublicKey:
+    fmt.Println("pub is of type DSA:", pub)
+case *ecdsa.PublicKey:
+    fmt.Println("pub is of type ECDSA:", pub)
+case ed25519.PublicKey:
+    fmt.Println("pub is of type Ed25519:", pub)
+default:
+    panic("unknown type of public key")
+}
+

func SetFallbackRoots 1.20

func SetFallbackRoots(roots *CertPool)

SetFallbackRoots sets the roots to use during certificate verification, if no custom roots are specified and a platform verifier or a system certificate pool is not available (for instance in a container which does not have a root certificate bundle). SetFallbackRoots will panic if roots is nil.

+

SetFallbackRoots may only be called once, if called multiple times it will panic.

+

The fallback behavior can be forced on all platforms, even when there is a system certificate pool, by setting GODEBUG=x509usefallbackroots=1 (note that on Windows and macOS this will disable usage of the platform verification APIs and cause the pure Go verifier to be used). Setting x509usefallbackroots=1 without calling SetFallbackRoots has no effect.

+

type CertPool

CertPool is a set of certificates.

+
type CertPool struct {
+    // contains filtered or unexported fields
+}
+

func NewCertPool

func NewCertPool() *CertPool

NewCertPool returns a new, empty CertPool.

+

func SystemCertPool 1.7

func SystemCertPool() (*CertPool, error)

SystemCertPool returns a copy of the system cert pool.

+

On Unix systems other than macOS the environment variables SSL_CERT_FILE and SSL_CERT_DIR can be used to override the system default locations for the SSL certificate file and SSL certificate files directory, respectively. The latter can be a colon-separated list.

+

Any mutations to the returned pool are not written to disk and do not affect any other pool returned by SystemCertPool.

+

New changes in the system cert pool might not be reflected in subsequent calls.

+

func (*CertPool) AddCert

func (s *CertPool) AddCert(cert *Certificate)

AddCert adds a certificate to a pool.

+

func (*CertPool) AddCertWithConstraint 1.22

func (s *CertPool) AddCertWithConstraint(cert *Certificate, constraint func([]*Certificate) error)

AddCertWithConstraint adds a certificate to the pool with the additional constraint. When Certificate.Verify builds a chain which is rooted by cert, it will additionally pass the whole chain to constraint to determine its validity. If constraint returns a non-nil error, the chain will be discarded. constraint may be called concurrently from multiple goroutines.

+

func (*CertPool) AppendCertsFromPEM

func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)

AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. It appends any certificates found to s and reports whether any certificates were successfully parsed.

+

On many Linux systems, /etc/ssl/cert.pem will contain the system wide set of root CAs in a format suitable for this function.

+

func (*CertPool) Clone 1.19

func (s *CertPool) Clone() *CertPool

Clone returns a copy of s.

+

func (*CertPool) Equal 1.19

func (s *CertPool) Equal(other *CertPool) bool

Equal reports whether s and other are equal.

+

func (*CertPool) Subjects

func (s *CertPool) Subjects() [][]byte

Subjects returns a list of the DER-encoded subjects of all of the certificates in the pool.

+

Deprecated: if s was returned by SystemCertPool, Subjects will not include the system roots.

+

type Certificate

A Certificate represents an X.509 certificate.

+
type Certificate struct {
+    Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
+    RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
+    RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
+    RawSubject              []byte // DER encoded Subject
+    RawIssuer               []byte // DER encoded Issuer
+
+    Signature          []byte
+    SignatureAlgorithm SignatureAlgorithm
+
+    PublicKeyAlgorithm PublicKeyAlgorithm
+    PublicKey          any
+
+    Version             int
+    SerialNumber        *big.Int
+    Issuer              pkix.Name
+    Subject             pkix.Name
+    NotBefore, NotAfter time.Time // Validity bounds.
+    KeyUsage            KeyUsage
+
+    // Extensions contains raw X.509 extensions. When parsing certificates,
+    // this can be used to extract non-critical extensions that are not
+    // parsed by this package. When marshaling certificates, the Extensions
+    // field is ignored, see ExtraExtensions.
+    Extensions []pkix.Extension // Go 1.2
+
+    // ExtraExtensions contains extensions to be copied, raw, into any
+    // marshaled certificates. Values override any extensions that would
+    // otherwise be produced based on the other fields. The ExtraExtensions
+    // field is not populated when parsing certificates, see Extensions.
+    ExtraExtensions []pkix.Extension // Go 1.2
+
+    // UnhandledCriticalExtensions contains a list of extension IDs that
+    // were not (fully) processed when parsing. Verify will fail if this
+    // slice is non-empty, unless verification is delegated to an OS
+    // library which understands all the critical extensions.
+    //
+    // Users can access these extensions using Extensions and can remove
+    // elements from this slice if they believe that they have been
+    // handled.
+    UnhandledCriticalExtensions []asn1.ObjectIdentifier // Go 1.5
+
+    ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
+    UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
+
+    // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
+    // and MaxPathLenZero are valid.
+    BasicConstraintsValid bool
+    IsCA                  bool
+
+    // MaxPathLen and MaxPathLenZero indicate the presence and
+    // value of the BasicConstraints' "pathLenConstraint".
+    //
+    // When parsing a certificate, a positive non-zero MaxPathLen
+    // means that the field was specified, -1 means it was unset,
+    // and MaxPathLenZero being true mean that the field was
+    // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
+    // should be treated equivalent to -1 (unset).
+    //
+    // When generating a certificate, an unset pathLenConstraint
+    // can be requested with either MaxPathLen == -1 or using the
+    // zero value for both MaxPathLen and MaxPathLenZero.
+    MaxPathLen int
+    // MaxPathLenZero indicates that BasicConstraintsValid==true
+    // and MaxPathLen==0 should be interpreted as an actual
+    // maximum path length of zero. Otherwise, that combination is
+    // interpreted as MaxPathLen not being set.
+    MaxPathLenZero bool // Go 1.4
+
+    SubjectKeyId   []byte
+    AuthorityKeyId []byte
+
+    // RFC 5280, 4.2.2.1 (Authority Information Access)
+    OCSPServer            []string // Go 1.2
+    IssuingCertificateURL []string // Go 1.2
+
+    // Subject Alternate Name values. (Note that these values may not be valid
+    // if invalid values were contained within a parsed certificate. For
+    // example, an element of DNSNames may not be a valid DNS domain name.)
+    DNSNames       []string
+    EmailAddresses []string
+    IPAddresses    []net.IP // Go 1.1
+    URIs           []*url.URL // Go 1.10
+
+    // Name constraints
+    PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
+    PermittedDNSDomains         []string
+    ExcludedDNSDomains          []string // Go 1.9
+    PermittedIPRanges           []*net.IPNet // Go 1.10
+    ExcludedIPRanges            []*net.IPNet // Go 1.10
+    PermittedEmailAddresses     []string // Go 1.10
+    ExcludedEmailAddresses      []string // Go 1.10
+    PermittedURIDomains         []string // Go 1.10
+    ExcludedURIDomains          []string // Go 1.10
+
+    // CRL Distribution Points
+    CRLDistributionPoints []string // Go 1.2
+
+    // PolicyIdentifiers contains asn1.ObjectIdentifiers, the components
+    // of which are limited to int32. If a certificate contains a policy which
+    // cannot be represented by asn1.ObjectIdentifier, it will not be included in
+    // PolicyIdentifiers, but will be present in Policies, which contains all parsed
+    // policy OIDs.
+    PolicyIdentifiers []asn1.ObjectIdentifier
+
+    // Policies contains all policy identifiers included in the certificate.
+    Policies []OID // Go 1.22
+}
+

func ParseCertificate

func ParseCertificate(der []byte) (*Certificate, error)

ParseCertificate parses a single certificate from the given ASN.1 DER data.

+

func ParseCertificates

func ParseCertificates(der []byte) ([]*Certificate, error)

ParseCertificates parses one or more certificates from the given ASN.1 DER data. The certificates must be concatenated with no intermediate padding.

+

func (*Certificate) CheckCRLSignature

func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error

CheckCRLSignature checks that the signature in crl is from c.

+

Deprecated: Use RevocationList.CheckSignatureFrom instead.

+

func (*Certificate) CheckSignature

func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error

CheckSignature verifies that signature is a valid signature over signed from c's public key.

+

This is a low-level API that performs no validity checks on the certificate.

+

MD5WithRSA signatures are rejected, while SHA1WithRSA and ECDSAWithSHA1 signatures are currently accepted.

+

func (*Certificate) CheckSignatureFrom

func (c *Certificate) CheckSignatureFrom(parent *Certificate) error

CheckSignatureFrom verifies that the signature on c is a valid signature from parent.

+

This is a low-level API that performs very limited checks, and not a full path verifier. Most users should use Certificate.Verify instead.

+

func (*Certificate) CreateCRL

func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error)

CreateCRL returns a DER encoded CRL, signed by this Certificate, that contains the given list of revoked certificates.

+

Deprecated: this method does not generate an RFC 5280 conformant X.509 v2 CRL. To generate a standards compliant CRL, use CreateRevocationList instead.

+

func (*Certificate) Equal

func (c *Certificate) Equal(other *Certificate) bool

func (*Certificate) Verify

func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)

Verify attempts to verify c by building one or more chains from c to a certificate in opts.Roots, using certificates in opts.Intermediates if needed. If successful, it returns one or more chains where the first element of the chain is c and the last element is from opts.Roots.

+

If opts.Roots is nil, the platform verifier might be used, and verification details might differ from what is described below. If system roots are unavailable the returned error will be of type SystemRootsError.

+

Name constraints in the intermediates will be applied to all names claimed in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim example.com if an intermediate doesn't permit it, even if example.com is not the name being validated. Note that DirectoryName constraints are not supported.

+

Name constraint validation follows the rules from RFC 5280, with the addition that DNS name constraints may use the leading period format defined for emails and URIs. When a constraint has a leading period it indicates that at least one additional label must be prepended to the constrained name to be considered valid.

+

Extended Key Usage values are enforced nested down a chain, so an intermediate or root that enumerates EKUs prevents a leaf from asserting an EKU not in that list. (While this is not specified, it is common practice in order to limit the types of certificates a CA can issue.)

+

Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported, and will not be used to build chains.

+

Certificates other than c in the returned chains should not be modified.

+

WARNING: this function doesn't do any revocation checking.

Example +

Code:

+// Verifying with a custom list of root certificates.
+
+const rootPEM = `
+-----BEGIN CERTIFICATE-----
+MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
+MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
+YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
+EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
+bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
+AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP
+VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv
+h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE
+ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ
+EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC
+DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7
+qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD
+VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g
+K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI
+KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n
+ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
+BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
+/iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
+zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
+HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
+WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
+yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
+-----END CERTIFICATE-----`
+
+const certPEM = `
+-----BEGIN CERTIFICATE-----
+MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE
+BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl
+cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMTI5MTMyNzQzWhcNMTQwNTI5MDAwMDAw
+WjBpMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN
+TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEYMBYGA1UEAwwPbWFp
+bC5nb29nbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfRrObuSW5T7q
+5CnSEqefEmtH4CCv6+5EckuriNr1CjfVvqzwfAhopXkLrq45EQm8vkmf7W96XJhC
+7ZM0dYi1/qOCAU8wggFLMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAa
+BgNVHREEEzARgg9tYWlsLmdvb2dsZS5jb20wCwYDVR0PBAQDAgeAMGgGCCsGAQUF
+BwEBBFwwWjArBggrBgEFBQcwAoYfaHR0cDovL3BraS5nb29nbGUuY29tL0dJQUcy
+LmNydDArBggrBgEFBQcwAYYfaHR0cDovL2NsaWVudHMxLmdvb2dsZS5jb20vb2Nz
+cDAdBgNVHQ4EFgQUiJxtimAuTfwb+aUtBn5UYKreKvMwDAYDVR0TAQH/BAIwADAf
+BgNVHSMEGDAWgBRK3QYWG7z2aLV29YG2u2IaulqBLzAXBgNVHSAEEDAOMAwGCisG
+AQQB1nkCBQEwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3BraS5nb29nbGUuY29t
+L0dJQUcyLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAH6RYHxHdcGpMpFE3oxDoFnP+
+gtuBCHan2yE2GRbJ2Cw8Lw0MmuKqHlf9RSeYfd3BXeKkj1qO6TVKwCh+0HdZk283
+TZZyzmEOyclm3UGFYe82P/iDFt+CeQ3NpmBg+GoaVCuWAARJN/KfglbLyyYygcQq
+0SgeDh8dRKUiaW3HQSoYvTvdTuqzwK4CXsr3b5/dAOY8uMuG/IAR3FgwTbZ1dtoW
+RvOTa8hYiU6A475WuZKyEHcwnGYe57u2I2KbMgcKjPniocj4QzgYsVAVKW3IwaOh
+yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
+-----END CERTIFICATE-----`
+
+// First, create the set of root certificates. For this example we only
+// have one. It's also possible to omit this in order to use the
+// default root set of the current operating system.
+roots := x509.NewCertPool()
+ok := roots.AppendCertsFromPEM([]byte(rootPEM))
+if !ok {
+    panic("failed to parse root certificate")
+}
+
+block, _ := pem.Decode([]byte(certPEM))
+if block == nil {
+    panic("failed to parse certificate PEM")
+}
+cert, err := x509.ParseCertificate(block.Bytes)
+if err != nil {
+    panic("failed to parse certificate: " + err.Error())
+}
+
+opts := x509.VerifyOptions{
+    DNSName: "mail.google.com",
+    Roots:   roots,
+}
+
+if _, err := cert.Verify(opts); err != nil {
+    panic("failed to verify certificate: " + err.Error())
+}
+

func (*Certificate) VerifyHostname

func (c *Certificate) VerifyHostname(h string) error

VerifyHostname returns nil if c is a valid certificate for the named host. Otherwise it returns an error describing the mismatch.

+

IP addresses can be optionally enclosed in square brackets and are checked against the IPAddresses field. Other names are checked case insensitively against the DNSNames field. If the names are valid hostnames, the certificate fields can have a wildcard as the complete left-most label (e.g. *.example.com).

+

Note that the legacy Common Name field is ignored.

+

type CertificateInvalidError

CertificateInvalidError results when an odd error occurs. Users of this library probably want to handle all these errors uniformly.

+
type CertificateInvalidError struct {
+    Cert   *Certificate
+    Reason InvalidReason
+    Detail string // Go 1.10
+}
+

func (CertificateInvalidError) Error

func (e CertificateInvalidError) Error() string

type CertificateRequest 1.3

CertificateRequest represents a PKCS #10, certificate signature request.

+
type CertificateRequest struct {
+    Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
+    RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
+    RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
+    RawSubject               []byte // DER encoded Subject.
+
+    Version            int
+    Signature          []byte
+    SignatureAlgorithm SignatureAlgorithm
+
+    PublicKeyAlgorithm PublicKeyAlgorithm
+    PublicKey          any
+
+    Subject pkix.Name
+
+    // Attributes contains the CSR attributes that can parse as
+    // pkix.AttributeTypeAndValueSET.
+    //
+    // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
+    // generating the requestedExtensions attribute.
+    Attributes []pkix.AttributeTypeAndValueSET
+
+    // Extensions contains all requested extensions, in raw form. When parsing
+    // CSRs, this can be used to extract extensions that are not parsed by this
+    // package.
+    Extensions []pkix.Extension
+
+    // ExtraExtensions contains extensions to be copied, raw, into any CSR
+    // marshaled by CreateCertificateRequest. Values override any extensions
+    // that would otherwise be produced based on the other fields but are
+    // overridden by any extensions specified in Attributes.
+    //
+    // The ExtraExtensions field is not populated by ParseCertificateRequest,
+    // see Extensions instead.
+    ExtraExtensions []pkix.Extension
+
+    // Subject Alternate Name values.
+    DNSNames       []string
+    EmailAddresses []string
+    IPAddresses    []net.IP
+    URIs           []*url.URL // Go 1.10
+}
+

func ParseCertificateRequest 1.3

func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)

ParseCertificateRequest parses a single certificate request from the given ASN.1 DER data.

+

func (*CertificateRequest) CheckSignature 1.5

func (c *CertificateRequest) CheckSignature() error

CheckSignature reports whether the signature on c is valid.

+

type ConstraintViolationError

ConstraintViolationError results when a requested usage is not permitted by a certificate. For example: checking a signature when the public key isn't a certificate signing key.

+
type ConstraintViolationError struct{}
+

func (ConstraintViolationError) Error

func (ConstraintViolationError) Error() string

type ExtKeyUsage

ExtKeyUsage represents an extended set of actions that are valid for a given key. Each of the ExtKeyUsage* constants define a unique action.

+
type ExtKeyUsage int
const (
+    ExtKeyUsageAny ExtKeyUsage = iota
+    ExtKeyUsageServerAuth
+    ExtKeyUsageClientAuth
+    ExtKeyUsageCodeSigning
+    ExtKeyUsageEmailProtection
+    ExtKeyUsageIPSECEndSystem
+    ExtKeyUsageIPSECTunnel
+    ExtKeyUsageIPSECUser
+    ExtKeyUsageTimeStamping
+    ExtKeyUsageOCSPSigning
+    ExtKeyUsageMicrosoftServerGatedCrypto
+    ExtKeyUsageNetscapeServerGatedCrypto
+    ExtKeyUsageMicrosoftCommercialCodeSigning
+    ExtKeyUsageMicrosoftKernelCodeSigning
+)

type HostnameError

HostnameError results when the set of authorized names doesn't match the requested name.

+
type HostnameError struct {
+    Certificate *Certificate
+    Host        string
+}
+

func (HostnameError) Error

func (h HostnameError) Error() string

type InsecureAlgorithmError 1.6

An InsecureAlgorithmError indicates that the SignatureAlgorithm used to generate the signature is not secure, and the signature has been rejected.

+

To temporarily restore support for SHA-1 signatures, include the value "x509sha1=1" in the GODEBUG environment variable. Note that this option will be removed in a future release.

+
type InsecureAlgorithmError SignatureAlgorithm

func (InsecureAlgorithmError) Error 1.6

func (e InsecureAlgorithmError) Error() string

type InvalidReason

type InvalidReason int
const (
+    // NotAuthorizedToSign results when a certificate is signed by another
+    // which isn't marked as a CA certificate.
+    NotAuthorizedToSign InvalidReason = iota
+    // Expired results when a certificate has expired, based on the time
+    // given in the VerifyOptions.
+    Expired
+    // CANotAuthorizedForThisName results when an intermediate or root
+    // certificate has a name constraint which doesn't permit a DNS or
+    // other name (including IP address) in the leaf certificate.
+    CANotAuthorizedForThisName
+    // TooManyIntermediates results when a path length constraint is
+    // violated.
+    TooManyIntermediates
+    // IncompatibleUsage results when the certificate's key usage indicates
+    // that it may only be used for a different purpose.
+    IncompatibleUsage
+    // NameMismatch results when the subject name of a parent certificate
+    // does not match the issuer name in the child.
+    NameMismatch
+    // NameConstraintsWithoutSANs is a legacy error and is no longer returned.
+    NameConstraintsWithoutSANs
+    // UnconstrainedName results when a CA certificate contains permitted
+    // name constraints, but leaf certificate contains a name of an
+    // unsupported or unconstrained type.
+    UnconstrainedName
+    // TooManyConstraints results when the number of comparison operations
+    // needed to check a certificate exceeds the limit set by
+    // VerifyOptions.MaxConstraintComparisions. This limit exists to
+    // prevent pathological certificates can consuming excessive amounts of
+    // CPU time to verify.
+    TooManyConstraints
+    // CANotAuthorizedForExtKeyUsage results when an intermediate or root
+    // certificate does not permit a requested extended key usage.
+    CANotAuthorizedForExtKeyUsage
+)

type KeyUsage

KeyUsage represents the set of actions that are valid for a given key. It's a bitmap of the KeyUsage* constants.

+
type KeyUsage int
const (
+    KeyUsageDigitalSignature KeyUsage = 1 << iota
+    KeyUsageContentCommitment
+    KeyUsageKeyEncipherment
+    KeyUsageDataEncipherment
+    KeyUsageKeyAgreement
+    KeyUsageCertSign
+    KeyUsageCRLSign
+    KeyUsageEncipherOnly
+    KeyUsageDecipherOnly
+)

type OID 1.22

An OID represents an ASN.1 OBJECT IDENTIFIER.

+
type OID struct {
+    // contains filtered or unexported fields
+}
+

func OIDFromInts 1.22

func OIDFromInts(oid []uint64) (OID, error)

OIDFromInts creates a new OID using ints, each integer is a separate component.

+

func (OID) Equal 1.22

func (oid OID) Equal(other OID) bool

Equal returns true when oid and other represents the same Object Identifier.

+

func (OID) EqualASN1OID 1.22

func (oid OID) EqualASN1OID(other asn1.ObjectIdentifier) bool

EqualASN1OID returns whether an OID equals an asn1.ObjectIdentifier. If asn1.ObjectIdentifier cannot represent the OID specified by oid, because a component of OID requires more than 31 bits, it returns false.

+

func (OID) String 1.22

func (oid OID) String() string

Strings returns the string representation of the Object Identifier.

+

type PEMCipher 1.1

type PEMCipher int

Possible values for the EncryptPEMBlock encryption algorithm.

+
const (
+    PEMCipherDES PEMCipher
+    PEMCipher3DES
+    PEMCipherAES128
+    PEMCipherAES192
+    PEMCipherAES256
+)

type PublicKeyAlgorithm

type PublicKeyAlgorithm int
const (
+    UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
+    RSA
+    DSA // Only supported for parsing.
+    ECDSA
+    Ed25519
+)

func (PublicKeyAlgorithm) String 1.10

func (algo PublicKeyAlgorithm) String() string

type RevocationList 1.15

RevocationList represents a Certificate Revocation List (CRL) as specified by RFC 5280.

+
type RevocationList struct {
+    // Raw contains the complete ASN.1 DER content of the CRL (tbsCertList,
+    // signatureAlgorithm, and signatureValue.)
+    Raw []byte // Go 1.19
+    // RawTBSRevocationList contains just the tbsCertList portion of the ASN.1
+    // DER.
+    RawTBSRevocationList []byte // Go 1.19
+    // RawIssuer contains the DER encoded Issuer.
+    RawIssuer []byte // Go 1.19
+
+    // Issuer contains the DN of the issuing certificate.
+    Issuer pkix.Name // Go 1.19
+    // AuthorityKeyId is used to identify the public key associated with the
+    // issuing certificate. It is populated from the authorityKeyIdentifier
+    // extension when parsing a CRL. It is ignored when creating a CRL; the
+    // extension is populated from the issuing certificate itself.
+    AuthorityKeyId []byte // Go 1.19
+
+    Signature []byte // Go 1.19
+    // SignatureAlgorithm is used to determine the signature algorithm to be
+    // used when signing the CRL. If 0 the default algorithm for the signing
+    // key will be used.
+    SignatureAlgorithm SignatureAlgorithm
+
+    // RevokedCertificateEntries represents the revokedCertificates sequence in
+    // the CRL. It is used when creating a CRL and also populated when parsing a
+    // CRL. When creating a CRL, it may be empty or nil, in which case the
+    // revokedCertificates ASN.1 sequence will be omitted from the CRL entirely.
+    RevokedCertificateEntries []RevocationListEntry // Go 1.21
+
+    // RevokedCertificates is used to populate the revokedCertificates
+    // sequence in the CRL if RevokedCertificateEntries is empty. It may be empty
+    // or nil, in which case an empty CRL will be created.
+    //
+    // Deprecated: Use RevokedCertificateEntries instead.
+    RevokedCertificates []pkix.RevokedCertificate
+
+    // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
+    // which should be a monotonically increasing sequence number for a given
+    // CRL scope and CRL issuer. It is also populated from the cRLNumber
+    // extension when parsing a CRL.
+    Number *big.Int
+
+    // ThisUpdate is used to populate the thisUpdate field in the CRL, which
+    // indicates the issuance date of the CRL.
+    ThisUpdate time.Time
+    // NextUpdate is used to populate the nextUpdate field in the CRL, which
+    // indicates the date by which the next CRL will be issued. NextUpdate
+    // must be greater than ThisUpdate.
+    NextUpdate time.Time
+
+    // Extensions contains raw X.509 extensions. When creating a CRL,
+    // the Extensions field is ignored, see ExtraExtensions.
+    Extensions []pkix.Extension // Go 1.19
+
+    // ExtraExtensions contains any additional extensions to add directly to
+    // the CRL.
+    ExtraExtensions []pkix.Extension
+}
+

func ParseRevocationList 1.19

func ParseRevocationList(der []byte) (*RevocationList, error)

ParseRevocationList parses a X509 v2 Certificate Revocation List from the given ASN.1 DER data.

+

func (*RevocationList) CheckSignatureFrom 1.19

func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error

CheckSignatureFrom verifies that the signature on rl is a valid signature from issuer.

+

type RevocationListEntry 1.21

RevocationListEntry represents an entry in the revokedCertificates sequence of a CRL.

+
type RevocationListEntry struct {
+    // Raw contains the raw bytes of the revokedCertificates entry. It is set when
+    // parsing a CRL; it is ignored when generating a CRL.
+    Raw []byte
+
+    // SerialNumber represents the serial number of a revoked certificate. It is
+    // both used when creating a CRL and populated when parsing a CRL. It must not
+    // be nil.
+    SerialNumber *big.Int
+    // RevocationTime represents the time at which the certificate was revoked. It
+    // is both used when creating a CRL and populated when parsing a CRL. It must
+    // not be the zero time.
+    RevocationTime time.Time
+    // ReasonCode represents the reason for revocation, using the integer enum
+    // values specified in RFC 5280 Section 5.3.1. When creating a CRL, the zero
+    // value will result in the reasonCode extension being omitted. When parsing a
+    // CRL, the zero value may represent either the reasonCode extension being
+    // absent (which implies the default revocation reason of 0/Unspecified), or
+    // it may represent the reasonCode extension being present and explicitly
+    // containing a value of 0/Unspecified (which should not happen according to
+    // the DER encoding rules, but can and does happen anyway).
+    ReasonCode int
+
+    // Extensions contains raw X.509 extensions. When parsing CRL entries,
+    // this can be used to extract non-critical extensions that are not
+    // parsed by this package. When marshaling CRL entries, the Extensions
+    // field is ignored, see ExtraExtensions.
+    Extensions []pkix.Extension
+    // ExtraExtensions contains extensions to be copied, raw, into any
+    // marshaled CRL entries. Values override any extensions that would
+    // otherwise be produced based on the other fields. The ExtraExtensions
+    // field is not populated when parsing CRL entries, see Extensions.
+    ExtraExtensions []pkix.Extension
+}
+

type SignatureAlgorithm

type SignatureAlgorithm int
const (
+    UnknownSignatureAlgorithm SignatureAlgorithm = iota
+
+    MD2WithRSA  // Unsupported.
+    MD5WithRSA  // Only supported for signing, not verification.
+    SHA1WithRSA // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
+    SHA256WithRSA
+    SHA384WithRSA
+    SHA512WithRSA
+    DSAWithSHA1   // Unsupported.
+    DSAWithSHA256 // Unsupported.
+    ECDSAWithSHA1 // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
+    ECDSAWithSHA256
+    ECDSAWithSHA384
+    ECDSAWithSHA512
+    SHA256WithRSAPSS
+    SHA384WithRSAPSS
+    SHA512WithRSAPSS
+    PureEd25519
+)

func (SignatureAlgorithm) String 1.6

func (algo SignatureAlgorithm) String() string

type SystemRootsError 1.1

SystemRootsError results when we fail to load the system root certificates.

+
type SystemRootsError struct {
+    Err error // Go 1.7
+}
+

func (SystemRootsError) Error 1.1

func (se SystemRootsError) Error() string

func (SystemRootsError) Unwrap 1.16

func (se SystemRootsError) Unwrap() error

type UnhandledCriticalExtension

type UnhandledCriticalExtension struct{}
+

func (UnhandledCriticalExtension) Error

func (h UnhandledCriticalExtension) Error() string

type UnknownAuthorityError

UnknownAuthorityError results when the certificate issuer is unknown

+
type UnknownAuthorityError struct {
+    Cert *Certificate // Go 1.8
+    // contains filtered or unexported fields
+}
+

func (UnknownAuthorityError) Error

func (e UnknownAuthorityError) Error() string

type VerifyOptions

VerifyOptions contains parameters for Certificate.Verify.

+
type VerifyOptions struct {
+    // DNSName, if set, is checked against the leaf certificate with
+    // Certificate.VerifyHostname or the platform verifier.
+    DNSName string
+
+    // Intermediates is an optional pool of certificates that are not trust
+    // anchors, but can be used to form a chain from the leaf certificate to a
+    // root certificate.
+    Intermediates *CertPool
+    // Roots is the set of trusted root certificates the leaf certificate needs
+    // to chain up to. If nil, the system roots or the platform verifier are used.
+    Roots *CertPool
+
+    // CurrentTime is used to check the validity of all certificates in the
+    // chain. If zero, the current time is used.
+    CurrentTime time.Time
+
+    // KeyUsages specifies which Extended Key Usage values are acceptable. A
+    // chain is accepted if it allows any of the listed values. An empty list
+    // means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
+    KeyUsages []ExtKeyUsage // Go 1.1
+
+    // MaxConstraintComparisions is the maximum number of comparisons to
+    // perform when checking a given certificate's name constraints. If
+    // zero, a sensible default is used. This limit prevents pathological
+    // certificates from consuming excessive amounts of CPU time when
+    // validating. It does not apply to the platform verifier.
+    MaxConstraintComparisions int // Go 1.10
+}
+

Subdirectories

Name Synopsis
..
pkix Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/x509/ +

+
diff --git a/devdocs/go/crypto%2Fx509%2Fpkix%2Findex.html b/devdocs/go/crypto%2Fx509%2Fpkix%2Findex.html new file mode 100644 index 00000000..4f255da5 --- /dev/null +++ b/devdocs/go/crypto%2Fx509%2Fpkix%2Findex.html @@ -0,0 +1,108 @@ +

Package pkix

Overview

Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.

Index

Package files

pkix.go

type AlgorithmIdentifier

AlgorithmIdentifier represents the ASN.1 structure of the same name. See RFC 5280, section 4.1.1.2.

+
type AlgorithmIdentifier struct {
+    Algorithm  asn1.ObjectIdentifier
+    Parameters asn1.RawValue `asn1:"optional"`
+}
+

type AttributeTypeAndValue

AttributeTypeAndValue mirrors the ASN.1 structure of the same name in RFC 5280, Section 4.1.2.4.

+
type AttributeTypeAndValue struct {
+    Type  asn1.ObjectIdentifier
+    Value any
+}
+

type AttributeTypeAndValueSET 1.3

AttributeTypeAndValueSET represents a set of ASN.1 sequences of AttributeTypeAndValue sequences from RFC 2986 (PKCS #10).

+
type AttributeTypeAndValueSET struct {
+    Type  asn1.ObjectIdentifier
+    Value [][]AttributeTypeAndValue `asn1:"set"`
+}
+

type CertificateList

CertificateList represents the ASN.1 structure of the same name. See RFC 5280, section 5.1. Use Certificate.CheckCRLSignature to verify the signature.

+

Deprecated: x509.RevocationList should be used instead.

+
type CertificateList struct {
+    TBSCertList        TBSCertificateList
+    SignatureAlgorithm AlgorithmIdentifier
+    SignatureValue     asn1.BitString
+}
+

func (*CertificateList) HasExpired

func (certList *CertificateList) HasExpired(now time.Time) bool

HasExpired reports whether certList should have been updated by now.

+

type Extension

Extension represents the ASN.1 structure of the same name. See RFC 5280, section 4.2.

+
type Extension struct {
+    Id       asn1.ObjectIdentifier
+    Critical bool `asn1:"optional"`
+    Value    []byte
+}
+

type Name

Name represents an X.509 distinguished name. This only includes the common elements of a DN. Note that Name is only an approximation of the X.509 structure. If an accurate representation is needed, asn1.Unmarshal the raw subject or issuer as an RDNSequence.

+
type Name struct {
+    Country, Organization, OrganizationalUnit []string
+    Locality, Province                        []string
+    StreetAddress, PostalCode                 []string
+    SerialNumber, CommonName                  string
+
+    // Names contains all parsed attributes. When parsing distinguished names,
+    // this can be used to extract non-standard attributes that are not parsed
+    // by this package. When marshaling to RDNSequences, the Names field is
+    // ignored, see ExtraNames.
+    Names []AttributeTypeAndValue
+
+    // ExtraNames contains attributes to be copied, raw, into any marshaled
+    // distinguished names. Values override any attributes with the same OID.
+    // The ExtraNames field is not populated when parsing, see Names.
+    ExtraNames []AttributeTypeAndValue // Go 1.5
+}
+

func (*Name) FillFromRDNSequence

func (n *Name) FillFromRDNSequence(rdns *RDNSequence)

FillFromRDNSequence populates n from the provided RDNSequence. Multi-entry RDNs are flattened, all entries are added to the relevant n fields, and the grouping is not preserved.

+

func (Name) String 1.10

func (n Name) String() string

String returns the string form of n, roughly following the RFC 2253 Distinguished Names syntax.

+

func (Name) ToRDNSequence

func (n Name) ToRDNSequence() (ret RDNSequence)

ToRDNSequence converts n into a single RDNSequence. The following attributes are encoded as multi-value RDNs:

+

Each ExtraNames entry is encoded as an individual RDN.

+

type RDNSequence

type RDNSequence []RelativeDistinguishedNameSET

func (RDNSequence) String 1.10

func (r RDNSequence) String() string

String returns a string representation of the sequence r, roughly following the RFC 2253 Distinguished Names syntax.

+

type RelativeDistinguishedNameSET

type RelativeDistinguishedNameSET []AttributeTypeAndValue

type RevokedCertificate

RevokedCertificate represents the ASN.1 structure of the same name. See RFC 5280, section 5.1.

+
type RevokedCertificate struct {
+    SerialNumber   *big.Int
+    RevocationTime time.Time
+    Extensions     []Extension `asn1:"optional"`
+}
+

type TBSCertificateList

TBSCertificateList represents the ASN.1 structure of the same name. See RFC 5280, section 5.1.

+

Deprecated: x509.RevocationList should be used instead.

+
type TBSCertificateList struct {
+    Raw                 asn1.RawContent
+    Version             int `asn1:"optional,default:0"`
+    Signature           AlgorithmIdentifier
+    Issuer              RDNSequence
+    ThisUpdate          time.Time
+    NextUpdate          time.Time            `asn1:"optional"`
+    RevokedCertificates []RevokedCertificate `asn1:"optional"`
+    Extensions          []Extension          `asn1:"tag:0,optional,explicit"`
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/crypto/x509/pkix/ +

+
diff --git a/devdocs/go/database%2Fsql%2Fdriver%2Findex.html b/devdocs/go/database%2Fsql%2Fdriver%2Findex.html new file mode 100644 index 00000000..3bbd892b --- /dev/null +++ b/devdocs/go/database%2Fsql%2Fdriver%2Findex.html @@ -0,0 +1,403 @@ +

Package driver

Overview

Package driver defines interfaces to be implemented by database drivers as used by package sql.

+

Most code should use the database/sql package.

+

The driver interface has evolved over time. Drivers should implement Connector and DriverContext interfaces. The Connector.Connect and Driver.Open methods should never return ErrBadConn. ErrBadConn should only be returned from Validator, SessionResetter, or a query method if the connection is already in an invalid (e.g. closed) state.

+

All Conn implementations should implement the following interfaces: Pinger, SessionResetter, and Validator.

+

If named parameters or context are supported, the driver's Conn should implement: ExecerContext, QueryerContext, ConnPrepareContext, and ConnBeginTx.

+

To support custom data types, implement NamedValueChecker. NamedValueChecker also allows queries to accept per-query options as a parameter by returning ErrRemoveArgument from CheckNamedValue.

+

If multiple result sets are supported, Rows should implement RowsNextResultSet. If the driver knows how to describe the types present in the returned result it should implement the following interfaces: RowsColumnTypeScanType, RowsColumnTypeDatabaseTypeName, RowsColumnTypeLength, RowsColumnTypeNullable, and RowsColumnTypePrecisionScale. A given row value may also return a Rows type, which may represent a database cursor value.

+

If a Conn implements Validator, then the IsValid method is called before returning the connection to the connection pool. If an entry in the connection pool implements SessionResetter, then ResetSession is called before reusing the connection for another query. If a connection is never returned to the connection pool but is immediately reused, then ResetSession is called prior to reuse but IsValid is not called.

Index

Package files

driver.go types.go

Variables

Bool is a ValueConverter that converts input values to bool.

+

The conversion rules are:

+
var Bool boolType

DefaultParameterConverter is the default implementation of ValueConverter that's used when a Stmt doesn't implement ColumnConverter.

+

DefaultParameterConverter returns its argument directly if IsValue(arg). Otherwise, if the argument implements Valuer, its Value method is used to return a Value. As a fallback, the provided argument's underlying type is used to convert it to a Value: underlying integer types are converted to int64, floats to float64, bool, string, and []byte to themselves. If the argument is a nil pointer, defaultConverter.ConvertValue returns a nil Value. If the argument is a non-nil pointer, it is dereferenced and defaultConverter.ConvertValue is called recursively. Other types are an error.

+
var DefaultParameterConverter defaultConverter

ErrBadConn should be returned by a driver to signal to the database/sql package that a driver.Conn is in a bad state (such as the server having earlier closed the connection) and the database/sql package should retry on a new connection.

+

To prevent duplicate operations, ErrBadConn should NOT be returned if there's a possibility that the database server might have performed the operation. Even if the server sends back an error, you shouldn't return ErrBadConn.

+

Errors will be checked using errors.Is. An error may wrap ErrBadConn or implement the Is(error) bool method.

+
var ErrBadConn = errors.New("driver: bad connection")

ErrRemoveArgument may be returned from NamedValueChecker to instruct the database/sql package to not pass the argument to the driver query interface. Return when accepting query specific options or structures that aren't SQL query arguments.

+
var ErrRemoveArgument = errors.New("driver: remove argument from query")

ErrSkip may be returned by some optional interfaces' methods to indicate at runtime that the fast path is unavailable and the sql package should continue as if the optional interface was not implemented. ErrSkip is only supported where explicitly documented.

+
var ErrSkip = errors.New("driver: skip fast-path; continue as if unimplemented")

Int32 is a ValueConverter that converts input values to int64, respecting the limits of an int32 value.

+
var Int32 int32Type

ResultNoRows is a pre-defined Result for drivers to return when a DDL command (such as a CREATE TABLE) succeeds. It returns an error for both LastInsertId and RowsAffected.

+
var ResultNoRows noRows

String is a ValueConverter that converts its input to a string. If the value is already a string or []byte, it's unchanged. If the value is of another type, conversion to string is done with fmt.Sprintf("%v", v).

+
var String stringType

func IsScanValue

func IsScanValue(v any) bool

IsScanValue is equivalent to IsValue. It exists for compatibility.

+

func IsValue

func IsValue(v any) bool

IsValue reports whether v is a valid Value parameter type.

+

type ColumnConverter

ColumnConverter may be optionally implemented by Stmt if the statement is aware of its own columns' types and can convert from any type to a driver Value.

+

Deprecated: Drivers should implement NamedValueChecker.

+
type ColumnConverter interface {
+    // ColumnConverter returns a ValueConverter for the provided
+    // column index. If the type of a specific column isn't known
+    // or shouldn't be handled specially, DefaultValueConverter
+    // can be returned.
+    ColumnConverter(idx int) ValueConverter
+}

type Conn

Conn is a connection to a database. It is not used concurrently by multiple goroutines.

+

Conn is assumed to be stateful.

+
type Conn interface {
+    // Prepare returns a prepared statement, bound to this connection.
+    Prepare(query string) (Stmt, error)
+
+    // Close invalidates and potentially stops any current
+    // prepared statements and transactions, marking this
+    // connection as no longer in use.
+    //
+    // Because the sql package maintains a free pool of
+    // connections and only calls Close when there's a surplus of
+    // idle connections, it shouldn't be necessary for drivers to
+    // do their own connection caching.
+    //
+    // Drivers must ensure all network calls made by Close
+    // do not block indefinitely (e.g. apply a timeout).
+    Close() error
+
+    // Begin starts and returns a new transaction.
+    //
+    // Deprecated: Drivers should implement ConnBeginTx instead (or additionally).
+    Begin() (Tx, error)
+}

type ConnBeginTx 1.8

ConnBeginTx enhances the Conn interface with context and TxOptions.

+
type ConnBeginTx interface {
+    // BeginTx starts and returns a new transaction.
+    // If the context is canceled by the user the sql package will
+    // call Tx.Rollback before discarding and closing the connection.
+    //
+    // This must check opts.Isolation to determine if there is a set
+    // isolation level. If the driver does not support a non-default
+    // level and one is set or if there is a non-default isolation level
+    // that is not supported, an error must be returned.
+    //
+    // This must also check opts.ReadOnly to determine if the read-only
+    // value is true to either set the read-only transaction property if supported
+    // or return an error if it is not supported.
+    BeginTx(ctx context.Context, opts TxOptions) (Tx, error)
+}

type ConnPrepareContext 1.8

ConnPrepareContext enhances the Conn interface with context.

+
type ConnPrepareContext interface {
+    // PrepareContext returns a prepared statement, bound to this connection.
+    // context is for the preparation of the statement,
+    // it must not store the context within the statement itself.
+    PrepareContext(ctx context.Context, query string) (Stmt, error)
+}

type Connector 1.10

A Connector represents a driver in a fixed configuration and can create any number of equivalent Conns for use by multiple goroutines.

+

A Connector can be passed to database/sql.OpenDB, to allow drivers to implement their own database/sql.DB constructors, or returned by DriverContext's OpenConnector method, to allow drivers access to context and to avoid repeated parsing of driver configuration.

+

If a Connector implements io.Closer, the database/sql.DB.Close method will call the Close method and return error (if any).

+
type Connector interface {
+    // Connect returns a connection to the database.
+    // Connect may return a cached connection (one previously
+    // closed), but doing so is unnecessary; the sql package
+    // maintains a pool of idle connections for efficient re-use.
+    //
+    // The provided context.Context is for dialing purposes only
+    // (see net.DialContext) and should not be stored or used for
+    // other purposes. A default timeout should still be used
+    // when dialing as a connection pool may call Connect
+    // asynchronously to any query.
+    //
+    // The returned connection is only used by one goroutine at a
+    // time.
+    Connect(context.Context) (Conn, error)
+
+    // Driver returns the underlying Driver of the Connector,
+    // mainly to maintain compatibility with the Driver method
+    // on sql.DB.
+    Driver() Driver
+}

type Driver

Driver is the interface that must be implemented by a database driver.

+

Database drivers may implement DriverContext for access to contexts and to parse the name only once for a pool of connections, instead of once per connection.

+
type Driver interface {
+    // Open returns a new connection to the database.
+    // The name is a string in a driver-specific format.
+    //
+    // Open may return a cached connection (one previously
+    // closed), but doing so is unnecessary; the sql package
+    // maintains a pool of idle connections for efficient re-use.
+    //
+    // The returned connection is only used by one goroutine at a
+    // time.
+    Open(name string) (Conn, error)
+}

type DriverContext 1.10

If a Driver implements DriverContext, then database/sql.DB will call OpenConnector to obtain a Connector and then invoke that Connector's Connect method to obtain each needed connection, instead of invoking the Driver's Open method for each connection. The two-step sequence allows drivers to parse the name just once and also provides access to per-Conn contexts.

+
type DriverContext interface {
+    // OpenConnector must parse the name in the same format that Driver.Open
+    // parses the name parameter.
+    OpenConnector(name string) (Connector, error)
+}

type Execer

Execer is an optional interface that may be implemented by a Conn.

+

If a Conn implements neither ExecerContext nor Execer, the database/sql.DB.Exec will first prepare a query, execute the statement, and then close the statement.

+

Exec may return ErrSkip.

+

Deprecated: Drivers should implement ExecerContext instead.

+
type Execer interface {
+    Exec(query string, args []Value) (Result, error)
+}

type ExecerContext 1.8

ExecerContext is an optional interface that may be implemented by a Conn.

+

If a Conn does not implement ExecerContext, the database/sql.DB.Exec will fall back to Execer; if the Conn does not implement Execer either, database/sql.DB.Exec will first prepare a query, execute the statement, and then close the statement.

+

ExecContext may return ErrSkip.

+

ExecContext must honor the context timeout and return when the context is canceled.

+
type ExecerContext interface {
+    ExecContext(ctx context.Context, query string, args []NamedValue) (Result, error)
+}

type IsolationLevel 1.8

IsolationLevel is the transaction isolation level stored in TxOptions.

+

This type should be considered identical to database/sql.IsolationLevel along with any values defined on it.

+
type IsolationLevel int

type NamedValue 1.8

NamedValue holds both the value name and value.

+
type NamedValue struct {
+    // If the Name is not empty it should be used for the parameter identifier and
+    // not the ordinal position.
+    //
+    // Name will not have a symbol prefix.
+    Name string
+
+    // Ordinal position of the parameter starting from one and is always set.
+    Ordinal int
+
+    // Value is the parameter value.
+    Value Value
+}
+

type NamedValueChecker 1.9

NamedValueChecker may be optionally implemented by Conn or Stmt. It provides the driver more control to handle Go and database types beyond the default Value types allowed.

+

The database/sql package checks for value checkers in the following order, stopping at the first found match: Stmt.NamedValueChecker, Conn.NamedValueChecker, Stmt.ColumnConverter, DefaultParameterConverter.

+

If CheckNamedValue returns ErrRemoveArgument, the NamedValue will not be included in the final query arguments. This may be used to pass special options to the query itself.

+

If ErrSkip is returned the column converter error checking path is used for the argument. Drivers may wish to return ErrSkip after they have exhausted their own special cases.

+
type NamedValueChecker interface {
+    // CheckNamedValue is called before passing arguments to the driver
+    // and is called in place of any ColumnConverter. CheckNamedValue must do type
+    // validation and conversion as appropriate for the driver.
+    CheckNamedValue(*NamedValue) error
+}

type NotNull

NotNull is a type that implements ValueConverter by disallowing nil values but otherwise delegating to another ValueConverter.

+
type NotNull struct {
+    Converter ValueConverter
+}
+

func (NotNull) ConvertValue

func (n NotNull) ConvertValue(v any) (Value, error)

type Null

Null is a type that implements ValueConverter by allowing nil values but otherwise delegating to another ValueConverter.

+
type Null struct {
+    Converter ValueConverter
+}
+

func (Null) ConvertValue

func (n Null) ConvertValue(v any) (Value, error)

type Pinger 1.8

Pinger is an optional interface that may be implemented by a Conn.

+

If a Conn does not implement Pinger, the database/sql.DB.Ping and database/sql.DB.PingContext will check if there is at least one Conn available.

+

If Conn.Ping returns ErrBadConn, database/sql.DB.Ping and database/sql.DB.PingContext will remove the Conn from pool.

+
type Pinger interface {
+    Ping(ctx context.Context) error
+}

type Queryer 1.1

Queryer is an optional interface that may be implemented by a Conn.

+

If a Conn implements neither QueryerContext nor Queryer, the database/sql.DB.Query will first prepare a query, execute the statement, and then close the statement.

+

Query may return ErrSkip.

+

Deprecated: Drivers should implement QueryerContext instead.

+
type Queryer interface {
+    Query(query string, args []Value) (Rows, error)
+}

type QueryerContext 1.8

QueryerContext is an optional interface that may be implemented by a Conn.

+

If a Conn does not implement QueryerContext, the database/sql.DB.Query will fall back to Queryer; if the Conn does not implement Queryer either, database/sql.DB.Query will first prepare a query, execute the statement, and then close the statement.

+

QueryContext may return ErrSkip.

+

QueryContext must honor the context timeout and return when the context is canceled.

+
type QueryerContext interface {
+    QueryContext(ctx context.Context, query string, args []NamedValue) (Rows, error)
+}

type Result

Result is the result of a query execution.

+
type Result interface {
+    // LastInsertId returns the database's auto-generated ID
+    // after, for example, an INSERT into a table with primary
+    // key.
+    LastInsertId() (int64, error)
+
+    // RowsAffected returns the number of rows affected by the
+    // query.
+    RowsAffected() (int64, error)
+}

type Rows

Rows is an iterator over an executed query's results.

+
type Rows interface {
+    // Columns returns the names of the columns. The number of
+    // columns of the result is inferred from the length of the
+    // slice. If a particular column name isn't known, an empty
+    // string should be returned for that entry.
+    Columns() []string
+
+    // Close closes the rows iterator.
+    Close() error
+
+    // Next is called to populate the next row of data into
+    // the provided slice. The provided slice will be the same
+    // size as the Columns() are wide.
+    //
+    // Next should return io.EOF when there are no more rows.
+    //
+    // The dest should not be written to outside of Next. Care
+    // should be taken when closing Rows not to modify
+    // a buffer held in dest.
+    Next(dest []Value) error
+}

type RowsAffected

RowsAffected implements Result for an INSERT or UPDATE operation which mutates a number of rows.

+
type RowsAffected int64

func (RowsAffected) LastInsertId

func (RowsAffected) LastInsertId() (int64, error)

func (RowsAffected) RowsAffected

func (v RowsAffected) RowsAffected() (int64, error)

type RowsColumnTypeDatabaseTypeName 1.8

RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the database system type name without the length. Type names should be uppercase. Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT", "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML", "TIMESTAMP".

+
type RowsColumnTypeDatabaseTypeName interface {
+    Rows
+    ColumnTypeDatabaseTypeName(index int) string
+}

type RowsColumnTypeLength 1.8

RowsColumnTypeLength may be implemented by Rows. It should return the length of the column type if the column is a variable length type. If the column is not a variable length type ok should return false. If length is not limited other than system limits, it should return math.MaxInt64. The following are examples of returned values for various types:

+
TEXT          (math.MaxInt64, true)
+varchar(10)   (10, true)
+nvarchar(10)  (10, true)
+decimal       (0, false)
+int           (0, false)
+bytea(30)     (30, true)
+
type RowsColumnTypeLength interface {
+    Rows
+    ColumnTypeLength(index int) (length int64, ok bool)
+}

type RowsColumnTypeNullable 1.8

RowsColumnTypeNullable may be implemented by Rows. The nullable value should be true if it is known the column may be null, or false if the column is known to be not nullable. If the column nullability is unknown, ok should be false.

+
type RowsColumnTypeNullable interface {
+    Rows
+    ColumnTypeNullable(index int) (nullable, ok bool)
+}

type RowsColumnTypePrecisionScale 1.8

RowsColumnTypePrecisionScale may be implemented by Rows. It should return the precision and scale for decimal types. If not applicable, ok should be false. The following are examples of returned values for various types:

+
decimal(38, 4)    (38, 4, true)
+int               (0, 0, false)
+decimal           (math.MaxInt64, math.MaxInt64, true)
+
type RowsColumnTypePrecisionScale interface {
+    Rows
+    ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool)
+}

type RowsColumnTypeScanType 1.8

RowsColumnTypeScanType may be implemented by Rows. It should return the value type that can be used to scan types into. For example, the database column type "bigint" this should return "reflect.TypeOf(int64(0))".

+
type RowsColumnTypeScanType interface {
+    Rows
+    ColumnTypeScanType(index int) reflect.Type
+}

type RowsNextResultSet 1.8

RowsNextResultSet extends the Rows interface by providing a way to signal the driver to advance to the next result set.

+
type RowsNextResultSet interface {
+    Rows
+
+    // HasNextResultSet is called at the end of the current result set and
+    // reports whether there is another result set after the current one.
+    HasNextResultSet() bool
+
+    // NextResultSet advances the driver to the next result set even
+    // if there are remaining rows in the current result set.
+    //
+    // NextResultSet should return io.EOF when there are no more result sets.
+    NextResultSet() error
+}

type SessionResetter 1.10

SessionResetter may be implemented by Conn to allow drivers to reset the session state associated with the connection and to signal a bad connection.

+
type SessionResetter interface {
+    // ResetSession is called prior to executing a query on the connection
+    // if the connection has been used before. If the driver returns ErrBadConn
+    // the connection is discarded.
+    ResetSession(ctx context.Context) error
+}

type Stmt

Stmt is a prepared statement. It is bound to a Conn and not used by multiple goroutines concurrently.

+
type Stmt interface {
+    // Close closes the statement.
+    //
+    // As of Go 1.1, a Stmt will not be closed if it's in use
+    // by any queries.
+    //
+    // Drivers must ensure all network calls made by Close
+    // do not block indefinitely (e.g. apply a timeout).
+    Close() error
+
+    // NumInput returns the number of placeholder parameters.
+    //
+    // If NumInput returns >= 0, the sql package will sanity check
+    // argument counts from callers and return errors to the caller
+    // before the statement's Exec or Query methods are called.
+    //
+    // NumInput may also return -1, if the driver doesn't know
+    // its number of placeholders. In that case, the sql package
+    // will not sanity check Exec or Query argument counts.
+    NumInput() int
+
+    // Exec executes a query that doesn't return rows, such
+    // as an INSERT or UPDATE.
+    //
+    // Deprecated: Drivers should implement StmtExecContext instead (or additionally).
+    Exec(args []Value) (Result, error)
+
+    // Query executes a query that may return rows, such as a
+    // SELECT.
+    //
+    // Deprecated: Drivers should implement StmtQueryContext instead (or additionally).
+    Query(args []Value) (Rows, error)
+}

type StmtExecContext 1.8

StmtExecContext enhances the Stmt interface by providing Exec with context.

+
type StmtExecContext interface {
+    // ExecContext executes a query that doesn't return rows, such
+    // as an INSERT or UPDATE.
+    //
+    // ExecContext must honor the context timeout and return when it is canceled.
+    ExecContext(ctx context.Context, args []NamedValue) (Result, error)
+}

type StmtQueryContext 1.8

StmtQueryContext enhances the Stmt interface by providing Query with context.

+
type StmtQueryContext interface {
+    // QueryContext executes a query that may return rows, such as a
+    // SELECT.
+    //
+    // QueryContext must honor the context timeout and return when it is canceled.
+    QueryContext(ctx context.Context, args []NamedValue) (Rows, error)
+}

type Tx

Tx is a transaction.

+
type Tx interface {
+    Commit() error
+    Rollback() error
+}

type TxOptions 1.8

TxOptions holds the transaction options.

+

This type should be considered identical to database/sql.TxOptions.

+
type TxOptions struct {
+    Isolation IsolationLevel
+    ReadOnly  bool
+}
+

type Validator 1.15

Validator may be implemented by Conn to allow drivers to signal if a connection is valid or if it should be discarded.

+

If implemented, drivers may return the underlying error from queries, even if the connection should be discarded by the connection pool.

+
type Validator interface {
+    // IsValid is called prior to placing the connection into the
+    // connection pool. The connection will be discarded if false is returned.
+    IsValid() bool
+}

type Value

Value is a value that drivers must be able to handle. It is either nil, a type handled by a database driver's NamedValueChecker interface, or an instance of one of these types:

+
int64
+float64
+bool
+[]byte
+string
+time.Time
+

If the driver supports cursors, a returned Value may also implement the Rows interface in this package. This is used, for example, when a user selects a cursor such as "select cursor(select * from my_table) from dual". If the Rows from the select is closed, the cursor Rows will also be closed.

+
type Value any

type ValueConverter

ValueConverter is the interface providing the ConvertValue method.

+

Various implementations of ValueConverter are provided by the driver package to provide consistent implementations of conversions between drivers. The ValueConverters have several uses:

+
type ValueConverter interface {
+    // ConvertValue converts a value to a driver Value.
+    ConvertValue(v any) (Value, error)
+}

type Valuer

Valuer is the interface providing the Value method.

+

Types implementing Valuer interface are able to convert themselves to a driver Value.

+
type Valuer interface {
+    // Value returns a driver Value.
+    // Value must not panic.
+    Value() (Value, error)
+}
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/database/sql/driver/ +

+
diff --git a/devdocs/go/database%2Fsql%2Findex.html b/devdocs/go/database%2Fsql%2Findex.html new file mode 100644 index 00000000..cc424241 --- /dev/null +++ b/devdocs/go/database%2Fsql%2Findex.html @@ -0,0 +1,1151 @@ +

Package sql

Overview

Package sql provides a generic interface around SQL (or SQL-like) databases.

+

The sql package must be used in conjunction with a database driver. See https://golang.org/s/sqldrivers for a list of drivers.

+

Drivers that do not support context cancellation will not return until after the query is completed.

+

For usage examples, see the wiki page at https://golang.org/s/sqlwiki.

Example (OpenDBCLI) +

Code:

package sql_test
+
+import (
+    "context"
+    "database/sql"
+    "flag"
+    "log"
+    "os"
+    "os/signal"
+    "time"
+)
+
+var pool *sql.DB // Database connection pool.
+
+func Example_openDBCLI() {
+    id := flag.Int64("id", 0, "person ID to find")
+    dsn := flag.String("dsn", os.Getenv("DSN"), "connection data source name")
+    flag.Parse()
+
+    if len(*dsn) == 0 {
+        log.Fatal("missing dsn flag")
+    }
+    if *id == 0 {
+        log.Fatal("missing person ID")
+    }
+    var err error
+
+    // Opening a driver typically will not attempt to connect to the database.
+    pool, err = sql.Open("driver-name", *dsn)
+    if err != nil {
+        // This will not be a connection error, but a DSN parse error or
+        // another initialization error.
+        log.Fatal("unable to use data source name", err)
+    }
+    defer pool.Close()
+
+    pool.SetConnMaxLifetime(0)
+    pool.SetMaxIdleConns(3)
+    pool.SetMaxOpenConns(3)
+
+    ctx, stop := context.WithCancel(context.Background())
+    defer stop()
+
+    appSignal := make(chan os.Signal, 3)
+    signal.Notify(appSignal, os.Interrupt)
+
+    go func() {
+        <-appSignal
+        stop()
+    }()
+
+    Ping(ctx)
+
+    Query(ctx, *id)
+}
+
+// Ping the database to verify DSN provided by the user is valid and the
+// server accessible. If the ping fails exit the program with an error.
+func Ping(ctx context.Context) {
+    ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
+    defer cancel()
+
+    if err := pool.PingContext(ctx); err != nil {
+        log.Fatalf("unable to connect to database: %v", err)
+    }
+}
+
+// Query the database for the information requested and prints the results.
+// If the query fails exit the program with an error.
+func Query(ctx context.Context, id int64) {
+    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+    defer cancel()
+
+    var name string
+    err := pool.QueryRowContext(ctx, "select p.name from people as p where p.id = :id;", sql.Named("id", id)).Scan(&name)
+    if err != nil {
+        log.Fatal("unable to execute search query", err)
+    }
+    log.Println("name=", name)
+}
+

Example (OpenDBService) +

Code:

package sql_test
+
+import (
+    "context"
+    "database/sql"
+    "encoding/json"
+    "fmt"
+    "io"
+    "log"
+    "net/http"
+    "time"
+)
+
+func Example_openDBService() {
+    // Opening a driver typically will not attempt to connect to the database.
+    db, err := sql.Open("driver-name", "database=test1")
+    if err != nil {
+        // This will not be a connection error, but a DSN parse error or
+        // another initialization error.
+        log.Fatal(err)
+    }
+    db.SetConnMaxLifetime(0)
+    db.SetMaxIdleConns(50)
+    db.SetMaxOpenConns(50)
+
+    s := &Service{db: db}
+
+    http.ListenAndServe(":8080", s)
+}
+
+type Service struct {
+    db *sql.DB
+}
+
+func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+    db := s.db
+    switch r.URL.Path {
+    default:
+        http.Error(w, "not found", http.StatusNotFound)
+        return
+    case "/healthz":
+        ctx, cancel := context.WithTimeout(r.Context(), 1*time.Second)
+        defer cancel()
+
+        err := s.db.PingContext(ctx)
+        if err != nil {
+            http.Error(w, fmt.Sprintf("db down: %v", err), http.StatusFailedDependency)
+            return
+        }
+        w.WriteHeader(http.StatusOK)
+        return
+    case "/quick-action":
+        // This is a short SELECT. Use the request context as the base of
+        // the context timeout.
+        ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
+        defer cancel()
+
+        id := 5
+        org := 10
+        var name string
+        err := db.QueryRowContext(ctx, `
+select
+    p.name
+from
+    people as p
+    join organization as o on p.organization = o.id
+where
+    p.id = :id
+    and o.id = :org
+;`,
+            sql.Named("id", id),
+            sql.Named("org", org),
+        ).Scan(&name)
+        if err != nil {
+            if err == sql.ErrNoRows {
+                http.Error(w, "not found", http.StatusNotFound)
+                return
+            }
+            http.Error(w, err.Error(), http.StatusInternalServerError)
+            return
+        }
+        io.WriteString(w, name)
+        return
+    case "/long-action":
+        // This is a long SELECT. Use the request context as the base of
+        // the context timeout, but give it some time to finish. If
+        // the client cancels before the query is done the query will also
+        // be canceled.
+        ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
+        defer cancel()
+
+        var names []string
+        rows, err := db.QueryContext(ctx, "select p.name from people as p where p.active = true;")
+        if err != nil {
+            http.Error(w, err.Error(), http.StatusInternalServerError)
+            return
+        }
+
+        for rows.Next() {
+            var name string
+            err = rows.Scan(&name)
+            if err != nil {
+                break
+            }
+            names = append(names, name)
+        }
+        // Check for errors during rows "Close".
+        // This may be more important if multiple statements are executed
+        // in a single batch and rows were written as well as read.
+        if closeErr := rows.Close(); closeErr != nil {
+            http.Error(w, closeErr.Error(), http.StatusInternalServerError)
+            return
+        }
+
+        // Check for row scan error.
+        if err != nil {
+            http.Error(w, err.Error(), http.StatusInternalServerError)
+            return
+        }
+
+        // Check for errors during row iteration.
+        if err = rows.Err(); err != nil {
+            http.Error(w, err.Error(), http.StatusInternalServerError)
+            return
+        }
+
+        json.NewEncoder(w).Encode(names)
+        return
+    case "/async-action":
+        // This action has side effects that we want to preserve
+        // even if the client cancels the HTTP request part way through.
+        // For this we do not use the http request context as a base for
+        // the timeout.
+        ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+        defer cancel()
+
+        var orderRef = "ABC123"
+        tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
+        _, err = tx.ExecContext(ctx, "stored_proc_name", orderRef)
+
+        if err != nil {
+            tx.Rollback()
+            http.Error(w, err.Error(), http.StatusInternalServerError)
+            return
+        }
+        err = tx.Commit()
+        if err != nil {
+            http.Error(w, "action in unknown state, check state before attempting again", http.StatusInternalServerError)
+            return
+        }
+        w.WriteHeader(http.StatusOK)
+        return
+    }
+}
+

Index

Examples

Conn.ExecContext
DB.BeginTx
DB.ExecContext
DB.PingContext
DB.Prepare
DB.QueryContext
DB.QueryRowContext
DB.Query (MultipleResultSets)
Rows
Stmt
Stmt.QueryRowContext
Tx.ExecContext
Tx.Prepare
Tx.Rollback
Package (OpenDBCLI)
Package (OpenDBService)

Package files

convert.go ctxutil.go sql.go

Variables

ErrConnDone is returned by any operation that is performed on a connection that has already been returned to the connection pool.

+
var ErrConnDone = errors.New("sql: connection is already closed")

ErrNoRows is returned by Row.Scan when DB.QueryRow doesn't return a row. In such a case, QueryRow returns a placeholder *Row value that defers this error until a Scan.

+
var ErrNoRows = errors.New("sql: no rows in result set")

ErrTxDone is returned by any operation that is performed on a transaction that has already been committed or rolled back.

+
var ErrTxDone = errors.New("sql: transaction has already been committed or rolled back")

func Drivers 1.4

func Drivers() []string

Drivers returns a sorted list of the names of the registered drivers.

+

func Register

func Register(name string, driver driver.Driver)

Register makes a database driver available by the provided name. If Register is called twice with the same name or if driver is nil, it panics.

+

type ColumnType 1.8

ColumnType contains the name and type of a column.

+
type ColumnType struct {
+    // contains filtered or unexported fields
+}
+

func (*ColumnType) DatabaseTypeName 1.8

func (ci *ColumnType) DatabaseTypeName() string

DatabaseTypeName returns the database system name of the column type. If an empty string is returned, then the driver type name is not supported. Consult your driver documentation for a list of driver data types. ColumnType.Length specifiers are not included. Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", "INT", and "BIGINT".

+

func (*ColumnType) DecimalSize 1.8

func (ci *ColumnType) DecimalSize() (precision, scale int64, ok bool)

DecimalSize returns the scale and precision of a decimal type. If not applicable or if not supported ok is false.

+

func (*ColumnType) Length 1.8

func (ci *ColumnType) Length() (length int64, ok bool)

Length returns the column type length for variable length column types such as text and binary field types. If the type length is unbounded the value will be math.MaxInt64 (any database limits will still apply). If the column type is not variable length, such as an int, or if not supported by the driver ok is false.

+

func (*ColumnType) Name 1.8

func (ci *ColumnType) Name() string

Name returns the name or alias of the column.

+

func (*ColumnType) Nullable 1.8

func (ci *ColumnType) Nullable() (nullable, ok bool)

Nullable reports whether the column may be null. If a driver does not support this property ok will be false.

+

func (*ColumnType) ScanType 1.8

func (ci *ColumnType) ScanType() reflect.Type

ScanType returns a Go type suitable for scanning into using Rows.Scan. If a driver does not support this property ScanType will return the type of an empty interface.

+

type Conn 1.9

Conn represents a single database connection rather than a pool of database connections. Prefer running queries from DB unless there is a specific need for a continuous single database connection.

+

A Conn must call Conn.Close to return the connection to the database pool and may do so concurrently with a running query.

+

After a call to Conn.Close, all operations on the connection fail with ErrConnDone.

+
type Conn struct {
+    // contains filtered or unexported fields
+}
+

func (*Conn) BeginTx 1.9

func (c *Conn) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)

BeginTx starts a transaction.

+

The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled.

+

The provided TxOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.

+

func (*Conn) Close 1.9

func (c *Conn) Close() error

Close returns the connection to the connection pool. All operations after a Close will return with ErrConnDone. Close is safe to call concurrently with other operations and will block until all other operations finish. It may be useful to first cancel any used context and then call close directly after.

+

func (*Conn) ExecContext 1.9

func (c *Conn) ExecContext(ctx context.Context, query string, args ...any) (Result, error)

ExecContext executes a query without returning any rows. The args are for any placeholder parameters in the query.

Example +

Code:

+// A *DB is a pool of connections. Call Conn to reserve a connection for
+// exclusive use.
+conn, err := db.Conn(ctx)
+if err != nil {
+    log.Fatal(err)
+}
+defer conn.Close() // Return the connection to the pool.
+id := 41
+result, err := conn.ExecContext(ctx, `UPDATE balances SET balance = balance + 10 WHERE user_id = ?;`, id)
+if err != nil {
+    log.Fatal(err)
+}
+rows, err := result.RowsAffected()
+if err != nil {
+    log.Fatal(err)
+}
+if rows != 1 {
+    log.Fatalf("expected single row affected, got %d rows affected", rows)
+}
+

func (*Conn) PingContext 1.9

func (c *Conn) PingContext(ctx context.Context) error

PingContext verifies the connection to the database is still alive.

+

func (*Conn) PrepareContext 1.9

func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error)

PrepareContext creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's *Stmt.Close method when the statement is no longer needed.

+

The provided context is used for the preparation of the statement, not for the execution of the statement.

+

func (*Conn) QueryContext 1.9

func (c *Conn) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)

QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

+

func (*Conn) QueryRowContext 1.9

func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...any) *Row

QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until the *Row.Scan method is called. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row and discards the rest.

+

func (*Conn) Raw 1.13

func (c *Conn) Raw(f func(driverConn any) error) (err error)

Raw executes f exposing the underlying driver connection for the duration of f. The driverConn must not be used outside of f.

+

Once f returns and err is not driver.ErrBadConn, the Conn will continue to be usable until Conn.Close is called.

+

type DB

DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines.

+

The sql package creates and frees connections automatically; it also maintains a free pool of idle connections. If the database has a concept of per-connection state, such state can be reliably observed within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the returned Tx is bound to a single connection. Once Tx.Commit or Tx.Rollback is called on the transaction, that transaction's connection is returned to DB's idle connection pool. The pool size can be controlled with DB.SetMaxIdleConns.

+
type DB struct {
+    // contains filtered or unexported fields
+}
+

func Open

func Open(driverName, dataSourceName string) (*DB, error)

Open opens a database specified by its database driver name and a driver-specific data source name, usually consisting of at least a database name and connection information.

+

Most users will open a database via a driver-specific connection helper function that returns a *DB. No database drivers are included in the Go standard library. See https://golang.org/s/sqldrivers for a list of third-party drivers.

+

Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call DB.Ping.

+

The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

+

func OpenDB 1.10

func OpenDB(c driver.Connector) *DB

OpenDB opens a database using a driver.Connector, allowing drivers to bypass a string based data source name.

+

Most users will open a database via a driver-specific connection helper function that returns a *DB. No database drivers are included in the Go standard library. See https://golang.org/s/sqldrivers for a list of third-party drivers.

+

OpenDB may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call DB.Ping.

+

The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the OpenDB function should be called just once. It is rarely necessary to close a DB.

+

func (*DB) Begin

func (db *DB) Begin() (*Tx, error)

Begin starts a transaction. The default isolation level is dependent on the driver.

+

Begin uses context.Background internally; to specify the context, use DB.BeginTx.

+

func (*DB) BeginTx 1.8

func (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)

BeginTx starts a transaction.

+

The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled.

+

The provided TxOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.

Example +

Code:

+tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
+if err != nil {
+    log.Fatal(err)
+}
+id := 37
+_, execErr := tx.Exec(`UPDATE users SET status = ? WHERE id = ?`, "paid", id)
+if execErr != nil {
+    _ = tx.Rollback()
+    log.Fatal(execErr)
+}
+if err := tx.Commit(); err != nil {
+    log.Fatal(err)
+}
+

func (*DB) Close

func (db *DB) Close() error

Close closes the database and prevents new queries from starting. Close then waits for all queries that have started processing on the server to finish.

+

It is rare to Close a DB, as the DB handle is meant to be long-lived and shared between many goroutines.

+

func (*DB) Conn 1.9

func (db *DB) Conn(ctx context.Context) (*Conn, error)

Conn returns a single connection by either opening a new connection or returning an existing connection from the connection pool. Conn will block until either a connection is returned or ctx is canceled. Queries run on the same Conn will be run in the same database session.

+

Every Conn must be returned to the database pool after use by calling Conn.Close.

+

func (*DB) Driver

func (db *DB) Driver() driver.Driver

Driver returns the database's underlying driver.

+

func (*DB) Exec

func (db *DB) Exec(query string, args ...any) (Result, error)

Exec executes a query without returning any rows. The args are for any placeholder parameters in the query.

+

Exec uses context.Background internally; to specify the context, use DB.ExecContext.

+

func (*DB) ExecContext 1.8

func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (Result, error)

ExecContext executes a query without returning any rows. The args are for any placeholder parameters in the query.

Example +

Code:

+id := 47
+result, err := db.ExecContext(ctx, "UPDATE balances SET balance = balance + 10 WHERE user_id = ?", id)
+if err != nil {
+    log.Fatal(err)
+}
+rows, err := result.RowsAffected()
+if err != nil {
+    log.Fatal(err)
+}
+if rows != 1 {
+    log.Fatalf("expected to affect 1 row, affected %d", rows)
+}
+

func (*DB) Ping 1.1

func (db *DB) Ping() error

Ping verifies a connection to the database is still alive, establishing a connection if necessary.

+

Ping uses context.Background internally; to specify the context, use DB.PingContext.

+

func (*DB) PingContext 1.8

func (db *DB) PingContext(ctx context.Context) error

PingContext verifies a connection to the database is still alive, establishing a connection if necessary.

Example +

Code:

+// Ping and PingContext may be used to determine if communication with
+// the database server is still possible.
+//
+// When used in a command line application Ping may be used to establish
+// that further queries are possible; that the provided DSN is valid.
+//
+// When used in long running service Ping may be part of the health
+// checking system.
+
+ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
+defer cancel()
+
+status := "up"
+if err := db.PingContext(ctx); err != nil {
+    status = "down"
+}
+log.Println(status)
+

func (*DB) Prepare

func (db *DB) Prepare(query string) (*Stmt, error)

Prepare creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's *Stmt.Close method when the statement is no longer needed.

+

Prepare uses context.Background internally; to specify the context, use DB.PrepareContext.

Example +

Code:

+projects := []struct {
+    mascot  string
+    release int
+}{
+    {"tux", 1991},
+    {"duke", 1996},
+    {"gopher", 2009},
+    {"moby dock", 2013},
+}
+
+stmt, err := db.Prepare("INSERT INTO projects(id, mascot, release, category) VALUES( ?, ?, ?, ? )")
+if err != nil {
+    log.Fatal(err)
+}
+defer stmt.Close() // Prepared statements take up server resources and should be closed after use.
+
+for id, project := range projects {
+    if _, err := stmt.Exec(id+1, project.mascot, project.release, "open source"); err != nil {
+        log.Fatal(err)
+    }
+}
+

func (*DB) PrepareContext 1.8

func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error)

PrepareContext creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's *Stmt.Close method when the statement is no longer needed.

+

The provided context is used for the preparation of the statement, not for the execution of the statement.

+

func (*DB) Query

func (db *DB) Query(query string, args ...any) (*Rows, error)

Query executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

+

Query uses context.Background internally; to specify the context, use DB.QueryContext.

Example (MultipleResultSets) +

Code:

+age := 27
+q := `
+create temp table uid (id bigint); -- Create temp table for queries.
+insert into uid
+select id from users where age < ?; -- Populate temp table.
+
+-- First result set.
+select
+    users.id, name
+from
+    users
+    join uid on users.id = uid.id
+;
+
+-- Second result set.
+select 
+    ur.user, ur.role
+from
+    user_roles as ur
+    join uid on uid.id = ur.user
+;
+    `
+rows, err := db.Query(q, age)
+if err != nil {
+    log.Fatal(err)
+}
+defer rows.Close()
+
+for rows.Next() {
+    var (
+        id   int64
+        name string
+    )
+    if err := rows.Scan(&id, &name); err != nil {
+        log.Fatal(err)
+    }
+    log.Printf("id %d name is %s\n", id, name)
+}
+if !rows.NextResultSet() {
+    log.Fatalf("expected more result sets: %v", rows.Err())
+}
+var roleMap = map[int64]string{
+    1: "user",
+    2: "admin",
+    3: "gopher",
+}
+for rows.Next() {
+    var (
+        id   int64
+        role int64
+    )
+    if err := rows.Scan(&id, &role); err != nil {
+        log.Fatal(err)
+    }
+    log.Printf("id %d has role %s\n", id, roleMap[role])
+}
+if err := rows.Err(); err != nil {
+    log.Fatal(err)
+}
+

func (*DB) QueryContext 1.8

func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)

QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

Example +

Code:

+age := 27
+rows, err := db.QueryContext(ctx, "SELECT name FROM users WHERE age=?", age)
+if err != nil {
+    log.Fatal(err)
+}
+defer rows.Close()
+names := make([]string, 0)
+
+for rows.Next() {
+    var name string
+    if err := rows.Scan(&name); err != nil {
+        // Check for a scan error.
+        // Query rows will be closed with defer.
+        log.Fatal(err)
+    }
+    names = append(names, name)
+}
+// If the database is being written to ensure to check for Close
+// errors that may be returned from the driver. The query may
+// encounter an auto-commit error and be forced to rollback changes.
+rerr := rows.Close()
+if rerr != nil {
+    log.Fatal(rerr)
+}
+
+// Rows.Err will report the last error encountered by Rows.Scan.
+if err := rows.Err(); err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%s are %d years old", strings.Join(names, ", "), age)
+

func (*DB) QueryRow

func (db *DB) QueryRow(query string, args ...any) *Row

QueryRow executes a query that is expected to return at most one row. QueryRow always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, *Row.Scan scans the first selected row and discards the rest.

+

QueryRow uses context.Background internally; to specify the context, use DB.QueryRowContext.

+

func (*DB) QueryRowContext 1.8

func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *Row

QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, *Row.Scan scans the first selected row and discards the rest.

Example +

Code:

+id := 123
+var username string
+var created time.Time
+err := db.QueryRowContext(ctx, "SELECT username, created_at FROM users WHERE id=?", id).Scan(&username, &created)
+switch {
+case err == sql.ErrNoRows:
+    log.Printf("no user with id %d\n", id)
+case err != nil:
+    log.Fatalf("query error: %v\n", err)
+default:
+    log.Printf("username is %q, account created on %s\n", username, created)
+}
+

func (*DB) SetConnMaxIdleTime 1.15

func (db *DB) SetConnMaxIdleTime(d time.Duration)

SetConnMaxIdleTime sets the maximum amount of time a connection may be idle.

+

Expired connections may be closed lazily before reuse.

+

If d <= 0, connections are not closed due to a connection's idle time.

+

func (*DB) SetConnMaxLifetime 1.6

func (db *DB) SetConnMaxLifetime(d time.Duration)

SetConnMaxLifetime sets the maximum amount of time a connection may be reused.

+

Expired connections may be closed lazily before reuse.

+

If d <= 0, connections are not closed due to a connection's age.

+

func (*DB) SetMaxIdleConns 1.1

func (db *DB) SetMaxIdleConns(n int)

SetMaxIdleConns sets the maximum number of connections in the idle connection pool.

+

If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, then the new MaxIdleConns will be reduced to match the MaxOpenConns limit.

+

If n <= 0, no idle connections are retained.

+

The default max idle connections is currently 2. This may change in a future release.

+

func (*DB) SetMaxOpenConns 1.2

func (db *DB) SetMaxOpenConns(n int)

SetMaxOpenConns sets the maximum number of open connections to the database.

+

If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than MaxIdleConns, then MaxIdleConns will be reduced to match the new MaxOpenConns limit.

+

If n <= 0, then there is no limit on the number of open connections. The default is 0 (unlimited).

+

func (*DB) Stats 1.5

func (db *DB) Stats() DBStats

Stats returns database statistics.

+

type DBStats 1.5

DBStats contains database statistics.

+
type DBStats struct {
+    MaxOpenConnections int // Maximum number of open connections to the database; added in Go 1.11
+
+    // Pool Status
+    OpenConnections int // The number of established connections both in use and idle.
+    InUse           int // The number of connections currently in use; added in Go 1.11
+    Idle            int // The number of idle connections; added in Go 1.11
+
+    // Counters
+    WaitCount         int64         // The total number of connections waited for; added in Go 1.11
+    WaitDuration      time.Duration // The total time blocked waiting for a new connection; added in Go 1.11
+    MaxIdleClosed     int64         // The total number of connections closed due to SetMaxIdleConns; added in Go 1.11
+    MaxIdleTimeClosed int64         // The total number of connections closed due to SetConnMaxIdleTime; added in Go 1.15
+    MaxLifetimeClosed int64         // The total number of connections closed due to SetConnMaxLifetime; added in Go 1.11
+}
+

type IsolationLevel 1.8

IsolationLevel is the transaction isolation level used in TxOptions.

+
type IsolationLevel int

Various isolation levels that drivers may support in DB.BeginTx. If a driver does not support a given isolation level an error may be returned.

+

See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.

+
const (
+    LevelDefault IsolationLevel = iota
+    LevelReadUncommitted
+    LevelReadCommitted
+    LevelWriteCommitted
+    LevelRepeatableRead
+    LevelSnapshot
+    LevelSerializable
+    LevelLinearizable
+)

func (IsolationLevel) String 1.11

func (i IsolationLevel) String() string

String returns the name of the transaction isolation level.

+

type NamedArg 1.8

A NamedArg is a named argument. NamedArg values may be used as arguments to DB.Query or DB.Exec and bind to the corresponding named parameter in the SQL statement.

+

For a more concise way to create NamedArg values, see the Named function.

+
type NamedArg struct {
+
+    // Name is the name of the parameter placeholder.
+    //
+    // If empty, the ordinal position in the argument list will be
+    // used.
+    //
+    // Name must omit any symbol prefix.
+    Name string
+
+    // Value is the value of the parameter.
+    // It may be assigned the same value types as the query
+    // arguments.
+    Value any
+    // contains filtered or unexported fields
+}
+

func Named 1.8

func Named(name string, value any) NamedArg

Named provides a more concise way to create NamedArg values.

+

Example usage:

+
db.ExecContext(ctx, `
+    delete from Invoice
+    where
+        TimeCreated < @end
+        and TimeCreated >= @start;`,
+    sql.Named("start", startTime),
+    sql.Named("end", endTime),
+)
+

type Null

Null represents a value that may be null. Null implements the Scanner interface so it can be used as a scan destination:

+
var s Null[string]
+err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
+...
+if s.Valid {
+   // use s.V
+} else {
+   // NULL value
+}
+
type Null[T any] struct {
+    V     T
+    Valid bool
+}
+

func (*Null[T]) Scan

func (n *Null[T]) Scan(value any) error

func (Null[T]) Value

func (n Null[T]) Value() (driver.Value, error)

type NullBool

NullBool represents a bool that may be null. NullBool implements the Scanner interface so it can be used as a scan destination, similar to NullString.

+
type NullBool struct {
+    Bool  bool
+    Valid bool // Valid is true if Bool is not NULL
+}
+

func (*NullBool) Scan

func (n *NullBool) Scan(value any) error

Scan implements the Scanner interface.

+

func (NullBool) Value

func (n NullBool) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

+

type NullByte 1.17

NullByte represents a byte that may be null. NullByte implements the Scanner interface so it can be used as a scan destination, similar to NullString.

+
type NullByte struct {
+    Byte  byte
+    Valid bool // Valid is true if Byte is not NULL
+}
+

func (*NullByte) Scan 1.17

func (n *NullByte) Scan(value any) error

Scan implements the Scanner interface.

+

func (NullByte) Value 1.17

func (n NullByte) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

+

type NullFloat64

NullFloat64 represents a float64 that may be null. NullFloat64 implements the Scanner interface so it can be used as a scan destination, similar to NullString.

+
type NullFloat64 struct {
+    Float64 float64
+    Valid   bool // Valid is true if Float64 is not NULL
+}
+

func (*NullFloat64) Scan

func (n *NullFloat64) Scan(value any) error

Scan implements the Scanner interface.

+

func (NullFloat64) Value

func (n NullFloat64) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

+

type NullInt16 1.17

NullInt16 represents an int16 that may be null. NullInt16 implements the Scanner interface so it can be used as a scan destination, similar to NullString.

+
type NullInt16 struct {
+    Int16 int16
+    Valid bool // Valid is true if Int16 is not NULL
+}
+

func (*NullInt16) Scan 1.17

func (n *NullInt16) Scan(value any) error

Scan implements the Scanner interface.

+

func (NullInt16) Value 1.17

func (n NullInt16) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

+

type NullInt32 1.13

NullInt32 represents an int32 that may be null. NullInt32 implements the Scanner interface so it can be used as a scan destination, similar to NullString.

+
type NullInt32 struct {
+    Int32 int32
+    Valid bool // Valid is true if Int32 is not NULL
+}
+

func (*NullInt32) Scan 1.13

func (n *NullInt32) Scan(value any) error

Scan implements the Scanner interface.

+

func (NullInt32) Value 1.13

func (n NullInt32) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

+

type NullInt64

NullInt64 represents an int64 that may be null. NullInt64 implements the Scanner interface so it can be used as a scan destination, similar to NullString.

+
type NullInt64 struct {
+    Int64 int64
+    Valid bool // Valid is true if Int64 is not NULL
+}
+

func (*NullInt64) Scan

func (n *NullInt64) Scan(value any) error

Scan implements the Scanner interface.

+

func (NullInt64) Value

func (n NullInt64) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

+

type NullString

NullString represents a string that may be null. NullString implements the Scanner interface so it can be used as a scan destination:

+
var s NullString
+err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
+...
+if s.Valid {
+   // use s.String
+} else {
+   // NULL value
+}
+
type NullString struct {
+    String string
+    Valid  bool // Valid is true if String is not NULL
+}
+

func (*NullString) Scan

func (ns *NullString) Scan(value any) error

Scan implements the Scanner interface.

+

func (NullString) Value

func (ns NullString) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

+

type NullTime 1.13

NullTime represents a time.Time that may be null. NullTime implements the Scanner interface so it can be used as a scan destination, similar to NullString.

+
type NullTime struct {
+    Time  time.Time
+    Valid bool // Valid is true if Time is not NULL
+}
+

func (*NullTime) Scan 1.13

func (n *NullTime) Scan(value any) error

Scan implements the Scanner interface.

+

func (NullTime) Value 1.13

func (n NullTime) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

+

type Out 1.9

Out may be used to retrieve OUTPUT value parameters from stored procedures.

+

Not all drivers and databases support OUTPUT value parameters.

+

Example usage:

+
var outArg string
+_, err := db.ExecContext(ctx, "ProcName", sql.Named("Arg1", sql.Out{Dest: &outArg}))
+
type Out struct {
+
+    // Dest is a pointer to the value that will be set to the result of the
+    // stored procedure's OUTPUT parameter.
+    Dest any
+
+    // In is whether the parameter is an INOUT parameter. If so, the input value to the stored
+    // procedure is the dereferenced value of Dest's pointer, which is then replaced with
+    // the output value.
+    In bool
+    // contains filtered or unexported fields
+}
+

type RawBytes

RawBytes is a byte slice that holds a reference to memory owned by the database itself. After a Rows.Scan into a RawBytes, the slice is only valid until the next call to Rows.Next, Rows.Scan, or Rows.Close.

+
type RawBytes []byte

type Result

A Result summarizes an executed SQL command.

+
type Result interface {
+    // LastInsertId returns the integer generated by the database
+    // in response to a command. Typically this will be from an
+    // "auto increment" column when inserting a new row. Not all
+    // databases support this feature, and the syntax of such
+    // statements varies.
+    LastInsertId() (int64, error)
+
+    // RowsAffected returns the number of rows affected by an
+    // update, insert, or delete. Not every database or database
+    // driver may support this.
+    RowsAffected() (int64, error)
+}

type Row

Row is the result of calling DB.QueryRow to select a single row.

+
type Row struct {
+    // contains filtered or unexported fields
+}
+

func (*Row) Err 1.15

func (r *Row) Err() error

Err provides a way for wrapping packages to check for query errors without calling Row.Scan. Err returns the error, if any, that was encountered while running the query. If this error is not nil, this error will also be returned from Row.Scan.

+

func (*Row) Scan

func (r *Row) Scan(dest ...any) error

Scan copies the columns from the matched row into the values pointed at by dest. See the documentation on Rows.Scan for details. If more than one row matches the query, Scan uses the first row and discards the rest. If no row matches the query, Scan returns ErrNoRows.

+

type Rows

Rows is the result of a query. Its cursor starts before the first row of the result set. Use Rows.Next to advance from row to row.

+
type Rows struct {
+    // contains filtered or unexported fields
+}
+

Example +

Code:

+age := 27
+rows, err := db.QueryContext(ctx, "SELECT name FROM users WHERE age=?", age)
+if err != nil {
+    log.Fatal(err)
+}
+defer rows.Close()
+
+names := make([]string, 0)
+for rows.Next() {
+    var name string
+    if err := rows.Scan(&name); err != nil {
+        log.Fatal(err)
+    }
+    names = append(names, name)
+}
+// Check for errors from iterating over rows.
+if err := rows.Err(); err != nil {
+    log.Fatal(err)
+}
+log.Printf("%s are %d years old", strings.Join(names, ", "), age)
+

func (*Rows) Close

func (rs *Rows) Close() error

Close closes the Rows, preventing further enumeration. If Rows.Next is called and returns false and there are no further result sets, the Rows are closed automatically and it will suffice to check the result of Rows.Err. Close is idempotent and does not affect the result of Rows.Err.

+

func (*Rows) ColumnTypes 1.8

func (rs *Rows) ColumnTypes() ([]*ColumnType, error)

ColumnTypes returns column information such as column type, length, and nullable. Some information may not be available from some drivers.

+

func (*Rows) Columns

func (rs *Rows) Columns() ([]string, error)

Columns returns the column names. Columns returns an error if the rows are closed.

+

func (*Rows) Err

func (rs *Rows) Err() error

Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Rows.Close.

+

func (*Rows) Next

func (rs *Rows) Next() bool

Next prepares the next result row for reading with the Rows.Scan method. It returns true on success, or false if there is no next result row or an error happened while preparing it. Rows.Err should be consulted to distinguish between the two cases.

+

Every call to Rows.Scan, even the first one, must be preceded by a call to Rows.Next.

+

func (*Rows) NextResultSet 1.8

func (rs *Rows) NextResultSet() bool

NextResultSet prepares the next result set for reading. It reports whether there is further result sets, or false if there is no further result set or if there is an error advancing to it. The Rows.Err method should be consulted to distinguish between the two cases.

+

After calling NextResultSet, the Rows.Next method should always be called before scanning. If there are further result sets they may not have rows in the result set.

+

func (*Rows) Scan

func (rs *Rows) Scan(dest ...any) error

Scan copies the columns in the current row into the values pointed at by dest. The number of values in dest must be the same as the number of columns in Rows.

+

Scan converts columns read from the database into the following common Go types and special types provided by the sql package:

+
*string
+*[]byte
+*int, *int8, *int16, *int32, *int64
+*uint, *uint8, *uint16, *uint32, *uint64
+*bool
+*float32, *float64
+*interface{}
+*RawBytes
+*Rows (cursor value)
+any type implementing Scanner (see Scanner docs)
+

In the most simple case, if the type of the value from the source column is an integer, bool or string type T and dest is of type *T, Scan simply assigns the value through the pointer.

+

Scan also converts between string and numeric types, as long as no information would be lost. While Scan stringifies all numbers scanned from numeric database columns into *string, scans into numeric types are checked for overflow. For example, a float64 with value 300 or a string with value "300" can scan into a uint16, but not into a uint8, though float64(255) or "255" can scan into a uint8. One exception is that scans of some float64 numbers to strings may lose information when stringifying. In general, scan floating point columns into *float64.

+

If a dest argument has type *[]byte, Scan saves in that argument a copy of the corresponding data. The copy is owned by the caller and can be modified and held indefinitely. The copy can be avoided by using an argument of type *RawBytes instead; see the documentation for RawBytes for restrictions on its use.

+

If an argument has type *interface{}, Scan copies the value provided by the underlying driver without conversion. When scanning from a source value of type []byte to *interface{}, a copy of the slice is made and the caller owns the result.

+

Source values of type time.Time may be scanned into values of type *time.Time, *interface{}, *string, or *[]byte. When converting to the latter two, time.RFC3339Nano is used.

+

Source values of type bool may be scanned into types *bool, *interface{}, *string, *[]byte, or *RawBytes.

+

For scanning into *bool, the source may be true, false, 1, 0, or string inputs parseable by strconv.ParseBool.

+

Scan can also convert a cursor returned from a query, such as "select cursor(select * from my_table) from dual", into a *Rows value that can itself be scanned from. The parent select query will close any cursor *Rows if the parent *Rows is closed.

+

If any of the first arguments implementing Scanner returns an error, that error will be wrapped in the returned error.

+

type Scanner

Scanner is an interface used by Rows.Scan.

+
type Scanner interface {
+    // Scan assigns a value from a database driver.
+    //
+    // The src value will be of one of the following types:
+    //
+    //    int64
+    //    float64
+    //    bool
+    //    []byte
+    //    string
+    //    time.Time
+    //    nil - for NULL values
+    //
+    // An error should be returned if the value cannot be stored
+    // without loss of information.
+    //
+    // Reference types such as []byte are only valid until the next call to Scan
+    // and should not be retained. Their underlying memory is owned by the driver.
+    // If retention is necessary, copy their values before the next call to Scan.
+    Scan(src any) error
+}

type Stmt

Stmt is a prepared statement. A Stmt is safe for concurrent use by multiple goroutines.

+

If a Stmt is prepared on a Tx or Conn, it will be bound to a single underlying connection forever. If the Tx or Conn closes, the Stmt will become unusable and all operations will return an error. If a Stmt is prepared on a DB, it will remain usable for the lifetime of the DB. When the Stmt needs to execute on a new underlying connection, it will prepare itself on the new connection automatically.

+
type Stmt struct {
+    // contains filtered or unexported fields
+}
+

Example +

Code:

+// In normal use, create one Stmt when your process starts.
+stmt, err := db.PrepareContext(ctx, "SELECT username FROM users WHERE id = ?")
+if err != nil {
+    log.Fatal(err)
+}
+defer stmt.Close()
+
+// Then reuse it each time you need to issue the query.
+id := 43
+var username string
+err = stmt.QueryRowContext(ctx, id).Scan(&username)
+switch {
+case err == sql.ErrNoRows:
+    log.Fatalf("no user with id %d", id)
+case err != nil:
+    log.Fatal(err)
+default:
+    log.Printf("username is %s\n", username)
+}
+

func (*Stmt) Close

func (s *Stmt) Close() error

Close closes the statement.

+

func (*Stmt) Exec

func (s *Stmt) Exec(args ...any) (Result, error)

Exec executes a prepared statement with the given arguments and returns a Result summarizing the effect of the statement.

+

Exec uses context.Background internally; to specify the context, use Stmt.ExecContext.

+

func (*Stmt) ExecContext 1.8

func (s *Stmt) ExecContext(ctx context.Context, args ...any) (Result, error)

ExecContext executes a prepared statement with the given arguments and returns a Result summarizing the effect of the statement.

+

func (*Stmt) Query

func (s *Stmt) Query(args ...any) (*Rows, error)

Query executes a prepared query statement with the given arguments and returns the query results as a *Rows.

+

Query uses context.Background internally; to specify the context, use Stmt.QueryContext.

+

func (*Stmt) QueryContext 1.8

func (s *Stmt) QueryContext(ctx context.Context, args ...any) (*Rows, error)

QueryContext executes a prepared query statement with the given arguments and returns the query results as a *Rows.

+

func (*Stmt) QueryRow

func (s *Stmt) QueryRow(args ...any) *Row

QueryRow executes a prepared query statement with the given arguments. If an error occurs during the execution of the statement, that error will be returned by a call to Scan on the returned *Row, which is always non-nil. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row and discards the rest.

+

Example usage:

+
var name string
+err := nameByUseridStmt.QueryRow(id).Scan(&name)
+

QueryRow uses context.Background internally; to specify the context, use Stmt.QueryRowContext.

+

func (*Stmt) QueryRowContext 1.8

func (s *Stmt) QueryRowContext(ctx context.Context, args ...any) *Row

QueryRowContext executes a prepared query statement with the given arguments. If an error occurs during the execution of the statement, that error will be returned by a call to Scan on the returned *Row, which is always non-nil. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row and discards the rest.

Example +

Code:

+// In normal use, create one Stmt when your process starts.
+stmt, err := db.PrepareContext(ctx, "SELECT username FROM users WHERE id = ?")
+if err != nil {
+    log.Fatal(err)
+}
+defer stmt.Close()
+
+// Then reuse it each time you need to issue the query.
+id := 43
+var username string
+err = stmt.QueryRowContext(ctx, id).Scan(&username)
+switch {
+case err == sql.ErrNoRows:
+    log.Fatalf("no user with id %d", id)
+case err != nil:
+    log.Fatal(err)
+default:
+    log.Printf("username is %s\n", username)
+}
+

type Tx

Tx is an in-progress database transaction.

+

A transaction must end with a call to Tx.Commit or Tx.Rollback.

+

After a call to Tx.Commit or Tx.Rollback, all operations on the transaction fail with ErrTxDone.

+

The statements prepared for a transaction by calling the transaction's Tx.Prepare or Tx.Stmt methods are closed by the call to Tx.Commit or Tx.Rollback.

+
type Tx struct {
+    // contains filtered or unexported fields
+}
+

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit commits the transaction.

+

func (*Tx) Exec

func (tx *Tx) Exec(query string, args ...any) (Result, error)

Exec executes a query that doesn't return rows. For example: an INSERT and UPDATE.

+

Exec uses context.Background internally; to specify the context, use Tx.ExecContext.

+

func (*Tx) ExecContext 1.8

func (tx *Tx) ExecContext(ctx context.Context, query string, args ...any) (Result, error)

ExecContext executes a query that doesn't return rows. For example: an INSERT and UPDATE.

Example +

Code:

+tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
+if err != nil {
+    log.Fatal(err)
+}
+id := 37
+_, execErr := tx.ExecContext(ctx, "UPDATE users SET status = ? WHERE id = ?", "paid", id)
+if execErr != nil {
+    if rollbackErr := tx.Rollback(); rollbackErr != nil {
+        log.Fatalf("update failed: %v, unable to rollback: %v\n", execErr, rollbackErr)
+    }
+    log.Fatalf("update failed: %v", execErr)
+}
+if err := tx.Commit(); err != nil {
+    log.Fatal(err)
+}
+

func (*Tx) Prepare

func (tx *Tx) Prepare(query string) (*Stmt, error)

Prepare creates a prepared statement for use within a transaction.

+

The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

+

To use an existing prepared statement on this transaction, see Tx.Stmt.

+

Prepare uses context.Background internally; to specify the context, use Tx.PrepareContext.

Example +

Code:

+projects := []struct {
+    mascot  string
+    release int
+}{
+    {"tux", 1991},
+    {"duke", 1996},
+    {"gopher", 2009},
+    {"moby dock", 2013},
+}
+
+tx, err := db.Begin()
+if err != nil {
+    log.Fatal(err)
+}
+defer tx.Rollback() // The rollback will be ignored if the tx has been committed later in the function.
+
+stmt, err := tx.Prepare("INSERT INTO projects(id, mascot, release, category) VALUES( ?, ?, ?, ? )")
+if err != nil {
+    log.Fatal(err)
+}
+defer stmt.Close() // Prepared statements take up server resources and should be closed after use.
+
+for id, project := range projects {
+    if _, err := stmt.Exec(id+1, project.mascot, project.release, "open source"); err != nil {
+        log.Fatal(err)
+    }
+}
+if err := tx.Commit(); err != nil {
+    log.Fatal(err)
+}
+

func (*Tx) PrepareContext 1.8

func (tx *Tx) PrepareContext(ctx context.Context, query string) (*Stmt, error)

PrepareContext creates a prepared statement for use within a transaction.

+

The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

+

To use an existing prepared statement on this transaction, see Tx.Stmt.

+

The provided context will be used for the preparation of the context, not for the execution of the returned statement. The returned statement will run in the transaction context.

+

func (*Tx) Query

func (tx *Tx) Query(query string, args ...any) (*Rows, error)

Query executes a query that returns rows, typically a SELECT.

+

Query uses context.Background internally; to specify the context, use Tx.QueryContext.

+

func (*Tx) QueryContext 1.8

func (tx *Tx) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)

QueryContext executes a query that returns rows, typically a SELECT.

+

func (*Tx) QueryRow

func (tx *Tx) QueryRow(query string, args ...any) *Row

QueryRow executes a query that is expected to return at most one row. QueryRow always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row and discards the rest.

+

QueryRow uses context.Background internally; to specify the context, use Tx.QueryRowContext.

+

func (*Tx) QueryRowContext 1.8

func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *Row

QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row and discards the rest.

+

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Rollback aborts the transaction.

Example +

Code:

+tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
+if err != nil {
+    log.Fatal(err)
+}
+id := 53
+_, err = tx.ExecContext(ctx, "UPDATE drivers SET status = ? WHERE id = ?;", "assigned", id)
+if err != nil {
+    if rollbackErr := tx.Rollback(); rollbackErr != nil {
+        log.Fatalf("update drivers: unable to rollback: %v", rollbackErr)
+    }
+    log.Fatal(err)
+}
+_, err = tx.ExecContext(ctx, "UPDATE pickups SET driver_id = $1;", id)
+if err != nil {
+    if rollbackErr := tx.Rollback(); rollbackErr != nil {
+        log.Fatalf("update failed: %v, unable to back: %v", err, rollbackErr)
+    }
+    log.Fatal(err)
+}
+if err := tx.Commit(); err != nil {
+    log.Fatal(err)
+}
+

func (*Tx) Stmt

func (tx *Tx) Stmt(stmt *Stmt) *Stmt

Stmt returns a transaction-specific prepared statement from an existing statement.

+

Example:

+
updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
+...
+tx, err := db.Begin()
+...
+res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
+

The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

+

Stmt uses context.Background internally; to specify the context, use Tx.StmtContext.

+

func (*Tx) StmtContext 1.8

func (tx *Tx) StmtContext(ctx context.Context, stmt *Stmt) *Stmt

StmtContext returns a transaction-specific prepared statement from an existing statement.

+

Example:

+
updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
+...
+tx, err := db.Begin()
+...
+res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203)
+

The provided context is used for the preparation of the statement, not for the execution of the statement.

+

The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

+

type TxOptions 1.8

TxOptions holds the transaction options to be used in DB.BeginTx.

+
type TxOptions struct {
+    // Isolation is the transaction isolation level.
+    // If zero, the driver or database's default level is used.
+    Isolation IsolationLevel
+    ReadOnly  bool
+}
+

Subdirectories

Name Synopsis
..
driver Package driver defines interfaces to be implemented by database drivers as used by package sql.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/database/sql/ +

+
diff --git a/devdocs/go/debug%2Fbuildinfo%2Findex.html b/devdocs/go/debug%2Fbuildinfo%2Findex.html new file mode 100644 index 00000000..beb6cce0 --- /dev/null +++ b/devdocs/go/debug%2Fbuildinfo%2Findex.html @@ -0,0 +1,19 @@ +

Package buildinfo

Overview

Package buildinfo provides access to information embedded in a Go binary about how it was built. This includes the Go toolchain version, and the set of modules used (for binaries built in module mode).

+

Build information is available for the currently running binary in runtime/debug.ReadBuildInfo.

Index

Package files

buildinfo.go

type BuildInfo 1.18

Type alias for build info. We cannot move the types here, since runtime/debug would need to import this package, which would make it a much larger dependency.

+
type BuildInfo = debug.BuildInfo

func Read 1.18

func Read(r io.ReaderAt) (*BuildInfo, error)

Read returns build information embedded in a Go binary file accessed through the given ReaderAt. Most information is only available for binaries built with module support.

+

func ReadFile 1.18

func ReadFile(name string) (info *BuildInfo, err error)

ReadFile returns build information embedded in a Go binary file at the given path. Most information is only available for binaries built with module support.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/debug/buildinfo/ +

+
diff --git a/devdocs/go/debug%2Fdwarf%2Findex.html b/devdocs/go/debug%2Fdwarf%2Findex.html new file mode 100644 index 00000000..312f3c19 --- /dev/null +++ b/devdocs/go/debug%2Fdwarf%2Findex.html @@ -0,0 +1,754 @@ +

Package dwarf

Overview

Package dwarf provides access to DWARF debugging information loaded from executable files, as defined in the DWARF 2.0 Standard at http://dwarfstd.org/doc/dwarf-2.0.0.pdf.

+

Security

This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

Index

Package files

attr_string.go buf.go class_string.go const.go entry.go line.go open.go tag_string.go type.go typeunit.go unit.go

Variables

ErrUnknownPC is the error returned by LineReader.ScanPC when the seek PC is not covered by any entry in the line table.

+
var ErrUnknownPC = errors.New("ErrUnknownPC")

type AddrType

An AddrType represents a machine address type.

+
type AddrType struct {
+    BasicType
+}
+

type ArrayType

An ArrayType represents a fixed size array type.

+
type ArrayType struct {
+    CommonType
+    Type          Type
+    StrideBitSize int64 // if > 0, number of bits to hold each element
+    Count         int64 // if == -1, an incomplete array, like char x[].
+}
+

func (*ArrayType) Size

func (t *ArrayType) Size() int64

func (*ArrayType) String

func (t *ArrayType) String() string

type Attr

An Attr identifies the attribute type in a DWARF [Entry.Field].

+
type Attr uint32
const (
+    AttrSibling        Attr = 0x01
+    AttrLocation       Attr = 0x02
+    AttrName           Attr = 0x03
+    AttrOrdering       Attr = 0x09
+    AttrByteSize       Attr = 0x0B
+    AttrBitOffset      Attr = 0x0C
+    AttrBitSize        Attr = 0x0D
+    AttrStmtList       Attr = 0x10
+    AttrLowpc          Attr = 0x11
+    AttrHighpc         Attr = 0x12
+    AttrLanguage       Attr = 0x13
+    AttrDiscr          Attr = 0x15
+    AttrDiscrValue     Attr = 0x16
+    AttrVisibility     Attr = 0x17
+    AttrImport         Attr = 0x18
+    AttrStringLength   Attr = 0x19
+    AttrCommonRef      Attr = 0x1A
+    AttrCompDir        Attr = 0x1B
+    AttrConstValue     Attr = 0x1C
+    AttrContainingType Attr = 0x1D
+    AttrDefaultValue   Attr = 0x1E
+    AttrInline         Attr = 0x20
+    AttrIsOptional     Attr = 0x21
+    AttrLowerBound     Attr = 0x22
+    AttrProducer       Attr = 0x25
+    AttrPrototyped     Attr = 0x27
+    AttrReturnAddr     Attr = 0x2A
+    AttrStartScope     Attr = 0x2C
+    AttrStrideSize     Attr = 0x2E
+    AttrUpperBound     Attr = 0x2F
+    AttrAbstractOrigin Attr = 0x31
+    AttrAccessibility  Attr = 0x32
+    AttrAddrClass      Attr = 0x33
+    AttrArtificial     Attr = 0x34
+    AttrBaseTypes      Attr = 0x35
+    AttrCalling        Attr = 0x36
+    AttrCount          Attr = 0x37
+    AttrDataMemberLoc  Attr = 0x38
+    AttrDeclColumn     Attr = 0x39
+    AttrDeclFile       Attr = 0x3A
+    AttrDeclLine       Attr = 0x3B
+    AttrDeclaration    Attr = 0x3C
+    AttrDiscrList      Attr = 0x3D
+    AttrEncoding       Attr = 0x3E
+    AttrExternal       Attr = 0x3F
+    AttrFrameBase      Attr = 0x40
+    AttrFriend         Attr = 0x41
+    AttrIdentifierCase Attr = 0x42
+    AttrMacroInfo      Attr = 0x43
+    AttrNamelistItem   Attr = 0x44
+    AttrPriority       Attr = 0x45
+    AttrSegment        Attr = 0x46
+    AttrSpecification  Attr = 0x47
+    AttrStaticLink     Attr = 0x48
+    AttrType           Attr = 0x49
+    AttrUseLocation    Attr = 0x4A
+    AttrVarParam       Attr = 0x4B
+    AttrVirtuality     Attr = 0x4C
+    AttrVtableElemLoc  Attr = 0x4D
+    // The following are new in DWARF 3.
+    AttrAllocated     Attr = 0x4E
+    AttrAssociated    Attr = 0x4F
+    AttrDataLocation  Attr = 0x50
+    AttrStride        Attr = 0x51
+    AttrEntrypc       Attr = 0x52
+    AttrUseUTF8       Attr = 0x53
+    AttrExtension     Attr = 0x54
+    AttrRanges        Attr = 0x55
+    AttrTrampoline    Attr = 0x56
+    AttrCallColumn    Attr = 0x57
+    AttrCallFile      Attr = 0x58
+    AttrCallLine      Attr = 0x59
+    AttrDescription   Attr = 0x5A
+    AttrBinaryScale   Attr = 0x5B
+    AttrDecimalScale  Attr = 0x5C
+    AttrSmall         Attr = 0x5D
+    AttrDecimalSign   Attr = 0x5E
+    AttrDigitCount    Attr = 0x5F
+    AttrPictureString Attr = 0x60
+    AttrMutable       Attr = 0x61
+    AttrThreadsScaled Attr = 0x62
+    AttrExplicit      Attr = 0x63
+    AttrObjectPointer Attr = 0x64
+    AttrEndianity     Attr = 0x65
+    AttrElemental     Attr = 0x66
+    AttrPure          Attr = 0x67
+    AttrRecursive     Attr = 0x68
+    // The following are new in DWARF 4.
+    AttrSignature      Attr = 0x69
+    AttrMainSubprogram Attr = 0x6A
+    AttrDataBitOffset  Attr = 0x6B
+    AttrConstExpr      Attr = 0x6C
+    AttrEnumClass      Attr = 0x6D
+    AttrLinkageName    Attr = 0x6E
+    // The following are new in DWARF 5.
+    AttrStringLengthBitSize  Attr = 0x6F
+    AttrStringLengthByteSize Attr = 0x70
+    AttrRank                 Attr = 0x71
+    AttrStrOffsetsBase       Attr = 0x72
+    AttrAddrBase             Attr = 0x73
+    AttrRnglistsBase         Attr = 0x74
+    AttrDwoName              Attr = 0x76
+    AttrReference            Attr = 0x77
+    AttrRvalueReference      Attr = 0x78
+    AttrMacros               Attr = 0x79
+    AttrCallAllCalls         Attr = 0x7A
+    AttrCallAllSourceCalls   Attr = 0x7B
+    AttrCallAllTailCalls     Attr = 0x7C
+    AttrCallReturnPC         Attr = 0x7D
+    AttrCallValue            Attr = 0x7E
+    AttrCallOrigin           Attr = 0x7F
+    AttrCallParameter        Attr = 0x80
+    AttrCallPC               Attr = 0x81
+    AttrCallTailCall         Attr = 0x82
+    AttrCallTarget           Attr = 0x83
+    AttrCallTargetClobbered  Attr = 0x84
+    AttrCallDataLocation     Attr = 0x85
+    AttrCallDataValue        Attr = 0x86
+    AttrNoreturn             Attr = 0x87
+    AttrAlignment            Attr = 0x88
+    AttrExportSymbols        Attr = 0x89
+    AttrDeleted              Attr = 0x8A
+    AttrDefaulted            Attr = 0x8B
+    AttrLoclistsBase         Attr = 0x8C
+)

func (Attr) GoString

func (a Attr) GoString() string

func (Attr) String

func (i Attr) String() string

type BasicType

A BasicType holds fields common to all basic types.

+

See the documentation for StructField for more info on the interpretation of the BitSize/BitOffset/DataBitOffset fields.

+
type BasicType struct {
+    CommonType
+    BitSize       int64
+    BitOffset     int64
+    DataBitOffset int64 // Go 1.18
+}
+

func (*BasicType) Basic

func (b *BasicType) Basic() *BasicType

func (*BasicType) String

func (t *BasicType) String() string

type BoolType

A BoolType represents a boolean type.

+
type BoolType struct {
+    BasicType
+}
+

type CharType

A CharType represents a signed character type.

+
type CharType struct {
+    BasicType
+}
+

type Class 1.5

A Class is the DWARF 4 class of an attribute value.

+

In general, a given attribute's value may take on one of several possible classes defined by DWARF, each of which leads to a slightly different interpretation of the attribute.

+

DWARF version 4 distinguishes attribute value classes more finely than previous versions of DWARF. The reader will disambiguate coarser classes from earlier versions of DWARF into the appropriate DWARF 4 class. For example, DWARF 2 uses "constant" for constants as well as all types of section offsets, but the reader will canonicalize attributes in DWARF 2 files that refer to section offsets to one of the Class*Ptr classes, even though these classes were only defined in DWARF 3.

+
type Class int
const (
+    // ClassUnknown represents values of unknown DWARF class.
+    ClassUnknown Class = iota
+
+    // ClassAddress represents values of type uint64 that are
+    // addresses on the target machine.
+    ClassAddress
+
+    // ClassBlock represents values of type []byte whose
+    // interpretation depends on the attribute.
+    ClassBlock
+
+    // ClassConstant represents values of type int64 that are
+    // constants. The interpretation of this constant depends on
+    // the attribute.
+    ClassConstant
+
+    // ClassExprLoc represents values of type []byte that contain
+    // an encoded DWARF expression or location description.
+    ClassExprLoc
+
+    // ClassFlag represents values of type bool.
+    ClassFlag
+
+    // ClassLinePtr represents values that are an int64 offset
+    // into the "line" section.
+    ClassLinePtr
+
+    // ClassLocListPtr represents values that are an int64 offset
+    // into the "loclist" section.
+    ClassLocListPtr
+
+    // ClassMacPtr represents values that are an int64 offset into
+    // the "mac" section.
+    ClassMacPtr
+
+    // ClassRangeListPtr represents values that are an int64 offset into
+    // the "rangelist" section.
+    ClassRangeListPtr
+
+    // ClassReference represents values that are an Offset offset
+    // of an Entry in the info section (for use with Reader.Seek).
+    // The DWARF specification combines ClassReference and
+    // ClassReferenceSig into class "reference".
+    ClassReference
+
+    // ClassReferenceSig represents values that are a uint64 type
+    // signature referencing a type Entry.
+    ClassReferenceSig
+
+    // ClassString represents values that are strings. If the
+    // compilation unit specifies the AttrUseUTF8 flag (strongly
+    // recommended), the string value will be encoded in UTF-8.
+    // Otherwise, the encoding is unspecified.
+    ClassString
+
+    // ClassReferenceAlt represents values of type int64 that are
+    // an offset into the DWARF "info" section of an alternate
+    // object file.
+    ClassReferenceAlt
+
+    // ClassStringAlt represents values of type int64 that are an
+    // offset into the DWARF string section of an alternate object
+    // file.
+    ClassStringAlt
+
+    // ClassAddrPtr represents values that are an int64 offset
+    // into the "addr" section.
+    ClassAddrPtr
+
+    // ClassLocList represents values that are an int64 offset
+    // into the "loclists" section.
+    ClassLocList
+
+    // ClassRngList represents values that are a uint64 offset
+    // from the base of the "rnglists" section.
+    ClassRngList
+
+    // ClassRngListsPtr represents values that are an int64 offset
+    // into the "rnglists" section. These are used as the base for
+    // ClassRngList values.
+    ClassRngListsPtr
+
+    // ClassStrOffsetsPtr represents values that are an int64
+    // offset into the "str_offsets" section.
+    ClassStrOffsetsPtr
+)

func (Class) GoString 1.5

func (i Class) GoString() string

func (Class) String 1.5

func (i Class) String() string

type CommonType

A CommonType holds fields common to multiple types. If a field is not known or not applicable for a given type, the zero value is used.

+
type CommonType struct {
+    ByteSize int64  // size of value of this type, in bytes
+    Name     string // name that can be used to refer to type
+}
+

func (*CommonType) Common

func (c *CommonType) Common() *CommonType

func (*CommonType) Size

func (c *CommonType) Size() int64

type ComplexType

A ComplexType represents a complex floating point type.

+
type ComplexType struct {
+    BasicType
+}
+

type Data

Data represents the DWARF debugging information loaded from an executable file (for example, an ELF or Mach-O executable).

+
type Data struct {
+    // contains filtered or unexported fields
+}
+

func New

func New(abbrev, aranges, frame, info, line, pubnames, ranges, str []byte) (*Data, error)

New returns a new Data object initialized from the given parameters. Rather than calling this function directly, clients should typically use the DWARF method of the File type of the appropriate package debug/elf, debug/macho, or debug/pe.

+

The []byte arguments are the data from the corresponding debug section in the object file; for example, for an ELF object, abbrev is the contents of the ".debug_abbrev" section.

+

func (*Data) AddSection 1.14

func (d *Data) AddSection(name string, contents []byte) error

AddSection adds another DWARF section by name. The name should be a DWARF section name such as ".debug_addr", ".debug_str_offsets", and so forth. This approach is used for new DWARF sections added in DWARF 5 and later.

+

func (*Data) AddTypes 1.3

func (d *Data) AddTypes(name string, types []byte) error

AddTypes will add one .debug_types section to the DWARF data. A typical object with DWARF version 4 debug info will have multiple .debug_types sections. The name is used for error reporting only, and serves to distinguish one .debug_types section from another.

+

func (*Data) LineReader 1.5

func (d *Data) LineReader(cu *Entry) (*LineReader, error)

LineReader returns a new reader for the line table of compilation unit cu, which must be an Entry with tag TagCompileUnit.

+

If this compilation unit has no line table, it returns nil, nil.

+

func (*Data) Ranges 1.7

func (d *Data) Ranges(e *Entry) ([][2]uint64, error)

Ranges returns the PC ranges covered by e, a slice of [low,high) pairs. Only some entry types, such as TagCompileUnit or TagSubprogram, have PC ranges; for others, this will return nil with no error.

+

func (*Data) Reader

func (d *Data) Reader() *Reader

Reader returns a new Reader for Data. The reader is positioned at byte offset 0 in the DWARF “info” section.

+

func (*Data) Type

func (d *Data) Type(off Offset) (Type, error)

Type reads the type at off in the DWARF “info” section.

+

type DecodeError

type DecodeError struct {
+    Name   string
+    Offset Offset
+    Err    string
+}
+

func (DecodeError) Error

func (e DecodeError) Error() string

type DotDotDotType

A DotDotDotType represents the variadic ... function parameter.

+
type DotDotDotType struct {
+    CommonType
+}
+

func (*DotDotDotType) String

func (t *DotDotDotType) String() string

type Entry

An entry is a sequence of attribute/value pairs.

+
type Entry struct {
+    Offset   Offset // offset of Entry in DWARF info
+    Tag      Tag    // tag (kind of Entry)
+    Children bool   // whether Entry is followed by children
+    Field    []Field
+}
+

func (*Entry) AttrField 1.5

func (e *Entry) AttrField(a Attr) *Field

AttrField returns the Field associated with attribute Attr in Entry, or nil if there is no such attribute.

+

func (*Entry) Val

func (e *Entry) Val(a Attr) any

Val returns the value associated with attribute Attr in Entry, or nil if there is no such attribute.

+

A common idiom is to merge the check for nil return with the check that the value has the expected dynamic type, as in:

+
v, ok := e.Val(AttrSibling).(int64)
+

type EnumType

An EnumType represents an enumerated type. The only indication of its native integer type is its ByteSize (inside CommonType).

+
type EnumType struct {
+    CommonType
+    EnumName string
+    Val      []*EnumValue
+}
+

func (*EnumType) String

func (t *EnumType) String() string

type EnumValue

An EnumValue represents a single enumeration value.

+
type EnumValue struct {
+    Name string
+    Val  int64
+}
+

type Field

A Field is a single attribute/value pair in an Entry.

+

A value can be one of several "attribute classes" defined by DWARF. The Go types corresponding to each class are:

+
DWARF class       Go type        Class
+-----------       -------        -----
+address           uint64         ClassAddress
+block             []byte         ClassBlock
+constant          int64          ClassConstant
+flag              bool           ClassFlag
+reference
+  to info         dwarf.Offset   ClassReference
+  to type unit    uint64         ClassReferenceSig
+string            string         ClassString
+exprloc           []byte         ClassExprLoc
+lineptr           int64          ClassLinePtr
+loclistptr        int64          ClassLocListPtr
+macptr            int64          ClassMacPtr
+rangelistptr      int64          ClassRangeListPtr
+

For unrecognized or vendor-defined attributes, Class may be ClassUnknown.

+
type Field struct {
+    Attr  Attr
+    Val   any
+    Class Class // Go 1.5
+}
+

type FloatType

A FloatType represents a floating point type.

+
type FloatType struct {
+    BasicType
+}
+

type FuncType

A FuncType represents a function type.

+
type FuncType struct {
+    CommonType
+    ReturnType Type
+    ParamType  []Type
+}
+

func (*FuncType) String

func (t *FuncType) String() string

type IntType

An IntType represents a signed integer type.

+
type IntType struct {
+    BasicType
+}
+

type LineEntry 1.5

A LineEntry is a row in a DWARF line table.

+
type LineEntry struct {
+    // Address is the program-counter value of a machine
+    // instruction generated by the compiler. This LineEntry
+    // applies to each instruction from Address to just before the
+    // Address of the next LineEntry.
+    Address uint64
+
+    // OpIndex is the index of an operation within a VLIW
+    // instruction. The index of the first operation is 0. For
+    // non-VLIW architectures, it will always be 0. Address and
+    // OpIndex together form an operation pointer that can
+    // reference any individual operation within the instruction
+    // stream.
+    OpIndex int
+
+    // File is the source file corresponding to these
+    // instructions.
+    File *LineFile
+
+    // Line is the source code line number corresponding to these
+    // instructions. Lines are numbered beginning at 1. It may be
+    // 0 if these instructions cannot be attributed to any source
+    // line.
+    Line int
+
+    // Column is the column number within the source line of these
+    // instructions. Columns are numbered beginning at 1. It may
+    // be 0 to indicate the "left edge" of the line.
+    Column int
+
+    // IsStmt indicates that Address is a recommended breakpoint
+    // location, such as the beginning of a line, statement, or a
+    // distinct subpart of a statement.
+    IsStmt bool
+
+    // BasicBlock indicates that Address is the beginning of a
+    // basic block.
+    BasicBlock bool
+
+    // PrologueEnd indicates that Address is one (of possibly
+    // many) PCs where execution should be suspended for a
+    // breakpoint on entry to the containing function.
+    //
+    // Added in DWARF 3.
+    PrologueEnd bool
+
+    // EpilogueBegin indicates that Address is one (of possibly
+    // many) PCs where execution should be suspended for a
+    // breakpoint on exit from this function.
+    //
+    // Added in DWARF 3.
+    EpilogueBegin bool
+
+    // ISA is the instruction set architecture for these
+    // instructions. Possible ISA values should be defined by the
+    // applicable ABI specification.
+    //
+    // Added in DWARF 3.
+    ISA int
+
+    // Discriminator is an arbitrary integer indicating the block
+    // to which these instructions belong. It serves to
+    // distinguish among multiple blocks that may all have with
+    // the same source file, line, and column. Where only one
+    // block exists for a given source position, it should be 0.
+    //
+    // Added in DWARF 3.
+    Discriminator int
+
+    // EndSequence indicates that Address is the first byte after
+    // the end of a sequence of target machine instructions. If it
+    // is set, only this and the Address field are meaningful. A
+    // line number table may contain information for multiple
+    // potentially disjoint instruction sequences. The last entry
+    // in a line table should always have EndSequence set.
+    EndSequence bool
+}
+

type LineFile 1.5

A LineFile is a source file referenced by a DWARF line table entry.

+
type LineFile struct {
+    Name   string
+    Mtime  uint64 // Implementation defined modification time, or 0 if unknown
+    Length int    // File length, or 0 if unknown
+}
+

type LineReader 1.5

A LineReader reads a sequence of LineEntry structures from a DWARF "line" section for a single compilation unit. LineEntries occur in order of increasing PC and each LineEntry gives metadata for the instructions from that LineEntry's PC to just before the next LineEntry's PC. The last entry will have the [LineEntry.EndSequence] field set.

+
type LineReader struct {
+    // contains filtered or unexported fields
+}
+

func (*LineReader) Files 1.14

func (r *LineReader) Files() []*LineFile

Files returns the file name table of this compilation unit as of the current position in the line table. The file name table may be referenced from attributes in this compilation unit such as AttrDeclFile.

+

Entry 0 is always nil, since file index 0 represents "no file".

+

The file name table of a compilation unit is not fixed. Files returns the file table as of the current position in the line table. This may contain more entries than the file table at an earlier position in the line table, though existing entries never change.

+

func (*LineReader) Next 1.5

func (r *LineReader) Next(entry *LineEntry) error

Next sets *entry to the next row in this line table and moves to the next row. If there are no more entries and the line table is properly terminated, it returns io.EOF.

+

Rows are always in order of increasing entry.Address, but entry.Line may go forward or backward.

+

func (*LineReader) Reset 1.5

func (r *LineReader) Reset()

Reset repositions the line table reader at the beginning of the line table.

+

func (*LineReader) Seek 1.5

func (r *LineReader) Seek(pos LineReaderPos)

Seek restores the line table reader to a position returned by LineReader.Tell.

+

The argument pos must have been returned by a call to LineReader.Tell on this line table.

+

func (*LineReader) SeekPC 1.5

func (r *LineReader) SeekPC(pc uint64, entry *LineEntry) error

SeekPC sets *entry to the LineEntry that includes pc and positions the reader on the next entry in the line table. If necessary, this will seek backwards to find pc.

+

If pc is not covered by any entry in this line table, SeekPC returns ErrUnknownPC. In this case, *entry and the final seek position are unspecified.

+

Note that DWARF line tables only permit sequential, forward scans. Hence, in the worst case, this takes time linear in the size of the line table. If the caller wishes to do repeated fast PC lookups, it should build an appropriate index of the line table.

+

func (*LineReader) Tell 1.5

func (r *LineReader) Tell() LineReaderPos

Tell returns the current position in the line table.

+

type LineReaderPos 1.5

A LineReaderPos represents a position in a line table.

+
type LineReaderPos struct {
+    // contains filtered or unexported fields
+}
+

type Offset

An Offset represents the location of an Entry within the DWARF info. (See Reader.Seek.)

+
type Offset uint32

type PtrType

A PtrType represents a pointer type.

+
type PtrType struct {
+    CommonType
+    Type Type
+}
+

func (*PtrType) String

func (t *PtrType) String() string

type QualType

A QualType represents a type that has the C/C++ "const", "restrict", or "volatile" qualifier.

+
type QualType struct {
+    CommonType
+    Qual string
+    Type Type
+}
+

func (*QualType) Size

func (t *QualType) Size() int64

func (*QualType) String

func (t *QualType) String() string

type Reader

A Reader allows reading Entry structures from a DWARF “info” section. The Entry structures are arranged in a tree. The Reader.Next function return successive entries from a pre-order traversal of the tree. If an entry has children, its Children field will be true, and the children follow, terminated by an Entry with Tag 0.

+
type Reader struct {
+    // contains filtered or unexported fields
+}
+

func (*Reader) AddressSize 1.5

func (r *Reader) AddressSize() int

AddressSize returns the size in bytes of addresses in the current compilation unit.

+

func (*Reader) ByteOrder 1.14

func (r *Reader) ByteOrder() binary.ByteOrder

ByteOrder returns the byte order in the current compilation unit.

+

func (*Reader) Next

func (r *Reader) Next() (*Entry, error)

Next reads the next entry from the encoded entry stream. It returns nil, nil when it reaches the end of the section. It returns an error if the current offset is invalid or the data at the offset cannot be decoded as a valid Entry.

+

func (*Reader) Seek

func (r *Reader) Seek(off Offset)

Seek positions the Reader at offset off in the encoded entry stream. Offset 0 can be used to denote the first entry.

+

func (*Reader) SeekPC 1.7

func (r *Reader) SeekPC(pc uint64) (*Entry, error)

SeekPC returns the Entry for the compilation unit that includes pc, and positions the reader to read the children of that unit. If pc is not covered by any unit, SeekPC returns ErrUnknownPC and the position of the reader is undefined.

+

Because compilation units can describe multiple regions of the executable, in the worst case SeekPC must search through all the ranges in all the compilation units. Each call to SeekPC starts the search at the compilation unit of the last call, so in general looking up a series of PCs will be faster if they are sorted. If the caller wishes to do repeated fast PC lookups, it should build an appropriate index using the Ranges method.

+

func (*Reader) SkipChildren

func (r *Reader) SkipChildren()

SkipChildren skips over the child entries associated with the last Entry returned by Reader.Next. If that Entry did not have children or Reader.Next has not been called, SkipChildren is a no-op.

+

type StructField

A StructField represents a field in a struct, union, or C++ class type.

+

Bit Fields

The BitSize, BitOffset, and DataBitOffset fields describe the bit size and offset of data members declared as bit fields in C/C++ struct/union/class types.

+

BitSize is the number of bits in the bit field.

+

DataBitOffset, if non-zero, is the number of bits from the start of the enclosing entity (e.g. containing struct/class/union) to the start of the bit field. This corresponds to the DW_AT_data_bit_offset DWARF attribute that was introduced in DWARF 4.

+

BitOffset, if non-zero, is the number of bits between the most significant bit of the storage unit holding the bit field to the most significant bit of the bit field. Here "storage unit" is the type name before the bit field (for a field "unsigned x:17", the storage unit is "unsigned"). BitOffset values can vary depending on the endianness of the system. BitOffset corresponds to the DW_AT_bit_offset DWARF attribute that was deprecated in DWARF 4 and removed in DWARF 5.

+

At most one of DataBitOffset and BitOffset will be non-zero; DataBitOffset/BitOffset will only be non-zero if BitSize is non-zero. Whether a C compiler uses one or the other will depend on compiler vintage and command line options.

+

Here is an example of C/C++ bit field use, along with what to expect in terms of DWARF bit offset info. Consider this code:

+
struct S {
+	int q;
+	int j:5;
+	int k:6;
+	int m:5;
+	int n:8;
+} s;
+

For the code above, one would expect to see the following for DW_AT_bit_offset values (using GCC 8):

+
       Little   |     Big
+       Endian   |    Endian
+                |
+"j":     27     |     0
+"k":     21     |     5
+"m":     16     |     11
+"n":     8      |     16
+

Note that in the above the offsets are purely with respect to the containing storage unit for j/k/m/n -- these values won't vary based on the size of prior data members in the containing struct.

+

If the compiler emits DW_AT_data_bit_offset, the expected values would be:

+
"j":     32
+"k":     37
+"m":     43
+"n":     48
+

Here the value 32 for "j" reflects the fact that the bit field is preceded by other data members (recall that DW_AT_data_bit_offset values are relative to the start of the containing struct). Hence DW_AT_data_bit_offset values can be quite large for structs with many fields.

+

DWARF also allow for the possibility of base types that have non-zero bit size and bit offset, so this information is also captured for base types, but it is worth noting that it is not possible to trigger this behavior using mainstream languages.

+
type StructField struct {
+    Name          string
+    Type          Type
+    ByteOffset    int64
+    ByteSize      int64 // usually zero; use Type.Size() for normal fields
+    BitOffset     int64
+    DataBitOffset int64 // Go 1.18
+    BitSize       int64 // zero if not a bit field
+}
+

type StructType

A StructType represents a struct, union, or C++ class type.

+
type StructType struct {
+    CommonType
+    StructName string
+    Kind       string // "struct", "union", or "class".
+    Field      []*StructField
+    Incomplete bool // if true, struct, union, class is declared but not defined
+}
+

func (*StructType) Defn

func (t *StructType) Defn() string

func (*StructType) String

func (t *StructType) String() string

type Tag

A Tag is the classification (the type) of an Entry.

+
type Tag uint32
const (
+    TagArrayType              Tag = 0x01
+    TagClassType              Tag = 0x02
+    TagEntryPoint             Tag = 0x03
+    TagEnumerationType        Tag = 0x04
+    TagFormalParameter        Tag = 0x05
+    TagImportedDeclaration    Tag = 0x08
+    TagLabel                  Tag = 0x0A
+    TagLexDwarfBlock          Tag = 0x0B
+    TagMember                 Tag = 0x0D
+    TagPointerType            Tag = 0x0F
+    TagReferenceType          Tag = 0x10
+    TagCompileUnit            Tag = 0x11
+    TagStringType             Tag = 0x12
+    TagStructType             Tag = 0x13
+    TagSubroutineType         Tag = 0x15
+    TagTypedef                Tag = 0x16
+    TagUnionType              Tag = 0x17
+    TagUnspecifiedParameters  Tag = 0x18
+    TagVariant                Tag = 0x19
+    TagCommonDwarfBlock       Tag = 0x1A
+    TagCommonInclusion        Tag = 0x1B
+    TagInheritance            Tag = 0x1C
+    TagInlinedSubroutine      Tag = 0x1D
+    TagModule                 Tag = 0x1E
+    TagPtrToMemberType        Tag = 0x1F
+    TagSetType                Tag = 0x20
+    TagSubrangeType           Tag = 0x21
+    TagWithStmt               Tag = 0x22
+    TagAccessDeclaration      Tag = 0x23
+    TagBaseType               Tag = 0x24
+    TagCatchDwarfBlock        Tag = 0x25
+    TagConstType              Tag = 0x26
+    TagConstant               Tag = 0x27
+    TagEnumerator             Tag = 0x28
+    TagFileType               Tag = 0x29
+    TagFriend                 Tag = 0x2A
+    TagNamelist               Tag = 0x2B
+    TagNamelistItem           Tag = 0x2C
+    TagPackedType             Tag = 0x2D
+    TagSubprogram             Tag = 0x2E
+    TagTemplateTypeParameter  Tag = 0x2F
+    TagTemplateValueParameter Tag = 0x30
+    TagThrownType             Tag = 0x31
+    TagTryDwarfBlock          Tag = 0x32
+    TagVariantPart            Tag = 0x33
+    TagVariable               Tag = 0x34
+    TagVolatileType           Tag = 0x35
+    // The following are new in DWARF 3.
+    TagDwarfProcedure  Tag = 0x36
+    TagRestrictType    Tag = 0x37
+    TagInterfaceType   Tag = 0x38
+    TagNamespace       Tag = 0x39
+    TagImportedModule  Tag = 0x3A
+    TagUnspecifiedType Tag = 0x3B
+    TagPartialUnit     Tag = 0x3C
+    TagImportedUnit    Tag = 0x3D
+    TagMutableType     Tag = 0x3E // Later removed from DWARF.
+    TagCondition       Tag = 0x3F
+    TagSharedType      Tag = 0x40
+    // The following are new in DWARF 4.
+    TagTypeUnit            Tag = 0x41
+    TagRvalueReferenceType Tag = 0x42
+    TagTemplateAlias       Tag = 0x43
+    // The following are new in DWARF 5.
+    TagCoarrayType       Tag = 0x44
+    TagGenericSubrange   Tag = 0x45
+    TagDynamicType       Tag = 0x46
+    TagAtomicType        Tag = 0x47
+    TagCallSite          Tag = 0x48
+    TagCallSiteParameter Tag = 0x49
+    TagSkeletonUnit      Tag = 0x4A
+    TagImmutableType     Tag = 0x4B
+)

func (Tag) GoString

func (t Tag) GoString() string

func (Tag) String

func (i Tag) String() string

type Type

A Type conventionally represents a pointer to any of the specific Type structures (CharType, StructType, etc.).

+
type Type interface {
+    Common() *CommonType
+    String() string
+    Size() int64
+}

type TypedefType

A TypedefType represents a named type.

+
type TypedefType struct {
+    CommonType
+    Type Type
+}
+

func (*TypedefType) Size

func (t *TypedefType) Size() int64

func (*TypedefType) String

func (t *TypedefType) String() string

type UcharType

A UcharType represents an unsigned character type.

+
type UcharType struct {
+    BasicType
+}
+

type UintType

A UintType represents an unsigned integer type.

+
type UintType struct {
+    BasicType
+}
+

type UnspecifiedType 1.4

An UnspecifiedType represents an implicit, unknown, ambiguous or nonexistent type.

+
type UnspecifiedType struct {
+    BasicType
+}
+

type UnsupportedType 1.13

An UnsupportedType is a placeholder returned in situations where we encounter a type that isn't supported.

+
type UnsupportedType struct {
+    CommonType
+    Tag Tag
+}
+

func (*UnsupportedType) String 1.13

func (t *UnsupportedType) String() string

type VoidType

A VoidType represents the C void type.

+
type VoidType struct {
+    CommonType
+}
+

func (*VoidType) String

func (t *VoidType) String() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/debug/dwarf/ +

+
diff --git a/devdocs/go/debug%2Felf%2Findex.html b/devdocs/go/debug%2Felf%2Findex.html new file mode 100644 index 00000000..657f7738 --- /dev/null +++ b/devdocs/go/debug%2Felf%2Findex.html @@ -0,0 +1,2116 @@ +

Package elf

Overview

Package elf implements access to ELF object files.

+

Security

This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

Index

Package files

elf.go file.go reader.go

Constants

Indexes into the Header.Ident array.

+
const (
+    EI_CLASS      = 4  /* Class of machine. */
+    EI_DATA       = 5  /* Data format. */
+    EI_VERSION    = 6  /* ELF format version. */
+    EI_OSABI      = 7  /* Operating system / ABI identification */
+    EI_ABIVERSION = 8  /* ABI version */
+    EI_PAD        = 9  /* Start of padding (per SVR4 ABI). */
+    EI_NIDENT     = 16 /* Size of e_ident array. */
+)

Magic number for the elf trampoline, chosen wisely to be an immediate value.

+
const ARM_MAGIC_TRAMP_NUMBER = 0x5c000003

Initial magic number for ELF files.

+
const ELFMAG = "\177ELF"
const Sym32Size = 16
const Sym64Size = 24

Variables

ErrNoSymbols is returned by File.Symbols and File.DynamicSymbols if there is no such section in the File.

+
var ErrNoSymbols = errors.New("no symbol section")

func R_INFO

func R_INFO(sym, typ uint32) uint64

func R_INFO32

func R_INFO32(sym, typ uint32) uint32

func R_SYM32

func R_SYM32(info uint32) uint32

func R_SYM64

func R_SYM64(info uint64) uint32

func R_TYPE32

func R_TYPE32(info uint32) uint32

func R_TYPE64

func R_TYPE64(info uint64) uint32

func ST_INFO

func ST_INFO(bind SymBind, typ SymType) uint8

type Chdr32 1.6

ELF32 Compression header.

+
type Chdr32 struct {
+    Type      uint32
+    Size      uint32
+    Addralign uint32
+}
+

type Chdr64 1.6

ELF64 Compression header.

+
type Chdr64 struct {
+    Type uint32
+
+    Size      uint64
+    Addralign uint64
+    // contains filtered or unexported fields
+}
+

type Class

Class is found in Header.Ident[EI_CLASS] and Header.Class.

+
type Class byte
const (
+    ELFCLASSNONE Class = 0 /* Unknown class. */
+    ELFCLASS32   Class = 1 /* 32-bit architecture. */
+    ELFCLASS64   Class = 2 /* 64-bit architecture. */
+)

func (Class) GoString

func (i Class) GoString() string

func (Class) String

func (i Class) String() string

type CompressionType 1.6

Section compression type.

+
type CompressionType int
const (
+    COMPRESS_ZLIB   CompressionType = 1          /* ZLIB compression. */
+    COMPRESS_ZSTD   CompressionType = 2          /* ZSTD compression. */
+    COMPRESS_LOOS   CompressionType = 0x60000000 /* First OS-specific. */
+    COMPRESS_HIOS   CompressionType = 0x6fffffff /* Last OS-specific. */
+    COMPRESS_LOPROC CompressionType = 0x70000000 /* First processor-specific type. */
+    COMPRESS_HIPROC CompressionType = 0x7fffffff /* Last processor-specific type. */
+)

func (CompressionType) GoString 1.6

func (i CompressionType) GoString() string

func (CompressionType) String 1.6

func (i CompressionType) String() string

type Data

Data is found in Header.Ident[EI_DATA] and Header.Data.

+
type Data byte
const (
+    ELFDATANONE Data = 0 /* Unknown data format. */
+    ELFDATA2LSB Data = 1 /* 2's complement little-endian. */
+    ELFDATA2MSB Data = 2 /* 2's complement big-endian. */
+)

func (Data) GoString

func (i Data) GoString() string

func (Data) String

func (i Data) String() string

type Dyn32

ELF32 Dynamic structure. The ".dynamic" section contains an array of them.

+
type Dyn32 struct {
+    Tag int32  /* Entry type. */
+    Val uint32 /* Integer/Address value. */
+}
+

type Dyn64

ELF64 Dynamic structure. The ".dynamic" section contains an array of them.

+
type Dyn64 struct {
+    Tag int64  /* Entry type. */
+    Val uint64 /* Integer/address value */
+}
+

type DynFlag

DT_FLAGS values.

+
type DynFlag int
const (
+    DF_ORIGIN DynFlag = 0x0001 /* Indicates that the object being loaded may
+       make reference to the
+       $ORIGIN substitution string */
+    DF_SYMBOLIC DynFlag = 0x0002 /* Indicates "symbolic" linking. */
+    DF_TEXTREL  DynFlag = 0x0004 /* Indicates there may be relocations in non-writable segments. */
+    DF_BIND_NOW DynFlag = 0x0008 /* Indicates that the dynamic linker should
+       process all relocations for the object
+       containing this entry before transferring
+       control to the program. */
+    DF_STATIC_TLS DynFlag = 0x0010 /* Indicates that the shared object or
+       executable contains code using a static
+       thread-local storage scheme. */
+)

func (DynFlag) GoString

func (i DynFlag) GoString() string

func (DynFlag) String

func (i DynFlag) String() string

type DynFlag1 1.21

DT_FLAGS_1 values.

+
type DynFlag1 uint32
const (
+    // Indicates that all relocations for this object must be processed before
+    // returning control to the program.
+    DF_1_NOW DynFlag1 = 0x00000001
+    // Unused.
+    DF_1_GLOBAL DynFlag1 = 0x00000002
+    // Indicates that the object is a member of a group.
+    DF_1_GROUP DynFlag1 = 0x00000004
+    // Indicates that the object cannot be deleted from a process.
+    DF_1_NODELETE DynFlag1 = 0x00000008
+    // Meaningful only for filters. Indicates that all associated filtees be
+    // processed immediately.
+    DF_1_LOADFLTR DynFlag1 = 0x00000010
+    // Indicates that this object's initialization section be run before any other
+    // objects loaded.
+    DF_1_INITFIRST DynFlag1 = 0x00000020
+    // Indicates that the object cannot be added to a running process with dlopen.
+    DF_1_NOOPEN DynFlag1 = 0x00000040
+    // Indicates the object requires $ORIGIN processing.
+    DF_1_ORIGIN DynFlag1 = 0x00000080
+    // Indicates that the object should use direct binding information.
+    DF_1_DIRECT DynFlag1 = 0x00000100
+    // Unused.
+    DF_1_TRANS DynFlag1 = 0x00000200
+    // Indicates that the objects symbol table is to interpose before all symbols
+    // except the primary load object, which is typically the executable.
+    DF_1_INTERPOSE DynFlag1 = 0x00000400
+    // Indicates that the search for dependencies of this object ignores any
+    // default library search paths.
+    DF_1_NODEFLIB DynFlag1 = 0x00000800
+    // Indicates that this object is not dumped by dldump. Candidates are objects
+    // with no relocations that might get included when generating alternative
+    // objects using.
+    DF_1_NODUMP DynFlag1 = 0x00001000
+    // Identifies this object as a configuration alternative object generated by
+    // crle. Triggers the runtime linker to search for a configuration file $ORIGIN/ld.config.app-name.
+    DF_1_CONFALT DynFlag1 = 0x00002000
+    // Meaningful only for filtees. Terminates a filters search for any
+    // further filtees.
+    DF_1_ENDFILTEE DynFlag1 = 0x00004000
+    // Indicates that this object has displacement relocations applied.
+    DF_1_DISPRELDNE DynFlag1 = 0x00008000
+    // Indicates that this object has displacement relocations pending.
+    DF_1_DISPRELPND DynFlag1 = 0x00010000
+    // Indicates that this object contains symbols that cannot be directly
+    // bound to.
+    DF_1_NODIRECT DynFlag1 = 0x00020000
+    // Reserved for internal use by the kernel runtime-linker.
+    DF_1_IGNMULDEF DynFlag1 = 0x00040000
+    // Reserved for internal use by the kernel runtime-linker.
+    DF_1_NOKSYMS DynFlag1 = 0x00080000
+    // Reserved for internal use by the kernel runtime-linker.
+    DF_1_NOHDR DynFlag1 = 0x00100000
+    // Indicates that this object has been edited or has been modified since the
+    // objects original construction by the link-editor.
+    DF_1_EDITED DynFlag1 = 0x00200000
+    // Reserved for internal use by the kernel runtime-linker.
+    DF_1_NORELOC DynFlag1 = 0x00400000
+    // Indicates that the object contains individual symbols that should interpose
+    // before all symbols except the primary load object, which is typically the
+    // executable.
+    DF_1_SYMINTPOSE DynFlag1 = 0x00800000
+    // Indicates that the executable requires global auditing.
+    DF_1_GLOBAUDIT DynFlag1 = 0x01000000
+    // Indicates that the object defines, or makes reference to singleton symbols.
+    DF_1_SINGLETON DynFlag1 = 0x02000000
+    // Indicates that the object is a stub.
+    DF_1_STUB DynFlag1 = 0x04000000
+    // Indicates that the object is a position-independent executable.
+    DF_1_PIE DynFlag1 = 0x08000000
+    // Indicates that the object is a kernel module.
+    DF_1_KMOD DynFlag1 = 0x10000000
+    // Indicates that the object is a weak standard filter.
+    DF_1_WEAKFILTER DynFlag1 = 0x20000000
+    // Unused.
+    DF_1_NOCOMMON DynFlag1 = 0x40000000
+)

func (DynFlag1) GoString 1.21

func (i DynFlag1) GoString() string

func (DynFlag1) String 1.21

func (i DynFlag1) String() string

type DynTag

Dyn.Tag

+
type DynTag int
const (
+    DT_NULL         DynTag = 0  /* Terminating entry. */
+    DT_NEEDED       DynTag = 1  /* String table offset of a needed shared library. */
+    DT_PLTRELSZ     DynTag = 2  /* Total size in bytes of PLT relocations. */
+    DT_PLTGOT       DynTag = 3  /* Processor-dependent address. */
+    DT_HASH         DynTag = 4  /* Address of symbol hash table. */
+    DT_STRTAB       DynTag = 5  /* Address of string table. */
+    DT_SYMTAB       DynTag = 6  /* Address of symbol table. */
+    DT_RELA         DynTag = 7  /* Address of ElfNN_Rela relocations. */
+    DT_RELASZ       DynTag = 8  /* Total size of ElfNN_Rela relocations. */
+    DT_RELAENT      DynTag = 9  /* Size of each ElfNN_Rela relocation entry. */
+    DT_STRSZ        DynTag = 10 /* Size of string table. */
+    DT_SYMENT       DynTag = 11 /* Size of each symbol table entry. */
+    DT_INIT         DynTag = 12 /* Address of initialization function. */
+    DT_FINI         DynTag = 13 /* Address of finalization function. */
+    DT_SONAME       DynTag = 14 /* String table offset of shared object name. */
+    DT_RPATH        DynTag = 15 /* String table offset of library path. [sup] */
+    DT_SYMBOLIC     DynTag = 16 /* Indicates "symbolic" linking. [sup] */
+    DT_REL          DynTag = 17 /* Address of ElfNN_Rel relocations. */
+    DT_RELSZ        DynTag = 18 /* Total size of ElfNN_Rel relocations. */
+    DT_RELENT       DynTag = 19 /* Size of each ElfNN_Rel relocation. */
+    DT_PLTREL       DynTag = 20 /* Type of relocation used for PLT. */
+    DT_DEBUG        DynTag = 21 /* Reserved (not used). */
+    DT_TEXTREL      DynTag = 22 /* Indicates there may be relocations in non-writable segments. [sup] */
+    DT_JMPREL       DynTag = 23 /* Address of PLT relocations. */
+    DT_BIND_NOW     DynTag = 24 /* [sup] */
+    DT_INIT_ARRAY   DynTag = 25 /* Address of the array of pointers to initialization functions */
+    DT_FINI_ARRAY   DynTag = 26 /* Address of the array of pointers to termination functions */
+    DT_INIT_ARRAYSZ DynTag = 27 /* Size in bytes of the array of initialization functions. */
+    DT_FINI_ARRAYSZ DynTag = 28 /* Size in bytes of the array of termination functions. */
+    DT_RUNPATH      DynTag = 29 /* String table offset of a null-terminated library search path string. */
+    DT_FLAGS        DynTag = 30 /* Object specific flag values. */
+    DT_ENCODING     DynTag = 32 /* Values greater than or equal to DT_ENCODING
+       and less than DT_LOOS follow the rules for
+       the interpretation of the d_un union
+       as follows: even == 'd_ptr', even == 'd_val'
+       or none */
+    DT_PREINIT_ARRAY   DynTag = 32 /* Address of the array of pointers to pre-initialization functions. */
+    DT_PREINIT_ARRAYSZ DynTag = 33 /* Size in bytes of the array of pre-initialization functions. */
+    DT_SYMTAB_SHNDX    DynTag = 34 /* Address of SHT_SYMTAB_SHNDX section. */
+
+    DT_LOOS DynTag = 0x6000000d /* First OS-specific */
+    DT_HIOS DynTag = 0x6ffff000 /* Last OS-specific */
+
+    DT_VALRNGLO       DynTag = 0x6ffffd00
+    DT_GNU_PRELINKED  DynTag = 0x6ffffdf5
+    DT_GNU_CONFLICTSZ DynTag = 0x6ffffdf6
+    DT_GNU_LIBLISTSZ  DynTag = 0x6ffffdf7
+    DT_CHECKSUM       DynTag = 0x6ffffdf8
+    DT_PLTPADSZ       DynTag = 0x6ffffdf9
+    DT_MOVEENT        DynTag = 0x6ffffdfa
+    DT_MOVESZ         DynTag = 0x6ffffdfb
+    DT_FEATURE        DynTag = 0x6ffffdfc
+    DT_POSFLAG_1      DynTag = 0x6ffffdfd
+    DT_SYMINSZ        DynTag = 0x6ffffdfe
+    DT_SYMINENT       DynTag = 0x6ffffdff
+    DT_VALRNGHI       DynTag = 0x6ffffdff
+
+    DT_ADDRRNGLO    DynTag = 0x6ffffe00
+    DT_GNU_HASH     DynTag = 0x6ffffef5
+    DT_TLSDESC_PLT  DynTag = 0x6ffffef6
+    DT_TLSDESC_GOT  DynTag = 0x6ffffef7
+    DT_GNU_CONFLICT DynTag = 0x6ffffef8
+    DT_GNU_LIBLIST  DynTag = 0x6ffffef9
+    DT_CONFIG       DynTag = 0x6ffffefa
+    DT_DEPAUDIT     DynTag = 0x6ffffefb
+    DT_AUDIT        DynTag = 0x6ffffefc
+    DT_PLTPAD       DynTag = 0x6ffffefd
+    DT_MOVETAB      DynTag = 0x6ffffefe
+    DT_SYMINFO      DynTag = 0x6ffffeff
+    DT_ADDRRNGHI    DynTag = 0x6ffffeff
+
+    DT_VERSYM     DynTag = 0x6ffffff0
+    DT_RELACOUNT  DynTag = 0x6ffffff9
+    DT_RELCOUNT   DynTag = 0x6ffffffa
+    DT_FLAGS_1    DynTag = 0x6ffffffb
+    DT_VERDEF     DynTag = 0x6ffffffc
+    DT_VERDEFNUM  DynTag = 0x6ffffffd
+    DT_VERNEED    DynTag = 0x6ffffffe
+    DT_VERNEEDNUM DynTag = 0x6fffffff
+
+    DT_LOPROC DynTag = 0x70000000 /* First processor-specific type. */
+
+    DT_MIPS_RLD_VERSION           DynTag = 0x70000001
+    DT_MIPS_TIME_STAMP            DynTag = 0x70000002
+    DT_MIPS_ICHECKSUM             DynTag = 0x70000003
+    DT_MIPS_IVERSION              DynTag = 0x70000004
+    DT_MIPS_FLAGS                 DynTag = 0x70000005
+    DT_MIPS_BASE_ADDRESS          DynTag = 0x70000006
+    DT_MIPS_MSYM                  DynTag = 0x70000007
+    DT_MIPS_CONFLICT              DynTag = 0x70000008
+    DT_MIPS_LIBLIST               DynTag = 0x70000009
+    DT_MIPS_LOCAL_GOTNO           DynTag = 0x7000000a
+    DT_MIPS_CONFLICTNO            DynTag = 0x7000000b
+    DT_MIPS_LIBLISTNO             DynTag = 0x70000010
+    DT_MIPS_SYMTABNO              DynTag = 0x70000011
+    DT_MIPS_UNREFEXTNO            DynTag = 0x70000012
+    DT_MIPS_GOTSYM                DynTag = 0x70000013
+    DT_MIPS_HIPAGENO              DynTag = 0x70000014
+    DT_MIPS_RLD_MAP               DynTag = 0x70000016
+    DT_MIPS_DELTA_CLASS           DynTag = 0x70000017
+    DT_MIPS_DELTA_CLASS_NO        DynTag = 0x70000018
+    DT_MIPS_DELTA_INSTANCE        DynTag = 0x70000019
+    DT_MIPS_DELTA_INSTANCE_NO     DynTag = 0x7000001a
+    DT_MIPS_DELTA_RELOC           DynTag = 0x7000001b
+    DT_MIPS_DELTA_RELOC_NO        DynTag = 0x7000001c
+    DT_MIPS_DELTA_SYM             DynTag = 0x7000001d
+    DT_MIPS_DELTA_SYM_NO          DynTag = 0x7000001e
+    DT_MIPS_DELTA_CLASSSYM        DynTag = 0x70000020
+    DT_MIPS_DELTA_CLASSSYM_NO     DynTag = 0x70000021
+    DT_MIPS_CXX_FLAGS             DynTag = 0x70000022
+    DT_MIPS_PIXIE_INIT            DynTag = 0x70000023
+    DT_MIPS_SYMBOL_LIB            DynTag = 0x70000024
+    DT_MIPS_LOCALPAGE_GOTIDX      DynTag = 0x70000025
+    DT_MIPS_LOCAL_GOTIDX          DynTag = 0x70000026
+    DT_MIPS_HIDDEN_GOTIDX         DynTag = 0x70000027
+    DT_MIPS_PROTECTED_GOTIDX      DynTag = 0x70000028
+    DT_MIPS_OPTIONS               DynTag = 0x70000029
+    DT_MIPS_INTERFACE             DynTag = 0x7000002a
+    DT_MIPS_DYNSTR_ALIGN          DynTag = 0x7000002b
+    DT_MIPS_INTERFACE_SIZE        DynTag = 0x7000002c
+    DT_MIPS_RLD_TEXT_RESOLVE_ADDR DynTag = 0x7000002d
+    DT_MIPS_PERF_SUFFIX           DynTag = 0x7000002e
+    DT_MIPS_COMPACT_SIZE          DynTag = 0x7000002f
+    DT_MIPS_GP_VALUE              DynTag = 0x70000030
+    DT_MIPS_AUX_DYNAMIC           DynTag = 0x70000031
+    DT_MIPS_PLTGOT                DynTag = 0x70000032
+    DT_MIPS_RWPLT                 DynTag = 0x70000034
+    DT_MIPS_RLD_MAP_REL           DynTag = 0x70000035
+
+    DT_PPC_GOT DynTag = 0x70000000
+    DT_PPC_OPT DynTag = 0x70000001
+
+    DT_PPC64_GLINK DynTag = 0x70000000
+    DT_PPC64_OPD   DynTag = 0x70000001
+    DT_PPC64_OPDSZ DynTag = 0x70000002
+    DT_PPC64_OPT   DynTag = 0x70000003
+
+    DT_SPARC_REGISTER DynTag = 0x70000001
+
+    DT_AUXILIARY DynTag = 0x7ffffffd
+    DT_USED      DynTag = 0x7ffffffe
+    DT_FILTER    DynTag = 0x7fffffff
+
+    DT_HIPROC DynTag = 0x7fffffff /* Last processor-specific type. */
+)

func (DynTag) GoString

func (i DynTag) GoString() string

func (DynTag) String

func (i DynTag) String() string

type File

A File represents an open ELF file.

+
type File struct {
+    FileHeader
+    Sections []*Section
+    Progs    []*Prog
+    // contains filtered or unexported fields
+}
+

func NewFile

func NewFile(r io.ReaderAt) (*File, error)

NewFile creates a new File for accessing an ELF binary in an underlying reader. The ELF binary is expected to start at position 0 in the ReaderAt.

+

func Open

func Open(name string) (*File, error)

Open opens the named file using os.Open and prepares it for use as an ELF binary.

+

func (*File) Close

func (f *File) Close() error

Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

+

func (*File) DWARF

func (f *File) DWARF() (*dwarf.Data, error)

func (*File) DynString 1.1

func (f *File) DynString(tag DynTag) ([]string, error)

DynString returns the strings listed for the given tag in the file's dynamic section.

+

The tag must be one that takes string values: DT_NEEDED, DT_SONAME, DT_RPATH, or DT_RUNPATH.

+

func (*File) DynValue 1.21

func (f *File) DynValue(tag DynTag) ([]uint64, error)

DynValue returns the values listed for the given tag in the file's dynamic section.

+

func (*File) DynamicSymbols 1.4

func (f *File) DynamicSymbols() ([]Symbol, error)

DynamicSymbols returns the dynamic symbol table for f. The symbols will be listed in the order they appear in f.

+

If f has a symbol version table, the returned File.Symbols will have initialized Version and Library fields.

+

For compatibility with File.Symbols, File.DynamicSymbols omits the null symbol at index 0. After retrieving the symbols as symtab, an externally supplied index x corresponds to symtab[x-1], not symtab[x].

+

func (*File) ImportedLibraries

func (f *File) ImportedLibraries() ([]string, error)

ImportedLibraries returns the names of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.

+

func (*File) ImportedSymbols

func (f *File) ImportedSymbols() ([]ImportedSymbol, error)

ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time. It does not return weak symbols.

+

func (*File) Section

func (f *File) Section(name string) *Section

Section returns a section with the given name, or nil if no such section exists.

+

func (*File) SectionByType

func (f *File) SectionByType(typ SectionType) *Section

SectionByType returns the first section in f with the given type, or nil if there is no such section.

+

func (*File) Symbols

func (f *File) Symbols() ([]Symbol, error)

Symbols returns the symbol table for f. The symbols will be listed in the order they appear in f.

+

For compatibility with Go 1.0, Symbols omits the null symbol at index 0. After retrieving the symbols as symtab, an externally supplied index x corresponds to symtab[x-1], not symtab[x].

+

type FileHeader

A FileHeader represents an ELF file header.

+
type FileHeader struct {
+    Class      Class
+    Data       Data
+    Version    Version
+    OSABI      OSABI
+    ABIVersion uint8
+    ByteOrder  binary.ByteOrder
+    Type       Type
+    Machine    Machine
+    Entry      uint64 // Go 1.1
+}
+

type FormatError

type FormatError struct {
+    // contains filtered or unexported fields
+}
+

func (*FormatError) Error

func (e *FormatError) Error() string

type Header32

ELF32 File header.

+
type Header32 struct {
+    Ident     [EI_NIDENT]byte /* File identification. */
+    Type      uint16          /* File type. */
+    Machine   uint16          /* Machine architecture. */
+    Version   uint32          /* ELF format version. */
+    Entry     uint32          /* Entry point. */
+    Phoff     uint32          /* Program header file offset. */
+    Shoff     uint32          /* Section header file offset. */
+    Flags     uint32          /* Architecture-specific flags. */
+    Ehsize    uint16          /* Size of ELF header in bytes. */
+    Phentsize uint16          /* Size of program header entry. */
+    Phnum     uint16          /* Number of program header entries. */
+    Shentsize uint16          /* Size of section header entry. */
+    Shnum     uint16          /* Number of section header entries. */
+    Shstrndx  uint16          /* Section name strings section. */
+}
+

type Header64

ELF64 file header.

+
type Header64 struct {
+    Ident     [EI_NIDENT]byte /* File identification. */
+    Type      uint16          /* File type. */
+    Machine   uint16          /* Machine architecture. */
+    Version   uint32          /* ELF format version. */
+    Entry     uint64          /* Entry point. */
+    Phoff     uint64          /* Program header file offset. */
+    Shoff     uint64          /* Section header file offset. */
+    Flags     uint32          /* Architecture-specific flags. */
+    Ehsize    uint16          /* Size of ELF header in bytes. */
+    Phentsize uint16          /* Size of program header entry. */
+    Phnum     uint16          /* Number of program header entries. */
+    Shentsize uint16          /* Size of section header entry. */
+    Shnum     uint16          /* Number of section header entries. */
+    Shstrndx  uint16          /* Section name strings section. */
+}
+

type ImportedSymbol

type ImportedSymbol struct {
+    Name    string
+    Version string
+    Library string
+}
+

type Machine

Machine is found in Header.Machine.

+
type Machine uint16
const (
+    EM_NONE          Machine = 0   /* Unknown machine. */
+    EM_M32           Machine = 1   /* AT&T WE32100. */
+    EM_SPARC         Machine = 2   /* Sun SPARC. */
+    EM_386           Machine = 3   /* Intel i386. */
+    EM_68K           Machine = 4   /* Motorola 68000. */
+    EM_88K           Machine = 5   /* Motorola 88000. */
+    EM_860           Machine = 7   /* Intel i860. */
+    EM_MIPS          Machine = 8   /* MIPS R3000 Big-Endian only. */
+    EM_S370          Machine = 9   /* IBM System/370. */
+    EM_MIPS_RS3_LE   Machine = 10  /* MIPS R3000 Little-Endian. */
+    EM_PARISC        Machine = 15  /* HP PA-RISC. */
+    EM_VPP500        Machine = 17  /* Fujitsu VPP500. */
+    EM_SPARC32PLUS   Machine = 18  /* SPARC v8plus. */
+    EM_960           Machine = 19  /* Intel 80960. */
+    EM_PPC           Machine = 20  /* PowerPC 32-bit. */
+    EM_PPC64         Machine = 21  /* PowerPC 64-bit. */
+    EM_S390          Machine = 22  /* IBM System/390. */
+    EM_V800          Machine = 36  /* NEC V800. */
+    EM_FR20          Machine = 37  /* Fujitsu FR20. */
+    EM_RH32          Machine = 38  /* TRW RH-32. */
+    EM_RCE           Machine = 39  /* Motorola RCE. */
+    EM_ARM           Machine = 40  /* ARM. */
+    EM_SH            Machine = 42  /* Hitachi SH. */
+    EM_SPARCV9       Machine = 43  /* SPARC v9 64-bit. */
+    EM_TRICORE       Machine = 44  /* Siemens TriCore embedded processor. */
+    EM_ARC           Machine = 45  /* Argonaut RISC Core. */
+    EM_H8_300        Machine = 46  /* Hitachi H8/300. */
+    EM_H8_300H       Machine = 47  /* Hitachi H8/300H. */
+    EM_H8S           Machine = 48  /* Hitachi H8S. */
+    EM_H8_500        Machine = 49  /* Hitachi H8/500. */
+    EM_IA_64         Machine = 50  /* Intel IA-64 Processor. */
+    EM_MIPS_X        Machine = 51  /* Stanford MIPS-X. */
+    EM_COLDFIRE      Machine = 52  /* Motorola ColdFire. */
+    EM_68HC12        Machine = 53  /* Motorola M68HC12. */
+    EM_MMA           Machine = 54  /* Fujitsu MMA. */
+    EM_PCP           Machine = 55  /* Siemens PCP. */
+    EM_NCPU          Machine = 56  /* Sony nCPU. */
+    EM_NDR1          Machine = 57  /* Denso NDR1 microprocessor. */
+    EM_STARCORE      Machine = 58  /* Motorola Star*Core processor. */
+    EM_ME16          Machine = 59  /* Toyota ME16 processor. */
+    EM_ST100         Machine = 60  /* STMicroelectronics ST100 processor. */
+    EM_TINYJ         Machine = 61  /* Advanced Logic Corp. TinyJ processor. */
+    EM_X86_64        Machine = 62  /* Advanced Micro Devices x86-64 */
+    EM_PDSP          Machine = 63  /* Sony DSP Processor */
+    EM_PDP10         Machine = 64  /* Digital Equipment Corp. PDP-10 */
+    EM_PDP11         Machine = 65  /* Digital Equipment Corp. PDP-11 */
+    EM_FX66          Machine = 66  /* Siemens FX66 microcontroller */
+    EM_ST9PLUS       Machine = 67  /* STMicroelectronics ST9+ 8/16 bit microcontroller */
+    EM_ST7           Machine = 68  /* STMicroelectronics ST7 8-bit microcontroller */
+    EM_68HC16        Machine = 69  /* Motorola MC68HC16 Microcontroller */
+    EM_68HC11        Machine = 70  /* Motorola MC68HC11 Microcontroller */
+    EM_68HC08        Machine = 71  /* Motorola MC68HC08 Microcontroller */
+    EM_68HC05        Machine = 72  /* Motorola MC68HC05 Microcontroller */
+    EM_SVX           Machine = 73  /* Silicon Graphics SVx */
+    EM_ST19          Machine = 74  /* STMicroelectronics ST19 8-bit microcontroller */
+    EM_VAX           Machine = 75  /* Digital VAX */
+    EM_CRIS          Machine = 76  /* Axis Communications 32-bit embedded processor */
+    EM_JAVELIN       Machine = 77  /* Infineon Technologies 32-bit embedded processor */
+    EM_FIREPATH      Machine = 78  /* Element 14 64-bit DSP Processor */
+    EM_ZSP           Machine = 79  /* LSI Logic 16-bit DSP Processor */
+    EM_MMIX          Machine = 80  /* Donald Knuth's educational 64-bit processor */
+    EM_HUANY         Machine = 81  /* Harvard University machine-independent object files */
+    EM_PRISM         Machine = 82  /* SiTera Prism */
+    EM_AVR           Machine = 83  /* Atmel AVR 8-bit microcontroller */
+    EM_FR30          Machine = 84  /* Fujitsu FR30 */
+    EM_D10V          Machine = 85  /* Mitsubishi D10V */
+    EM_D30V          Machine = 86  /* Mitsubishi D30V */
+    EM_V850          Machine = 87  /* NEC v850 */
+    EM_M32R          Machine = 88  /* Mitsubishi M32R */
+    EM_MN10300       Machine = 89  /* Matsushita MN10300 */
+    EM_MN10200       Machine = 90  /* Matsushita MN10200 */
+    EM_PJ            Machine = 91  /* picoJava */
+    EM_OPENRISC      Machine = 92  /* OpenRISC 32-bit embedded processor */
+    EM_ARC_COMPACT   Machine = 93  /* ARC International ARCompact processor (old spelling/synonym: EM_ARC_A5) */
+    EM_XTENSA        Machine = 94  /* Tensilica Xtensa Architecture */
+    EM_VIDEOCORE     Machine = 95  /* Alphamosaic VideoCore processor */
+    EM_TMM_GPP       Machine = 96  /* Thompson Multimedia General Purpose Processor */
+    EM_NS32K         Machine = 97  /* National Semiconductor 32000 series */
+    EM_TPC           Machine = 98  /* Tenor Network TPC processor */
+    EM_SNP1K         Machine = 99  /* Trebia SNP 1000 processor */
+    EM_ST200         Machine = 100 /* STMicroelectronics (www.st.com) ST200 microcontroller */
+    EM_IP2K          Machine = 101 /* Ubicom IP2xxx microcontroller family */
+    EM_MAX           Machine = 102 /* MAX Processor */
+    EM_CR            Machine = 103 /* National Semiconductor CompactRISC microprocessor */
+    EM_F2MC16        Machine = 104 /* Fujitsu F2MC16 */
+    EM_MSP430        Machine = 105 /* Texas Instruments embedded microcontroller msp430 */
+    EM_BLACKFIN      Machine = 106 /* Analog Devices Blackfin (DSP) processor */
+    EM_SE_C33        Machine = 107 /* S1C33 Family of Seiko Epson processors */
+    EM_SEP           Machine = 108 /* Sharp embedded microprocessor */
+    EM_ARCA          Machine = 109 /* Arca RISC Microprocessor */
+    EM_UNICORE       Machine = 110 /* Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University */
+    EM_EXCESS        Machine = 111 /* eXcess: 16/32/64-bit configurable embedded CPU */
+    EM_DXP           Machine = 112 /* Icera Semiconductor Inc. Deep Execution Processor */
+    EM_ALTERA_NIOS2  Machine = 113 /* Altera Nios II soft-core processor */
+    EM_CRX           Machine = 114 /* National Semiconductor CompactRISC CRX microprocessor */
+    EM_XGATE         Machine = 115 /* Motorola XGATE embedded processor */
+    EM_C166          Machine = 116 /* Infineon C16x/XC16x processor */
+    EM_M16C          Machine = 117 /* Renesas M16C series microprocessors */
+    EM_DSPIC30F      Machine = 118 /* Microchip Technology dsPIC30F Digital Signal Controller */
+    EM_CE            Machine = 119 /* Freescale Communication Engine RISC core */
+    EM_M32C          Machine = 120 /* Renesas M32C series microprocessors */
+    EM_TSK3000       Machine = 131 /* Altium TSK3000 core */
+    EM_RS08          Machine = 132 /* Freescale RS08 embedded processor */
+    EM_SHARC         Machine = 133 /* Analog Devices SHARC family of 32-bit DSP processors */
+    EM_ECOG2         Machine = 134 /* Cyan Technology eCOG2 microprocessor */
+    EM_SCORE7        Machine = 135 /* Sunplus S+core7 RISC processor */
+    EM_DSP24         Machine = 136 /* New Japan Radio (NJR) 24-bit DSP Processor */
+    EM_VIDEOCORE3    Machine = 137 /* Broadcom VideoCore III processor */
+    EM_LATTICEMICO32 Machine = 138 /* RISC processor for Lattice FPGA architecture */
+    EM_SE_C17        Machine = 139 /* Seiko Epson C17 family */
+    EM_TI_C6000      Machine = 140 /* The Texas Instruments TMS320C6000 DSP family */
+    EM_TI_C2000      Machine = 141 /* The Texas Instruments TMS320C2000 DSP family */
+    EM_TI_C5500      Machine = 142 /* The Texas Instruments TMS320C55x DSP family */
+    EM_TI_ARP32      Machine = 143 /* Texas Instruments Application Specific RISC Processor, 32bit fetch */
+    EM_TI_PRU        Machine = 144 /* Texas Instruments Programmable Realtime Unit */
+    EM_MMDSP_PLUS    Machine = 160 /* STMicroelectronics 64bit VLIW Data Signal Processor */
+    EM_CYPRESS_M8C   Machine = 161 /* Cypress M8C microprocessor */
+    EM_R32C          Machine = 162 /* Renesas R32C series microprocessors */
+    EM_TRIMEDIA      Machine = 163 /* NXP Semiconductors TriMedia architecture family */
+    EM_QDSP6         Machine = 164 /* QUALCOMM DSP6 Processor */
+    EM_8051          Machine = 165 /* Intel 8051 and variants */
+    EM_STXP7X        Machine = 166 /* STMicroelectronics STxP7x family of configurable and extensible RISC processors */
+    EM_NDS32         Machine = 167 /* Andes Technology compact code size embedded RISC processor family */
+    EM_ECOG1         Machine = 168 /* Cyan Technology eCOG1X family */
+    EM_ECOG1X        Machine = 168 /* Cyan Technology eCOG1X family */
+    EM_MAXQ30        Machine = 169 /* Dallas Semiconductor MAXQ30 Core Micro-controllers */
+    EM_XIMO16        Machine = 170 /* New Japan Radio (NJR) 16-bit DSP Processor */
+    EM_MANIK         Machine = 171 /* M2000 Reconfigurable RISC Microprocessor */
+    EM_CRAYNV2       Machine = 172 /* Cray Inc. NV2 vector architecture */
+    EM_RX            Machine = 173 /* Renesas RX family */
+    EM_METAG         Machine = 174 /* Imagination Technologies META processor architecture */
+    EM_MCST_ELBRUS   Machine = 175 /* MCST Elbrus general purpose hardware architecture */
+    EM_ECOG16        Machine = 176 /* Cyan Technology eCOG16 family */
+    EM_CR16          Machine = 177 /* National Semiconductor CompactRISC CR16 16-bit microprocessor */
+    EM_ETPU          Machine = 178 /* Freescale Extended Time Processing Unit */
+    EM_SLE9X         Machine = 179 /* Infineon Technologies SLE9X core */
+    EM_L10M          Machine = 180 /* Intel L10M */
+    EM_K10M          Machine = 181 /* Intel K10M */
+    EM_AARCH64       Machine = 183 /* ARM 64-bit Architecture (AArch64) */
+    EM_AVR32         Machine = 185 /* Atmel Corporation 32-bit microprocessor family */
+    EM_STM8          Machine = 186 /* STMicroeletronics STM8 8-bit microcontroller */
+    EM_TILE64        Machine = 187 /* Tilera TILE64 multicore architecture family */
+    EM_TILEPRO       Machine = 188 /* Tilera TILEPro multicore architecture family */
+    EM_MICROBLAZE    Machine = 189 /* Xilinx MicroBlaze 32-bit RISC soft processor core */
+    EM_CUDA          Machine = 190 /* NVIDIA CUDA architecture */
+    EM_TILEGX        Machine = 191 /* Tilera TILE-Gx multicore architecture family */
+    EM_CLOUDSHIELD   Machine = 192 /* CloudShield architecture family */
+    EM_COREA_1ST     Machine = 193 /* KIPO-KAIST Core-A 1st generation processor family */
+    EM_COREA_2ND     Machine = 194 /* KIPO-KAIST Core-A 2nd generation processor family */
+    EM_ARC_COMPACT2  Machine = 195 /* Synopsys ARCompact V2 */
+    EM_OPEN8         Machine = 196 /* Open8 8-bit RISC soft processor core */
+    EM_RL78          Machine = 197 /* Renesas RL78 family */
+    EM_VIDEOCORE5    Machine = 198 /* Broadcom VideoCore V processor */
+    EM_78KOR         Machine = 199 /* Renesas 78KOR family */
+    EM_56800EX       Machine = 200 /* Freescale 56800EX Digital Signal Controller (DSC) */
+    EM_BA1           Machine = 201 /* Beyond BA1 CPU architecture */
+    EM_BA2           Machine = 202 /* Beyond BA2 CPU architecture */
+    EM_XCORE         Machine = 203 /* XMOS xCORE processor family */
+    EM_MCHP_PIC      Machine = 204 /* Microchip 8-bit PIC(r) family */
+    EM_INTEL205      Machine = 205 /* Reserved by Intel */
+    EM_INTEL206      Machine = 206 /* Reserved by Intel */
+    EM_INTEL207      Machine = 207 /* Reserved by Intel */
+    EM_INTEL208      Machine = 208 /* Reserved by Intel */
+    EM_INTEL209      Machine = 209 /* Reserved by Intel */
+    EM_KM32          Machine = 210 /* KM211 KM32 32-bit processor */
+    EM_KMX32         Machine = 211 /* KM211 KMX32 32-bit processor */
+    EM_KMX16         Machine = 212 /* KM211 KMX16 16-bit processor */
+    EM_KMX8          Machine = 213 /* KM211 KMX8 8-bit processor */
+    EM_KVARC         Machine = 214 /* KM211 KVARC processor */
+    EM_CDP           Machine = 215 /* Paneve CDP architecture family */
+    EM_COGE          Machine = 216 /* Cognitive Smart Memory Processor */
+    EM_COOL          Machine = 217 /* Bluechip Systems CoolEngine */
+    EM_NORC          Machine = 218 /* Nanoradio Optimized RISC */
+    EM_CSR_KALIMBA   Machine = 219 /* CSR Kalimba architecture family */
+    EM_Z80           Machine = 220 /* Zilog Z80 */
+    EM_VISIUM        Machine = 221 /* Controls and Data Services VISIUMcore processor */
+    EM_FT32          Machine = 222 /* FTDI Chip FT32 high performance 32-bit RISC architecture */
+    EM_MOXIE         Machine = 223 /* Moxie processor family */
+    EM_AMDGPU        Machine = 224 /* AMD GPU architecture */
+    EM_RISCV         Machine = 243 /* RISC-V */
+    EM_LANAI         Machine = 244 /* Lanai 32-bit processor */
+    EM_BPF           Machine = 247 /* Linux BPF – in-kernel virtual machine */
+    EM_LOONGARCH     Machine = 258 /* LoongArch */
+
+    /* Non-standard or deprecated. */
+    EM_486         Machine = 6      /* Intel i486. */
+    EM_MIPS_RS4_BE Machine = 10     /* MIPS R4000 Big-Endian */
+    EM_ALPHA_STD   Machine = 41     /* Digital Alpha (standard value). */
+    EM_ALPHA       Machine = 0x9026 /* Alpha (written in the absence of an ABI) */
+)

func (Machine) GoString

func (i Machine) GoString() string

func (Machine) String

func (i Machine) String() string

type NType

NType values; used in core files.

+
type NType int
const (
+    NT_PRSTATUS NType = 1 /* Process status. */
+    NT_FPREGSET NType = 2 /* Floating point registers. */
+    NT_PRPSINFO NType = 3 /* Process state info. */
+)

func (NType) GoString

func (i NType) GoString() string

func (NType) String

func (i NType) String() string

type OSABI

OSABI is found in Header.Ident[EI_OSABI] and Header.OSABI.

+
type OSABI byte
const (
+    ELFOSABI_NONE       OSABI = 0   /* UNIX System V ABI */
+    ELFOSABI_HPUX       OSABI = 1   /* HP-UX operating system */
+    ELFOSABI_NETBSD     OSABI = 2   /* NetBSD */
+    ELFOSABI_LINUX      OSABI = 3   /* Linux */
+    ELFOSABI_HURD       OSABI = 4   /* Hurd */
+    ELFOSABI_86OPEN     OSABI = 5   /* 86Open common IA32 ABI */
+    ELFOSABI_SOLARIS    OSABI = 6   /* Solaris */
+    ELFOSABI_AIX        OSABI = 7   /* AIX */
+    ELFOSABI_IRIX       OSABI = 8   /* IRIX */
+    ELFOSABI_FREEBSD    OSABI = 9   /* FreeBSD */
+    ELFOSABI_TRU64      OSABI = 10  /* TRU64 UNIX */
+    ELFOSABI_MODESTO    OSABI = 11  /* Novell Modesto */
+    ELFOSABI_OPENBSD    OSABI = 12  /* OpenBSD */
+    ELFOSABI_OPENVMS    OSABI = 13  /* Open VMS */
+    ELFOSABI_NSK        OSABI = 14  /* HP Non-Stop Kernel */
+    ELFOSABI_AROS       OSABI = 15  /* Amiga Research OS */
+    ELFOSABI_FENIXOS    OSABI = 16  /* The FenixOS highly scalable multi-core OS */
+    ELFOSABI_CLOUDABI   OSABI = 17  /* Nuxi CloudABI */
+    ELFOSABI_ARM        OSABI = 97  /* ARM */
+    ELFOSABI_STANDALONE OSABI = 255 /* Standalone (embedded) application */
+)

func (OSABI) GoString

func (i OSABI) GoString() string

func (OSABI) String

func (i OSABI) String() string

type Prog

A Prog represents a single ELF program header in an ELF binary.

+
type Prog struct {
+    ProgHeader
+
+    // Embed ReaderAt for ReadAt method.
+    // Do not embed SectionReader directly
+    // to avoid having Read and Seek.
+    // If a client wants Read and Seek it must use
+    // Open() to avoid fighting over the seek offset
+    // with other clients.
+    io.ReaderAt
+    // contains filtered or unexported fields
+}
+

func (*Prog) Open

func (p *Prog) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the ELF program body.

+

type Prog32

ELF32 Program header.

+
type Prog32 struct {
+    Type   uint32 /* Entry type. */
+    Off    uint32 /* File offset of contents. */
+    Vaddr  uint32 /* Virtual address in memory image. */
+    Paddr  uint32 /* Physical address (not used). */
+    Filesz uint32 /* Size of contents in file. */
+    Memsz  uint32 /* Size of contents in memory. */
+    Flags  uint32 /* Access permission flags. */
+    Align  uint32 /* Alignment in memory and file. */
+}
+

type Prog64

ELF64 Program header.

+
type Prog64 struct {
+    Type   uint32 /* Entry type. */
+    Flags  uint32 /* Access permission flags. */
+    Off    uint64 /* File offset of contents. */
+    Vaddr  uint64 /* Virtual address in memory image. */
+    Paddr  uint64 /* Physical address (not used). */
+    Filesz uint64 /* Size of contents in file. */
+    Memsz  uint64 /* Size of contents in memory. */
+    Align  uint64 /* Alignment in memory and file. */
+}
+

type ProgFlag

Prog.Flag

+
type ProgFlag uint32
const (
+    PF_X        ProgFlag = 0x1        /* Executable. */
+    PF_W        ProgFlag = 0x2        /* Writable. */
+    PF_R        ProgFlag = 0x4        /* Readable. */
+    PF_MASKOS   ProgFlag = 0x0ff00000 /* Operating system-specific. */
+    PF_MASKPROC ProgFlag = 0xf0000000 /* Processor-specific. */
+)

func (ProgFlag) GoString

func (i ProgFlag) GoString() string

func (ProgFlag) String

func (i ProgFlag) String() string

type ProgHeader

A ProgHeader represents a single ELF program header.

+
type ProgHeader struct {
+    Type   ProgType
+    Flags  ProgFlag
+    Off    uint64
+    Vaddr  uint64
+    Paddr  uint64
+    Filesz uint64
+    Memsz  uint64
+    Align  uint64
+}
+

type ProgType

Prog.Type

+
type ProgType int
const (
+    PT_NULL    ProgType = 0 /* Unused entry. */
+    PT_LOAD    ProgType = 1 /* Loadable segment. */
+    PT_DYNAMIC ProgType = 2 /* Dynamic linking information segment. */
+    PT_INTERP  ProgType = 3 /* Pathname of interpreter. */
+    PT_NOTE    ProgType = 4 /* Auxiliary information. */
+    PT_SHLIB   ProgType = 5 /* Reserved (not used). */
+    PT_PHDR    ProgType = 6 /* Location of program header itself. */
+    PT_TLS     ProgType = 7 /* Thread local storage segment */
+
+    PT_LOOS ProgType = 0x60000000 /* First OS-specific. */
+
+    PT_GNU_EH_FRAME ProgType = 0x6474e550 /* Frame unwind information */
+    PT_GNU_STACK    ProgType = 0x6474e551 /* Stack flags */
+    PT_GNU_RELRO    ProgType = 0x6474e552 /* Read only after relocs */
+    PT_GNU_PROPERTY ProgType = 0x6474e553 /* GNU property */
+    PT_GNU_MBIND_LO ProgType = 0x6474e555 /* Mbind segments start */
+    PT_GNU_MBIND_HI ProgType = 0x6474f554 /* Mbind segments finish */
+
+    PT_PAX_FLAGS ProgType = 0x65041580 /* PAX flags */
+
+    PT_OPENBSD_RANDOMIZE ProgType = 0x65a3dbe6 /* Random data */
+    PT_OPENBSD_WXNEEDED  ProgType = 0x65a3dbe7 /* W^X violations */
+    PT_OPENBSD_BOOTDATA  ProgType = 0x65a41be6 /* Boot arguments */
+
+    PT_SUNW_EH_FRAME ProgType = 0x6474e550 /* Frame unwind information */
+    PT_SUNWSTACK     ProgType = 0x6ffffffb /* Stack segment */
+
+    PT_HIOS ProgType = 0x6fffffff /* Last OS-specific. */
+
+    PT_LOPROC ProgType = 0x70000000 /* First processor-specific type. */
+
+    PT_ARM_ARCHEXT ProgType = 0x70000000 /* Architecture compatibility */
+    PT_ARM_EXIDX   ProgType = 0x70000001 /* Exception unwind tables */
+
+    PT_AARCH64_ARCHEXT ProgType = 0x70000000 /* Architecture compatibility */
+    PT_AARCH64_UNWIND  ProgType = 0x70000001 /* Exception unwind tables */
+
+    PT_MIPS_REGINFO  ProgType = 0x70000000 /* Register usage */
+    PT_MIPS_RTPROC   ProgType = 0x70000001 /* Runtime procedures */
+    PT_MIPS_OPTIONS  ProgType = 0x70000002 /* Options */
+    PT_MIPS_ABIFLAGS ProgType = 0x70000003 /* ABI flags */
+
+    PT_S390_PGSTE ProgType = 0x70000000 /* 4k page table size */
+
+    PT_HIPROC ProgType = 0x7fffffff /* Last processor-specific type. */
+)

func (ProgType) GoString

func (i ProgType) GoString() string

func (ProgType) String

func (i ProgType) String() string

type R_386

Relocation types for 386.

+
type R_386 int
const (
+    R_386_NONE          R_386 = 0  /* No relocation. */
+    R_386_32            R_386 = 1  /* Add symbol value. */
+    R_386_PC32          R_386 = 2  /* Add PC-relative symbol value. */
+    R_386_GOT32         R_386 = 3  /* Add PC-relative GOT offset. */
+    R_386_PLT32         R_386 = 4  /* Add PC-relative PLT offset. */
+    R_386_COPY          R_386 = 5  /* Copy data from shared object. */
+    R_386_GLOB_DAT      R_386 = 6  /* Set GOT entry to data address. */
+    R_386_JMP_SLOT      R_386 = 7  /* Set GOT entry to code address. */
+    R_386_RELATIVE      R_386 = 8  /* Add load address of shared object. */
+    R_386_GOTOFF        R_386 = 9  /* Add GOT-relative symbol address. */
+    R_386_GOTPC         R_386 = 10 /* Add PC-relative GOT table address. */
+    R_386_32PLT         R_386 = 11
+    R_386_TLS_TPOFF     R_386 = 14 /* Negative offset in static TLS block */
+    R_386_TLS_IE        R_386 = 15 /* Absolute address of GOT for -ve static TLS */
+    R_386_TLS_GOTIE     R_386 = 16 /* GOT entry for negative static TLS block */
+    R_386_TLS_LE        R_386 = 17 /* Negative offset relative to static TLS */
+    R_386_TLS_GD        R_386 = 18 /* 32 bit offset to GOT (index,off) pair */
+    R_386_TLS_LDM       R_386 = 19 /* 32 bit offset to GOT (index,zero) pair */
+    R_386_16            R_386 = 20
+    R_386_PC16          R_386 = 21
+    R_386_8             R_386 = 22
+    R_386_PC8           R_386 = 23
+    R_386_TLS_GD_32     R_386 = 24 /* 32 bit offset to GOT (index,off) pair */
+    R_386_TLS_GD_PUSH   R_386 = 25 /* pushl instruction for Sun ABI GD sequence */
+    R_386_TLS_GD_CALL   R_386 = 26 /* call instruction for Sun ABI GD sequence */
+    R_386_TLS_GD_POP    R_386 = 27 /* popl instruction for Sun ABI GD sequence */
+    R_386_TLS_LDM_32    R_386 = 28 /* 32 bit offset to GOT (index,zero) pair */
+    R_386_TLS_LDM_PUSH  R_386 = 29 /* pushl instruction for Sun ABI LD sequence */
+    R_386_TLS_LDM_CALL  R_386 = 30 /* call instruction for Sun ABI LD sequence */
+    R_386_TLS_LDM_POP   R_386 = 31 /* popl instruction for Sun ABI LD sequence */
+    R_386_TLS_LDO_32    R_386 = 32 /* 32 bit offset from start of TLS block */
+    R_386_TLS_IE_32     R_386 = 33 /* 32 bit offset to GOT static TLS offset entry */
+    R_386_TLS_LE_32     R_386 = 34 /* 32 bit offset within static TLS block */
+    R_386_TLS_DTPMOD32  R_386 = 35 /* GOT entry containing TLS index */
+    R_386_TLS_DTPOFF32  R_386 = 36 /* GOT entry containing TLS offset */
+    R_386_TLS_TPOFF32   R_386 = 37 /* GOT entry of -ve static TLS offset */
+    R_386_SIZE32        R_386 = 38
+    R_386_TLS_GOTDESC   R_386 = 39
+    R_386_TLS_DESC_CALL R_386 = 40
+    R_386_TLS_DESC      R_386 = 41
+    R_386_IRELATIVE     R_386 = 42
+    R_386_GOT32X        R_386 = 43
+)

func (R_386) GoString

func (i R_386) GoString() string

func (R_386) String

func (i R_386) String() string

type R_390 1.7

Relocation types for s390x processors.

+
type R_390 int
const (
+    R_390_NONE        R_390 = 0
+    R_390_8           R_390 = 1
+    R_390_12          R_390 = 2
+    R_390_16          R_390 = 3
+    R_390_32          R_390 = 4
+    R_390_PC32        R_390 = 5
+    R_390_GOT12       R_390 = 6
+    R_390_GOT32       R_390 = 7
+    R_390_PLT32       R_390 = 8
+    R_390_COPY        R_390 = 9
+    R_390_GLOB_DAT    R_390 = 10
+    R_390_JMP_SLOT    R_390 = 11
+    R_390_RELATIVE    R_390 = 12
+    R_390_GOTOFF      R_390 = 13
+    R_390_GOTPC       R_390 = 14
+    R_390_GOT16       R_390 = 15
+    R_390_PC16        R_390 = 16
+    R_390_PC16DBL     R_390 = 17
+    R_390_PLT16DBL    R_390 = 18
+    R_390_PC32DBL     R_390 = 19
+    R_390_PLT32DBL    R_390 = 20
+    R_390_GOTPCDBL    R_390 = 21
+    R_390_64          R_390 = 22
+    R_390_PC64        R_390 = 23
+    R_390_GOT64       R_390 = 24
+    R_390_PLT64       R_390 = 25
+    R_390_GOTENT      R_390 = 26
+    R_390_GOTOFF16    R_390 = 27
+    R_390_GOTOFF64    R_390 = 28
+    R_390_GOTPLT12    R_390 = 29
+    R_390_GOTPLT16    R_390 = 30
+    R_390_GOTPLT32    R_390 = 31
+    R_390_GOTPLT64    R_390 = 32
+    R_390_GOTPLTENT   R_390 = 33
+    R_390_GOTPLTOFF16 R_390 = 34
+    R_390_GOTPLTOFF32 R_390 = 35
+    R_390_GOTPLTOFF64 R_390 = 36
+    R_390_TLS_LOAD    R_390 = 37
+    R_390_TLS_GDCALL  R_390 = 38
+    R_390_TLS_LDCALL  R_390 = 39
+    R_390_TLS_GD32    R_390 = 40
+    R_390_TLS_GD64    R_390 = 41
+    R_390_TLS_GOTIE12 R_390 = 42
+    R_390_TLS_GOTIE32 R_390 = 43
+    R_390_TLS_GOTIE64 R_390 = 44
+    R_390_TLS_LDM32   R_390 = 45
+    R_390_TLS_LDM64   R_390 = 46
+    R_390_TLS_IE32    R_390 = 47
+    R_390_TLS_IE64    R_390 = 48
+    R_390_TLS_IEENT   R_390 = 49
+    R_390_TLS_LE32    R_390 = 50
+    R_390_TLS_LE64    R_390 = 51
+    R_390_TLS_LDO32   R_390 = 52
+    R_390_TLS_LDO64   R_390 = 53
+    R_390_TLS_DTPMOD  R_390 = 54
+    R_390_TLS_DTPOFF  R_390 = 55
+    R_390_TLS_TPOFF   R_390 = 56
+    R_390_20          R_390 = 57
+    R_390_GOT20       R_390 = 58
+    R_390_GOTPLT20    R_390 = 59
+    R_390_TLS_GOTIE20 R_390 = 60
+)

func (R_390) GoString 1.7

func (i R_390) GoString() string

func (R_390) String 1.7

func (i R_390) String() string

type R_AARCH64 1.4

Relocation types for AArch64 (aka arm64)

+
type R_AARCH64 int
const (
+    R_AARCH64_NONE                            R_AARCH64 = 0
+    R_AARCH64_P32_ABS32                       R_AARCH64 = 1
+    R_AARCH64_P32_ABS16                       R_AARCH64 = 2
+    R_AARCH64_P32_PREL32                      R_AARCH64 = 3
+    R_AARCH64_P32_PREL16                      R_AARCH64 = 4
+    R_AARCH64_P32_MOVW_UABS_G0                R_AARCH64 = 5
+    R_AARCH64_P32_MOVW_UABS_G0_NC             R_AARCH64 = 6
+    R_AARCH64_P32_MOVW_UABS_G1                R_AARCH64 = 7
+    R_AARCH64_P32_MOVW_SABS_G0                R_AARCH64 = 8
+    R_AARCH64_P32_LD_PREL_LO19                R_AARCH64 = 9
+    R_AARCH64_P32_ADR_PREL_LO21               R_AARCH64 = 10
+    R_AARCH64_P32_ADR_PREL_PG_HI21            R_AARCH64 = 11
+    R_AARCH64_P32_ADD_ABS_LO12_NC             R_AARCH64 = 12
+    R_AARCH64_P32_LDST8_ABS_LO12_NC           R_AARCH64 = 13
+    R_AARCH64_P32_LDST16_ABS_LO12_NC          R_AARCH64 = 14
+    R_AARCH64_P32_LDST32_ABS_LO12_NC          R_AARCH64 = 15
+    R_AARCH64_P32_LDST64_ABS_LO12_NC          R_AARCH64 = 16
+    R_AARCH64_P32_LDST128_ABS_LO12_NC         R_AARCH64 = 17
+    R_AARCH64_P32_TSTBR14                     R_AARCH64 = 18
+    R_AARCH64_P32_CONDBR19                    R_AARCH64 = 19
+    R_AARCH64_P32_JUMP26                      R_AARCH64 = 20
+    R_AARCH64_P32_CALL26                      R_AARCH64 = 21
+    R_AARCH64_P32_GOT_LD_PREL19               R_AARCH64 = 25
+    R_AARCH64_P32_ADR_GOT_PAGE                R_AARCH64 = 26
+    R_AARCH64_P32_LD32_GOT_LO12_NC            R_AARCH64 = 27
+    R_AARCH64_P32_TLSGD_ADR_PAGE21            R_AARCH64 = 81
+    R_AARCH64_P32_TLSGD_ADD_LO12_NC           R_AARCH64 = 82
+    R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21   R_AARCH64 = 103
+    R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC R_AARCH64 = 104
+    R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19    R_AARCH64 = 105
+    R_AARCH64_P32_TLSLE_MOVW_TPREL_G1         R_AARCH64 = 106
+    R_AARCH64_P32_TLSLE_MOVW_TPREL_G0         R_AARCH64 = 107
+    R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC      R_AARCH64 = 108
+    R_AARCH64_P32_TLSLE_ADD_TPREL_HI12        R_AARCH64 = 109
+    R_AARCH64_P32_TLSLE_ADD_TPREL_LO12        R_AARCH64 = 110
+    R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC     R_AARCH64 = 111
+    R_AARCH64_P32_TLSDESC_LD_PREL19           R_AARCH64 = 122
+    R_AARCH64_P32_TLSDESC_ADR_PREL21          R_AARCH64 = 123
+    R_AARCH64_P32_TLSDESC_ADR_PAGE21          R_AARCH64 = 124
+    R_AARCH64_P32_TLSDESC_LD32_LO12_NC        R_AARCH64 = 125
+    R_AARCH64_P32_TLSDESC_ADD_LO12_NC         R_AARCH64 = 126
+    R_AARCH64_P32_TLSDESC_CALL                R_AARCH64 = 127
+    R_AARCH64_P32_COPY                        R_AARCH64 = 180
+    R_AARCH64_P32_GLOB_DAT                    R_AARCH64 = 181
+    R_AARCH64_P32_JUMP_SLOT                   R_AARCH64 = 182
+    R_AARCH64_P32_RELATIVE                    R_AARCH64 = 183
+    R_AARCH64_P32_TLS_DTPMOD                  R_AARCH64 = 184
+    R_AARCH64_P32_TLS_DTPREL                  R_AARCH64 = 185
+    R_AARCH64_P32_TLS_TPREL                   R_AARCH64 = 186
+    R_AARCH64_P32_TLSDESC                     R_AARCH64 = 187
+    R_AARCH64_P32_IRELATIVE                   R_AARCH64 = 188
+    R_AARCH64_NULL                            R_AARCH64 = 256
+    R_AARCH64_ABS64                           R_AARCH64 = 257
+    R_AARCH64_ABS32                           R_AARCH64 = 258
+    R_AARCH64_ABS16                           R_AARCH64 = 259
+    R_AARCH64_PREL64                          R_AARCH64 = 260
+    R_AARCH64_PREL32                          R_AARCH64 = 261
+    R_AARCH64_PREL16                          R_AARCH64 = 262
+    R_AARCH64_MOVW_UABS_G0                    R_AARCH64 = 263
+    R_AARCH64_MOVW_UABS_G0_NC                 R_AARCH64 = 264
+    R_AARCH64_MOVW_UABS_G1                    R_AARCH64 = 265
+    R_AARCH64_MOVW_UABS_G1_NC                 R_AARCH64 = 266
+    R_AARCH64_MOVW_UABS_G2                    R_AARCH64 = 267
+    R_AARCH64_MOVW_UABS_G2_NC                 R_AARCH64 = 268
+    R_AARCH64_MOVW_UABS_G3                    R_AARCH64 = 269
+    R_AARCH64_MOVW_SABS_G0                    R_AARCH64 = 270
+    R_AARCH64_MOVW_SABS_G1                    R_AARCH64 = 271
+    R_AARCH64_MOVW_SABS_G2                    R_AARCH64 = 272
+    R_AARCH64_LD_PREL_LO19                    R_AARCH64 = 273
+    R_AARCH64_ADR_PREL_LO21                   R_AARCH64 = 274
+    R_AARCH64_ADR_PREL_PG_HI21                R_AARCH64 = 275
+    R_AARCH64_ADR_PREL_PG_HI21_NC             R_AARCH64 = 276
+    R_AARCH64_ADD_ABS_LO12_NC                 R_AARCH64 = 277
+    R_AARCH64_LDST8_ABS_LO12_NC               R_AARCH64 = 278
+    R_AARCH64_TSTBR14                         R_AARCH64 = 279
+    R_AARCH64_CONDBR19                        R_AARCH64 = 280
+    R_AARCH64_JUMP26                          R_AARCH64 = 282
+    R_AARCH64_CALL26                          R_AARCH64 = 283
+    R_AARCH64_LDST16_ABS_LO12_NC              R_AARCH64 = 284
+    R_AARCH64_LDST32_ABS_LO12_NC              R_AARCH64 = 285
+    R_AARCH64_LDST64_ABS_LO12_NC              R_AARCH64 = 286
+    R_AARCH64_LDST128_ABS_LO12_NC             R_AARCH64 = 299
+    R_AARCH64_GOT_LD_PREL19                   R_AARCH64 = 309
+    R_AARCH64_LD64_GOTOFF_LO15                R_AARCH64 = 310
+    R_AARCH64_ADR_GOT_PAGE                    R_AARCH64 = 311
+    R_AARCH64_LD64_GOT_LO12_NC                R_AARCH64 = 312
+    R_AARCH64_LD64_GOTPAGE_LO15               R_AARCH64 = 313
+    R_AARCH64_TLSGD_ADR_PREL21                R_AARCH64 = 512
+    R_AARCH64_TLSGD_ADR_PAGE21                R_AARCH64 = 513
+    R_AARCH64_TLSGD_ADD_LO12_NC               R_AARCH64 = 514
+    R_AARCH64_TLSGD_MOVW_G1                   R_AARCH64 = 515
+    R_AARCH64_TLSGD_MOVW_G0_NC                R_AARCH64 = 516
+    R_AARCH64_TLSLD_ADR_PREL21                R_AARCH64 = 517
+    R_AARCH64_TLSLD_ADR_PAGE21                R_AARCH64 = 518
+    R_AARCH64_TLSIE_MOVW_GOTTPREL_G1          R_AARCH64 = 539
+    R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC       R_AARCH64 = 540
+    R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21       R_AARCH64 = 541
+    R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC     R_AARCH64 = 542
+    R_AARCH64_TLSIE_LD_GOTTPREL_PREL19        R_AARCH64 = 543
+    R_AARCH64_TLSLE_MOVW_TPREL_G2             R_AARCH64 = 544
+    R_AARCH64_TLSLE_MOVW_TPREL_G1             R_AARCH64 = 545
+    R_AARCH64_TLSLE_MOVW_TPREL_G1_NC          R_AARCH64 = 546
+    R_AARCH64_TLSLE_MOVW_TPREL_G0             R_AARCH64 = 547
+    R_AARCH64_TLSLE_MOVW_TPREL_G0_NC          R_AARCH64 = 548
+    R_AARCH64_TLSLE_ADD_TPREL_HI12            R_AARCH64 = 549
+    R_AARCH64_TLSLE_ADD_TPREL_LO12            R_AARCH64 = 550
+    R_AARCH64_TLSLE_ADD_TPREL_LO12_NC         R_AARCH64 = 551
+    R_AARCH64_TLSDESC_LD_PREL19               R_AARCH64 = 560
+    R_AARCH64_TLSDESC_ADR_PREL21              R_AARCH64 = 561
+    R_AARCH64_TLSDESC_ADR_PAGE21              R_AARCH64 = 562
+    R_AARCH64_TLSDESC_LD64_LO12_NC            R_AARCH64 = 563
+    R_AARCH64_TLSDESC_ADD_LO12_NC             R_AARCH64 = 564
+    R_AARCH64_TLSDESC_OFF_G1                  R_AARCH64 = 565
+    R_AARCH64_TLSDESC_OFF_G0_NC               R_AARCH64 = 566
+    R_AARCH64_TLSDESC_LDR                     R_AARCH64 = 567
+    R_AARCH64_TLSDESC_ADD                     R_AARCH64 = 568
+    R_AARCH64_TLSDESC_CALL                    R_AARCH64 = 569
+    R_AARCH64_TLSLE_LDST128_TPREL_LO12        R_AARCH64 = 570
+    R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC     R_AARCH64 = 571
+    R_AARCH64_TLSLD_LDST128_DTPREL_LO12       R_AARCH64 = 572
+    R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC    R_AARCH64 = 573
+    R_AARCH64_COPY                            R_AARCH64 = 1024
+    R_AARCH64_GLOB_DAT                        R_AARCH64 = 1025
+    R_AARCH64_JUMP_SLOT                       R_AARCH64 = 1026
+    R_AARCH64_RELATIVE                        R_AARCH64 = 1027
+    R_AARCH64_TLS_DTPMOD64                    R_AARCH64 = 1028
+    R_AARCH64_TLS_DTPREL64                    R_AARCH64 = 1029
+    R_AARCH64_TLS_TPREL64                     R_AARCH64 = 1030
+    R_AARCH64_TLSDESC                         R_AARCH64 = 1031
+    R_AARCH64_IRELATIVE                       R_AARCH64 = 1032
+)

func (R_AARCH64) GoString 1.4

func (i R_AARCH64) GoString() string

func (R_AARCH64) String 1.4

func (i R_AARCH64) String() string

type R_ALPHA

Relocation types for Alpha.

+
type R_ALPHA int
const (
+    R_ALPHA_NONE           R_ALPHA = 0  /* No reloc */
+    R_ALPHA_REFLONG        R_ALPHA = 1  /* Direct 32 bit */
+    R_ALPHA_REFQUAD        R_ALPHA = 2  /* Direct 64 bit */
+    R_ALPHA_GPREL32        R_ALPHA = 3  /* GP relative 32 bit */
+    R_ALPHA_LITERAL        R_ALPHA = 4  /* GP relative 16 bit w/optimization */
+    R_ALPHA_LITUSE         R_ALPHA = 5  /* Optimization hint for LITERAL */
+    R_ALPHA_GPDISP         R_ALPHA = 6  /* Add displacement to GP */
+    R_ALPHA_BRADDR         R_ALPHA = 7  /* PC+4 relative 23 bit shifted */
+    R_ALPHA_HINT           R_ALPHA = 8  /* PC+4 relative 16 bit shifted */
+    R_ALPHA_SREL16         R_ALPHA = 9  /* PC relative 16 bit */
+    R_ALPHA_SREL32         R_ALPHA = 10 /* PC relative 32 bit */
+    R_ALPHA_SREL64         R_ALPHA = 11 /* PC relative 64 bit */
+    R_ALPHA_OP_PUSH        R_ALPHA = 12 /* OP stack push */
+    R_ALPHA_OP_STORE       R_ALPHA = 13 /* OP stack pop and store */
+    R_ALPHA_OP_PSUB        R_ALPHA = 14 /* OP stack subtract */
+    R_ALPHA_OP_PRSHIFT     R_ALPHA = 15 /* OP stack right shift */
+    R_ALPHA_GPVALUE        R_ALPHA = 16
+    R_ALPHA_GPRELHIGH      R_ALPHA = 17
+    R_ALPHA_GPRELLOW       R_ALPHA = 18
+    R_ALPHA_IMMED_GP_16    R_ALPHA = 19
+    R_ALPHA_IMMED_GP_HI32  R_ALPHA = 20
+    R_ALPHA_IMMED_SCN_HI32 R_ALPHA = 21
+    R_ALPHA_IMMED_BR_HI32  R_ALPHA = 22
+    R_ALPHA_IMMED_LO32     R_ALPHA = 23
+    R_ALPHA_COPY           R_ALPHA = 24 /* Copy symbol at runtime */
+    R_ALPHA_GLOB_DAT       R_ALPHA = 25 /* Create GOT entry */
+    R_ALPHA_JMP_SLOT       R_ALPHA = 26 /* Create PLT entry */
+    R_ALPHA_RELATIVE       R_ALPHA = 27 /* Adjust by program base */
+)

func (R_ALPHA) GoString

func (i R_ALPHA) GoString() string

func (R_ALPHA) String

func (i R_ALPHA) String() string

type R_ARM

Relocation types for ARM.

+
type R_ARM int
const (
+    R_ARM_NONE               R_ARM = 0 /* No relocation. */
+    R_ARM_PC24               R_ARM = 1
+    R_ARM_ABS32              R_ARM = 2
+    R_ARM_REL32              R_ARM = 3
+    R_ARM_PC13               R_ARM = 4
+    R_ARM_ABS16              R_ARM = 5
+    R_ARM_ABS12              R_ARM = 6
+    R_ARM_THM_ABS5           R_ARM = 7
+    R_ARM_ABS8               R_ARM = 8
+    R_ARM_SBREL32            R_ARM = 9
+    R_ARM_THM_PC22           R_ARM = 10
+    R_ARM_THM_PC8            R_ARM = 11
+    R_ARM_AMP_VCALL9         R_ARM = 12
+    R_ARM_SWI24              R_ARM = 13
+    R_ARM_THM_SWI8           R_ARM = 14
+    R_ARM_XPC25              R_ARM = 15
+    R_ARM_THM_XPC22          R_ARM = 16
+    R_ARM_TLS_DTPMOD32       R_ARM = 17
+    R_ARM_TLS_DTPOFF32       R_ARM = 18
+    R_ARM_TLS_TPOFF32        R_ARM = 19
+    R_ARM_COPY               R_ARM = 20 /* Copy data from shared object. */
+    R_ARM_GLOB_DAT           R_ARM = 21 /* Set GOT entry to data address. */
+    R_ARM_JUMP_SLOT          R_ARM = 22 /* Set GOT entry to code address. */
+    R_ARM_RELATIVE           R_ARM = 23 /* Add load address of shared object. */
+    R_ARM_GOTOFF             R_ARM = 24 /* Add GOT-relative symbol address. */
+    R_ARM_GOTPC              R_ARM = 25 /* Add PC-relative GOT table address. */
+    R_ARM_GOT32              R_ARM = 26 /* Add PC-relative GOT offset. */
+    R_ARM_PLT32              R_ARM = 27 /* Add PC-relative PLT offset. */
+    R_ARM_CALL               R_ARM = 28
+    R_ARM_JUMP24             R_ARM = 29
+    R_ARM_THM_JUMP24         R_ARM = 30
+    R_ARM_BASE_ABS           R_ARM = 31
+    R_ARM_ALU_PCREL_7_0      R_ARM = 32
+    R_ARM_ALU_PCREL_15_8     R_ARM = 33
+    R_ARM_ALU_PCREL_23_15    R_ARM = 34
+    R_ARM_LDR_SBREL_11_10_NC R_ARM = 35
+    R_ARM_ALU_SBREL_19_12_NC R_ARM = 36
+    R_ARM_ALU_SBREL_27_20_CK R_ARM = 37
+    R_ARM_TARGET1            R_ARM = 38
+    R_ARM_SBREL31            R_ARM = 39
+    R_ARM_V4BX               R_ARM = 40
+    R_ARM_TARGET2            R_ARM = 41
+    R_ARM_PREL31             R_ARM = 42
+    R_ARM_MOVW_ABS_NC        R_ARM = 43
+    R_ARM_MOVT_ABS           R_ARM = 44
+    R_ARM_MOVW_PREL_NC       R_ARM = 45
+    R_ARM_MOVT_PREL          R_ARM = 46
+    R_ARM_THM_MOVW_ABS_NC    R_ARM = 47
+    R_ARM_THM_MOVT_ABS       R_ARM = 48
+    R_ARM_THM_MOVW_PREL_NC   R_ARM = 49
+    R_ARM_THM_MOVT_PREL      R_ARM = 50
+    R_ARM_THM_JUMP19         R_ARM = 51
+    R_ARM_THM_JUMP6          R_ARM = 52
+    R_ARM_THM_ALU_PREL_11_0  R_ARM = 53
+    R_ARM_THM_PC12           R_ARM = 54
+    R_ARM_ABS32_NOI          R_ARM = 55
+    R_ARM_REL32_NOI          R_ARM = 56
+    R_ARM_ALU_PC_G0_NC       R_ARM = 57
+    R_ARM_ALU_PC_G0          R_ARM = 58
+    R_ARM_ALU_PC_G1_NC       R_ARM = 59
+    R_ARM_ALU_PC_G1          R_ARM = 60
+    R_ARM_ALU_PC_G2          R_ARM = 61
+    R_ARM_LDR_PC_G1          R_ARM = 62
+    R_ARM_LDR_PC_G2          R_ARM = 63
+    R_ARM_LDRS_PC_G0         R_ARM = 64
+    R_ARM_LDRS_PC_G1         R_ARM = 65
+    R_ARM_LDRS_PC_G2         R_ARM = 66
+    R_ARM_LDC_PC_G0          R_ARM = 67
+    R_ARM_LDC_PC_G1          R_ARM = 68
+    R_ARM_LDC_PC_G2          R_ARM = 69
+    R_ARM_ALU_SB_G0_NC       R_ARM = 70
+    R_ARM_ALU_SB_G0          R_ARM = 71
+    R_ARM_ALU_SB_G1_NC       R_ARM = 72
+    R_ARM_ALU_SB_G1          R_ARM = 73
+    R_ARM_ALU_SB_G2          R_ARM = 74
+    R_ARM_LDR_SB_G0          R_ARM = 75
+    R_ARM_LDR_SB_G1          R_ARM = 76
+    R_ARM_LDR_SB_G2          R_ARM = 77
+    R_ARM_LDRS_SB_G0         R_ARM = 78
+    R_ARM_LDRS_SB_G1         R_ARM = 79
+    R_ARM_LDRS_SB_G2         R_ARM = 80
+    R_ARM_LDC_SB_G0          R_ARM = 81
+    R_ARM_LDC_SB_G1          R_ARM = 82
+    R_ARM_LDC_SB_G2          R_ARM = 83
+    R_ARM_MOVW_BREL_NC       R_ARM = 84
+    R_ARM_MOVT_BREL          R_ARM = 85
+    R_ARM_MOVW_BREL          R_ARM = 86
+    R_ARM_THM_MOVW_BREL_NC   R_ARM = 87
+    R_ARM_THM_MOVT_BREL      R_ARM = 88
+    R_ARM_THM_MOVW_BREL      R_ARM = 89
+    R_ARM_TLS_GOTDESC        R_ARM = 90
+    R_ARM_TLS_CALL           R_ARM = 91
+    R_ARM_TLS_DESCSEQ        R_ARM = 92
+    R_ARM_THM_TLS_CALL       R_ARM = 93
+    R_ARM_PLT32_ABS          R_ARM = 94
+    R_ARM_GOT_ABS            R_ARM = 95
+    R_ARM_GOT_PREL           R_ARM = 96
+    R_ARM_GOT_BREL12         R_ARM = 97
+    R_ARM_GOTOFF12           R_ARM = 98
+    R_ARM_GOTRELAX           R_ARM = 99
+    R_ARM_GNU_VTENTRY        R_ARM = 100
+    R_ARM_GNU_VTINHERIT      R_ARM = 101
+    R_ARM_THM_JUMP11         R_ARM = 102
+    R_ARM_THM_JUMP8          R_ARM = 103
+    R_ARM_TLS_GD32           R_ARM = 104
+    R_ARM_TLS_LDM32          R_ARM = 105
+    R_ARM_TLS_LDO32          R_ARM = 106
+    R_ARM_TLS_IE32           R_ARM = 107
+    R_ARM_TLS_LE32           R_ARM = 108
+    R_ARM_TLS_LDO12          R_ARM = 109
+    R_ARM_TLS_LE12           R_ARM = 110
+    R_ARM_TLS_IE12GP         R_ARM = 111
+    R_ARM_PRIVATE_0          R_ARM = 112
+    R_ARM_PRIVATE_1          R_ARM = 113
+    R_ARM_PRIVATE_2          R_ARM = 114
+    R_ARM_PRIVATE_3          R_ARM = 115
+    R_ARM_PRIVATE_4          R_ARM = 116
+    R_ARM_PRIVATE_5          R_ARM = 117
+    R_ARM_PRIVATE_6          R_ARM = 118
+    R_ARM_PRIVATE_7          R_ARM = 119
+    R_ARM_PRIVATE_8          R_ARM = 120
+    R_ARM_PRIVATE_9          R_ARM = 121
+    R_ARM_PRIVATE_10         R_ARM = 122
+    R_ARM_PRIVATE_11         R_ARM = 123
+    R_ARM_PRIVATE_12         R_ARM = 124
+    R_ARM_PRIVATE_13         R_ARM = 125
+    R_ARM_PRIVATE_14         R_ARM = 126
+    R_ARM_PRIVATE_15         R_ARM = 127
+    R_ARM_ME_TOO             R_ARM = 128
+    R_ARM_THM_TLS_DESCSEQ16  R_ARM = 129
+    R_ARM_THM_TLS_DESCSEQ32  R_ARM = 130
+    R_ARM_THM_GOT_BREL12     R_ARM = 131
+    R_ARM_THM_ALU_ABS_G0_NC  R_ARM = 132
+    R_ARM_THM_ALU_ABS_G1_NC  R_ARM = 133
+    R_ARM_THM_ALU_ABS_G2_NC  R_ARM = 134
+    R_ARM_THM_ALU_ABS_G3     R_ARM = 135
+    R_ARM_IRELATIVE          R_ARM = 160
+    R_ARM_RXPC25             R_ARM = 249
+    R_ARM_RSBREL32           R_ARM = 250
+    R_ARM_THM_RPC22          R_ARM = 251
+    R_ARM_RREL32             R_ARM = 252
+    R_ARM_RABS32             R_ARM = 253
+    R_ARM_RPC24              R_ARM = 254
+    R_ARM_RBASE              R_ARM = 255
+)

func (R_ARM) GoString

func (i R_ARM) GoString() string

func (R_ARM) String

func (i R_ARM) String() string

type R_LARCH 1.19

Relocation types for LoongArch.

+
type R_LARCH int
const (
+    R_LARCH_NONE                       R_LARCH = 0
+    R_LARCH_32                         R_LARCH = 1
+    R_LARCH_64                         R_LARCH = 2
+    R_LARCH_RELATIVE                   R_LARCH = 3
+    R_LARCH_COPY                       R_LARCH = 4
+    R_LARCH_JUMP_SLOT                  R_LARCH = 5
+    R_LARCH_TLS_DTPMOD32               R_LARCH = 6
+    R_LARCH_TLS_DTPMOD64               R_LARCH = 7
+    R_LARCH_TLS_DTPREL32               R_LARCH = 8
+    R_LARCH_TLS_DTPREL64               R_LARCH = 9
+    R_LARCH_TLS_TPREL32                R_LARCH = 10
+    R_LARCH_TLS_TPREL64                R_LARCH = 11
+    R_LARCH_IRELATIVE                  R_LARCH = 12
+    R_LARCH_MARK_LA                    R_LARCH = 20
+    R_LARCH_MARK_PCREL                 R_LARCH = 21
+    R_LARCH_SOP_PUSH_PCREL             R_LARCH = 22
+    R_LARCH_SOP_PUSH_ABSOLUTE          R_LARCH = 23
+    R_LARCH_SOP_PUSH_DUP               R_LARCH = 24
+    R_LARCH_SOP_PUSH_GPREL             R_LARCH = 25
+    R_LARCH_SOP_PUSH_TLS_TPREL         R_LARCH = 26
+    R_LARCH_SOP_PUSH_TLS_GOT           R_LARCH = 27
+    R_LARCH_SOP_PUSH_TLS_GD            R_LARCH = 28
+    R_LARCH_SOP_PUSH_PLT_PCREL         R_LARCH = 29
+    R_LARCH_SOP_ASSERT                 R_LARCH = 30
+    R_LARCH_SOP_NOT                    R_LARCH = 31
+    R_LARCH_SOP_SUB                    R_LARCH = 32
+    R_LARCH_SOP_SL                     R_LARCH = 33
+    R_LARCH_SOP_SR                     R_LARCH = 34
+    R_LARCH_SOP_ADD                    R_LARCH = 35
+    R_LARCH_SOP_AND                    R_LARCH = 36
+    R_LARCH_SOP_IF_ELSE                R_LARCH = 37
+    R_LARCH_SOP_POP_32_S_10_5          R_LARCH = 38
+    R_LARCH_SOP_POP_32_U_10_12         R_LARCH = 39
+    R_LARCH_SOP_POP_32_S_10_12         R_LARCH = 40
+    R_LARCH_SOP_POP_32_S_10_16         R_LARCH = 41
+    R_LARCH_SOP_POP_32_S_10_16_S2      R_LARCH = 42
+    R_LARCH_SOP_POP_32_S_5_20          R_LARCH = 43
+    R_LARCH_SOP_POP_32_S_0_5_10_16_S2  R_LARCH = 44
+    R_LARCH_SOP_POP_32_S_0_10_10_16_S2 R_LARCH = 45
+    R_LARCH_SOP_POP_32_U               R_LARCH = 46
+    R_LARCH_ADD8                       R_LARCH = 47
+    R_LARCH_ADD16                      R_LARCH = 48
+    R_LARCH_ADD24                      R_LARCH = 49
+    R_LARCH_ADD32                      R_LARCH = 50
+    R_LARCH_ADD64                      R_LARCH = 51
+    R_LARCH_SUB8                       R_LARCH = 52
+    R_LARCH_SUB16                      R_LARCH = 53
+    R_LARCH_SUB24                      R_LARCH = 54
+    R_LARCH_SUB32                      R_LARCH = 55
+    R_LARCH_SUB64                      R_LARCH = 56
+    R_LARCH_GNU_VTINHERIT              R_LARCH = 57
+    R_LARCH_GNU_VTENTRY                R_LARCH = 58
+    R_LARCH_B16                        R_LARCH = 64
+    R_LARCH_B21                        R_LARCH = 65
+    R_LARCH_B26                        R_LARCH = 66
+    R_LARCH_ABS_HI20                   R_LARCH = 67
+    R_LARCH_ABS_LO12                   R_LARCH = 68
+    R_LARCH_ABS64_LO20                 R_LARCH = 69
+    R_LARCH_ABS64_HI12                 R_LARCH = 70
+    R_LARCH_PCALA_HI20                 R_LARCH = 71
+    R_LARCH_PCALA_LO12                 R_LARCH = 72
+    R_LARCH_PCALA64_LO20               R_LARCH = 73
+    R_LARCH_PCALA64_HI12               R_LARCH = 74
+    R_LARCH_GOT_PC_HI20                R_LARCH = 75
+    R_LARCH_GOT_PC_LO12                R_LARCH = 76
+    R_LARCH_GOT64_PC_LO20              R_LARCH = 77
+    R_LARCH_GOT64_PC_HI12              R_LARCH = 78
+    R_LARCH_GOT_HI20                   R_LARCH = 79
+    R_LARCH_GOT_LO12                   R_LARCH = 80
+    R_LARCH_GOT64_LO20                 R_LARCH = 81
+    R_LARCH_GOT64_HI12                 R_LARCH = 82
+    R_LARCH_TLS_LE_HI20                R_LARCH = 83
+    R_LARCH_TLS_LE_LO12                R_LARCH = 84
+    R_LARCH_TLS_LE64_LO20              R_LARCH = 85
+    R_LARCH_TLS_LE64_HI12              R_LARCH = 86
+    R_LARCH_TLS_IE_PC_HI20             R_LARCH = 87
+    R_LARCH_TLS_IE_PC_LO12             R_LARCH = 88
+    R_LARCH_TLS_IE64_PC_LO20           R_LARCH = 89
+    R_LARCH_TLS_IE64_PC_HI12           R_LARCH = 90
+    R_LARCH_TLS_IE_HI20                R_LARCH = 91
+    R_LARCH_TLS_IE_LO12                R_LARCH = 92
+    R_LARCH_TLS_IE64_LO20              R_LARCH = 93
+    R_LARCH_TLS_IE64_HI12              R_LARCH = 94
+    R_LARCH_TLS_LD_PC_HI20             R_LARCH = 95
+    R_LARCH_TLS_LD_HI20                R_LARCH = 96
+    R_LARCH_TLS_GD_PC_HI20             R_LARCH = 97
+    R_LARCH_TLS_GD_HI20                R_LARCH = 98
+    R_LARCH_32_PCREL                   R_LARCH = 99
+    R_LARCH_RELAX                      R_LARCH = 100
+    R_LARCH_DELETE                     R_LARCH = 101
+    R_LARCH_ALIGN                      R_LARCH = 102
+    R_LARCH_PCREL20_S2                 R_LARCH = 103
+    R_LARCH_CFA                        R_LARCH = 104
+    R_LARCH_ADD6                       R_LARCH = 105
+    R_LARCH_SUB6                       R_LARCH = 106
+    R_LARCH_ADD_ULEB128                R_LARCH = 107
+    R_LARCH_SUB_ULEB128                R_LARCH = 108
+    R_LARCH_64_PCREL                   R_LARCH = 109
+)

func (R_LARCH) GoString 1.19

func (i R_LARCH) GoString() string

func (R_LARCH) String 1.19

func (i R_LARCH) String() string

type R_MIPS 1.6

Relocation types for MIPS.

+
type R_MIPS int
const (
+    R_MIPS_NONE          R_MIPS = 0
+    R_MIPS_16            R_MIPS = 1
+    R_MIPS_32            R_MIPS = 2
+    R_MIPS_REL32         R_MIPS = 3
+    R_MIPS_26            R_MIPS = 4
+    R_MIPS_HI16          R_MIPS = 5  /* high 16 bits of symbol value */
+    R_MIPS_LO16          R_MIPS = 6  /* low 16 bits of symbol value */
+    R_MIPS_GPREL16       R_MIPS = 7  /* GP-relative reference  */
+    R_MIPS_LITERAL       R_MIPS = 8  /* Reference to literal section  */
+    R_MIPS_GOT16         R_MIPS = 9  /* Reference to global offset table */
+    R_MIPS_PC16          R_MIPS = 10 /* 16 bit PC relative reference */
+    R_MIPS_CALL16        R_MIPS = 11 /* 16 bit call through glbl offset tbl */
+    R_MIPS_GPREL32       R_MIPS = 12
+    R_MIPS_SHIFT5        R_MIPS = 16
+    R_MIPS_SHIFT6        R_MIPS = 17
+    R_MIPS_64            R_MIPS = 18
+    R_MIPS_GOT_DISP      R_MIPS = 19
+    R_MIPS_GOT_PAGE      R_MIPS = 20
+    R_MIPS_GOT_OFST      R_MIPS = 21
+    R_MIPS_GOT_HI16      R_MIPS = 22
+    R_MIPS_GOT_LO16      R_MIPS = 23
+    R_MIPS_SUB           R_MIPS = 24
+    R_MIPS_INSERT_A      R_MIPS = 25
+    R_MIPS_INSERT_B      R_MIPS = 26
+    R_MIPS_DELETE        R_MIPS = 27
+    R_MIPS_HIGHER        R_MIPS = 28
+    R_MIPS_HIGHEST       R_MIPS = 29
+    R_MIPS_CALL_HI16     R_MIPS = 30
+    R_MIPS_CALL_LO16     R_MIPS = 31
+    R_MIPS_SCN_DISP      R_MIPS = 32
+    R_MIPS_REL16         R_MIPS = 33
+    R_MIPS_ADD_IMMEDIATE R_MIPS = 34
+    R_MIPS_PJUMP         R_MIPS = 35
+    R_MIPS_RELGOT        R_MIPS = 36
+    R_MIPS_JALR          R_MIPS = 37
+
+    R_MIPS_TLS_DTPMOD32    R_MIPS = 38 /* Module number 32 bit */
+    R_MIPS_TLS_DTPREL32    R_MIPS = 39 /* Module-relative offset 32 bit */
+    R_MIPS_TLS_DTPMOD64    R_MIPS = 40 /* Module number 64 bit */
+    R_MIPS_TLS_DTPREL64    R_MIPS = 41 /* Module-relative offset 64 bit */
+    R_MIPS_TLS_GD          R_MIPS = 42 /* 16 bit GOT offset for GD */
+    R_MIPS_TLS_LDM         R_MIPS = 43 /* 16 bit GOT offset for LDM */
+    R_MIPS_TLS_DTPREL_HI16 R_MIPS = 44 /* Module-relative offset, high 16 bits */
+    R_MIPS_TLS_DTPREL_LO16 R_MIPS = 45 /* Module-relative offset, low 16 bits */
+    R_MIPS_TLS_GOTTPREL    R_MIPS = 46 /* 16 bit GOT offset for IE */
+    R_MIPS_TLS_TPREL32     R_MIPS = 47 /* TP-relative offset, 32 bit */
+    R_MIPS_TLS_TPREL64     R_MIPS = 48 /* TP-relative offset, 64 bit */
+    R_MIPS_TLS_TPREL_HI16  R_MIPS = 49 /* TP-relative offset, high 16 bits */
+    R_MIPS_TLS_TPREL_LO16  R_MIPS = 50 /* TP-relative offset, low 16 bits */
+
+    R_MIPS_PC32 R_MIPS = 248 /* 32 bit PC relative reference */
+)

func (R_MIPS) GoString 1.6

func (i R_MIPS) GoString() string

func (R_MIPS) String 1.6

func (i R_MIPS) String() string

type R_PPC

Relocation types for PowerPC.

+

Values that are shared by both R_PPC and R_PPC64 are prefixed with R_POWERPC_ in the ELF standard. For the R_PPC type, the relevant shared relocations have been renamed with the prefix R_PPC_. The original name follows the value in a comment.

+
type R_PPC int
const (
+    R_PPC_NONE            R_PPC = 0  // R_POWERPC_NONE
+    R_PPC_ADDR32          R_PPC = 1  // R_POWERPC_ADDR32
+    R_PPC_ADDR24          R_PPC = 2  // R_POWERPC_ADDR24
+    R_PPC_ADDR16          R_PPC = 3  // R_POWERPC_ADDR16
+    R_PPC_ADDR16_LO       R_PPC = 4  // R_POWERPC_ADDR16_LO
+    R_PPC_ADDR16_HI       R_PPC = 5  // R_POWERPC_ADDR16_HI
+    R_PPC_ADDR16_HA       R_PPC = 6  // R_POWERPC_ADDR16_HA
+    R_PPC_ADDR14          R_PPC = 7  // R_POWERPC_ADDR14
+    R_PPC_ADDR14_BRTAKEN  R_PPC = 8  // R_POWERPC_ADDR14_BRTAKEN
+    R_PPC_ADDR14_BRNTAKEN R_PPC = 9  // R_POWERPC_ADDR14_BRNTAKEN
+    R_PPC_REL24           R_PPC = 10 // R_POWERPC_REL24
+    R_PPC_REL14           R_PPC = 11 // R_POWERPC_REL14
+    R_PPC_REL14_BRTAKEN   R_PPC = 12 // R_POWERPC_REL14_BRTAKEN
+    R_PPC_REL14_BRNTAKEN  R_PPC = 13 // R_POWERPC_REL14_BRNTAKEN
+    R_PPC_GOT16           R_PPC = 14 // R_POWERPC_GOT16
+    R_PPC_GOT16_LO        R_PPC = 15 // R_POWERPC_GOT16_LO
+    R_PPC_GOT16_HI        R_PPC = 16 // R_POWERPC_GOT16_HI
+    R_PPC_GOT16_HA        R_PPC = 17 // R_POWERPC_GOT16_HA
+    R_PPC_PLTREL24        R_PPC = 18
+    R_PPC_COPY            R_PPC = 19 // R_POWERPC_COPY
+    R_PPC_GLOB_DAT        R_PPC = 20 // R_POWERPC_GLOB_DAT
+    R_PPC_JMP_SLOT        R_PPC = 21 // R_POWERPC_JMP_SLOT
+    R_PPC_RELATIVE        R_PPC = 22 // R_POWERPC_RELATIVE
+    R_PPC_LOCAL24PC       R_PPC = 23
+    R_PPC_UADDR32         R_PPC = 24 // R_POWERPC_UADDR32
+    R_PPC_UADDR16         R_PPC = 25 // R_POWERPC_UADDR16
+    R_PPC_REL32           R_PPC = 26 // R_POWERPC_REL32
+    R_PPC_PLT32           R_PPC = 27 // R_POWERPC_PLT32
+    R_PPC_PLTREL32        R_PPC = 28 // R_POWERPC_PLTREL32
+    R_PPC_PLT16_LO        R_PPC = 29 // R_POWERPC_PLT16_LO
+    R_PPC_PLT16_HI        R_PPC = 30 // R_POWERPC_PLT16_HI
+    R_PPC_PLT16_HA        R_PPC = 31 // R_POWERPC_PLT16_HA
+    R_PPC_SDAREL16        R_PPC = 32
+    R_PPC_SECTOFF         R_PPC = 33 // R_POWERPC_SECTOFF
+    R_PPC_SECTOFF_LO      R_PPC = 34 // R_POWERPC_SECTOFF_LO
+    R_PPC_SECTOFF_HI      R_PPC = 35 // R_POWERPC_SECTOFF_HI
+    R_PPC_SECTOFF_HA      R_PPC = 36 // R_POWERPC_SECTOFF_HA
+    R_PPC_TLS             R_PPC = 67 // R_POWERPC_TLS
+    R_PPC_DTPMOD32        R_PPC = 68 // R_POWERPC_DTPMOD32
+    R_PPC_TPREL16         R_PPC = 69 // R_POWERPC_TPREL16
+    R_PPC_TPREL16_LO      R_PPC = 70 // R_POWERPC_TPREL16_LO
+    R_PPC_TPREL16_HI      R_PPC = 71 // R_POWERPC_TPREL16_HI
+    R_PPC_TPREL16_HA      R_PPC = 72 // R_POWERPC_TPREL16_HA
+    R_PPC_TPREL32         R_PPC = 73 // R_POWERPC_TPREL32
+    R_PPC_DTPREL16        R_PPC = 74 // R_POWERPC_DTPREL16
+    R_PPC_DTPREL16_LO     R_PPC = 75 // R_POWERPC_DTPREL16_LO
+    R_PPC_DTPREL16_HI     R_PPC = 76 // R_POWERPC_DTPREL16_HI
+    R_PPC_DTPREL16_HA     R_PPC = 77 // R_POWERPC_DTPREL16_HA
+    R_PPC_DTPREL32        R_PPC = 78 // R_POWERPC_DTPREL32
+    R_PPC_GOT_TLSGD16     R_PPC = 79 // R_POWERPC_GOT_TLSGD16
+    R_PPC_GOT_TLSGD16_LO  R_PPC = 80 // R_POWERPC_GOT_TLSGD16_LO
+    R_PPC_GOT_TLSGD16_HI  R_PPC = 81 // R_POWERPC_GOT_TLSGD16_HI
+    R_PPC_GOT_TLSGD16_HA  R_PPC = 82 // R_POWERPC_GOT_TLSGD16_HA
+    R_PPC_GOT_TLSLD16     R_PPC = 83 // R_POWERPC_GOT_TLSLD16
+    R_PPC_GOT_TLSLD16_LO  R_PPC = 84 // R_POWERPC_GOT_TLSLD16_LO
+    R_PPC_GOT_TLSLD16_HI  R_PPC = 85 // R_POWERPC_GOT_TLSLD16_HI
+    R_PPC_GOT_TLSLD16_HA  R_PPC = 86 // R_POWERPC_GOT_TLSLD16_HA
+    R_PPC_GOT_TPREL16     R_PPC = 87 // R_POWERPC_GOT_TPREL16
+    R_PPC_GOT_TPREL16_LO  R_PPC = 88 // R_POWERPC_GOT_TPREL16_LO
+    R_PPC_GOT_TPREL16_HI  R_PPC = 89 // R_POWERPC_GOT_TPREL16_HI
+    R_PPC_GOT_TPREL16_HA  R_PPC = 90 // R_POWERPC_GOT_TPREL16_HA
+    R_PPC_EMB_NADDR32     R_PPC = 101
+    R_PPC_EMB_NADDR16     R_PPC = 102
+    R_PPC_EMB_NADDR16_LO  R_PPC = 103
+    R_PPC_EMB_NADDR16_HI  R_PPC = 104
+    R_PPC_EMB_NADDR16_HA  R_PPC = 105
+    R_PPC_EMB_SDAI16      R_PPC = 106
+    R_PPC_EMB_SDA2I16     R_PPC = 107
+    R_PPC_EMB_SDA2REL     R_PPC = 108
+    R_PPC_EMB_SDA21       R_PPC = 109
+    R_PPC_EMB_MRKREF      R_PPC = 110
+    R_PPC_EMB_RELSEC16    R_PPC = 111
+    R_PPC_EMB_RELST_LO    R_PPC = 112
+    R_PPC_EMB_RELST_HI    R_PPC = 113
+    R_PPC_EMB_RELST_HA    R_PPC = 114
+    R_PPC_EMB_BIT_FLD     R_PPC = 115
+    R_PPC_EMB_RELSDA      R_PPC = 116
+)

func (R_PPC) GoString

func (i R_PPC) GoString() string

func (R_PPC) String

func (i R_PPC) String() string

type R_PPC64 1.5

Relocation types for 64-bit PowerPC or Power Architecture processors.

+

Values that are shared by both R_PPC and R_PPC64 are prefixed with R_POWERPC_ in the ELF standard. For the R_PPC64 type, the relevant shared relocations have been renamed with the prefix R_PPC64_. The original name follows the value in a comment.

+
type R_PPC64 int
const (
+    R_PPC64_NONE               R_PPC64 = 0  // R_POWERPC_NONE
+    R_PPC64_ADDR32             R_PPC64 = 1  // R_POWERPC_ADDR32
+    R_PPC64_ADDR24             R_PPC64 = 2  // R_POWERPC_ADDR24
+    R_PPC64_ADDR16             R_PPC64 = 3  // R_POWERPC_ADDR16
+    R_PPC64_ADDR16_LO          R_PPC64 = 4  // R_POWERPC_ADDR16_LO
+    R_PPC64_ADDR16_HI          R_PPC64 = 5  // R_POWERPC_ADDR16_HI
+    R_PPC64_ADDR16_HA          R_PPC64 = 6  // R_POWERPC_ADDR16_HA
+    R_PPC64_ADDR14             R_PPC64 = 7  // R_POWERPC_ADDR14
+    R_PPC64_ADDR14_BRTAKEN     R_PPC64 = 8  // R_POWERPC_ADDR14_BRTAKEN
+    R_PPC64_ADDR14_BRNTAKEN    R_PPC64 = 9  // R_POWERPC_ADDR14_BRNTAKEN
+    R_PPC64_REL24              R_PPC64 = 10 // R_POWERPC_REL24
+    R_PPC64_REL14              R_PPC64 = 11 // R_POWERPC_REL14
+    R_PPC64_REL14_BRTAKEN      R_PPC64 = 12 // R_POWERPC_REL14_BRTAKEN
+    R_PPC64_REL14_BRNTAKEN     R_PPC64 = 13 // R_POWERPC_REL14_BRNTAKEN
+    R_PPC64_GOT16              R_PPC64 = 14 // R_POWERPC_GOT16
+    R_PPC64_GOT16_LO           R_PPC64 = 15 // R_POWERPC_GOT16_LO
+    R_PPC64_GOT16_HI           R_PPC64 = 16 // R_POWERPC_GOT16_HI
+    R_PPC64_GOT16_HA           R_PPC64 = 17 // R_POWERPC_GOT16_HA
+    R_PPC64_COPY               R_PPC64 = 19 // R_POWERPC_COPY
+    R_PPC64_GLOB_DAT           R_PPC64 = 20 // R_POWERPC_GLOB_DAT
+    R_PPC64_JMP_SLOT           R_PPC64 = 21 // R_POWERPC_JMP_SLOT
+    R_PPC64_RELATIVE           R_PPC64 = 22 // R_POWERPC_RELATIVE
+    R_PPC64_UADDR32            R_PPC64 = 24 // R_POWERPC_UADDR32
+    R_PPC64_UADDR16            R_PPC64 = 25 // R_POWERPC_UADDR16
+    R_PPC64_REL32              R_PPC64 = 26 // R_POWERPC_REL32
+    R_PPC64_PLT32              R_PPC64 = 27 // R_POWERPC_PLT32
+    R_PPC64_PLTREL32           R_PPC64 = 28 // R_POWERPC_PLTREL32
+    R_PPC64_PLT16_LO           R_PPC64 = 29 // R_POWERPC_PLT16_LO
+    R_PPC64_PLT16_HI           R_PPC64 = 30 // R_POWERPC_PLT16_HI
+    R_PPC64_PLT16_HA           R_PPC64 = 31 // R_POWERPC_PLT16_HA
+    R_PPC64_SECTOFF            R_PPC64 = 33 // R_POWERPC_SECTOFF
+    R_PPC64_SECTOFF_LO         R_PPC64 = 34 // R_POWERPC_SECTOFF_LO
+    R_PPC64_SECTOFF_HI         R_PPC64 = 35 // R_POWERPC_SECTOFF_HI
+    R_PPC64_SECTOFF_HA         R_PPC64 = 36 // R_POWERPC_SECTOFF_HA
+    R_PPC64_REL30              R_PPC64 = 37 // R_POWERPC_ADDR30
+    R_PPC64_ADDR64             R_PPC64 = 38
+    R_PPC64_ADDR16_HIGHER      R_PPC64 = 39
+    R_PPC64_ADDR16_HIGHERA     R_PPC64 = 40
+    R_PPC64_ADDR16_HIGHEST     R_PPC64 = 41
+    R_PPC64_ADDR16_HIGHESTA    R_PPC64 = 42
+    R_PPC64_UADDR64            R_PPC64 = 43
+    R_PPC64_REL64              R_PPC64 = 44
+    R_PPC64_PLT64              R_PPC64 = 45
+    R_PPC64_PLTREL64           R_PPC64 = 46
+    R_PPC64_TOC16              R_PPC64 = 47
+    R_PPC64_TOC16_LO           R_PPC64 = 48
+    R_PPC64_TOC16_HI           R_PPC64 = 49
+    R_PPC64_TOC16_HA           R_PPC64 = 50
+    R_PPC64_TOC                R_PPC64 = 51
+    R_PPC64_PLTGOT16           R_PPC64 = 52
+    R_PPC64_PLTGOT16_LO        R_PPC64 = 53
+    R_PPC64_PLTGOT16_HI        R_PPC64 = 54
+    R_PPC64_PLTGOT16_HA        R_PPC64 = 55
+    R_PPC64_ADDR16_DS          R_PPC64 = 56
+    R_PPC64_ADDR16_LO_DS       R_PPC64 = 57
+    R_PPC64_GOT16_DS           R_PPC64 = 58
+    R_PPC64_GOT16_LO_DS        R_PPC64 = 59
+    R_PPC64_PLT16_LO_DS        R_PPC64 = 60
+    R_PPC64_SECTOFF_DS         R_PPC64 = 61
+    R_PPC64_SECTOFF_LO_DS      R_PPC64 = 62
+    R_PPC64_TOC16_DS           R_PPC64 = 63
+    R_PPC64_TOC16_LO_DS        R_PPC64 = 64
+    R_PPC64_PLTGOT16_DS        R_PPC64 = 65
+    R_PPC64_PLTGOT_LO_DS       R_PPC64 = 66
+    R_PPC64_TLS                R_PPC64 = 67 // R_POWERPC_TLS
+    R_PPC64_DTPMOD64           R_PPC64 = 68 // R_POWERPC_DTPMOD64
+    R_PPC64_TPREL16            R_PPC64 = 69 // R_POWERPC_TPREL16
+    R_PPC64_TPREL16_LO         R_PPC64 = 70 // R_POWERPC_TPREL16_LO
+    R_PPC64_TPREL16_HI         R_PPC64 = 71 // R_POWERPC_TPREL16_HI
+    R_PPC64_TPREL16_HA         R_PPC64 = 72 // R_POWERPC_TPREL16_HA
+    R_PPC64_TPREL64            R_PPC64 = 73 // R_POWERPC_TPREL64
+    R_PPC64_DTPREL16           R_PPC64 = 74 // R_POWERPC_DTPREL16
+    R_PPC64_DTPREL16_LO        R_PPC64 = 75 // R_POWERPC_DTPREL16_LO
+    R_PPC64_DTPREL16_HI        R_PPC64 = 76 // R_POWERPC_DTPREL16_HI
+    R_PPC64_DTPREL16_HA        R_PPC64 = 77 // R_POWERPC_DTPREL16_HA
+    R_PPC64_DTPREL64           R_PPC64 = 78 // R_POWERPC_DTPREL64
+    R_PPC64_GOT_TLSGD16        R_PPC64 = 79 // R_POWERPC_GOT_TLSGD16
+    R_PPC64_GOT_TLSGD16_LO     R_PPC64 = 80 // R_POWERPC_GOT_TLSGD16_LO
+    R_PPC64_GOT_TLSGD16_HI     R_PPC64 = 81 // R_POWERPC_GOT_TLSGD16_HI
+    R_PPC64_GOT_TLSGD16_HA     R_PPC64 = 82 // R_POWERPC_GOT_TLSGD16_HA
+    R_PPC64_GOT_TLSLD16        R_PPC64 = 83 // R_POWERPC_GOT_TLSLD16
+    R_PPC64_GOT_TLSLD16_LO     R_PPC64 = 84 // R_POWERPC_GOT_TLSLD16_LO
+    R_PPC64_GOT_TLSLD16_HI     R_PPC64 = 85 // R_POWERPC_GOT_TLSLD16_HI
+    R_PPC64_GOT_TLSLD16_HA     R_PPC64 = 86 // R_POWERPC_GOT_TLSLD16_HA
+    R_PPC64_GOT_TPREL16_DS     R_PPC64 = 87 // R_POWERPC_GOT_TPREL16_DS
+    R_PPC64_GOT_TPREL16_LO_DS  R_PPC64 = 88 // R_POWERPC_GOT_TPREL16_LO_DS
+    R_PPC64_GOT_TPREL16_HI     R_PPC64 = 89 // R_POWERPC_GOT_TPREL16_HI
+    R_PPC64_GOT_TPREL16_HA     R_PPC64 = 90 // R_POWERPC_GOT_TPREL16_HA
+    R_PPC64_GOT_DTPREL16_DS    R_PPC64 = 91 // R_POWERPC_GOT_DTPREL16_DS
+    R_PPC64_GOT_DTPREL16_LO_DS R_PPC64 = 92 // R_POWERPC_GOT_DTPREL16_LO_DS
+    R_PPC64_GOT_DTPREL16_HI    R_PPC64 = 93 // R_POWERPC_GOT_DTPREL16_HI
+    R_PPC64_GOT_DTPREL16_HA    R_PPC64 = 94 // R_POWERPC_GOT_DTPREL16_HA
+    R_PPC64_TPREL16_DS         R_PPC64 = 95
+    R_PPC64_TPREL16_LO_DS      R_PPC64 = 96
+    R_PPC64_TPREL16_HIGHER     R_PPC64 = 97
+    R_PPC64_TPREL16_HIGHERA    R_PPC64 = 98
+    R_PPC64_TPREL16_HIGHEST    R_PPC64 = 99
+    R_PPC64_TPREL16_HIGHESTA   R_PPC64 = 100
+    R_PPC64_DTPREL16_DS        R_PPC64 = 101
+    R_PPC64_DTPREL16_LO_DS     R_PPC64 = 102
+    R_PPC64_DTPREL16_HIGHER    R_PPC64 = 103
+    R_PPC64_DTPREL16_HIGHERA   R_PPC64 = 104
+    R_PPC64_DTPREL16_HIGHEST   R_PPC64 = 105
+    R_PPC64_DTPREL16_HIGHESTA  R_PPC64 = 106
+    R_PPC64_TLSGD              R_PPC64 = 107
+    R_PPC64_TLSLD              R_PPC64 = 108
+    R_PPC64_TOCSAVE            R_PPC64 = 109
+    R_PPC64_ADDR16_HIGH        R_PPC64 = 110
+    R_PPC64_ADDR16_HIGHA       R_PPC64 = 111
+    R_PPC64_TPREL16_HIGH       R_PPC64 = 112
+    R_PPC64_TPREL16_HIGHA      R_PPC64 = 113
+    R_PPC64_DTPREL16_HIGH      R_PPC64 = 114
+    R_PPC64_DTPREL16_HIGHA     R_PPC64 = 115
+    R_PPC64_REL24_NOTOC        R_PPC64 = 116
+    R_PPC64_ADDR64_LOCAL       R_PPC64 = 117
+    R_PPC64_ENTRY              R_PPC64 = 118
+    R_PPC64_PLTSEQ             R_PPC64 = 119
+    R_PPC64_PLTCALL            R_PPC64 = 120
+    R_PPC64_PLTSEQ_NOTOC       R_PPC64 = 121
+    R_PPC64_PLTCALL_NOTOC      R_PPC64 = 122
+    R_PPC64_PCREL_OPT          R_PPC64 = 123
+    R_PPC64_REL24_P9NOTOC      R_PPC64 = 124
+    R_PPC64_D34                R_PPC64 = 128
+    R_PPC64_D34_LO             R_PPC64 = 129
+    R_PPC64_D34_HI30           R_PPC64 = 130
+    R_PPC64_D34_HA30           R_PPC64 = 131
+    R_PPC64_PCREL34            R_PPC64 = 132
+    R_PPC64_GOT_PCREL34        R_PPC64 = 133
+    R_PPC64_PLT_PCREL34        R_PPC64 = 134
+    R_PPC64_PLT_PCREL34_NOTOC  R_PPC64 = 135
+    R_PPC64_ADDR16_HIGHER34    R_PPC64 = 136
+    R_PPC64_ADDR16_HIGHERA34   R_PPC64 = 137
+    R_PPC64_ADDR16_HIGHEST34   R_PPC64 = 138
+    R_PPC64_ADDR16_HIGHESTA34  R_PPC64 = 139
+    R_PPC64_REL16_HIGHER34     R_PPC64 = 140
+    R_PPC64_REL16_HIGHERA34    R_PPC64 = 141
+    R_PPC64_REL16_HIGHEST34    R_PPC64 = 142
+    R_PPC64_REL16_HIGHESTA34   R_PPC64 = 143
+    R_PPC64_D28                R_PPC64 = 144
+    R_PPC64_PCREL28            R_PPC64 = 145
+    R_PPC64_TPREL34            R_PPC64 = 146
+    R_PPC64_DTPREL34           R_PPC64 = 147
+    R_PPC64_GOT_TLSGD_PCREL34  R_PPC64 = 148
+    R_PPC64_GOT_TLSLD_PCREL34  R_PPC64 = 149
+    R_PPC64_GOT_TPREL_PCREL34  R_PPC64 = 150
+    R_PPC64_GOT_DTPREL_PCREL34 R_PPC64 = 151
+    R_PPC64_REL16_HIGH         R_PPC64 = 240
+    R_PPC64_REL16_HIGHA        R_PPC64 = 241
+    R_PPC64_REL16_HIGHER       R_PPC64 = 242
+    R_PPC64_REL16_HIGHERA      R_PPC64 = 243
+    R_PPC64_REL16_HIGHEST      R_PPC64 = 244
+    R_PPC64_REL16_HIGHESTA     R_PPC64 = 245
+    R_PPC64_REL16DX_HA         R_PPC64 = 246 // R_POWERPC_REL16DX_HA
+    R_PPC64_JMP_IREL           R_PPC64 = 247
+    R_PPC64_IRELATIVE          R_PPC64 = 248 // R_POWERPC_IRELATIVE
+    R_PPC64_REL16              R_PPC64 = 249 // R_POWERPC_REL16
+    R_PPC64_REL16_LO           R_PPC64 = 250 // R_POWERPC_REL16_LO
+    R_PPC64_REL16_HI           R_PPC64 = 251 // R_POWERPC_REL16_HI
+    R_PPC64_REL16_HA           R_PPC64 = 252 // R_POWERPC_REL16_HA
+    R_PPC64_GNU_VTINHERIT      R_PPC64 = 253
+    R_PPC64_GNU_VTENTRY        R_PPC64 = 254
+)

func (R_PPC64) GoString 1.5

func (i R_PPC64) GoString() string

func (R_PPC64) String 1.5

func (i R_PPC64) String() string

type R_RISCV 1.11

Relocation types for RISC-V processors.

+
type R_RISCV int
const (
+    R_RISCV_NONE          R_RISCV = 0  /* No relocation. */
+    R_RISCV_32            R_RISCV = 1  /* Add 32 bit zero extended symbol value */
+    R_RISCV_64            R_RISCV = 2  /* Add 64 bit symbol value. */
+    R_RISCV_RELATIVE      R_RISCV = 3  /* Add load address of shared object. */
+    R_RISCV_COPY          R_RISCV = 4  /* Copy data from shared object. */
+    R_RISCV_JUMP_SLOT     R_RISCV = 5  /* Set GOT entry to code address. */
+    R_RISCV_TLS_DTPMOD32  R_RISCV = 6  /* 32 bit ID of module containing symbol */
+    R_RISCV_TLS_DTPMOD64  R_RISCV = 7  /* ID of module containing symbol */
+    R_RISCV_TLS_DTPREL32  R_RISCV = 8  /* 32 bit relative offset in TLS block */
+    R_RISCV_TLS_DTPREL64  R_RISCV = 9  /* Relative offset in TLS block */
+    R_RISCV_TLS_TPREL32   R_RISCV = 10 /* 32 bit relative offset in static TLS block */
+    R_RISCV_TLS_TPREL64   R_RISCV = 11 /* Relative offset in static TLS block */
+    R_RISCV_BRANCH        R_RISCV = 16 /* PC-relative branch */
+    R_RISCV_JAL           R_RISCV = 17 /* PC-relative jump */
+    R_RISCV_CALL          R_RISCV = 18 /* PC-relative call */
+    R_RISCV_CALL_PLT      R_RISCV = 19 /* PC-relative call (PLT) */
+    R_RISCV_GOT_HI20      R_RISCV = 20 /* PC-relative GOT reference */
+    R_RISCV_TLS_GOT_HI20  R_RISCV = 21 /* PC-relative TLS IE GOT offset */
+    R_RISCV_TLS_GD_HI20   R_RISCV = 22 /* PC-relative TLS GD reference */
+    R_RISCV_PCREL_HI20    R_RISCV = 23 /* PC-relative reference */
+    R_RISCV_PCREL_LO12_I  R_RISCV = 24 /* PC-relative reference */
+    R_RISCV_PCREL_LO12_S  R_RISCV = 25 /* PC-relative reference */
+    R_RISCV_HI20          R_RISCV = 26 /* Absolute address */
+    R_RISCV_LO12_I        R_RISCV = 27 /* Absolute address */
+    R_RISCV_LO12_S        R_RISCV = 28 /* Absolute address */
+    R_RISCV_TPREL_HI20    R_RISCV = 29 /* TLS LE thread offset */
+    R_RISCV_TPREL_LO12_I  R_RISCV = 30 /* TLS LE thread offset */
+    R_RISCV_TPREL_LO12_S  R_RISCV = 31 /* TLS LE thread offset */
+    R_RISCV_TPREL_ADD     R_RISCV = 32 /* TLS LE thread usage */
+    R_RISCV_ADD8          R_RISCV = 33 /* 8-bit label addition */
+    R_RISCV_ADD16         R_RISCV = 34 /* 16-bit label addition */
+    R_RISCV_ADD32         R_RISCV = 35 /* 32-bit label addition */
+    R_RISCV_ADD64         R_RISCV = 36 /* 64-bit label addition */
+    R_RISCV_SUB8          R_RISCV = 37 /* 8-bit label subtraction */
+    R_RISCV_SUB16         R_RISCV = 38 /* 16-bit label subtraction */
+    R_RISCV_SUB32         R_RISCV = 39 /* 32-bit label subtraction */
+    R_RISCV_SUB64         R_RISCV = 40 /* 64-bit label subtraction */
+    R_RISCV_GNU_VTINHERIT R_RISCV = 41 /* GNU C++ vtable hierarchy */
+    R_RISCV_GNU_VTENTRY   R_RISCV = 42 /* GNU C++ vtable member usage */
+    R_RISCV_ALIGN         R_RISCV = 43 /* Alignment statement */
+    R_RISCV_RVC_BRANCH    R_RISCV = 44 /* PC-relative branch offset */
+    R_RISCV_RVC_JUMP      R_RISCV = 45 /* PC-relative jump offset */
+    R_RISCV_RVC_LUI       R_RISCV = 46 /* Absolute address */
+    R_RISCV_GPREL_I       R_RISCV = 47 /* GP-relative reference */
+    R_RISCV_GPREL_S       R_RISCV = 48 /* GP-relative reference */
+    R_RISCV_TPREL_I       R_RISCV = 49 /* TP-relative TLS LE load */
+    R_RISCV_TPREL_S       R_RISCV = 50 /* TP-relative TLS LE store */
+    R_RISCV_RELAX         R_RISCV = 51 /* Instruction pair can be relaxed */
+    R_RISCV_SUB6          R_RISCV = 52 /* Local label subtraction */
+    R_RISCV_SET6          R_RISCV = 53 /* Local label subtraction */
+    R_RISCV_SET8          R_RISCV = 54 /* Local label subtraction */
+    R_RISCV_SET16         R_RISCV = 55 /* Local label subtraction */
+    R_RISCV_SET32         R_RISCV = 56 /* Local label subtraction */
+    R_RISCV_32_PCREL      R_RISCV = 57 /* 32-bit PC relative */
+)

func (R_RISCV) GoString 1.11

func (i R_RISCV) GoString() string

func (R_RISCV) String 1.11

func (i R_RISCV) String() string

type R_SPARC

Relocation types for SPARC.

+
type R_SPARC int
const (
+    R_SPARC_NONE     R_SPARC = 0
+    R_SPARC_8        R_SPARC = 1
+    R_SPARC_16       R_SPARC = 2
+    R_SPARC_32       R_SPARC = 3
+    R_SPARC_DISP8    R_SPARC = 4
+    R_SPARC_DISP16   R_SPARC = 5
+    R_SPARC_DISP32   R_SPARC = 6
+    R_SPARC_WDISP30  R_SPARC = 7
+    R_SPARC_WDISP22  R_SPARC = 8
+    R_SPARC_HI22     R_SPARC = 9
+    R_SPARC_22       R_SPARC = 10
+    R_SPARC_13       R_SPARC = 11
+    R_SPARC_LO10     R_SPARC = 12
+    R_SPARC_GOT10    R_SPARC = 13
+    R_SPARC_GOT13    R_SPARC = 14
+    R_SPARC_GOT22    R_SPARC = 15
+    R_SPARC_PC10     R_SPARC = 16
+    R_SPARC_PC22     R_SPARC = 17
+    R_SPARC_WPLT30   R_SPARC = 18
+    R_SPARC_COPY     R_SPARC = 19
+    R_SPARC_GLOB_DAT R_SPARC = 20
+    R_SPARC_JMP_SLOT R_SPARC = 21
+    R_SPARC_RELATIVE R_SPARC = 22
+    R_SPARC_UA32     R_SPARC = 23
+    R_SPARC_PLT32    R_SPARC = 24
+    R_SPARC_HIPLT22  R_SPARC = 25
+    R_SPARC_LOPLT10  R_SPARC = 26
+    R_SPARC_PCPLT32  R_SPARC = 27
+    R_SPARC_PCPLT22  R_SPARC = 28
+    R_SPARC_PCPLT10  R_SPARC = 29
+    R_SPARC_10       R_SPARC = 30
+    R_SPARC_11       R_SPARC = 31
+    R_SPARC_64       R_SPARC = 32
+    R_SPARC_OLO10    R_SPARC = 33
+    R_SPARC_HH22     R_SPARC = 34
+    R_SPARC_HM10     R_SPARC = 35
+    R_SPARC_LM22     R_SPARC = 36
+    R_SPARC_PC_HH22  R_SPARC = 37
+    R_SPARC_PC_HM10  R_SPARC = 38
+    R_SPARC_PC_LM22  R_SPARC = 39
+    R_SPARC_WDISP16  R_SPARC = 40
+    R_SPARC_WDISP19  R_SPARC = 41
+    R_SPARC_GLOB_JMP R_SPARC = 42
+    R_SPARC_7        R_SPARC = 43
+    R_SPARC_5        R_SPARC = 44
+    R_SPARC_6        R_SPARC = 45
+    R_SPARC_DISP64   R_SPARC = 46
+    R_SPARC_PLT64    R_SPARC = 47
+    R_SPARC_HIX22    R_SPARC = 48
+    R_SPARC_LOX10    R_SPARC = 49
+    R_SPARC_H44      R_SPARC = 50
+    R_SPARC_M44      R_SPARC = 51
+    R_SPARC_L44      R_SPARC = 52
+    R_SPARC_REGISTER R_SPARC = 53
+    R_SPARC_UA64     R_SPARC = 54
+    R_SPARC_UA16     R_SPARC = 55
+)

func (R_SPARC) GoString

func (i R_SPARC) GoString() string

func (R_SPARC) String

func (i R_SPARC) String() string

type R_X86_64

Relocation types for x86-64.

+
type R_X86_64 int
const (
+    R_X86_64_NONE            R_X86_64 = 0  /* No relocation. */
+    R_X86_64_64              R_X86_64 = 1  /* Add 64 bit symbol value. */
+    R_X86_64_PC32            R_X86_64 = 2  /* PC-relative 32 bit signed sym value. */
+    R_X86_64_GOT32           R_X86_64 = 3  /* PC-relative 32 bit GOT offset. */
+    R_X86_64_PLT32           R_X86_64 = 4  /* PC-relative 32 bit PLT offset. */
+    R_X86_64_COPY            R_X86_64 = 5  /* Copy data from shared object. */
+    R_X86_64_GLOB_DAT        R_X86_64 = 6  /* Set GOT entry to data address. */
+    R_X86_64_JMP_SLOT        R_X86_64 = 7  /* Set GOT entry to code address. */
+    R_X86_64_RELATIVE        R_X86_64 = 8  /* Add load address of shared object. */
+    R_X86_64_GOTPCREL        R_X86_64 = 9  /* Add 32 bit signed pcrel offset to GOT. */
+    R_X86_64_32              R_X86_64 = 10 /* Add 32 bit zero extended symbol value */
+    R_X86_64_32S             R_X86_64 = 11 /* Add 32 bit sign extended symbol value */
+    R_X86_64_16              R_X86_64 = 12 /* Add 16 bit zero extended symbol value */
+    R_X86_64_PC16            R_X86_64 = 13 /* Add 16 bit signed extended pc relative symbol value */
+    R_X86_64_8               R_X86_64 = 14 /* Add 8 bit zero extended symbol value */
+    R_X86_64_PC8             R_X86_64 = 15 /* Add 8 bit signed extended pc relative symbol value */
+    R_X86_64_DTPMOD64        R_X86_64 = 16 /* ID of module containing symbol */
+    R_X86_64_DTPOFF64        R_X86_64 = 17 /* Offset in TLS block */
+    R_X86_64_TPOFF64         R_X86_64 = 18 /* Offset in static TLS block */
+    R_X86_64_TLSGD           R_X86_64 = 19 /* PC relative offset to GD GOT entry */
+    R_X86_64_TLSLD           R_X86_64 = 20 /* PC relative offset to LD GOT entry */
+    R_X86_64_DTPOFF32        R_X86_64 = 21 /* Offset in TLS block */
+    R_X86_64_GOTTPOFF        R_X86_64 = 22 /* PC relative offset to IE GOT entry */
+    R_X86_64_TPOFF32         R_X86_64 = 23 /* Offset in static TLS block */
+    R_X86_64_PC64            R_X86_64 = 24 /* PC relative 64-bit sign extended symbol value. */
+    R_X86_64_GOTOFF64        R_X86_64 = 25
+    R_X86_64_GOTPC32         R_X86_64 = 26
+    R_X86_64_GOT64           R_X86_64 = 27
+    R_X86_64_GOTPCREL64      R_X86_64 = 28
+    R_X86_64_GOTPC64         R_X86_64 = 29
+    R_X86_64_GOTPLT64        R_X86_64 = 30
+    R_X86_64_PLTOFF64        R_X86_64 = 31
+    R_X86_64_SIZE32          R_X86_64 = 32
+    R_X86_64_SIZE64          R_X86_64 = 33
+    R_X86_64_GOTPC32_TLSDESC R_X86_64 = 34
+    R_X86_64_TLSDESC_CALL    R_X86_64 = 35
+    R_X86_64_TLSDESC         R_X86_64 = 36
+    R_X86_64_IRELATIVE       R_X86_64 = 37
+    R_X86_64_RELATIVE64      R_X86_64 = 38
+    R_X86_64_PC32_BND        R_X86_64 = 39
+    R_X86_64_PLT32_BND       R_X86_64 = 40
+    R_X86_64_GOTPCRELX       R_X86_64 = 41
+    R_X86_64_REX_GOTPCRELX   R_X86_64 = 42
+)

func (R_X86_64) GoString

func (i R_X86_64) GoString() string

func (R_X86_64) String

func (i R_X86_64) String() string

type Rel32

ELF32 Relocations that don't need an addend field.

+
type Rel32 struct {
+    Off  uint32 /* Location to be relocated. */
+    Info uint32 /* Relocation type and symbol index. */
+}
+

type Rel64

ELF64 relocations that don't need an addend field.

+
type Rel64 struct {
+    Off  uint64 /* Location to be relocated. */
+    Info uint64 /* Relocation type and symbol index. */
+}
+

type Rela32

ELF32 Relocations that need an addend field.

+
type Rela32 struct {
+    Off    uint32 /* Location to be relocated. */
+    Info   uint32 /* Relocation type and symbol index. */
+    Addend int32  /* Addend. */
+}
+

type Rela64

ELF64 relocations that need an addend field.

+
type Rela64 struct {
+    Off    uint64 /* Location to be relocated. */
+    Info   uint64 /* Relocation type and symbol index. */
+    Addend int64  /* Addend. */
+}
+

type Section

A Section represents a single section in an ELF file.

+
type Section struct {
+    SectionHeader
+
+    // Embed ReaderAt for ReadAt method.
+    // Do not embed SectionReader directly
+    // to avoid having Read and Seek.
+    // If a client wants Read and Seek it must use
+    // Open() to avoid fighting over the seek offset
+    // with other clients.
+    //
+    // ReaderAt may be nil if the section is not easily available
+    // in a random-access form. For example, a compressed section
+    // may have a nil ReaderAt.
+    io.ReaderAt
+    // contains filtered or unexported fields
+}
+

func (*Section) Data

func (s *Section) Data() ([]byte, error)

Data reads and returns the contents of the ELF section. Even if the section is stored compressed in the ELF file, Data returns uncompressed data.

+

For an SHT_NOBITS section, Data always returns a non-nil error.

+

func (*Section) Open

func (s *Section) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the ELF section. Even if the section is stored compressed in the ELF file, the ReadSeeker reads uncompressed data.

+

For an SHT_NOBITS section, all calls to the opened reader will return a non-nil error.

+

type Section32

ELF32 Section header.

+
type Section32 struct {
+    Name      uint32 /* Section name (index into the section header string table). */
+    Type      uint32 /* Section type. */
+    Flags     uint32 /* Section flags. */
+    Addr      uint32 /* Address in memory image. */
+    Off       uint32 /* Offset in file. */
+    Size      uint32 /* Size in bytes. */
+    Link      uint32 /* Index of a related section. */
+    Info      uint32 /* Depends on section type. */
+    Addralign uint32 /* Alignment in bytes. */
+    Entsize   uint32 /* Size of each entry in section. */
+}
+

type Section64

ELF64 Section header.

+
type Section64 struct {
+    Name      uint32 /* Section name (index into the section header string table). */
+    Type      uint32 /* Section type. */
+    Flags     uint64 /* Section flags. */
+    Addr      uint64 /* Address in memory image. */
+    Off       uint64 /* Offset in file. */
+    Size      uint64 /* Size in bytes. */
+    Link      uint32 /* Index of a related section. */
+    Info      uint32 /* Depends on section type. */
+    Addralign uint64 /* Alignment in bytes. */
+    Entsize   uint64 /* Size of each entry in section. */
+}
+

type SectionFlag

Section flags.

+
type SectionFlag uint32
const (
+    SHF_WRITE            SectionFlag = 0x1        /* Section contains writable data. */
+    SHF_ALLOC            SectionFlag = 0x2        /* Section occupies memory. */
+    SHF_EXECINSTR        SectionFlag = 0x4        /* Section contains instructions. */
+    SHF_MERGE            SectionFlag = 0x10       /* Section may be merged. */
+    SHF_STRINGS          SectionFlag = 0x20       /* Section contains strings. */
+    SHF_INFO_LINK        SectionFlag = 0x40       /* sh_info holds section index. */
+    SHF_LINK_ORDER       SectionFlag = 0x80       /* Special ordering requirements. */
+    SHF_OS_NONCONFORMING SectionFlag = 0x100      /* OS-specific processing required. */
+    SHF_GROUP            SectionFlag = 0x200      /* Member of section group. */
+    SHF_TLS              SectionFlag = 0x400      /* Section contains TLS data. */
+    SHF_COMPRESSED       SectionFlag = 0x800      /* Section is compressed. */
+    SHF_MASKOS           SectionFlag = 0x0ff00000 /* OS-specific semantics. */
+    SHF_MASKPROC         SectionFlag = 0xf0000000 /* Processor-specific semantics. */
+)

func (SectionFlag) GoString

func (i SectionFlag) GoString() string

func (SectionFlag) String

func (i SectionFlag) String() string

type SectionHeader

A SectionHeader represents a single ELF section header.

+
type SectionHeader struct {
+    Name      string
+    Type      SectionType
+    Flags     SectionFlag
+    Addr      uint64
+    Offset    uint64
+    Size      uint64
+    Link      uint32
+    Info      uint32
+    Addralign uint64
+    Entsize   uint64
+
+    // FileSize is the size of this section in the file in bytes.
+    // If a section is compressed, FileSize is the size of the
+    // compressed data, while Size (above) is the size of the
+    // uncompressed data.
+    FileSize uint64 // Go 1.6
+}
+

type SectionIndex

Special section indices.

+
type SectionIndex int
const (
+    SHN_UNDEF     SectionIndex = 0      /* Undefined, missing, irrelevant. */
+    SHN_LORESERVE SectionIndex = 0xff00 /* First of reserved range. */
+    SHN_LOPROC    SectionIndex = 0xff00 /* First processor-specific. */
+    SHN_HIPROC    SectionIndex = 0xff1f /* Last processor-specific. */
+    SHN_LOOS      SectionIndex = 0xff20 /* First operating system-specific. */
+    SHN_HIOS      SectionIndex = 0xff3f /* Last operating system-specific. */
+    SHN_ABS       SectionIndex = 0xfff1 /* Absolute values. */
+    SHN_COMMON    SectionIndex = 0xfff2 /* Common data. */
+    SHN_XINDEX    SectionIndex = 0xffff /* Escape; index stored elsewhere. */
+    SHN_HIRESERVE SectionIndex = 0xffff /* Last of reserved range. */
+)

func (SectionIndex) GoString

func (i SectionIndex) GoString() string

func (SectionIndex) String

func (i SectionIndex) String() string

type SectionType

Section type.

+
type SectionType uint32
const (
+    SHT_NULL           SectionType = 0          /* inactive */
+    SHT_PROGBITS       SectionType = 1          /* program defined information */
+    SHT_SYMTAB         SectionType = 2          /* symbol table section */
+    SHT_STRTAB         SectionType = 3          /* string table section */
+    SHT_RELA           SectionType = 4          /* relocation section with addends */
+    SHT_HASH           SectionType = 5          /* symbol hash table section */
+    SHT_DYNAMIC        SectionType = 6          /* dynamic section */
+    SHT_NOTE           SectionType = 7          /* note section */
+    SHT_NOBITS         SectionType = 8          /* no space section */
+    SHT_REL            SectionType = 9          /* relocation section - no addends */
+    SHT_SHLIB          SectionType = 10         /* reserved - purpose unknown */
+    SHT_DYNSYM         SectionType = 11         /* dynamic symbol table section */
+    SHT_INIT_ARRAY     SectionType = 14         /* Initialization function pointers. */
+    SHT_FINI_ARRAY     SectionType = 15         /* Termination function pointers. */
+    SHT_PREINIT_ARRAY  SectionType = 16         /* Pre-initialization function ptrs. */
+    SHT_GROUP          SectionType = 17         /* Section group. */
+    SHT_SYMTAB_SHNDX   SectionType = 18         /* Section indexes (see SHN_XINDEX). */
+    SHT_LOOS           SectionType = 0x60000000 /* First of OS specific semantics */
+    SHT_GNU_ATTRIBUTES SectionType = 0x6ffffff5 /* GNU object attributes */
+    SHT_GNU_HASH       SectionType = 0x6ffffff6 /* GNU hash table */
+    SHT_GNU_LIBLIST    SectionType = 0x6ffffff7 /* GNU prelink library list */
+    SHT_GNU_VERDEF     SectionType = 0x6ffffffd /* GNU version definition section */
+    SHT_GNU_VERNEED    SectionType = 0x6ffffffe /* GNU version needs section */
+    SHT_GNU_VERSYM     SectionType = 0x6fffffff /* GNU version symbol table */
+    SHT_HIOS           SectionType = 0x6fffffff /* Last of OS specific semantics */
+    SHT_LOPROC         SectionType = 0x70000000 /* reserved range for processor */
+    SHT_MIPS_ABIFLAGS  SectionType = 0x7000002a /* .MIPS.abiflags */
+    SHT_HIPROC         SectionType = 0x7fffffff /* specific section header types */
+    SHT_LOUSER         SectionType = 0x80000000 /* reserved range for application */
+    SHT_HIUSER         SectionType = 0xffffffff /* specific indexes */
+)

func (SectionType) GoString

func (i SectionType) GoString() string

func (SectionType) String

func (i SectionType) String() string

type Sym32

ELF32 Symbol.

+
type Sym32 struct {
+    Name  uint32
+    Value uint32
+    Size  uint32
+    Info  uint8
+    Other uint8
+    Shndx uint16
+}
+

type Sym64

ELF64 symbol table entries.

+
type Sym64 struct {
+    Name  uint32 /* String table index of name. */
+    Info  uint8  /* Type and binding information. */
+    Other uint8  /* Reserved (not used). */
+    Shndx uint16 /* Section index of symbol. */
+    Value uint64 /* Symbol value. */
+    Size  uint64 /* Size of associated object. */
+}
+

type SymBind

Symbol Binding - ELFNN_ST_BIND - st_info

+
type SymBind int
const (
+    STB_LOCAL  SymBind = 0  /* Local symbol */
+    STB_GLOBAL SymBind = 1  /* Global symbol */
+    STB_WEAK   SymBind = 2  /* like global - lower precedence */
+    STB_LOOS   SymBind = 10 /* Reserved range for operating system */
+    STB_HIOS   SymBind = 12 /*   specific semantics. */
+    STB_LOPROC SymBind = 13 /* reserved range for processor */
+    STB_HIPROC SymBind = 15 /*   specific semantics. */
+)

func ST_BIND

func ST_BIND(info uint8) SymBind

func (SymBind) GoString

func (i SymBind) GoString() string

func (SymBind) String

func (i SymBind) String() string

type SymType

Symbol type - ELFNN_ST_TYPE - st_info

+
type SymType int
const (
+    STT_NOTYPE  SymType = 0  /* Unspecified type. */
+    STT_OBJECT  SymType = 1  /* Data object. */
+    STT_FUNC    SymType = 2  /* Function. */
+    STT_SECTION SymType = 3  /* Section. */
+    STT_FILE    SymType = 4  /* Source file. */
+    STT_COMMON  SymType = 5  /* Uninitialized common block. */
+    STT_TLS     SymType = 6  /* TLS object. */
+    STT_LOOS    SymType = 10 /* Reserved range for operating system */
+    STT_HIOS    SymType = 12 /*   specific semantics. */
+    STT_LOPROC  SymType = 13 /* reserved range for processor */
+    STT_HIPROC  SymType = 15 /*   specific semantics. */
+)

func ST_TYPE

func ST_TYPE(info uint8) SymType

func (SymType) GoString

func (i SymType) GoString() string

func (SymType) String

func (i SymType) String() string

type SymVis

Symbol visibility - ELFNN_ST_VISIBILITY - st_other

+
type SymVis int
const (
+    STV_DEFAULT   SymVis = 0x0 /* Default visibility (see binding). */
+    STV_INTERNAL  SymVis = 0x1 /* Special meaning in relocatable objects. */
+    STV_HIDDEN    SymVis = 0x2 /* Not visible. */
+    STV_PROTECTED SymVis = 0x3 /* Visible but not preemptible. */
+)

func ST_VISIBILITY

func ST_VISIBILITY(other uint8) SymVis

func (SymVis) GoString

func (i SymVis) GoString() string

func (SymVis) String

func (i SymVis) String() string

type Symbol

A Symbol represents an entry in an ELF symbol table section.

+
type Symbol struct {
+    Name        string
+    Info, Other byte
+    Section     SectionIndex
+    Value, Size uint64
+
+    // Version and Library are present only for the dynamic symbol
+    // table.
+    Version string // Go 1.13
+    Library string // Go 1.13
+}
+

type Type

Type is found in Header.Type.

+
type Type uint16
const (
+    ET_NONE   Type = 0      /* Unknown type. */
+    ET_REL    Type = 1      /* Relocatable. */
+    ET_EXEC   Type = 2      /* Executable. */
+    ET_DYN    Type = 3      /* Shared object. */
+    ET_CORE   Type = 4      /* Core file. */
+    ET_LOOS   Type = 0xfe00 /* First operating system specific. */
+    ET_HIOS   Type = 0xfeff /* Last operating system-specific. */
+    ET_LOPROC Type = 0xff00 /* First processor-specific. */
+    ET_HIPROC Type = 0xffff /* Last processor-specific. */
+)

func (Type) GoString

func (i Type) GoString() string

func (Type) String

func (i Type) String() string

type Version

Version is found in Header.Ident[EI_VERSION] and Header.Version.

+
type Version byte
const (
+    EV_NONE    Version = 0
+    EV_CURRENT Version = 1
+)

func (Version) GoString

func (i Version) GoString() string

func (Version) String

func (i Version) String() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/debug/elf/ +

+
diff --git a/devdocs/go/debug%2Fgosym%2Findex.html b/devdocs/go/debug%2Fgosym%2Findex.html new file mode 100644 index 00000000..3b5510a0 --- /dev/null +++ b/devdocs/go/debug%2Fgosym%2Findex.html @@ -0,0 +1,133 @@ +

Package gosym

Overview

Package gosym implements access to the Go symbol and line number tables embedded in Go binaries generated by the gc compilers.

Index

Package files

pclntab.go symtab.go

type DecodingError

DecodingError represents an error during the decoding of the symbol table.

+
type DecodingError struct {
+    // contains filtered or unexported fields
+}
+

func (*DecodingError) Error

func (e *DecodingError) Error() string

type Func

A Func collects information about a single function.

+
type Func struct {
+    Entry uint64
+    *Sym
+    End       uint64
+    Params    []*Sym // nil for Go 1.3 and later binaries
+    Locals    []*Sym // nil for Go 1.3 and later binaries
+    FrameSize int
+    LineTable *LineTable
+    Obj       *Obj
+}
+

type LineTable

A LineTable is a data structure mapping program counters to line numbers.

+

In Go 1.1 and earlier, each function (represented by a Func) had its own LineTable, and the line number corresponded to a numbering of all source lines in the program, across all files. That absolute line number would then have to be converted separately to a file name and line number within the file.

+

In Go 1.2, the format of the data changed so that there is a single LineTable for the entire program, shared by all Funcs, and there are no absolute line numbers, just line numbers within specific files.

+

For the most part, LineTable's methods should be treated as an internal detail of the package; callers should use the methods on Table instead.

+
type LineTable struct {
+    Data []byte
+    PC   uint64
+    Line int
+    // contains filtered or unexported fields
+}
+

func NewLineTable

func NewLineTable(data []byte, text uint64) *LineTable

NewLineTable returns a new PC/line table corresponding to the encoded data. Text must be the start address of the corresponding text segment.

+

func (*LineTable) LineToPC

func (t *LineTable) LineToPC(line int, maxpc uint64) uint64

LineToPC returns the program counter for the given line number, considering only program counters before maxpc.

+

Deprecated: Use Table's LineToPC method instead.

+

func (*LineTable) PCToLine

func (t *LineTable) PCToLine(pc uint64) int

PCToLine returns the line number for the given program counter.

+

Deprecated: Use Table's PCToLine method instead.

+

type Obj

An Obj represents a collection of functions in a symbol table.

+

The exact method of division of a binary into separate Objs is an internal detail of the symbol table format.

+

In early versions of Go each source file became a different Obj.

+

In Go 1 and Go 1.1, each package produced one Obj for all Go sources and one Obj per C source file.

+

In Go 1.2, there is a single Obj for the entire program.

+
type Obj struct {
+    // Funcs is a list of functions in the Obj.
+    Funcs []Func
+
+    // In Go 1.1 and earlier, Paths is a list of symbols corresponding
+    // to the source file names that produced the Obj.
+    // In Go 1.2, Paths is nil.
+    // Use the keys of Table.Files to obtain a list of source files.
+    Paths []Sym // meta
+}
+

type Sym

A Sym represents a single symbol table entry.

+
type Sym struct {
+    Value  uint64
+    Type   byte
+    Name   string
+    GoType uint64
+    // If this symbol is a function symbol, the corresponding Func
+    Func *Func
+    // contains filtered or unexported fields
+}
+

func (*Sym) BaseName

func (s *Sym) BaseName() string

BaseName returns the symbol name without the package or receiver name.

+

func (*Sym) PackageName

func (s *Sym) PackageName() string

PackageName returns the package part of the symbol name, or the empty string if there is none.

+

func (*Sym) ReceiverName

func (s *Sym) ReceiverName() string

ReceiverName returns the receiver type name of this symbol, or the empty string if there is none. A receiver name is only detected in the case that s.Name is fully-specified with a package name.

+

func (*Sym) Static

func (s *Sym) Static() bool

Static reports whether this symbol is static (not visible outside its file).

+

type Table

Table represents a Go symbol table. It stores all of the symbols decoded from the program and provides methods to translate between symbols, names, and addresses.

+
type Table struct {
+    Syms  []Sym // nil for Go 1.3 and later binaries
+    Funcs []Func
+    Files map[string]*Obj // for Go 1.2 and later all files map to one Obj
+    Objs  []Obj           // for Go 1.2 and later only one Obj in slice
+    // contains filtered or unexported fields
+}
+

func NewTable

func NewTable(symtab []byte, pcln *LineTable) (*Table, error)

NewTable decodes the Go symbol table (the ".gosymtab" section in ELF), returning an in-memory representation. Starting with Go 1.3, the Go symbol table no longer includes symbol data.

+

func (*Table) LineToPC

func (t *Table) LineToPC(file string, line int) (pc uint64, fn *Func, err error)

LineToPC looks up the first program counter on the given line in the named file. It returns UnknownFileError or UnknownLineError if there is an error looking up this line.

+

func (*Table) LookupFunc

func (t *Table) LookupFunc(name string) *Func

LookupFunc returns the text, data, or bss symbol with the given name, or nil if no such symbol is found.

+

func (*Table) LookupSym

func (t *Table) LookupSym(name string) *Sym

LookupSym returns the text, data, or bss symbol with the given name, or nil if no such symbol is found.

+

func (*Table) PCToFunc

func (t *Table) PCToFunc(pc uint64) *Func

PCToFunc returns the function containing the program counter pc, or nil if there is no such function.

+

func (*Table) PCToLine

func (t *Table) PCToLine(pc uint64) (file string, line int, fn *Func)

PCToLine looks up line number information for a program counter. If there is no information, it returns fn == nil.

+

func (*Table) SymByAddr

func (t *Table) SymByAddr(addr uint64) *Sym

SymByAddr returns the text, data, or bss symbol starting at the given address.

+

type UnknownFileError

UnknownFileError represents a failure to find the specific file in the symbol table.

+
type UnknownFileError string

func (UnknownFileError) Error

func (e UnknownFileError) Error() string

type UnknownLineError

UnknownLineError represents a failure to map a line to a program counter, either because the line is beyond the bounds of the file or because there is no code on the given line.

+
type UnknownLineError struct {
+    File string
+    Line int
+}
+

func (*UnknownLineError) Error

func (e *UnknownLineError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/debug/gosym/ +

+
diff --git a/devdocs/go/debug%2Fmacho%2Findex.html b/devdocs/go/debug%2Fmacho%2Findex.html new file mode 100644 index 00000000..2dadd0f1 --- /dev/null +++ b/devdocs/go/debug%2Fmacho%2Findex.html @@ -0,0 +1,542 @@ +

Package macho

Overview

Package macho implements access to Mach-O object files.

+

Security

This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

Index

Package files

fat.go file.go macho.go reloctype.go reloctype_string.go

Constants

const (
+    Magic32  uint32 = 0xfeedface
+    Magic64  uint32 = 0xfeedfacf
+    MagicFat uint32 = 0xcafebabe
+)
const (
+    FlagNoUndefs              uint32 = 0x1
+    FlagIncrLink              uint32 = 0x2
+    FlagDyldLink              uint32 = 0x4
+    FlagBindAtLoad            uint32 = 0x8
+    FlagPrebound              uint32 = 0x10
+    FlagSplitSegs             uint32 = 0x20
+    FlagLazyInit              uint32 = 0x40
+    FlagTwoLevel              uint32 = 0x80
+    FlagForceFlat             uint32 = 0x100
+    FlagNoMultiDefs           uint32 = 0x200
+    FlagNoFixPrebinding       uint32 = 0x400
+    FlagPrebindable           uint32 = 0x800
+    FlagAllModsBound          uint32 = 0x1000
+    FlagSubsectionsViaSymbols uint32 = 0x2000
+    FlagCanonical             uint32 = 0x4000
+    FlagWeakDefines           uint32 = 0x8000
+    FlagBindsToWeak           uint32 = 0x10000
+    FlagAllowStackExecution   uint32 = 0x20000
+    FlagRootSafe              uint32 = 0x40000
+    FlagSetuidSafe            uint32 = 0x80000
+    FlagNoReexportedDylibs    uint32 = 0x100000
+    FlagPIE                   uint32 = 0x200000
+    FlagDeadStrippableDylib   uint32 = 0x400000
+    FlagHasTLVDescriptors     uint32 = 0x800000
+    FlagNoHeapExecution       uint32 = 0x1000000
+    FlagAppExtensionSafe      uint32 = 0x2000000
+)

Variables

ErrNotFat is returned from NewFatFile or OpenFat when the file is not a universal binary but may be a thin binary, based on its magic number.

+
var ErrNotFat = &FormatError{0, "not a fat Mach-O file", nil}

type Cpu

A Cpu is a Mach-O cpu type.

+
type Cpu uint32
const (
+    Cpu386   Cpu = 7
+    CpuAmd64 Cpu = Cpu386 | cpuArch64
+    CpuArm   Cpu = 12
+    CpuArm64 Cpu = CpuArm | cpuArch64
+    CpuPpc   Cpu = 18
+    CpuPpc64 Cpu = CpuPpc | cpuArch64
+)

func (Cpu) GoString

func (i Cpu) GoString() string

func (Cpu) String

func (i Cpu) String() string

type Dylib

A Dylib represents a Mach-O load dynamic library command.

+
type Dylib struct {
+    LoadBytes
+    Name           string
+    Time           uint32
+    CurrentVersion uint32
+    CompatVersion  uint32
+}
+

type DylibCmd

A DylibCmd is a Mach-O load dynamic library command.

+
type DylibCmd struct {
+    Cmd            LoadCmd
+    Len            uint32
+    Name           uint32
+    Time           uint32
+    CurrentVersion uint32
+    CompatVersion  uint32
+}
+

type Dysymtab

A Dysymtab represents a Mach-O dynamic symbol table command.

+
type Dysymtab struct {
+    LoadBytes
+    DysymtabCmd
+    IndirectSyms []uint32 // indices into Symtab.Syms
+}
+

type DysymtabCmd

A DysymtabCmd is a Mach-O dynamic symbol table command.

+
type DysymtabCmd struct {
+    Cmd            LoadCmd
+    Len            uint32
+    Ilocalsym      uint32
+    Nlocalsym      uint32
+    Iextdefsym     uint32
+    Nextdefsym     uint32
+    Iundefsym      uint32
+    Nundefsym      uint32
+    Tocoffset      uint32
+    Ntoc           uint32
+    Modtaboff      uint32
+    Nmodtab        uint32
+    Extrefsymoff   uint32
+    Nextrefsyms    uint32
+    Indirectsymoff uint32
+    Nindirectsyms  uint32
+    Extreloff      uint32
+    Nextrel        uint32
+    Locreloff      uint32
+    Nlocrel        uint32
+}
+

type FatArch 1.3

A FatArch is a Mach-O File inside a FatFile.

+
type FatArch struct {
+    FatArchHeader
+    *File
+}
+

type FatArchHeader 1.3

A FatArchHeader represents a fat header for a specific image architecture.

+
type FatArchHeader struct {
+    Cpu    Cpu
+    SubCpu uint32
+    Offset uint32
+    Size   uint32
+    Align  uint32
+}
+

type FatFile 1.3

A FatFile is a Mach-O universal binary that contains at least one architecture.

+
type FatFile struct {
+    Magic  uint32
+    Arches []FatArch
+    // contains filtered or unexported fields
+}
+

func NewFatFile 1.3

func NewFatFile(r io.ReaderAt) (*FatFile, error)

NewFatFile creates a new FatFile for accessing all the Mach-O images in a universal binary. The Mach-O binary is expected to start at position 0 in the ReaderAt.

+

func OpenFat 1.3

func OpenFat(name string) (*FatFile, error)

OpenFat opens the named file using os.Open and prepares it for use as a Mach-O universal binary.

+

func (*FatFile) Close 1.3

func (ff *FatFile) Close() error

type File

A File represents an open Mach-O file.

+
type File struct {
+    FileHeader
+    ByteOrder binary.ByteOrder
+    Loads     []Load
+    Sections  []*Section
+
+    Symtab   *Symtab
+    Dysymtab *Dysymtab
+    // contains filtered or unexported fields
+}
+

func NewFile

func NewFile(r io.ReaderAt) (*File, error)

NewFile creates a new File for accessing a Mach-O binary in an underlying reader. The Mach-O binary is expected to start at position 0 in the ReaderAt.

+

func Open

func Open(name string) (*File, error)

Open opens the named file using os.Open and prepares it for use as a Mach-O binary.

+

func (*File) Close

func (f *File) Close() error

Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

+

func (*File) DWARF

func (f *File) DWARF() (*dwarf.Data, error)

DWARF returns the DWARF debug information for the Mach-O file.

+

func (*File) ImportedLibraries

func (f *File) ImportedLibraries() ([]string, error)

ImportedLibraries returns the paths of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.

+

func (*File) ImportedSymbols

func (f *File) ImportedSymbols() ([]string, error)

ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time.

+

func (*File) Section

func (f *File) Section(name string) *Section

Section returns the first section with the given name, or nil if no such section exists.

+

func (*File) Segment

func (f *File) Segment(name string) *Segment

Segment returns the first Segment with the given name, or nil if no such segment exists.

+

type FileHeader

A FileHeader represents a Mach-O file header.

+
type FileHeader struct {
+    Magic  uint32
+    Cpu    Cpu
+    SubCpu uint32
+    Type   Type
+    Ncmd   uint32
+    Cmdsz  uint32
+    Flags  uint32
+}
+

type FormatError

FormatError is returned by some operations if the data does not have the correct format for an object file.

+
type FormatError struct {
+    // contains filtered or unexported fields
+}
+

func (*FormatError) Error

func (e *FormatError) Error() string

type Load

A Load represents any Mach-O load command.

+
type Load interface {
+    Raw() []byte
+}

type LoadBytes

A LoadBytes is the uninterpreted bytes of a Mach-O load command.

+
type LoadBytes []byte

func (LoadBytes) Raw

func (b LoadBytes) Raw() []byte

type LoadCmd

A LoadCmd is a Mach-O load command.

+
type LoadCmd uint32
const (
+    LoadCmdSegment    LoadCmd = 0x1
+    LoadCmdSymtab     LoadCmd = 0x2
+    LoadCmdThread     LoadCmd = 0x4
+    LoadCmdUnixThread LoadCmd = 0x5 // thread+stack
+    LoadCmdDysymtab   LoadCmd = 0xb
+    LoadCmdDylib      LoadCmd = 0xc // load dylib command
+    LoadCmdDylinker   LoadCmd = 0xf // id dylinker command (not load dylinker command)
+    LoadCmdSegment64  LoadCmd = 0x19
+    LoadCmdRpath      LoadCmd = 0x8000001c
+)

func (LoadCmd) GoString

func (i LoadCmd) GoString() string

func (LoadCmd) String

func (i LoadCmd) String() string

type Nlist32

An Nlist32 is a Mach-O 32-bit symbol table entry.

+
type Nlist32 struct {
+    Name  uint32
+    Type  uint8
+    Sect  uint8
+    Desc  uint16
+    Value uint32
+}
+

type Nlist64

An Nlist64 is a Mach-O 64-bit symbol table entry.

+
type Nlist64 struct {
+    Name  uint32
+    Type  uint8
+    Sect  uint8
+    Desc  uint16
+    Value uint64
+}
+

type Regs386

Regs386 is the Mach-O 386 register structure.

+
type Regs386 struct {
+    AX    uint32
+    BX    uint32
+    CX    uint32
+    DX    uint32
+    DI    uint32
+    SI    uint32
+    BP    uint32
+    SP    uint32
+    SS    uint32
+    FLAGS uint32
+    IP    uint32
+    CS    uint32
+    DS    uint32
+    ES    uint32
+    FS    uint32
+    GS    uint32
+}
+

type RegsAMD64

RegsAMD64 is the Mach-O AMD64 register structure.

+
type RegsAMD64 struct {
+    AX    uint64
+    BX    uint64
+    CX    uint64
+    DX    uint64
+    DI    uint64
+    SI    uint64
+    BP    uint64
+    SP    uint64
+    R8    uint64
+    R9    uint64
+    R10   uint64
+    R11   uint64
+    R12   uint64
+    R13   uint64
+    R14   uint64
+    R15   uint64
+    IP    uint64
+    FLAGS uint64
+    CS    uint64
+    FS    uint64
+    GS    uint64
+}
+

type Reloc 1.10

A Reloc represents a Mach-O relocation.

+
type Reloc struct {
+    Addr  uint32
+    Value uint32
+    // when Scattered == false && Extern == true, Value is the symbol number.
+    // when Scattered == false && Extern == false, Value is the section number.
+    // when Scattered == true, Value is the value that this reloc refers to.
+    Type      uint8
+    Len       uint8 // 0=byte, 1=word, 2=long, 3=quad
+    Pcrel     bool
+    Extern    bool // valid if Scattered == false
+    Scattered bool
+}
+

type RelocTypeARM 1.10

type RelocTypeARM int
const (
+    ARM_RELOC_VANILLA        RelocTypeARM = 0
+    ARM_RELOC_PAIR           RelocTypeARM = 1
+    ARM_RELOC_SECTDIFF       RelocTypeARM = 2
+    ARM_RELOC_LOCAL_SECTDIFF RelocTypeARM = 3
+    ARM_RELOC_PB_LA_PTR      RelocTypeARM = 4
+    ARM_RELOC_BR24           RelocTypeARM = 5
+    ARM_THUMB_RELOC_BR22     RelocTypeARM = 6
+    ARM_THUMB_32BIT_BRANCH   RelocTypeARM = 7
+    ARM_RELOC_HALF           RelocTypeARM = 8
+    ARM_RELOC_HALF_SECTDIFF  RelocTypeARM = 9
+)

func (RelocTypeARM) GoString 1.10

func (r RelocTypeARM) GoString() string

func (RelocTypeARM) String 1.10

func (i RelocTypeARM) String() string

type RelocTypeARM64 1.10

type RelocTypeARM64 int
const (
+    ARM64_RELOC_UNSIGNED            RelocTypeARM64 = 0
+    ARM64_RELOC_SUBTRACTOR          RelocTypeARM64 = 1
+    ARM64_RELOC_BRANCH26            RelocTypeARM64 = 2
+    ARM64_RELOC_PAGE21              RelocTypeARM64 = 3
+    ARM64_RELOC_PAGEOFF12           RelocTypeARM64 = 4
+    ARM64_RELOC_GOT_LOAD_PAGE21     RelocTypeARM64 = 5
+    ARM64_RELOC_GOT_LOAD_PAGEOFF12  RelocTypeARM64 = 6
+    ARM64_RELOC_POINTER_TO_GOT      RelocTypeARM64 = 7
+    ARM64_RELOC_TLVP_LOAD_PAGE21    RelocTypeARM64 = 8
+    ARM64_RELOC_TLVP_LOAD_PAGEOFF12 RelocTypeARM64 = 9
+    ARM64_RELOC_ADDEND              RelocTypeARM64 = 10
+)

func (RelocTypeARM64) GoString 1.10

func (r RelocTypeARM64) GoString() string

func (RelocTypeARM64) String 1.10

func (i RelocTypeARM64) String() string

type RelocTypeGeneric 1.10

type RelocTypeGeneric int
const (
+    GENERIC_RELOC_VANILLA        RelocTypeGeneric = 0
+    GENERIC_RELOC_PAIR           RelocTypeGeneric = 1
+    GENERIC_RELOC_SECTDIFF       RelocTypeGeneric = 2
+    GENERIC_RELOC_PB_LA_PTR      RelocTypeGeneric = 3
+    GENERIC_RELOC_LOCAL_SECTDIFF RelocTypeGeneric = 4
+    GENERIC_RELOC_TLV            RelocTypeGeneric = 5
+)

func (RelocTypeGeneric) GoString 1.10

func (r RelocTypeGeneric) GoString() string

func (RelocTypeGeneric) String 1.10

func (i RelocTypeGeneric) String() string

type RelocTypeX86_64 1.10

type RelocTypeX86_64 int
const (
+    X86_64_RELOC_UNSIGNED   RelocTypeX86_64 = 0
+    X86_64_RELOC_SIGNED     RelocTypeX86_64 = 1
+    X86_64_RELOC_BRANCH     RelocTypeX86_64 = 2
+    X86_64_RELOC_GOT_LOAD   RelocTypeX86_64 = 3
+    X86_64_RELOC_GOT        RelocTypeX86_64 = 4
+    X86_64_RELOC_SUBTRACTOR RelocTypeX86_64 = 5
+    X86_64_RELOC_SIGNED_1   RelocTypeX86_64 = 6
+    X86_64_RELOC_SIGNED_2   RelocTypeX86_64 = 7
+    X86_64_RELOC_SIGNED_4   RelocTypeX86_64 = 8
+    X86_64_RELOC_TLV        RelocTypeX86_64 = 9
+)

func (RelocTypeX86_64) GoString 1.10

func (r RelocTypeX86_64) GoString() string

func (RelocTypeX86_64) String 1.10

func (i RelocTypeX86_64) String() string

type Rpath 1.10

A Rpath represents a Mach-O rpath command.

+
type Rpath struct {
+    LoadBytes
+    Path string
+}
+

type RpathCmd 1.10

A RpathCmd is a Mach-O rpath command.

+
type RpathCmd struct {
+    Cmd  LoadCmd
+    Len  uint32
+    Path uint32
+}
+

type Section

type Section struct {
+    SectionHeader
+    Relocs []Reloc // Go 1.10
+
+    // Embed ReaderAt for ReadAt method.
+    // Do not embed SectionReader directly
+    // to avoid having Read and Seek.
+    // If a client wants Read and Seek it must use
+    // Open() to avoid fighting over the seek offset
+    // with other clients.
+    io.ReaderAt
+    // contains filtered or unexported fields
+}
+

func (*Section) Data

func (s *Section) Data() ([]byte, error)

Data reads and returns the contents of the Mach-O section.

+

func (*Section) Open

func (s *Section) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the Mach-O section.

+

type Section32

A Section32 is a 32-bit Mach-O section header.

+
type Section32 struct {
+    Name     [16]byte
+    Seg      [16]byte
+    Addr     uint32
+    Size     uint32
+    Offset   uint32
+    Align    uint32
+    Reloff   uint32
+    Nreloc   uint32
+    Flags    uint32
+    Reserve1 uint32
+    Reserve2 uint32
+}
+

type Section64

A Section64 is a 64-bit Mach-O section header.

+
type Section64 struct {
+    Name     [16]byte
+    Seg      [16]byte
+    Addr     uint64
+    Size     uint64
+    Offset   uint32
+    Align    uint32
+    Reloff   uint32
+    Nreloc   uint32
+    Flags    uint32
+    Reserve1 uint32
+    Reserve2 uint32
+    Reserve3 uint32
+}
+

type SectionHeader

type SectionHeader struct {
+    Name   string
+    Seg    string
+    Addr   uint64
+    Size   uint64
+    Offset uint32
+    Align  uint32
+    Reloff uint32
+    Nreloc uint32
+    Flags  uint32
+}
+

type Segment

A Segment represents a Mach-O 32-bit or 64-bit load segment command.

+
type Segment struct {
+    LoadBytes
+    SegmentHeader
+
+    // Embed ReaderAt for ReadAt method.
+    // Do not embed SectionReader directly
+    // to avoid having Read and Seek.
+    // If a client wants Read and Seek it must use
+    // Open() to avoid fighting over the seek offset
+    // with other clients.
+    io.ReaderAt
+    // contains filtered or unexported fields
+}
+

func (*Segment) Data

func (s *Segment) Data() ([]byte, error)

Data reads and returns the contents of the segment.

+

func (*Segment) Open

func (s *Segment) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the segment.

+

type Segment32

A Segment32 is a 32-bit Mach-O segment load command.

+
type Segment32 struct {
+    Cmd     LoadCmd
+    Len     uint32
+    Name    [16]byte
+    Addr    uint32
+    Memsz   uint32
+    Offset  uint32
+    Filesz  uint32
+    Maxprot uint32
+    Prot    uint32
+    Nsect   uint32
+    Flag    uint32
+}
+

type Segment64

A Segment64 is a 64-bit Mach-O segment load command.

+
type Segment64 struct {
+    Cmd     LoadCmd
+    Len     uint32
+    Name    [16]byte
+    Addr    uint64
+    Memsz   uint64
+    Offset  uint64
+    Filesz  uint64
+    Maxprot uint32
+    Prot    uint32
+    Nsect   uint32
+    Flag    uint32
+}
+

type SegmentHeader

A SegmentHeader is the header for a Mach-O 32-bit or 64-bit load segment command.

+
type SegmentHeader struct {
+    Cmd     LoadCmd
+    Len     uint32
+    Name    string
+    Addr    uint64
+    Memsz   uint64
+    Offset  uint64
+    Filesz  uint64
+    Maxprot uint32
+    Prot    uint32
+    Nsect   uint32
+    Flag    uint32
+}
+

type Symbol

A Symbol is a Mach-O 32-bit or 64-bit symbol table entry.

+
type Symbol struct {
+    Name  string
+    Type  uint8
+    Sect  uint8
+    Desc  uint16
+    Value uint64
+}
+

type Symtab

A Symtab represents a Mach-O symbol table command.

+
type Symtab struct {
+    LoadBytes
+    SymtabCmd
+    Syms []Symbol
+}
+

type SymtabCmd

A SymtabCmd is a Mach-O symbol table command.

+
type SymtabCmd struct {
+    Cmd     LoadCmd
+    Len     uint32
+    Symoff  uint32
+    Nsyms   uint32
+    Stroff  uint32
+    Strsize uint32
+}
+

type Thread

A Thread is a Mach-O thread state command.

+
type Thread struct {
+    Cmd  LoadCmd
+    Len  uint32
+    Type uint32
+    Data []uint32
+}
+

type Type

A Type is the Mach-O file type, e.g. an object file, executable, or dynamic library.

+
type Type uint32
const (
+    TypeObj    Type = 1
+    TypeExec   Type = 2
+    TypeDylib  Type = 6
+    TypeBundle Type = 8
+)

func (Type) GoString 1.10

func (t Type) GoString() string

func (Type) String 1.10

func (t Type) String() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/debug/macho/ +

+
diff --git a/devdocs/go/debug%2Fpe%2Findex.html b/devdocs/go/debug%2Fpe%2Findex.html new file mode 100644 index 00000000..5df3a667 --- /dev/null +++ b/devdocs/go/debug%2Fpe%2Findex.html @@ -0,0 +1,350 @@ +

Package pe

Overview

Package pe implements access to PE (Microsoft Windows Portable Executable) files.

+

Security

This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

Index

Package files

file.go pe.go section.go string.go symbol.go

Constants

const (
+    IMAGE_FILE_MACHINE_UNKNOWN     = 0x0
+    IMAGE_FILE_MACHINE_AM33        = 0x1d3
+    IMAGE_FILE_MACHINE_AMD64       = 0x8664
+    IMAGE_FILE_MACHINE_ARM         = 0x1c0
+    IMAGE_FILE_MACHINE_ARMNT       = 0x1c4
+    IMAGE_FILE_MACHINE_ARM64       = 0xaa64
+    IMAGE_FILE_MACHINE_EBC         = 0xebc
+    IMAGE_FILE_MACHINE_I386        = 0x14c
+    IMAGE_FILE_MACHINE_IA64        = 0x200
+    IMAGE_FILE_MACHINE_LOONGARCH32 = 0x6232
+    IMAGE_FILE_MACHINE_LOONGARCH64 = 0x6264
+    IMAGE_FILE_MACHINE_M32R        = 0x9041
+    IMAGE_FILE_MACHINE_MIPS16      = 0x266
+    IMAGE_FILE_MACHINE_MIPSFPU     = 0x366
+    IMAGE_FILE_MACHINE_MIPSFPU16   = 0x466
+    IMAGE_FILE_MACHINE_POWERPC     = 0x1f0
+    IMAGE_FILE_MACHINE_POWERPCFP   = 0x1f1
+    IMAGE_FILE_MACHINE_R4000       = 0x166
+    IMAGE_FILE_MACHINE_SH3         = 0x1a2
+    IMAGE_FILE_MACHINE_SH3DSP      = 0x1a3
+    IMAGE_FILE_MACHINE_SH4         = 0x1a6
+    IMAGE_FILE_MACHINE_SH5         = 0x1a8
+    IMAGE_FILE_MACHINE_THUMB       = 0x1c2
+    IMAGE_FILE_MACHINE_WCEMIPSV2   = 0x169
+    IMAGE_FILE_MACHINE_RISCV32     = 0x5032
+    IMAGE_FILE_MACHINE_RISCV64     = 0x5064
+    IMAGE_FILE_MACHINE_RISCV128    = 0x5128
+)

IMAGE_DIRECTORY_ENTRY constants

+
const (
+    IMAGE_DIRECTORY_ENTRY_EXPORT         = 0
+    IMAGE_DIRECTORY_ENTRY_IMPORT         = 1
+    IMAGE_DIRECTORY_ENTRY_RESOURCE       = 2
+    IMAGE_DIRECTORY_ENTRY_EXCEPTION      = 3
+    IMAGE_DIRECTORY_ENTRY_SECURITY       = 4
+    IMAGE_DIRECTORY_ENTRY_BASERELOC      = 5
+    IMAGE_DIRECTORY_ENTRY_DEBUG          = 6
+    IMAGE_DIRECTORY_ENTRY_ARCHITECTURE   = 7
+    IMAGE_DIRECTORY_ENTRY_GLOBALPTR      = 8
+    IMAGE_DIRECTORY_ENTRY_TLS            = 9
+    IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG    = 10
+    IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT   = 11
+    IMAGE_DIRECTORY_ENTRY_IAT            = 12
+    IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT   = 13
+    IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14
+)

Values of IMAGE_FILE_HEADER.Characteristics. These can be combined together.

+
const (
+    IMAGE_FILE_RELOCS_STRIPPED         = 0x0001
+    IMAGE_FILE_EXECUTABLE_IMAGE        = 0x0002
+    IMAGE_FILE_LINE_NUMS_STRIPPED      = 0x0004
+    IMAGE_FILE_LOCAL_SYMS_STRIPPED     = 0x0008
+    IMAGE_FILE_AGGRESIVE_WS_TRIM       = 0x0010
+    IMAGE_FILE_LARGE_ADDRESS_AWARE     = 0x0020
+    IMAGE_FILE_BYTES_REVERSED_LO       = 0x0080
+    IMAGE_FILE_32BIT_MACHINE           = 0x0100
+    IMAGE_FILE_DEBUG_STRIPPED          = 0x0200
+    IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400
+    IMAGE_FILE_NET_RUN_FROM_SWAP       = 0x0800
+    IMAGE_FILE_SYSTEM                  = 0x1000
+    IMAGE_FILE_DLL                     = 0x2000
+    IMAGE_FILE_UP_SYSTEM_ONLY          = 0x4000
+    IMAGE_FILE_BYTES_REVERSED_HI       = 0x8000
+)

OptionalHeader64.Subsystem and OptionalHeader32.Subsystem values.

+
const (
+    IMAGE_SUBSYSTEM_UNKNOWN                  = 0
+    IMAGE_SUBSYSTEM_NATIVE                   = 1
+    IMAGE_SUBSYSTEM_WINDOWS_GUI              = 2
+    IMAGE_SUBSYSTEM_WINDOWS_CUI              = 3
+    IMAGE_SUBSYSTEM_OS2_CUI                  = 5
+    IMAGE_SUBSYSTEM_POSIX_CUI                = 7
+    IMAGE_SUBSYSTEM_NATIVE_WINDOWS           = 8
+    IMAGE_SUBSYSTEM_WINDOWS_CE_GUI           = 9
+    IMAGE_SUBSYSTEM_EFI_APPLICATION          = 10
+    IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER  = 11
+    IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER       = 12
+    IMAGE_SUBSYSTEM_EFI_ROM                  = 13
+    IMAGE_SUBSYSTEM_XBOX                     = 14
+    IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION = 16
+)

OptionalHeader64.DllCharacteristics and OptionalHeader32.DllCharacteristics values. These can be combined together.

+
const (
+    IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA       = 0x0020
+    IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE          = 0x0040
+    IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY       = 0x0080
+    IMAGE_DLLCHARACTERISTICS_NX_COMPAT             = 0x0100
+    IMAGE_DLLCHARACTERISTICS_NO_ISOLATION          = 0x0200
+    IMAGE_DLLCHARACTERISTICS_NO_SEH                = 0x0400
+    IMAGE_DLLCHARACTERISTICS_NO_BIND               = 0x0800
+    IMAGE_DLLCHARACTERISTICS_APPCONTAINER          = 0x1000
+    IMAGE_DLLCHARACTERISTICS_WDM_DRIVER            = 0x2000
+    IMAGE_DLLCHARACTERISTICS_GUARD_CF              = 0x4000
+    IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000
+)

Section characteristics flags.

+
const (
+    IMAGE_SCN_CNT_CODE               = 0x00000020
+    IMAGE_SCN_CNT_INITIALIZED_DATA   = 0x00000040
+    IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080
+    IMAGE_SCN_LNK_COMDAT             = 0x00001000
+    IMAGE_SCN_MEM_DISCARDABLE        = 0x02000000
+    IMAGE_SCN_MEM_EXECUTE            = 0x20000000
+    IMAGE_SCN_MEM_READ               = 0x40000000
+    IMAGE_SCN_MEM_WRITE              = 0x80000000
+)

These constants make up the possible values for the 'Selection' field in an AuxFormat5.

+
const (
+    IMAGE_COMDAT_SELECT_NODUPLICATES = 1
+    IMAGE_COMDAT_SELECT_ANY          = 2
+    IMAGE_COMDAT_SELECT_SAME_SIZE    = 3
+    IMAGE_COMDAT_SELECT_EXACT_MATCH  = 4
+    IMAGE_COMDAT_SELECT_ASSOCIATIVE  = 5
+    IMAGE_COMDAT_SELECT_LARGEST      = 6
+)
const COFFSymbolSize = 18

type COFFSymbol 1.1

COFFSymbol represents single COFF symbol table record.

+
type COFFSymbol struct {
+    Name               [8]uint8
+    Value              uint32
+    SectionNumber      int16
+    Type               uint16
+    StorageClass       uint8
+    NumberOfAuxSymbols uint8
+}
+

func (*COFFSymbol) FullName 1.8

func (sym *COFFSymbol) FullName(st StringTable) (string, error)

FullName finds real name of symbol sym. Normally name is stored in sym.Name, but if it is longer then 8 characters, it is stored in COFF string table st instead.

+

type COFFSymbolAuxFormat5 1.19

COFFSymbolAuxFormat5 describes the expected form of an aux symbol attached to a section definition symbol. The PE format defines a number of different aux symbol formats: format 1 for function definitions, format 2 for .be and .ef symbols, and so on. Format 5 holds extra info associated with a section definition, including number of relocations + line numbers, as well as COMDAT info. See https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-format-5-section-definitions for more on what's going on here.

+
type COFFSymbolAuxFormat5 struct {
+    Size           uint32
+    NumRelocs      uint16
+    NumLineNumbers uint16
+    Checksum       uint32
+    SecNum         uint16
+    Selection      uint8
+    // contains filtered or unexported fields
+}
+

type DataDirectory 1.3

type DataDirectory struct {
+    VirtualAddress uint32
+    Size           uint32
+}
+

type File

A File represents an open PE file.

+
type File struct {
+    FileHeader
+    OptionalHeader any // of type *OptionalHeader32 or *OptionalHeader64; added in Go 1.3
+    Sections       []*Section
+    Symbols        []*Symbol    // COFF symbols with auxiliary symbol records removed; added in Go 1.1
+    COFFSymbols    []COFFSymbol // all COFF symbols (including auxiliary symbol records); added in Go 1.8
+    StringTable    StringTable // Go 1.8
+    // contains filtered or unexported fields
+}
+

func NewFile

func NewFile(r io.ReaderAt) (*File, error)

NewFile creates a new File for accessing a PE binary in an underlying reader.

+

func Open

func Open(name string) (*File, error)

Open opens the named file using os.Open and prepares it for use as a PE binary.

+

func (*File) COFFSymbolReadSectionDefAux 1.19

func (f *File) COFFSymbolReadSectionDefAux(idx int) (*COFFSymbolAuxFormat5, error)

COFFSymbolReadSectionDefAux returns a blob of auxiliary information (including COMDAT info) for a section definition symbol. Here 'idx' is the index of a section symbol in the main COFFSymbol array for the File. Return value is a pointer to the appropriate aux symbol struct. For more info, see:

+

auxiliary symbols: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-symbol-records COMDAT sections: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#comdat-sections-object-only auxiliary info for section definitions: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-format-5-section-definitions

+

func (*File) Close

func (f *File) Close() error

Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

+

func (*File) DWARF

func (f *File) DWARF() (*dwarf.Data, error)

func (*File) ImportedLibraries

func (f *File) ImportedLibraries() ([]string, error)

ImportedLibraries returns the names of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.

+

func (*File) ImportedSymbols

func (f *File) ImportedSymbols() ([]string, error)

ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time. It does not return weak symbols.

+

func (*File) Section

func (f *File) Section(name string) *Section

Section returns the first section with the given name, or nil if no such section exists.

+

type FileHeader

type FileHeader struct {
+    Machine              uint16
+    NumberOfSections     uint16
+    TimeDateStamp        uint32
+    PointerToSymbolTable uint32
+    NumberOfSymbols      uint32
+    SizeOfOptionalHeader uint16
+    Characteristics      uint16
+}
+

type FormatError

FormatError is unused. The type is retained for compatibility.

+
type FormatError struct {
+}
+

func (*FormatError) Error

func (e *FormatError) Error() string

type ImportDirectory

type ImportDirectory struct {
+    OriginalFirstThunk uint32
+    TimeDateStamp      uint32
+    ForwarderChain     uint32
+    Name               uint32
+    FirstThunk         uint32
+    // contains filtered or unexported fields
+}
+

type OptionalHeader32 1.3

type OptionalHeader32 struct {
+    Magic                       uint16
+    MajorLinkerVersion          uint8
+    MinorLinkerVersion          uint8
+    SizeOfCode                  uint32
+    SizeOfInitializedData       uint32
+    SizeOfUninitializedData     uint32
+    AddressOfEntryPoint         uint32
+    BaseOfCode                  uint32
+    BaseOfData                  uint32
+    ImageBase                   uint32
+    SectionAlignment            uint32
+    FileAlignment               uint32
+    MajorOperatingSystemVersion uint16
+    MinorOperatingSystemVersion uint16
+    MajorImageVersion           uint16
+    MinorImageVersion           uint16
+    MajorSubsystemVersion       uint16
+    MinorSubsystemVersion       uint16
+    Win32VersionValue           uint32
+    SizeOfImage                 uint32
+    SizeOfHeaders               uint32
+    CheckSum                    uint32
+    Subsystem                   uint16
+    DllCharacteristics          uint16
+    SizeOfStackReserve          uint32
+    SizeOfStackCommit           uint32
+    SizeOfHeapReserve           uint32
+    SizeOfHeapCommit            uint32
+    LoaderFlags                 uint32
+    NumberOfRvaAndSizes         uint32
+    DataDirectory               [16]DataDirectory
+}
+

type OptionalHeader64 1.3

type OptionalHeader64 struct {
+    Magic                       uint16
+    MajorLinkerVersion          uint8
+    MinorLinkerVersion          uint8
+    SizeOfCode                  uint32
+    SizeOfInitializedData       uint32
+    SizeOfUninitializedData     uint32
+    AddressOfEntryPoint         uint32
+    BaseOfCode                  uint32
+    ImageBase                   uint64
+    SectionAlignment            uint32
+    FileAlignment               uint32
+    MajorOperatingSystemVersion uint16
+    MinorOperatingSystemVersion uint16
+    MajorImageVersion           uint16
+    MinorImageVersion           uint16
+    MajorSubsystemVersion       uint16
+    MinorSubsystemVersion       uint16
+    Win32VersionValue           uint32
+    SizeOfImage                 uint32
+    SizeOfHeaders               uint32
+    CheckSum                    uint32
+    Subsystem                   uint16
+    DllCharacteristics          uint16
+    SizeOfStackReserve          uint64
+    SizeOfStackCommit           uint64
+    SizeOfHeapReserve           uint64
+    SizeOfHeapCommit            uint64
+    LoaderFlags                 uint32
+    NumberOfRvaAndSizes         uint32
+    DataDirectory               [16]DataDirectory
+}
+

type Reloc 1.8

Reloc represents a PE COFF relocation. Each section contains its own relocation list.

+
type Reloc struct {
+    VirtualAddress   uint32
+    SymbolTableIndex uint32
+    Type             uint16
+}
+

type Section

Section provides access to PE COFF section.

+
type Section struct {
+    SectionHeader
+    Relocs []Reloc // Go 1.8
+
+    // Embed ReaderAt for ReadAt method.
+    // Do not embed SectionReader directly
+    // to avoid having Read and Seek.
+    // If a client wants Read and Seek it must use
+    // Open() to avoid fighting over the seek offset
+    // with other clients.
+    io.ReaderAt
+    // contains filtered or unexported fields
+}
+

func (*Section) Data

func (s *Section) Data() ([]byte, error)

Data reads and returns the contents of the PE section s.

+

If s.Offset is 0, the section has no contents, and Data will always return a non-nil error.

+

func (*Section) Open

func (s *Section) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the PE section s.

+

If s.Offset is 0, the section has no contents, and all calls to the returned reader will return a non-nil error.

+

type SectionHeader

SectionHeader is similar to SectionHeader32 with Name field replaced by Go string.

+
type SectionHeader struct {
+    Name                 string
+    VirtualSize          uint32
+    VirtualAddress       uint32
+    Size                 uint32
+    Offset               uint32
+    PointerToRelocations uint32
+    PointerToLineNumbers uint32
+    NumberOfRelocations  uint16
+    NumberOfLineNumbers  uint16
+    Characteristics      uint32
+}
+

type SectionHeader32

SectionHeader32 represents real PE COFF section header.

+
type SectionHeader32 struct {
+    Name                 [8]uint8
+    VirtualSize          uint32
+    VirtualAddress       uint32
+    SizeOfRawData        uint32
+    PointerToRawData     uint32
+    PointerToRelocations uint32
+    PointerToLineNumbers uint32
+    NumberOfRelocations  uint16
+    NumberOfLineNumbers  uint16
+    Characteristics      uint32
+}
+

type StringTable 1.8

StringTable is a COFF string table.

+
type StringTable []byte

func (StringTable) String 1.8

func (st StringTable) String(start uint32) (string, error)

String extracts string from COFF string table st at offset start.

+

type Symbol 1.1

Symbol is similar to COFFSymbol with Name field replaced by Go string. Symbol also does not have NumberOfAuxSymbols.

+
type Symbol struct {
+    Name          string
+    Value         uint32
+    SectionNumber int16
+    Type          uint16
+    StorageClass  uint8
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/debug/pe/ +

+
diff --git a/devdocs/go/debug%2Fplan9obj%2Findex.html b/devdocs/go/debug%2Fplan9obj%2Findex.html new file mode 100644 index 00000000..d4abc113 --- /dev/null +++ b/devdocs/go/debug%2Fplan9obj%2Findex.html @@ -0,0 +1,87 @@ +

Package plan9obj

Overview

Package plan9obj implements access to Plan 9 a.out object files.

+

Security

This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

Index

Package files

file.go plan9obj.go

Constants

const (
+    Magic64 = 0x8000 // 64-bit expanded header
+
+    Magic386   = (4*11+0)*11 + 7
+    MagicAMD64 = (4*26+0)*26 + 7 + Magic64
+    MagicARM   = (4*20+0)*20 + 7
+)

Variables

ErrNoSymbols is returned by File.Symbols if there is no such section in the File.

+
var ErrNoSymbols = errors.New("no symbol section")

type File 1.3

A File represents an open Plan 9 a.out file.

+
type File struct {
+    FileHeader
+    Sections []*Section
+    // contains filtered or unexported fields
+}
+

func NewFile 1.3

func NewFile(r io.ReaderAt) (*File, error)

NewFile creates a new File for accessing a Plan 9 binary in an underlying reader. The Plan 9 binary is expected to start at position 0 in the ReaderAt.

+

func Open 1.3

func Open(name string) (*File, error)

Open opens the named file using os.Open and prepares it for use as a Plan 9 a.out binary.

+

func (*File) Close 1.3

func (f *File) Close() error

Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

+

func (*File) Section 1.3

func (f *File) Section(name string) *Section

Section returns a section with the given name, or nil if no such section exists.

+

func (*File) Symbols 1.3

func (f *File) Symbols() ([]Sym, error)

Symbols returns the symbol table for f.

+

type FileHeader 1.3

A FileHeader represents a Plan 9 a.out file header.

+
type FileHeader struct {
+    Magic       uint32
+    Bss         uint32
+    Entry       uint64
+    PtrSize     int
+    LoadAddress uint64 // Go 1.4
+    HdrSize     uint64 // Go 1.4
+}
+

type Section 1.3

A Section represents a single section in a Plan 9 a.out file.

+
type Section struct {
+    SectionHeader
+
+    // Embed ReaderAt for ReadAt method.
+    // Do not embed SectionReader directly
+    // to avoid having Read and Seek.
+    // If a client wants Read and Seek it must use
+    // Open() to avoid fighting over the seek offset
+    // with other clients.
+    io.ReaderAt
+    // contains filtered or unexported fields
+}
+

func (*Section) Data 1.3

func (s *Section) Data() ([]byte, error)

Data reads and returns the contents of the Plan 9 a.out section.

+

func (*Section) Open 1.3

func (s *Section) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the Plan 9 a.out section.

+

type SectionHeader 1.3

A SectionHeader represents a single Plan 9 a.out section header. This structure doesn't exist on-disk, but eases navigation through the object file.

+
type SectionHeader struct {
+    Name   string
+    Size   uint32
+    Offset uint32
+}
+

type Sym 1.3

A Symbol represents an entry in a Plan 9 a.out symbol table section.

+
type Sym struct {
+    Value uint64
+    Type  rune
+    Name  string
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/debug/plan9obj/ +

+
diff --git a/devdocs/go/embed%2Findex.html b/devdocs/go/embed%2Findex.html new file mode 100644 index 00000000..39d4e2af --- /dev/null +++ b/devdocs/go/embed%2Findex.html @@ -0,0 +1,102 @@ +

Package embed

Overview

Package embed provides access to files embedded in the running Go program.

+

Go source files that import "embed" can use the //go:embed directive to initialize a variable of type string, []byte, or FS with the contents of files read from the package directory or subdirectories at compile time.

+

For example, here are three ways to embed a file named hello.txt and then print its contents at run time.

+

Embedding one file into a string:

+
import _ "embed"
+
+//go:embed hello.txt
+var s string
+print(s)
+

Embedding one file into a slice of bytes:

+
import _ "embed"
+
+//go:embed hello.txt
+var b []byte
+print(string(b))
+

Embedded one or more files into a file system:

+
import "embed"
+
+//go:embed hello.txt
+var f embed.FS
+data, _ := f.ReadFile("hello.txt")
+print(string(data))
+

Directives

A //go:embed directive above a variable declaration specifies which files to embed, using one or more path.Match patterns.

+

The directive must immediately precede a line containing the declaration of a single variable. Only blank lines and ‘//’ line comments are permitted between the directive and the declaration.

+

The type of the variable must be a string type, or a slice of a byte type, or FS (or an alias of FS).

+

For example:

+
package server
+
+import "embed"
+
+// content holds our static web server content.
+//go:embed image/* template/*
+//go:embed html/index.html
+var content embed.FS
+

The Go build system will recognize the directives and arrange for the declared variable (in the example above, content) to be populated with the matching files from the file system.

+

The //go:embed directive accepts multiple space-separated patterns for brevity, but it can also be repeated, to avoid very long lines when there are many patterns. The patterns are interpreted relative to the package directory containing the source file. The path separator is a forward slash, even on Windows systems. Patterns may not contain ‘.’ or ‘..’ or empty path elements, nor may they begin or end with a slash. To match everything in the current directory, use ‘*’ instead of ‘.’. To allow for naming files with spaces in their names, patterns can be written as Go double-quoted or back-quoted string literals.

+

If a pattern names a directory, all files in the subtree rooted at that directory are embedded (recursively), except that files with names beginning with ‘.’ or ‘_’ are excluded. So the variable in the above example is almost equivalent to:

+
// content is our static web server content.
+//go:embed image template html/index.html
+var content embed.FS
+

The difference is that ‘image/*’ embeds ‘image/.tempfile’ while ‘image’ does not. Neither embeds ‘image/dir/.tempfile’.

+

If a pattern begins with the prefix ‘all:’, then the rule for walking directories is changed to include those files beginning with ‘.’ or ‘_’. For example, ‘all:image’ embeds both ‘image/.tempfile’ and ‘image/dir/.tempfile’.

+

The //go:embed directive can be used with both exported and unexported variables, depending on whether the package wants to make the data available to other packages. It can only be used with variables at package scope, not with local variables.

+

Patterns must not match files outside the package's module, such as ‘.git/*’ or symbolic links. Patterns must not match files whose names include the special punctuation characters " * < > ? ` ' | / \ and :. Matches for empty directories are ignored. After that, each pattern in a //go:embed line must match at least one file or non-empty directory.

+

If any patterns are invalid or have invalid matches, the build will fail.

+

Strings and Bytes

The //go:embed line for a variable of type string or []byte can have only a single pattern, and that pattern can match only a single file. The string or []byte is initialized with the contents of that file.

+

The //go:embed directive requires importing "embed", even when using a string or []byte. In source files that don't refer to embed.FS, use a blank import (import _ "embed").

+

File Systems

For embedding a single file, a variable of type string or []byte is often best. The FS type enables embedding a tree of files, such as a directory of static web server content, as in the example above.

+

FS implements the io/fs package's FS interface, so it can be used with any package that understands file systems, including net/http, text/template, and html/template.

+

For example, given the content variable in the example above, we can write:

+
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(content))))
+
+template.ParseFS(content, "*.tmpl")
+

Tools

To support tools that analyze Go packages, the patterns found in //go:embed lines are available in “go list” output. See the EmbedPatterns, TestEmbedPatterns, and XTestEmbedPatterns fields in the “go help list” output.

Example +

Code:

package embed_test
+
+import (
+    "embed"
+    "log"
+    "net/http"
+)
+
+//go:embed internal/embedtest/testdata/*.txt
+var content embed.FS
+
+func Example() {
+    mux := http.NewServeMux()
+    mux.Handle("/", http.FileServer(http.FS(content)))
+    err := http.ListenAndServe(":8080", mux)
+    if err != nil {
+        log.Fatal(err)
+    }
+}
+

Index

Examples

Package

Package files

embed.go

type FS 1.16

An FS is a read-only collection of files, usually initialized with a //go:embed directive. When declared without a //go:embed directive, an FS is an empty file system.

+

An FS is a read-only value, so it is safe to use from multiple goroutines simultaneously and also safe to assign values of type FS to each other.

+

FS implements fs.FS, so it can be used with any package that understands file system interfaces, including net/http, text/template, and html/template.

+

See the package documentation for more details about initializing an FS.

+
type FS struct {
+    // contains filtered or unexported fields
+}
+

func (FS) Open 1.16

func (f FS) Open(name string) (fs.File, error)

Open opens the named file for reading and returns it as an fs.File.

+

The returned file implements io.Seeker and io.ReaderAt when the file is not a directory.

+

func (FS) ReadDir 1.16

func (f FS) ReadDir(name string) ([]fs.DirEntry, error)

ReadDir reads and returns the entire named directory.

+

func (FS) ReadFile 1.16

func (f FS) ReadFile(name string) ([]byte, error)

ReadFile reads and returns the content of the named file.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/embed/ +

+
diff --git a/devdocs/go/encoding%2Fascii85%2Findex.html b/devdocs/go/encoding%2Fascii85%2Findex.html new file mode 100644 index 00000000..675d07d8 --- /dev/null +++ b/devdocs/go/encoding%2Fascii85%2Findex.html @@ -0,0 +1,28 @@ +

Package ascii85

Overview

Package ascii85 implements the ascii85 data encoding as used in the btoa tool and Adobe's PostScript and PDF document formats.

Index

Package files

ascii85.go

func Decode

func Decode(dst, src []byte, flush bool) (ndst, nsrc int, err error)

Decode decodes src into dst, returning both the number of bytes written to dst and the number consumed from src. If src contains invalid ascii85 data, Decode will return the number of bytes successfully written and a CorruptInputError. Decode ignores space and control characters in src. Often, ascii85-encoded data is wrapped in <~ and ~> symbols. Decode expects these to have been stripped by the caller.

+

If flush is true, Decode assumes that src represents the end of the input stream and processes it completely rather than wait for the completion of another 32-bit block.

+

NewDecoder wraps an io.Reader interface around Decode.

+

func Encode

func Encode(dst, src []byte) int

Encode encodes src into at most MaxEncodedLen(len(src)) bytes of dst, returning the actual number of bytes written.

+

The encoding handles 4-byte chunks, using a special encoding for the last fragment, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder instead.

+

Often, ascii85-encoded data is wrapped in <~ and ~> symbols. Encode does not add these.

+

func MaxEncodedLen

func MaxEncodedLen(n int) int

MaxEncodedLen returns the maximum length of an encoding of n source bytes.

+

func NewDecoder

func NewDecoder(r io.Reader) io.Reader

NewDecoder constructs a new ascii85 stream decoder.

+

func NewEncoder

func NewEncoder(w io.Writer) io.WriteCloser

NewEncoder returns a new ascii85 stream encoder. Data written to the returned writer will be encoded and then written to w. Ascii85 encodings operate in 32-bit blocks; when finished writing, the caller must Close the returned encoder to flush any trailing partial block.

+

type CorruptInputError

type CorruptInputError int64

func (CorruptInputError) Error

func (e CorruptInputError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/encoding/ascii85/ +

+
diff --git a/devdocs/go/encoding%2Fasn1%2Findex.html b/devdocs/go/encoding%2Fasn1%2Findex.html new file mode 100644 index 00000000..d31a7032 --- /dev/null +++ b/devdocs/go/encoding%2Fasn1%2Findex.html @@ -0,0 +1,130 @@ +

Package asn1

Overview

Package asn1 implements parsing of DER-encoded ASN.1 data structures, as defined in ITU-T Rec X.690.

+

See also “A Layman's Guide to a Subset of ASN.1, BER, and DER,” http://luca.ntop.org/Teaching/Appunti/asn1.html.

Index

Package files

asn1.go common.go marshal.go

Constants

ASN.1 tags represent the type of the following object.

+
const (
+    TagBoolean         = 1
+    TagInteger         = 2
+    TagBitString       = 3
+    TagOctetString     = 4
+    TagNull            = 5
+    TagOID             = 6
+    TagEnum            = 10
+    TagUTF8String      = 12
+    TagSequence        = 16
+    TagSet             = 17
+    TagNumericString   = 18
+    TagPrintableString = 19
+    TagT61String       = 20
+    TagIA5String       = 22
+    TagUTCTime         = 23
+    TagGeneralizedTime = 24
+    TagGeneralString   = 27
+    TagBMPString       = 30
+)

ASN.1 class types represent the namespace of the tag.

+
const (
+    ClassUniversal       = 0
+    ClassApplication     = 1
+    ClassContextSpecific = 2
+    ClassPrivate         = 3
+)

Variables

NullBytes contains bytes representing the DER-encoded ASN.1 NULL type.

+
var NullBytes = []byte{TagNull, 0}

NullRawValue is a RawValue with its Tag set to the ASN.1 NULL type tag (5).

+
var NullRawValue = RawValue{Tag: TagNull}

func Marshal

func Marshal(val any) ([]byte, error)

Marshal returns the ASN.1 encoding of val.

+

In addition to the struct tags recognized by Unmarshal, the following can be used:

+
ia5:         causes strings to be marshaled as ASN.1, IA5String values
+omitempty:   causes empty slices to be skipped
+printable:   causes strings to be marshaled as ASN.1, PrintableString values
+utf8:        causes strings to be marshaled as ASN.1, UTF8String values
+utc:         causes time.Time to be marshaled as ASN.1, UTCTime values
+generalized: causes time.Time to be marshaled as ASN.1, GeneralizedTime values
+

func MarshalWithParams 1.10

func MarshalWithParams(val any, params string) ([]byte, error)

MarshalWithParams allows field parameters to be specified for the top-level element. The form of the params is the same as the field tags.

+

func Unmarshal

func Unmarshal(b []byte, val any) (rest []byte, err error)

Unmarshal parses the DER-encoded ASN.1 data structure b and uses the reflect package to fill in an arbitrary value pointed at by val. Because Unmarshal uses the reflect package, the structs being written to must use upper case field names. If val is nil or not a pointer, Unmarshal returns an error.

+

After parsing b, any bytes that were leftover and not used to fill val will be returned in rest. When parsing a SEQUENCE into a struct, any trailing elements of the SEQUENCE that do not have matching fields in val will not be included in rest, as these are considered valid elements of the SEQUENCE and not trailing data.

+

The following tags on struct fields have special meaning to Unmarshal:

+
application specifies that an APPLICATION tag is used
+private     specifies that a PRIVATE tag is used
+default:x   sets the default value for optional integer fields (only used if optional is also present)
+explicit    specifies that an additional, explicit tag wraps the implicit one
+optional    marks the field as ASN.1 OPTIONAL
+set         causes a SET, rather than a SEQUENCE type to be expected
+tag:x       specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC
+

When decoding an ASN.1 value with an IMPLICIT tag into a string field, Unmarshal will default to a PrintableString, which doesn't support characters such as '@' and '&'. To force other encodings, use the following tags:

+
ia5     causes strings to be unmarshaled as ASN.1 IA5String values
+numeric causes strings to be unmarshaled as ASN.1 NumericString values
+utf8    causes strings to be unmarshaled as ASN.1 UTF8String values
+

If the type of the first field of a structure is RawContent then the raw ASN1 contents of the struct will be stored in it.

+

If the name of a slice type ends with "SET" then it's treated as if the "set" tag was set on it. This results in interpreting the type as a SET OF x rather than a SEQUENCE OF x. This can be used with nested slices where a struct tag cannot be given.

+

Other ASN.1 types are not supported; if it encounters them, Unmarshal returns a parse error.

+

func UnmarshalWithParams

func UnmarshalWithParams(b []byte, val any, params string) (rest []byte, err error)

UnmarshalWithParams allows field parameters to be specified for the top-level element. The form of the params is the same as the field tags.

+

type BitString

BitString is the structure to use when you want an ASN.1 BIT STRING type. A bit string is padded up to the nearest byte in memory and the number of valid bits is recorded. Padding bits will be zero.

+
type BitString struct {
+    Bytes     []byte // bits packed into bytes.
+    BitLength int    // length in bits.
+}
+

func (BitString) At

func (b BitString) At(i int) int

At returns the bit at the given index. If the index is out of range it returns 0.

+

func (BitString) RightAlign

func (b BitString) RightAlign() []byte

RightAlign returns a slice where the padding bits are at the beginning. The slice may share memory with the BitString.

+

type Enumerated

An Enumerated is represented as a plain int.

+
type Enumerated int

type Flag

A Flag accepts any data and is set to true if present.

+
type Flag bool

type ObjectIdentifier

An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER.

+
type ObjectIdentifier []int

func (ObjectIdentifier) Equal

func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool

Equal reports whether oi and other represent the same identifier.

+

func (ObjectIdentifier) String 1.3

func (oi ObjectIdentifier) String() string

type RawContent

RawContent is used to signal that the undecoded, DER data needs to be preserved for a struct. To use it, the first field of the struct must have this type. It's an error for any of the other fields to have this type.

+
type RawContent []byte

type RawValue

A RawValue represents an undecoded ASN.1 object.

+
type RawValue struct {
+    Class, Tag int
+    IsCompound bool
+    Bytes      []byte
+    FullBytes  []byte // includes the tag and length
+}
+

type StructuralError

A StructuralError suggests that the ASN.1 data is valid, but the Go type which is receiving it doesn't match.

+
type StructuralError struct {
+    Msg string
+}
+

func (StructuralError) Error

func (e StructuralError) Error() string

type SyntaxError

A SyntaxError suggests that the ASN.1 data is invalid.

+
type SyntaxError struct {
+    Msg string
+}
+

func (SyntaxError) Error

func (e SyntaxError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/encoding/asn1/ +

+
diff --git a/devdocs/go/encoding%2Fbase32%2Findex.html b/devdocs/go/encoding%2Fbase32%2Findex.html new file mode 100644 index 00000000..d0c213b2 --- /dev/null +++ b/devdocs/go/encoding%2Fbase32%2Findex.html @@ -0,0 +1,96 @@ +

Package base32

Overview

Package base32 implements base32 encoding as specified by RFC 4648.

Index

Examples

Encoding.Decode
Encoding.DecodeString
Encoding.Encode
Encoding.EncodeToString
NewEncoder

Package files

base32.go

Constants

const (
+    StdPadding rune = '=' // Standard padding character
+    NoPadding  rune = -1  // No padding
+)

Variables

HexEncoding is the “Extended Hex Alphabet” defined in RFC 4648. It is typically used in DNS.

+
var HexEncoding = NewEncoding("0123456789ABCDEFGHIJKLMNOPQRSTUV")

StdEncoding is the standard base32 encoding, as defined in RFC 4648.

+
var StdEncoding = NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")

func NewDecoder

func NewDecoder(enc *Encoding, r io.Reader) io.Reader

NewDecoder constructs a new base32 stream decoder.

+

func NewEncoder

func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser

NewEncoder returns a new base32 stream encoder. Data written to the returned writer will be encoded using enc and then written to w. Base32 encodings operate in 5-byte blocks; when finished writing, the caller must Close the returned encoder to flush any partially written blocks.

Example +

Code:

input := []byte("foo\x00bar")
+encoder := base32.NewEncoder(base32.StdEncoding, os.Stdout)
+encoder.Write(input)
+// Must close the encoder when finished to flush any partial blocks.
+// If you comment out the following line, the last partial block "r"
+// won't be encoded.
+encoder.Close()
+

Output:

MZXW6ADCMFZA====
+

type CorruptInputError

type CorruptInputError int64

func (CorruptInputError) Error

func (e CorruptInputError) Error() string

type Encoding

An Encoding is a radix 32 encoding/decoding scheme, defined by a 32-character alphabet. The most common is the "base32" encoding introduced for SASL GSSAPI and standardized in RFC 4648. The alternate "base32hex" encoding is used in DNSSEC.

+
type Encoding struct {
+    // contains filtered or unexported fields
+}
+

func NewEncoding

func NewEncoding(encoder string) *Encoding

NewEncoding returns a new padded Encoding defined by the given alphabet, which must be a 32-byte string that contains unique byte values and does not contain the padding character or CR / LF ('\r', '\n'). The alphabet is treated as a sequence of byte values without any special treatment for multi-byte UTF-8. The resulting Encoding uses the default padding character ('='), which may be changed or disabled via Encoding.WithPadding.

+

func (*Encoding) AppendDecode 1.22

func (enc *Encoding) AppendDecode(dst, src []byte) ([]byte, error)

AppendDecode appends the base32 decoded src to dst and returns the extended buffer. If the input is malformed, it returns the partially decoded src and an error.

+

func (*Encoding) AppendEncode 1.22

func (enc *Encoding) AppendEncode(dst, src []byte) []byte

AppendEncode appends the base32 encoded src to dst and returns the extended buffer.

+

func (*Encoding) Decode

func (enc *Encoding) Decode(dst, src []byte) (n int, err error)

Decode decodes src using the encoding enc. It writes at most Encoding.DecodedLen(len(src)) bytes to dst and returns the number of bytes written. If src contains invalid base32 data, it will return the number of bytes successfully written and CorruptInputError. Newline characters (\r and \n) are ignored.

Example +

Code:

str := "JBSWY3DPFQQHO33SNRSCC==="
+dst := make([]byte, base32.StdEncoding.DecodedLen(len(str)))
+n, err := base32.StdEncoding.Decode(dst, []byte(str))
+if err != nil {
+    fmt.Println("decode error:", err)
+    return
+}
+dst = dst[:n]
+fmt.Printf("%q\n", dst)
+

Output:

"Hello, world!"
+

func (*Encoding) DecodeString

func (enc *Encoding) DecodeString(s string) ([]byte, error)

DecodeString returns the bytes represented by the base32 string s.

Example +

Code:

str := "ONXW2ZJAMRQXIYJAO5UXI2BAAAQGC3TEEDX3XPY="
+data, err := base32.StdEncoding.DecodeString(str)
+if err != nil {
+    fmt.Println("error:", err)
+    return
+}
+fmt.Printf("%q\n", data)
+

Output:

"some data with \x00 and \ufeff"
+

func (*Encoding) DecodedLen

func (enc *Encoding) DecodedLen(n int) int

DecodedLen returns the maximum length in bytes of the decoded data corresponding to n bytes of base32-encoded data.

+

func (*Encoding) Encode

func (enc *Encoding) Encode(dst, src []byte)

Encode encodes src using the encoding enc, writing Encoding.EncodedLen(len(src)) bytes to dst.

+

The encoding pads the output to a multiple of 8 bytes, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder instead.

Example +

Code:

data := []byte("Hello, world!")
+dst := make([]byte, base32.StdEncoding.EncodedLen(len(data)))
+base32.StdEncoding.Encode(dst, data)
+fmt.Println(string(dst))
+

Output:

JBSWY3DPFQQHO33SNRSCC===
+

func (*Encoding) EncodeToString

func (enc *Encoding) EncodeToString(src []byte) string

EncodeToString returns the base32 encoding of src.

Example +

Code:

data := []byte("any + old & data")
+str := base32.StdEncoding.EncodeToString(data)
+fmt.Println(str)
+

Output:

MFXHSIBLEBXWYZBAEYQGIYLUME======
+

func (*Encoding) EncodedLen

func (enc *Encoding) EncodedLen(n int) int

EncodedLen returns the length in bytes of the base32 encoding of an input buffer of length n.

+

func (Encoding) WithPadding 1.9

func (enc Encoding) WithPadding(padding rune) *Encoding

WithPadding creates a new encoding identical to enc except with a specified padding character, or NoPadding to disable padding. The padding character must not be '\r' or '\n', must not be contained in the encoding's alphabet, must not be negative, and must be a rune equal or below '\xff'. Padding characters above '\x7f' are encoded as their exact byte value rather than using the UTF-8 representation of the codepoint.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/encoding/base32/ +

+
diff --git a/devdocs/go/encoding%2Fbase64%2Findex.html b/devdocs/go/encoding%2Fbase64%2Findex.html new file mode 100644 index 00000000..91acad34 --- /dev/null +++ b/devdocs/go/encoding%2Fbase64%2Findex.html @@ -0,0 +1,114 @@ +

Package base64

Overview

Package base64 implements base64 encoding as specified by RFC 4648.

Example +

Code:

msg := "Hello, 世界"
+encoded := base64.StdEncoding.EncodeToString([]byte(msg))
+fmt.Println(encoded)
+decoded, err := base64.StdEncoding.DecodeString(encoded)
+if err != nil {
+    fmt.Println("decode error:", err)
+    return
+}
+fmt.Println(string(decoded))
+

Output:

SGVsbG8sIOS4lueVjA==
+Hello, 世界
+

Index

Examples

Package
Encoding.Decode
Encoding.DecodeString
Encoding.Encode
Encoding.EncodeToString
NewEncoder

Package files

base64.go

Constants

const (
+    StdPadding rune = '=' // Standard padding character
+    NoPadding  rune = -1  // No padding
+)

Variables

RawStdEncoding is the standard raw, unpadded base64 encoding, as defined in RFC 4648 section 3.2. This is the same as StdEncoding but omits padding characters.

+
var RawStdEncoding = StdEncoding.WithPadding(NoPadding)

RawURLEncoding is the unpadded alternate base64 encoding defined in RFC 4648. It is typically used in URLs and file names. This is the same as URLEncoding but omits padding characters.

+
var RawURLEncoding = URLEncoding.WithPadding(NoPadding)

StdEncoding is the standard base64 encoding, as defined in RFC 4648.

+
var StdEncoding = NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")

URLEncoding is the alternate base64 encoding defined in RFC 4648. It is typically used in URLs and file names.

+
var URLEncoding = NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")

func NewDecoder

func NewDecoder(enc *Encoding, r io.Reader) io.Reader

NewDecoder constructs a new base64 stream decoder.

+

func NewEncoder

func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser

NewEncoder returns a new base64 stream encoder. Data written to the returned writer will be encoded using enc and then written to w. Base64 encodings operate in 4-byte blocks; when finished writing, the caller must Close the returned encoder to flush any partially written blocks.

Example +

Code:

input := []byte("foo\x00bar")
+encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
+encoder.Write(input)
+// Must close the encoder when finished to flush any partial blocks.
+// If you comment out the following line, the last partial block "r"
+// won't be encoded.
+encoder.Close()
+

Output:

Zm9vAGJhcg==
+

type CorruptInputError

type CorruptInputError int64

func (CorruptInputError) Error

func (e CorruptInputError) Error() string

type Encoding

An Encoding is a radix 64 encoding/decoding scheme, defined by a 64-character alphabet. The most common encoding is the "base64" encoding defined in RFC 4648 and used in MIME (RFC 2045) and PEM (RFC 1421). RFC 4648 also defines an alternate encoding, which is the standard encoding with - and _ substituted for + and /.

+
type Encoding struct {
+    // contains filtered or unexported fields
+}
+

func NewEncoding

func NewEncoding(encoder string) *Encoding

NewEncoding returns a new padded Encoding defined by the given alphabet, which must be a 64-byte string that contains unique byte values and does not contain the padding character or CR / LF ('\r', '\n'). The alphabet is treated as a sequence of byte values without any special treatment for multi-byte UTF-8. The resulting Encoding uses the default padding character ('='), which may be changed or disabled via Encoding.WithPadding.

+

func (*Encoding) AppendDecode 1.22

func (enc *Encoding) AppendDecode(dst, src []byte) ([]byte, error)

AppendDecode appends the base64 decoded src to dst and returns the extended buffer. If the input is malformed, it returns the partially decoded src and an error.

+

func (*Encoding) AppendEncode 1.22

func (enc *Encoding) AppendEncode(dst, src []byte) []byte

AppendEncode appends the base64 encoded src to dst and returns the extended buffer.

+

func (*Encoding) Decode

func (enc *Encoding) Decode(dst, src []byte) (n int, err error)

Decode decodes src using the encoding enc. It writes at most Encoding.DecodedLen(len(src)) bytes to dst and returns the number of bytes written. If src contains invalid base64 data, it will return the number of bytes successfully written and CorruptInputError. New line characters (\r and \n) are ignored.

Example +

Code:

str := "SGVsbG8sIHdvcmxkIQ=="
+dst := make([]byte, base64.StdEncoding.DecodedLen(len(str)))
+n, err := base64.StdEncoding.Decode(dst, []byte(str))
+if err != nil {
+    fmt.Println("decode error:", err)
+    return
+}
+dst = dst[:n]
+fmt.Printf("%q\n", dst)
+

Output:

"Hello, world!"
+

func (*Encoding) DecodeString

func (enc *Encoding) DecodeString(s string) ([]byte, error)

DecodeString returns the bytes represented by the base64 string s.

Example +

Code:

str := "c29tZSBkYXRhIHdpdGggACBhbmQg77u/"
+data, err := base64.StdEncoding.DecodeString(str)
+if err != nil {
+    fmt.Println("error:", err)
+    return
+}
+fmt.Printf("%q\n", data)
+

Output:

"some data with \x00 and \ufeff"
+

func (*Encoding) DecodedLen

func (enc *Encoding) DecodedLen(n int) int

DecodedLen returns the maximum length in bytes of the decoded data corresponding to n bytes of base64-encoded data.

+

func (*Encoding) Encode

func (enc *Encoding) Encode(dst, src []byte)

Encode encodes src using the encoding enc, writing Encoding.EncodedLen(len(src)) bytes to dst.

+

The encoding pads the output to a multiple of 4 bytes, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder instead.

Example +

Code:

data := []byte("Hello, world!")
+dst := make([]byte, base64.StdEncoding.EncodedLen(len(data)))
+base64.StdEncoding.Encode(dst, data)
+fmt.Println(string(dst))
+

Output:

SGVsbG8sIHdvcmxkIQ==
+

func (*Encoding) EncodeToString

func (enc *Encoding) EncodeToString(src []byte) string

EncodeToString returns the base64 encoding of src.

Example +

Code:

data := []byte("any + old & data")
+str := base64.StdEncoding.EncodeToString(data)
+fmt.Println(str)
+

Output:

YW55ICsgb2xkICYgZGF0YQ==
+

func (*Encoding) EncodedLen

func (enc *Encoding) EncodedLen(n int) int

EncodedLen returns the length in bytes of the base64 encoding of an input buffer of length n.

+

func (Encoding) Strict 1.8

func (enc Encoding) Strict() *Encoding

Strict creates a new encoding identical to enc except with strict decoding enabled. In this mode, the decoder requires that trailing padding bits are zero, as described in RFC 4648 section 3.5.

+

Note that the input is still malleable, as new line characters (CR and LF) are still ignored.

+

func (Encoding) WithPadding 1.5

func (enc Encoding) WithPadding(padding rune) *Encoding

WithPadding creates a new encoding identical to enc except with a specified padding character, or NoPadding to disable padding. The padding character must not be '\r' or '\n', must not be contained in the encoding's alphabet, must not be negative, and must be a rune equal or below '\xff'. Padding characters above '\x7f' are encoded as their exact byte value rather than using the UTF-8 representation of the codepoint.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/encoding/base64/ +

+
diff --git a/devdocs/go/encoding%2Fbinary%2Findex.html b/devdocs/go/encoding%2Fbinary%2Findex.html new file mode 100644 index 00000000..d018b748 --- /dev/null +++ b/devdocs/go/encoding%2Fbinary%2Findex.html @@ -0,0 +1,217 @@ +

Package binary

Overview

Package binary implements simple translation between numbers and byte sequences and encoding and decoding of varints.

+

Numbers are translated by reading and writing fixed-size values. A fixed-size value is either a fixed-size arithmetic type (bool, int8, uint8, int16, float32, complex64, ...) or an array or struct containing only fixed-size values.

+

The varint functions encode and decode single integer values using a variable-length encoding; smaller values require fewer bytes. For a specification, see https://developers.google.com/protocol-buffers/docs/encoding.

+

This package favors simplicity over efficiency. Clients that require high-performance serialization, especially for large data structures, should look at more advanced solutions such as the encoding/gob package or google.golang.org/protobuf for protocol buffers.

Index

Examples

ByteOrder (Get)
ByteOrder (Put)
PutUvarint
PutVarint
Read
Read (Multi)
Uvarint
Varint
Write
Write (Multi)

Package files

binary.go native_endian_little.go varint.go

Constants

MaxVarintLenN is the maximum length of a varint-encoded N-bit integer.

+
const (
+    MaxVarintLen16 = 3
+    MaxVarintLen32 = 5
+    MaxVarintLen64 = 10
+)

Variables

BigEndian is the big-endian implementation of ByteOrder and AppendByteOrder.

+
var BigEndian bigEndian

LittleEndian is the little-endian implementation of ByteOrder and AppendByteOrder.

+
var LittleEndian littleEndian

NativeEndian is the native-endian implementation of ByteOrder and AppendByteOrder.

+
var NativeEndian nativeEndian

func AppendUvarint 1.19

func AppendUvarint(buf []byte, x uint64) []byte

AppendUvarint appends the varint-encoded form of x, as generated by PutUvarint, to buf and returns the extended buffer.

+

func AppendVarint 1.19

func AppendVarint(buf []byte, x int64) []byte

AppendVarint appends the varint-encoded form of x, as generated by PutVarint, to buf and returns the extended buffer.

+

func PutUvarint

func PutUvarint(buf []byte, x uint64) int

PutUvarint encodes a uint64 into buf and returns the number of bytes written. If the buffer is too small, PutUvarint will panic.

Example +

Code:

buf := make([]byte, binary.MaxVarintLen64)
+
+for _, x := range []uint64{1, 2, 127, 128, 255, 256} {
+    n := binary.PutUvarint(buf, x)
+    fmt.Printf("%x\n", buf[:n])
+}
+

Output:

01
+02
+7f
+8001
+ff01
+8002
+

func PutVarint

func PutVarint(buf []byte, x int64) int

PutVarint encodes an int64 into buf and returns the number of bytes written. If the buffer is too small, PutVarint will panic.

Example +

Code:

buf := make([]byte, binary.MaxVarintLen64)
+
+for _, x := range []int64{-65, -64, -2, -1, 0, 1, 2, 63, 64} {
+    n := binary.PutVarint(buf, x)
+    fmt.Printf("%x\n", buf[:n])
+}
+

Output:

8101
+7f
+03
+01
+00
+02
+04
+7e
+8001
+

func Read

func Read(r io.Reader, order ByteOrder, data any) error

Read reads structured binary data from r into data. Data must be a pointer to a fixed-size value or a slice of fixed-size values. Bytes read from r are decoded using the specified byte order and written to successive fields of the data. When decoding boolean values, a zero byte is decoded as false, and any other non-zero byte is decoded as true. When reading into structs, the field data for fields with blank (_) field names is skipped; i.e., blank field names may be used for padding. When reading into a struct, all non-blank fields must be exported or Read may panic.

+

The error is io.EOF only if no bytes were read. If an io.EOF happens after reading some but not all the bytes, Read returns io.ErrUnexpectedEOF.

Example +

Code:

var pi float64
+b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40}
+buf := bytes.NewReader(b)
+err := binary.Read(buf, binary.LittleEndian, &pi)
+if err != nil {
+    fmt.Println("binary.Read failed:", err)
+}
+fmt.Print(pi)
+

Output:

3.141592653589793
+

Example (Multi) +

Code:

b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40, 0xff, 0x01, 0x02, 0x03, 0xbe, 0xef}
+r := bytes.NewReader(b)
+
+var data struct {
+    PI   float64
+    Uate uint8
+    Mine [3]byte
+    Too  uint16
+}
+
+if err := binary.Read(r, binary.LittleEndian, &data); err != nil {
+    fmt.Println("binary.Read failed:", err)
+}
+
+fmt.Println(data.PI)
+fmt.Println(data.Uate)
+fmt.Printf("% x\n", data.Mine)
+fmt.Println(data.Too)
+

Output:

3.141592653589793
+255
+01 02 03
+61374
+

func ReadUvarint

func ReadUvarint(r io.ByteReader) (uint64, error)

ReadUvarint reads an encoded unsigned integer from r and returns it as a uint64. The error is io.EOF only if no bytes were read. If an io.EOF happens after reading some but not all the bytes, ReadUvarint returns io.ErrUnexpectedEOF.

+

func ReadVarint

func ReadVarint(r io.ByteReader) (int64, error)

ReadVarint reads an encoded signed integer from r and returns it as an int64. The error is io.EOF only if no bytes were read. If an io.EOF happens after reading some but not all the bytes, ReadVarint returns io.ErrUnexpectedEOF.

+

func Size

func Size(v any) int

Size returns how many bytes Write would generate to encode the value v, which must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. If v is neither of these, Size returns -1.

+

func Uvarint

func Uvarint(buf []byte) (uint64, int)

Uvarint decodes a uint64 from buf and returns that value and the number of bytes read (> 0). If an error occurred, the value is 0 and the number of bytes n is <= 0 meaning:

+
n == 0: buf too small
+n  < 0: value larger than 64 bits (overflow)
+        and -n is the number of bytes read
+

Example +

Code:

inputs := [][]byte{
+    {0x01},
+    {0x02},
+    {0x7f},
+    {0x80, 0x01},
+    {0xff, 0x01},
+    {0x80, 0x02},
+}
+for _, b := range inputs {
+    x, n := binary.Uvarint(b)
+    if n != len(b) {
+        fmt.Println("Uvarint did not consume all of in")
+    }
+    fmt.Println(x)
+}
+

Output:

1
+2
+127
+128
+255
+256
+

func Varint

func Varint(buf []byte) (int64, int)

Varint decodes an int64 from buf and returns that value and the number of bytes read (> 0). If an error occurred, the value is 0 and the number of bytes n is <= 0 with the following meaning:

+
n == 0: buf too small
+n  < 0: value larger than 64 bits (overflow)
+        and -n is the number of bytes read
+

Example +

Code:

inputs := [][]byte{
+    {0x81, 0x01},
+    {0x7f},
+    {0x03},
+    {0x01},
+    {0x00},
+    {0x02},
+    {0x04},
+    {0x7e},
+    {0x80, 0x01},
+}
+for _, b := range inputs {
+    x, n := binary.Varint(b)
+    if n != len(b) {
+        fmt.Println("Varint did not consume all of in")
+    }
+    fmt.Println(x)
+}
+

Output:

-65
+-64
+-2
+-1
+0
+1
+2
+63
+64
+

func Write

func Write(w io.Writer, order ByteOrder, data any) error

Write writes the binary representation of data into w. Data must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. Boolean values encode as one byte: 1 for true, and 0 for false. Bytes written to w are encoded using the specified byte order and read from successive fields of the data. When writing structs, zero values are written for fields with blank (_) field names.

Example +

Code:

buf := new(bytes.Buffer)
+var pi float64 = math.Pi
+err := binary.Write(buf, binary.LittleEndian, pi)
+if err != nil {
+    fmt.Println("binary.Write failed:", err)
+}
+fmt.Printf("% x", buf.Bytes())
+

Output:

18 2d 44 54 fb 21 09 40
+

Example (Multi) +

Code:

buf := new(bytes.Buffer)
+var data = []any{
+    uint16(61374),
+    int8(-54),
+    uint8(254),
+}
+for _, v := range data {
+    err := binary.Write(buf, binary.LittleEndian, v)
+    if err != nil {
+        fmt.Println("binary.Write failed:", err)
+    }
+}
+fmt.Printf("%x", buf.Bytes())
+

Output:

beefcafe
+

type AppendByteOrder 1.19

AppendByteOrder specifies how to append 16-, 32-, or 64-bit unsigned integers into a byte slice.

+

It is implemented by LittleEndian, BigEndian, and NativeEndian.

+
type AppendByteOrder interface {
+    AppendUint16([]byte, uint16) []byte
+    AppendUint32([]byte, uint32) []byte
+    AppendUint64([]byte, uint64) []byte
+    String() string
+}

type ByteOrder

A ByteOrder specifies how to convert byte slices into 16-, 32-, or 64-bit unsigned integers.

+

It is implemented by LittleEndian, BigEndian, and NativeEndian.

+
type ByteOrder interface {
+    Uint16([]byte) uint16
+    Uint32([]byte) uint32
+    Uint64([]byte) uint64
+    PutUint16([]byte, uint16)
+    PutUint32([]byte, uint32)
+    PutUint64([]byte, uint64)
+    String() string
+}

Example (Get) +

Code:

b := []byte{0xe8, 0x03, 0xd0, 0x07}
+x1 := binary.LittleEndian.Uint16(b[0:])
+x2 := binary.LittleEndian.Uint16(b[2:])
+fmt.Printf("%#04x %#04x\n", x1, x2)
+

Output:

0x03e8 0x07d0
+

Example (Put) +

Code:

b := make([]byte, 4)
+binary.LittleEndian.PutUint16(b[0:], 0x03e8)
+binary.LittleEndian.PutUint16(b[2:], 0x07d0)
+fmt.Printf("% x\n", b)
+

Output:

e8 03 d0 07
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/encoding/binary/ +

+
diff --git a/devdocs/go/encoding%2Fcsv%2Findex.html b/devdocs/go/encoding%2Fcsv%2Findex.html new file mode 100644 index 00000000..ce4b7e36 --- /dev/null +++ b/devdocs/go/encoding%2Fcsv%2Findex.html @@ -0,0 +1,239 @@ +

Package csv

Overview

Package csv reads and writes comma-separated values (CSV) files. There are many kinds of CSV files; this package supports the format described in RFC 4180.

+

A csv file contains zero or more records of one or more fields per record. Each record is separated by the newline character. The final record may optionally be followed by a newline character.

+
field1,field2,field3
+

White space is considered part of a field.

+

Carriage returns before newline characters are silently removed.

+

Blank lines are ignored. A line with only whitespace characters (excluding the ending newline character) is not considered a blank line.

+

Fields which start and stop with the quote character " are called quoted-fields. The beginning and ending quote are not part of the field.

+

The source:

+
normal string,"quoted-field"
+

results in the fields

+
{`normal string`, `quoted-field`}
+

Within a quoted-field a quote character followed by a second quote character is considered a single quote.

+
"the ""word"" is true","a ""quoted-field"""
+

results in

+
{`the "word" is true`, `a "quoted-field"`}
+

Newlines and commas may be included in a quoted-field

+
"Multi-line
+field","comma is ,"
+

results in

+
{`Multi-line
+field`, `comma is ,`}
+

Index

Examples

Reader
Reader.ReadAll
Reader (Options)
Writer
Writer.WriteAll

Package files

reader.go writer.go

Variables

These are the errors that can be returned in [ParseError.Err].

+
var (
+    ErrBareQuote  = errors.New("bare \" in non-quoted-field")
+    ErrQuote      = errors.New("extraneous or missing \" in quoted-field")
+    ErrFieldCount = errors.New("wrong number of fields")
+
+    // Deprecated: ErrTrailingComma is no longer used.
+    ErrTrailingComma = errors.New("extra delimiter at end of line")
+)

type ParseError

A ParseError is returned for parsing errors. Line and column numbers are 1-indexed.

+
type ParseError struct {
+    StartLine int   // Line where the record starts; added in Go 1.10
+    Line      int   // Line where the error occurred
+    Column    int   // Column (1-based byte index) where the error occurred
+    Err       error // The actual error
+}
+

func (*ParseError) Error

func (e *ParseError) Error() string

func (*ParseError) Unwrap 1.13

func (e *ParseError) Unwrap() error

type Reader

A Reader reads records from a CSV-encoded file.

+

As returned by NewReader, a Reader expects input conforming to RFC 4180. The exported fields can be changed to customize the details before the first call to Reader.Read or Reader.ReadAll.

+

The Reader converts all \r\n sequences in its input to plain \n, including in multiline field values, so that the returned data does not depend on which line-ending convention an input file uses.

+
type Reader struct {
+    // Comma is the field delimiter.
+    // It is set to comma (',') by NewReader.
+    // Comma must be a valid rune and must not be \r, \n,
+    // or the Unicode replacement character (0xFFFD).
+    Comma rune
+
+    // Comment, if not 0, is the comment character. Lines beginning with the
+    // Comment character without preceding whitespace are ignored.
+    // With leading whitespace the Comment character becomes part of the
+    // field, even if TrimLeadingSpace is true.
+    // Comment must be a valid rune and must not be \r, \n,
+    // or the Unicode replacement character (0xFFFD).
+    // It must also not be equal to Comma.
+    Comment rune
+
+    // FieldsPerRecord is the number of expected fields per record.
+    // If FieldsPerRecord is positive, Read requires each record to
+    // have the given number of fields. If FieldsPerRecord is 0, Read sets it to
+    // the number of fields in the first record, so that future records must
+    // have the same field count. If FieldsPerRecord is negative, no check is
+    // made and records may have a variable number of fields.
+    FieldsPerRecord int
+
+    // If LazyQuotes is true, a quote may appear in an unquoted field and a
+    // non-doubled quote may appear in a quoted field.
+    LazyQuotes bool
+
+    // If TrimLeadingSpace is true, leading white space in a field is ignored.
+    // This is done even if the field delimiter, Comma, is white space.
+    TrimLeadingSpace bool
+
+    // ReuseRecord controls whether calls to Read may return a slice sharing
+    // the backing array of the previous call's returned slice for performance.
+    // By default, each call to Read returns newly allocated memory owned by the caller.
+    ReuseRecord bool // Go 1.9
+
+    // Deprecated: TrailingComma is no longer used.
+    TrailingComma bool
+    // contains filtered or unexported fields
+}
+

Example +

Code:

in := `first_name,last_name,username
+"Rob","Pike",rob
+Ken,Thompson,ken
+"Robert","Griesemer","gri"
+`
+r := csv.NewReader(strings.NewReader(in))
+
+for {
+    record, err := r.Read()
+    if err == io.EOF {
+        break
+    }
+    if err != nil {
+        log.Fatal(err)
+    }
+
+    fmt.Println(record)
+}
+

Output:

[first_name last_name username]
+[Rob Pike rob]
+[Ken Thompson ken]
+[Robert Griesemer gri]
+

Example (Options) +

This example shows how csv.Reader can be configured to handle other types of CSV files.

Code:

in := `first_name;last_name;username
+"Rob";"Pike";rob
+# lines beginning with a # character are ignored
+Ken;Thompson;ken
+"Robert";"Griesemer";"gri"
+`
+r := csv.NewReader(strings.NewReader(in))
+r.Comma = ';'
+r.Comment = '#'
+
+records, err := r.ReadAll()
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Print(records)
+

Output:

[[first_name last_name username] [Rob Pike rob] [Ken Thompson ken] [Robert Griesemer gri]]
+

func NewReader

func NewReader(r io.Reader) *Reader

NewReader returns a new Reader that reads from r.

+

func (*Reader) FieldPos 1.17

func (r *Reader) FieldPos(field int) (line, column int)

FieldPos returns the line and column corresponding to the start of the field with the given index in the slice most recently returned by Reader.Read. Numbering of lines and columns starts at 1; columns are counted in bytes, not runes.

+

If this is called with an out-of-bounds index, it panics.

+

func (*Reader) InputOffset 1.19

func (r *Reader) InputOffset() int64

InputOffset returns the input stream byte offset of the current reader position. The offset gives the location of the end of the most recently read row and the beginning of the next row.

+

func (*Reader) Read

func (r *Reader) Read() (record []string, err error)

Read reads one record (a slice of fields) from r. If the record has an unexpected number of fields, Read returns the record along with the error ErrFieldCount. If the record contains a field that cannot be parsed, Read returns a partial record along with the parse error. The partial record contains all fields read before the error. If there is no data left to be read, Read returns nil, io.EOF. If [Reader.ReuseRecord] is true, the returned slice may be shared between multiple calls to Read.

+

func (*Reader) ReadAll

func (r *Reader) ReadAll() (records [][]string, err error)

ReadAll reads all the remaining records from r. Each record is a slice of fields. A successful call returns err == nil, not err == io.EOF. Because ReadAll is defined to read until EOF, it does not treat end of file as an error to be reported.

Example +

Code:

in := `first_name,last_name,username
+"Rob","Pike",rob
+Ken,Thompson,ken
+"Robert","Griesemer","gri"
+`
+r := csv.NewReader(strings.NewReader(in))
+
+records, err := r.ReadAll()
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Print(records)
+

Output:

[[first_name last_name username] [Rob Pike rob] [Ken Thompson ken] [Robert Griesemer gri]]
+

type Writer

A Writer writes records using CSV encoding.

+

As returned by NewWriter, a Writer writes records terminated by a newline and uses ',' as the field delimiter. The exported fields can be changed to customize the details before the first call to Writer.Write or Writer.WriteAll.

+

[Writer.Comma] is the field delimiter.

+

If [Writer.UseCRLF] is true, the Writer ends each output line with \r\n instead of \n.

+

The writes of individual records are buffered. After all data has been written, the client should call the Writer.Flush method to guarantee all data has been forwarded to the underlying io.Writer. Any errors that occurred should be checked by calling the Writer.Error method.

+
type Writer struct {
+    Comma   rune // Field delimiter (set to ',' by NewWriter)
+    UseCRLF bool // True to use \r\n as the line terminator
+    // contains filtered or unexported fields
+}
+

Example +

Code:

records := [][]string{
+    {"first_name", "last_name", "username"},
+    {"Rob", "Pike", "rob"},
+    {"Ken", "Thompson", "ken"},
+    {"Robert", "Griesemer", "gri"},
+}
+
+w := csv.NewWriter(os.Stdout)
+
+for _, record := range records {
+    if err := w.Write(record); err != nil {
+        log.Fatalln("error writing record to csv:", err)
+    }
+}
+
+// Write any buffered data to the underlying writer (standard output).
+w.Flush()
+
+if err := w.Error(); err != nil {
+    log.Fatal(err)
+}
+

Output:

first_name,last_name,username
+Rob,Pike,rob
+Ken,Thompson,ken
+Robert,Griesemer,gri
+

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter returns a new Writer that writes to w.

+

func (*Writer) Error 1.1

func (w *Writer) Error() error

Error reports any error that has occurred during a previous Writer.Write or Writer.Flush.

+

func (*Writer) Flush

func (w *Writer) Flush()

Flush writes any buffered data to the underlying io.Writer. To check if an error occurred during Flush, call Writer.Error.

+

func (*Writer) Write

func (w *Writer) Write(record []string) error

Write writes a single CSV record to w along with any necessary quoting. A record is a slice of strings with each string being one field. Writes are buffered, so Writer.Flush must eventually be called to ensure that the record is written to the underlying io.Writer.

+

func (*Writer) WriteAll

func (w *Writer) WriteAll(records [][]string) error

WriteAll writes multiple CSV records to w using Writer.Write and then calls Writer.Flush, returning any error from the Flush.

Example +

Code:

records := [][]string{
+    {"first_name", "last_name", "username"},
+    {"Rob", "Pike", "rob"},
+    {"Ken", "Thompson", "ken"},
+    {"Robert", "Griesemer", "gri"},
+}
+
+w := csv.NewWriter(os.Stdout)
+w.WriteAll(records) // calls Flush internally
+
+if err := w.Error(); err != nil {
+    log.Fatalln("error writing csv:", err)
+}
+

Output:

first_name,last_name,username
+Rob,Pike,rob
+Ken,Thompson,ken
+Robert,Griesemer,gri
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/encoding/csv/ +

+
diff --git a/devdocs/go/encoding%2Fgob%2Findex.html b/devdocs/go/encoding%2Fgob%2Findex.html new file mode 100644 index 00000000..867a1b6c --- /dev/null +++ b/devdocs/go/encoding%2Fgob%2Findex.html @@ -0,0 +1,374 @@ +

Package gob

Overview

Package gob manages streams of gobs - binary values exchanged between an Encoder (transmitter) and a Decoder (receiver). A typical use is transporting arguments and results of remote procedure calls (RPCs) such as those provided by net/rpc.

+

The implementation compiles a custom codec for each data type in the stream and is most efficient when a single Encoder is used to transmit a stream of values, amortizing the cost of compilation.

+

Basics

A stream of gobs is self-describing. Each data item in the stream is preceded by a specification of its type, expressed in terms of a small set of predefined types. Pointers are not transmitted, but the things they point to are transmitted; that is, the values are flattened. Nil pointers are not permitted, as they have no value. Recursive types work fine, but recursive values (data with cycles) are problematic. This may change.

+

To use gobs, create an Encoder and present it with a series of data items as values or addresses that can be dereferenced to values. The Encoder makes sure all type information is sent before it is needed. At the receive side, a Decoder retrieves values from the encoded stream and unpacks them into local variables.

+

Types and Values

The source and destination values/types need not correspond exactly. For structs, fields (identified by name) that are in the source but absent from the receiving variable will be ignored. Fields that are in the receiving variable but missing from the transmitted type or value will be ignored in the destination. If a field with the same name is present in both, their types must be compatible. Both the receiver and transmitter will do all necessary indirection and dereferencing to convert between gobs and actual Go values. For instance, a gob type that is schematically,

+
struct { A, B int }
+

can be sent from or received into any of these Go types:

+
struct { A, B int }	// the same
+*struct { A, B int }	// extra indirection of the struct
+struct { *A, **B int }	// extra indirection of the fields
+struct { A, B int64 }	// different concrete value type; see below
+

It may also be received into any of these:

+
struct { A, B int }	// the same
+struct { B, A int }	// ordering doesn't matter; matching is by name
+struct { A, B, C int }	// extra field (C) ignored
+struct { B int }	// missing field (A) ignored; data will be dropped
+struct { B, C int }	// missing field (A) ignored; extra field (C) ignored.
+

Attempting to receive into these types will draw a decode error:

+
struct { A int; B uint }	// change of signedness for B
+struct { A int; B float }	// change of type for B
+struct { }			// no field names in common
+struct { C, D int }		// no field names in common
+

Integers are transmitted two ways: arbitrary precision signed integers or arbitrary precision unsigned integers. There is no int8, int16 etc. discrimination in the gob format; there are only signed and unsigned integers. As described below, the transmitter sends the value in a variable-length encoding; the receiver accepts the value and stores it in the destination variable. Floating-point numbers are always sent using IEEE-754 64-bit precision (see below).

+

Signed integers may be received into any signed integer variable: int, int16, etc.; unsigned integers may be received into any unsigned integer variable; and floating point values may be received into any floating point variable. However, the destination variable must be able to represent the value or the decode operation will fail.

+

Structs, arrays and slices are also supported. Structs encode and decode only exported fields. Strings and arrays of bytes are supported with a special, efficient representation (see below). When a slice is decoded, if the existing slice has capacity the slice will be extended in place; if not, a new array is allocated. Regardless, the length of the resulting slice reports the number of elements decoded.

+

In general, if allocation is required, the decoder will allocate memory. If not, it will update the destination variables with values read from the stream. It does not initialize them first, so if the destination is a compound value such as a map, struct, or slice, the decoded values will be merged elementwise into the existing variables.

+

Functions and channels will not be sent in a gob. Attempting to encode such a value at the top level will fail. A struct field of chan or func type is treated exactly like an unexported field and is ignored.

+

Gob can encode a value of any type implementing the GobEncoder or encoding.BinaryMarshaler interfaces by calling the corresponding method, in that order of preference.

+

Gob can decode a value of any type implementing the GobDecoder or encoding.BinaryUnmarshaler interfaces by calling the corresponding method, again in that order of preference.

+

Encoding Details

This section documents the encoding, details that are not important for most users. Details are presented bottom-up.

+

An unsigned integer is sent one of two ways. If it is less than 128, it is sent as a byte with that value. Otherwise it is sent as a minimal-length big-endian (high byte first) byte stream holding the value, preceded by one byte holding the byte count, negated. Thus 0 is transmitted as (00), 7 is transmitted as (07) and 256 is transmitted as (FE 01 00).

+

A boolean is encoded within an unsigned integer: 0 for false, 1 for true.

+

A signed integer, i, is encoded within an unsigned integer, u. Within u, bits 1 upward contain the value; bit 0 says whether they should be complemented upon receipt. The encode algorithm looks like this:

+
var u uint
+if i < 0 {
+	u = (^uint(i) << 1) | 1 // complement i, bit 0 is 1
+} else {
+	u = (uint(i) << 1) // do not complement i, bit 0 is 0
+}
+encodeUnsigned(u)
+

The low bit is therefore analogous to a sign bit, but making it the complement bit instead guarantees that the largest negative integer is not a special case. For example, -129=^128=(^256>>1) encodes as (FE 01 01).

+

Floating-point numbers are always sent as a representation of a float64 value. That value is converted to a uint64 using math.Float64bits. The uint64 is then byte-reversed and sent as a regular unsigned integer. The byte-reversal means the exponent and high-precision part of the mantissa go first. Since the low bits are often zero, this can save encoding bytes. For instance, 17.0 is encoded in only three bytes (FE 31 40).

+

Strings and slices of bytes are sent as an unsigned count followed by that many uninterpreted bytes of the value.

+

All other slices and arrays are sent as an unsigned count followed by that many elements using the standard gob encoding for their type, recursively.

+

Maps are sent as an unsigned count followed by that many key, element pairs. Empty but non-nil maps are sent, so if the receiver has not allocated one already, one will always be allocated on receipt unless the transmitted map is nil and not at the top level.

+

In slices and arrays, as well as maps, all elements, even zero-valued elements, are transmitted, even if all the elements are zero.

+

Structs are sent as a sequence of (field number, field value) pairs. The field value is sent using the standard gob encoding for its type, recursively. If a field has the zero value for its type (except for arrays; see above), it is omitted from the transmission. The field number is defined by the type of the encoded struct: the first field of the encoded type is field 0, the second is field 1, etc. When encoding a value, the field numbers are delta encoded for efficiency and the fields are always sent in order of increasing field number; the deltas are therefore unsigned. The initialization for the delta encoding sets the field number to -1, so an unsigned integer field 0 with value 7 is transmitted as unsigned delta = 1, unsigned value = 7 or (01 07). Finally, after all the fields have been sent a terminating mark denotes the end of the struct. That mark is a delta=0 value, which has representation (00).

+

Interface types are not checked for compatibility; all interface types are treated, for transmission, as members of a single "interface" type, analogous to int or []byte - in effect they're all treated as interface{}. Interface values are transmitted as a string identifying the concrete type being sent (a name that must be pre-defined by calling Register), followed by a byte count of the length of the following data (so the value can be skipped if it cannot be stored), followed by the usual encoding of concrete (dynamic) value stored in the interface value. (A nil interface value is identified by the empty string and transmits no value.) Upon receipt, the decoder verifies that the unpacked concrete item satisfies the interface of the receiving variable.

+

If a value is passed to Encoder.Encode and the type is not a struct (or pointer to struct, etc.), for simplicity of processing it is represented as a struct of one field. The only visible effect of this is to encode a zero byte after the value, just as after the last field of an encoded struct, so that the decode algorithm knows when the top-level value is complete.

+

The representation of types is described below. When a type is defined on a given connection between an Encoder and Decoder, it is assigned a signed integer type id. When Encoder.Encode(v) is called, it makes sure there is an id assigned for the type of v and all its elements and then it sends the pair (typeid, encoded-v) where typeid is the type id of the encoded type of v and encoded-v is the gob encoding of the value v.

+

To define a type, the encoder chooses an unused, positive type id and sends the pair (-type id, encoded-type) where encoded-type is the gob encoding of a wireType description, constructed from these types:

+
type wireType struct {
+	ArrayT           *ArrayType
+	SliceT           *SliceType
+	StructT          *StructType
+	MapT             *MapType
+	GobEncoderT      *gobEncoderType
+	BinaryMarshalerT *gobEncoderType
+	TextMarshalerT   *gobEncoderType
+
+}
+type arrayType struct {
+	CommonType
+	Elem typeId
+	Len  int
+}
+type CommonType struct {
+	Name string // the name of the struct type
+	Id  int    // the id of the type, repeated so it's inside the type
+}
+type sliceType struct {
+	CommonType
+	Elem typeId
+}
+type structType struct {
+	CommonType
+	Field []*fieldType // the fields of the struct.
+}
+type fieldType struct {
+	Name string // the name of the field.
+	Id   int    // the type id of the field, which must be already defined
+}
+type mapType struct {
+	CommonType
+	Key  typeId
+	Elem typeId
+}
+type gobEncoderType struct {
+	CommonType
+}
+

If there are nested type ids, the types for all inner type ids must be defined before the top-level type id is used to describe an encoded-v.

+

For simplicity in setup, the connection is defined to understand these types a priori, as well as the basic gob types int, uint, etc. Their ids are:

+
bool        1
+int         2
+uint        3
+float       4
+[]byte      5
+string      6
+complex     7
+interface   8
+// gap for reserved ids.
+WireType    16
+ArrayType   17
+CommonType  18
+SliceType   19
+StructType  20
+FieldType   21
+// 22 is slice of fieldType.
+MapType     23
+

Finally, each message created by a call to Encode is preceded by an encoded unsigned integer count of the number of bytes remaining in the message. After the initial type name, interface values are wrapped the same way; in effect, the interface value acts like a recursive invocation of Encode.

+

In summary, a gob stream looks like

+
(byteCount (-type id, encoding of a wireType)* (type id, encoding of a value))*
+

where * signifies zero or more repetitions and the type id of a value must be predefined or be defined before the value in the stream.

+

Compatibility: Any future changes to the package will endeavor to maintain compatibility with streams encoded using previous versions. That is, any released version of this package should be able to decode data written with any previously released version, subject to issues such as security fixes. See the Go compatibility document for background: https://golang.org/doc/go1compat

+

See "Gobs of data" for a design discussion of the gob wire format: https://blog.golang.org/gobs-of-data

+

Security

This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, the Decoder does only basic sanity checking on decoded input sizes, and its limits are not configurable. Care should be taken when decoding gob data from untrusted sources, which may consume significant resources.

Example (Basic) +

This example shows the basic usage of the package: Create an encoder, transmit some values, receive them with a decoder.

Code:

package gob_test
+
+import (
+    "bytes"
+    "encoding/gob"
+    "fmt"
+    "log"
+)
+
+type P struct {
+    X, Y, Z int
+    Name    string
+}
+
+type Q struct {
+    X, Y *int32
+    Name string
+}
+
+// This example shows the basic usage of the package: Create an encoder,
+// transmit some values, receive them with a decoder.
+func Example_basic() {
+    // Initialize the encoder and decoder. Normally enc and dec would be
+    // bound to network connections and the encoder and decoder would
+    // run in different processes.
+    var network bytes.Buffer        // Stand-in for a network connection
+    enc := gob.NewEncoder(&network) // Will write to network.
+    dec := gob.NewDecoder(&network) // Will read from network.
+
+    // Encode (send) some values.
+    err := enc.Encode(P{3, 4, 5, "Pythagoras"})
+    if err != nil {
+        log.Fatal("encode error:", err)
+    }
+    err = enc.Encode(P{1782, 1841, 1922, "Treehouse"})
+    if err != nil {
+        log.Fatal("encode error:", err)
+    }
+
+    // Decode (receive) and print the values.
+    var q Q
+    err = dec.Decode(&q)
+    if err != nil {
+        log.Fatal("decode error 1:", err)
+    }
+    fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y)
+    err = dec.Decode(&q)
+    if err != nil {
+        log.Fatal("decode error 2:", err)
+    }
+    fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y)
+
+    // Output:
+    // "Pythagoras": {3, 4}
+    // "Treehouse": {1782, 1841}
+}
+

Example (EncodeDecode) +

This example transmits a value that implements the custom encoding and decoding methods.

Code:

package gob_test
+
+import (
+    "bytes"
+    "encoding/gob"
+    "fmt"
+    "log"
+)
+
+// The Vector type has unexported fields, which the package cannot access.
+// We therefore write a BinaryMarshal/BinaryUnmarshal method pair to allow us
+// to send and receive the type with the gob package. These interfaces are
+// defined in the "encoding" package.
+// We could equivalently use the locally defined GobEncode/GobDecoder
+// interfaces.
+type Vector struct {
+    x, y, z int
+}
+
+func (v Vector) MarshalBinary() ([]byte, error) {
+    // A simple encoding: plain text.
+    var b bytes.Buffer
+    fmt.Fprintln(&b, v.x, v.y, v.z)
+    return b.Bytes(), nil
+}
+
+// UnmarshalBinary modifies the receiver so it must take a pointer receiver.
+func (v *Vector) UnmarshalBinary(data []byte) error {
+    // A simple encoding: plain text.
+    b := bytes.NewBuffer(data)
+    _, err := fmt.Fscanln(b, &v.x, &v.y, &v.z)
+    return err
+}
+
+// This example transmits a value that implements the custom encoding and decoding methods.
+func Example_encodeDecode() {
+    var network bytes.Buffer // Stand-in for the network.
+
+    // Create an encoder and send a value.
+    enc := gob.NewEncoder(&network)
+    err := enc.Encode(Vector{3, 4, 5})
+    if err != nil {
+        log.Fatal("encode:", err)
+    }
+
+    // Create a decoder and receive a value.
+    dec := gob.NewDecoder(&network)
+    var v Vector
+    err = dec.Decode(&v)
+    if err != nil {
+        log.Fatal("decode:", err)
+    }
+    fmt.Println(v)
+
+    // Output:
+    // {3 4 5}
+}
+

Example (Interface) +

This example shows how to encode an interface value. The key distinction from regular types is to register the concrete type that implements the interface.

Code:

package gob_test
+
+import (
+    "bytes"
+    "encoding/gob"
+    "fmt"
+    "log"
+    "math"
+)
+
+type Point struct {
+    X, Y int
+}
+
+func (p Point) Hypotenuse() float64 {
+    return math.Hypot(float64(p.X), float64(p.Y))
+}
+
+type Pythagoras interface {
+    Hypotenuse() float64
+}
+
+// This example shows how to encode an interface value. The key
+// distinction from regular types is to register the concrete type that
+// implements the interface.
+func Example_interface() {
+    var network bytes.Buffer // Stand-in for the network.
+
+    // We must register the concrete type for the encoder and decoder (which would
+    // normally be on a separate machine from the encoder). On each end, this tells the
+    // engine which concrete type is being sent that implements the interface.
+    gob.Register(Point{})
+
+    // Create an encoder and send some values.
+    enc := gob.NewEncoder(&network)
+    for i := 1; i <= 3; i++ {
+        interfaceEncode(enc, Point{3 * i, 4 * i})
+    }
+
+    // Create a decoder and receive some values.
+    dec := gob.NewDecoder(&network)
+    for i := 1; i <= 3; i++ {
+        result := interfaceDecode(dec)
+        fmt.Println(result.Hypotenuse())
+    }
+
+    // Output:
+    // 5
+    // 10
+    // 15
+}
+
+// interfaceEncode encodes the interface value into the encoder.
+func interfaceEncode(enc *gob.Encoder, p Pythagoras) {
+    // The encode will fail unless the concrete type has been
+    // registered. We registered it in the calling function.
+
+    // Pass pointer to interface so Encode sees (and hence sends) a value of
+    // interface type. If we passed p directly it would see the concrete type instead.
+    // See the blog post, "The Laws of Reflection" for background.
+    err := enc.Encode(&p)
+    if err != nil {
+        log.Fatal("encode:", err)
+    }
+}
+
+// interfaceDecode decodes the next interface value from the stream and returns it.
+func interfaceDecode(dec *gob.Decoder) Pythagoras {
+    // The decode will fail unless the concrete type on the wire has been
+    // registered. We registered it in the calling function.
+    var p Pythagoras
+    err := dec.Decode(&p)
+    if err != nil {
+        log.Fatal("decode:", err)
+    }
+    return p
+}
+

Index

Examples

Package (Basic)
Package (EncodeDecode)
Package (Interface)

Package files

dec_helpers.go decode.go decoder.go doc.go enc_helpers.go encode.go encoder.go error.go type.go

func Register

func Register(value any)

Register records a type, identified by a value for that type, under its internal type name. That name will identify the concrete type of a value sent or received as an interface variable. Only types that will be transferred as implementations of interface values need to be registered. Expecting to be used only during initialization, it panics if the mapping between types and names is not a bijection.

+

func RegisterName

func RegisterName(name string, value any)

RegisterName is like Register but uses the provided name rather than the type's default.

+

type CommonType

CommonType holds elements of all types. It is a historical artifact, kept for binary compatibility and exported only for the benefit of the package's encoding of type descriptors. It is not intended for direct use by clients.

+
type CommonType struct {
+    Name string
+    Id   typeId
+}
+

type Decoder

A Decoder manages the receipt of type and data information read from the remote side of a connection. It is safe for concurrent use by multiple goroutines.

+

The Decoder does only basic sanity checking on decoded input sizes, and its limits are not configurable. Take caution when decoding gob data from untrusted sources.

+
type Decoder struct {
+    // contains filtered or unexported fields
+}
+

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads from the io.Reader. If r does not also implement io.ByteReader, it will be wrapped in a bufio.Reader.

+

func (*Decoder) Decode

func (dec *Decoder) Decode(e any) error

Decode reads the next value from the input stream and stores it in the data represented by the empty interface value. If e is nil, the value will be discarded. Otherwise, the value underlying e must be a pointer to the correct type for the next data item received. If the input is at EOF, Decode returns io.EOF and does not modify e.

+

func (*Decoder) DecodeValue

func (dec *Decoder) DecodeValue(v reflect.Value) error

DecodeValue reads the next value from the input stream. If v is the zero reflect.Value (v.Kind() == Invalid), DecodeValue discards the value. Otherwise, it stores the value into v. In that case, v must represent a non-nil pointer to data or be an assignable reflect.Value (v.CanSet()) If the input is at EOF, DecodeValue returns io.EOF and does not modify v.

+

type Encoder

An Encoder manages the transmission of type and data information to the other side of a connection. It is safe for concurrent use by multiple goroutines.

+
type Encoder struct {
+    // contains filtered or unexported fields
+}
+

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that will transmit on the io.Writer.

+

func (*Encoder) Encode

func (enc *Encoder) Encode(e any) error

Encode transmits the data item represented by the empty interface value, guaranteeing that all necessary type information has been transmitted first. Passing a nil pointer to Encoder will panic, as they cannot be transmitted by gob.

+

func (*Encoder) EncodeValue

func (enc *Encoder) EncodeValue(value reflect.Value) error

EncodeValue transmits the data item represented by the reflection value, guaranteeing that all necessary type information has been transmitted first. Passing a nil pointer to EncodeValue will panic, as they cannot be transmitted by gob.

+

type GobDecoder

GobDecoder is the interface describing data that provides its own routine for decoding transmitted values sent by a GobEncoder.

+
type GobDecoder interface {
+    // GobDecode overwrites the receiver, which must be a pointer,
+    // with the value represented by the byte slice, which was written
+    // by GobEncode, usually for the same concrete type.
+    GobDecode([]byte) error
+}

type GobEncoder

GobEncoder is the interface describing data that provides its own representation for encoding values for transmission to a GobDecoder. A type that implements GobEncoder and GobDecoder has complete control over the representation of its data and may therefore contain things such as private fields, channels, and functions, which are not usually transmissible in gob streams.

+

Note: Since gobs can be stored permanently, it is good design to guarantee the encoding used by a GobEncoder is stable as the software evolves. For instance, it might make sense for GobEncode to include a version number in the encoding.

+
type GobEncoder interface {
+    // GobEncode returns a byte slice representing the encoding of the
+    // receiver for transmission to a GobDecoder, usually of the same
+    // concrete type.
+    GobEncode() ([]byte, error)
+}
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/encoding/gob/ +

+
diff --git a/devdocs/go/encoding%2Fhex%2Findex.html b/devdocs/go/encoding%2Fhex%2Findex.html new file mode 100644 index 00000000..57e8bc67 --- /dev/null +++ b/devdocs/go/encoding%2Fhex%2Findex.html @@ -0,0 +1,106 @@ +

Package hex

Overview

Package hex implements hexadecimal encoding and decoding.

Index

Examples

Decode
DecodeString
Dump
Dumper
Encode
EncodeToString

Package files

hex.go

Variables

ErrLength reports an attempt to decode an odd-length input using Decode or DecodeString. The stream-based Decoder returns io.ErrUnexpectedEOF instead of ErrLength.

+
var ErrLength = errors.New("encoding/hex: odd length hex string")

func AppendDecode 1.22

func AppendDecode(dst, src []byte) ([]byte, error)

AppendDecode appends the hexadecimally decoded src to dst and returns the extended buffer. If the input is malformed, it returns the partially decoded src and an error.

+

func AppendEncode 1.22

func AppendEncode(dst, src []byte) []byte

AppendEncode appends the hexadecimally encoded src to dst and returns the extended buffer.

+

func Decode

func Decode(dst, src []byte) (int, error)

Decode decodes src into DecodedLen(len(src)) bytes, returning the actual number of bytes written to dst.

+

Decode expects that src contains only hexadecimal characters and that src has even length. If the input is malformed, Decode returns the number of bytes decoded before the error.

Example +

Code:

src := []byte("48656c6c6f20476f7068657221")
+
+dst := make([]byte, hex.DecodedLen(len(src)))
+n, err := hex.Decode(dst, src)
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%s\n", dst[:n])
+
+

Output:

Hello Gopher!
+

func DecodeString

func DecodeString(s string) ([]byte, error)

DecodeString returns the bytes represented by the hexadecimal string s.

+

DecodeString expects that src contains only hexadecimal characters and that src has even length. If the input is malformed, DecodeString returns the bytes decoded before the error.

Example +

Code:

const s = "48656c6c6f20476f7068657221"
+decoded, err := hex.DecodeString(s)
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%s\n", decoded)
+
+

Output:

Hello Gopher!
+

func DecodedLen

func DecodedLen(x int) int

DecodedLen returns the length of a decoding of x source bytes. Specifically, it returns x / 2.

+

func Dump

func Dump(data []byte) string

Dump returns a string that contains a hex dump of the given data. The format of the hex dump matches the output of `hexdump -C` on the command line.

Example +

Code:

content := []byte("Go is an open source programming language.")
+
+fmt.Printf("%s", hex.Dump(content))
+
+

Output:

00000000  47 6f 20 69 73 20 61 6e  20 6f 70 65 6e 20 73 6f  |Go is an open so|
+00000010  75 72 63 65 20 70 72 6f  67 72 61 6d 6d 69 6e 67  |urce programming|
+00000020  20 6c 61 6e 67 75 61 67  65 2e                    | language.|
+

func Dumper

func Dumper(w io.Writer) io.WriteCloser

Dumper returns a io.WriteCloser that writes a hex dump of all written data to w. The format of the dump matches the output of `hexdump -C` on the command line.

Example +

Code:

lines := []string{
+    "Go is an open source programming language.",
+    "\n",
+    "We encourage all Go users to subscribe to golang-announce.",
+}
+
+stdoutDumper := hex.Dumper(os.Stdout)
+
+defer stdoutDumper.Close()
+
+for _, line := range lines {
+    stdoutDumper.Write([]byte(line))
+}
+
+

Output:

00000000  47 6f 20 69 73 20 61 6e  20 6f 70 65 6e 20 73 6f  |Go is an open so|
+00000010  75 72 63 65 20 70 72 6f  67 72 61 6d 6d 69 6e 67  |urce programming|
+00000020  20 6c 61 6e 67 75 61 67  65 2e 0a 57 65 20 65 6e  | language..We en|
+00000030  63 6f 75 72 61 67 65 20  61 6c 6c 20 47 6f 20 75  |courage all Go u|
+00000040  73 65 72 73 20 74 6f 20  73 75 62 73 63 72 69 62  |sers to subscrib|
+00000050  65 20 74 6f 20 67 6f 6c  61 6e 67 2d 61 6e 6e 6f  |e to golang-anno|
+00000060  75 6e 63 65 2e                                    |unce.|
+

func Encode

func Encode(dst, src []byte) int

Encode encodes src into EncodedLen(len(src)) bytes of dst. As a convenience, it returns the number of bytes written to dst, but this value is always EncodedLen(len(src)). Encode implements hexadecimal encoding.

Example +

Code:

src := []byte("Hello Gopher!")
+
+dst := make([]byte, hex.EncodedLen(len(src)))
+hex.Encode(dst, src)
+
+fmt.Printf("%s\n", dst)
+
+

Output:

48656c6c6f20476f7068657221
+

func EncodeToString

func EncodeToString(src []byte) string

EncodeToString returns the hexadecimal encoding of src.

Example +

Code:

src := []byte("Hello")
+encodedStr := hex.EncodeToString(src)
+
+fmt.Printf("%s\n", encodedStr)
+
+

Output:

48656c6c6f
+

func EncodedLen

func EncodedLen(n int) int

EncodedLen returns the length of an encoding of n source bytes. Specifically, it returns n * 2.

+

func NewDecoder 1.10

func NewDecoder(r io.Reader) io.Reader

NewDecoder returns an io.Reader that decodes hexadecimal characters from r. NewDecoder expects that r contain only an even number of hexadecimal characters.

+

func NewEncoder 1.10

func NewEncoder(w io.Writer) io.Writer

NewEncoder returns an io.Writer that writes lowercase hexadecimal characters to w.

+

type InvalidByteError

InvalidByteError values describe errors resulting from an invalid byte in a hex string.

+
type InvalidByteError byte

func (InvalidByteError) Error

func (e InvalidByteError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/encoding/hex/ +

+
diff --git a/devdocs/go/encoding%2Findex.html b/devdocs/go/encoding%2Findex.html new file mode 100644 index 00000000..c613be2e --- /dev/null +++ b/devdocs/go/encoding%2Findex.html @@ -0,0 +1,33 @@ +

Package encoding

Overview

Package encoding defines interfaces shared by other packages that convert data to and from byte-level and textual representations. Packages that check for these interfaces include encoding/gob, encoding/json, and encoding/xml. As a result, implementing an interface once can make a type useful in multiple encodings. Standard types that implement these interfaces include time.Time and net.IP. The interfaces come in pairs that produce and consume encoded data.

+

Adding encoding/decoding methods to existing types may constitute a breaking change, as they can be used for serialization in communicating with programs written with different library versions. The policy for packages maintained by the Go project is to only allow the addition of marshaling functions if no existing, reasonable marshaling exists.

Index

Package files

encoding.go

type BinaryMarshaler 1.2

BinaryMarshaler is the interface implemented by an object that can marshal itself into a binary form.

+

MarshalBinary encodes the receiver into a binary form and returns the result.

+
type BinaryMarshaler interface {
+    MarshalBinary() (data []byte, err error)
+}

type BinaryUnmarshaler 1.2

BinaryUnmarshaler is the interface implemented by an object that can unmarshal a binary representation of itself.

+

UnmarshalBinary must be able to decode the form generated by MarshalBinary. UnmarshalBinary must copy the data if it wishes to retain the data after returning.

+
type BinaryUnmarshaler interface {
+    UnmarshalBinary(data []byte) error
+}

type TextMarshaler 1.2

TextMarshaler is the interface implemented by an object that can marshal itself into a textual form.

+

MarshalText encodes the receiver into UTF-8-encoded text and returns the result.

+
type TextMarshaler interface {
+    MarshalText() (text []byte, err error)
+}

type TextUnmarshaler 1.2

TextUnmarshaler is the interface implemented by an object that can unmarshal a textual representation of itself.

+

UnmarshalText must be able to decode the form generated by MarshalText. UnmarshalText must copy the text if it wishes to retain the text after returning.

+
type TextUnmarshaler interface {
+    UnmarshalText(text []byte) error
+}

Subdirectories

Name Synopsis
..
ascii85 Package ascii85 implements the ascii85 data encoding as used in the btoa tool and Adobe's PostScript and PDF document formats.
asn1 Package asn1 implements parsing of DER-encoded ASN.1 data structures, as defined in ITU-T Rec X.690.
base32 Package base32 implements base32 encoding as specified by RFC 4648.
base64 Package base64 implements base64 encoding as specified by RFC 4648.
binary Package binary implements simple translation between numbers and byte sequences and encoding and decoding of varints.
csv Package csv reads and writes comma-separated values (CSV) files.
gob Package gob manages streams of gobs - binary values exchanged between an [Encoder] (transmitter) and a [Decoder] (receiver).
hex Package hex implements hexadecimal encoding and decoding.
json Package json implements encoding and decoding of JSON as defined in RFC 7159.
pem Package pem implements the PEM data encoding, which originated in Privacy Enhanced Mail.
xml Package xml implements a simple XML 1.0 parser that understands XML name spaces.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/encoding/ +

+
diff --git a/devdocs/go/encoding%2Fjson%2Findex.html b/devdocs/go/encoding%2Fjson%2Findex.html new file mode 100644 index 00000000..4754164c --- /dev/null +++ b/devdocs/go/encoding%2Fjson%2Findex.html @@ -0,0 +1,640 @@ +

Package json

Overview

Package json implements encoding and decoding of JSON as defined in RFC 7159. The mapping between JSON and Go values is described in the documentation for the Marshal and Unmarshal functions.

+

See "JSON and Go" for an introduction to this package: https://golang.org/doc/articles/json_and_go.html

Example (CustomMarshalJSON) +

Code:

package json_test
+
+import (
+    "encoding/json"
+    "fmt"
+    "log"
+    "strings"
+)
+
+type Animal int
+
+const (
+    Unknown Animal = iota
+    Gopher
+    Zebra
+)
+
+func (a *Animal) UnmarshalJSON(b []byte) error {
+    var s string
+    if err := json.Unmarshal(b, &s); err != nil {
+        return err
+    }
+    switch strings.ToLower(s) {
+    default:
+        *a = Unknown
+    case "gopher":
+        *a = Gopher
+    case "zebra":
+        *a = Zebra
+    }
+
+    return nil
+}
+
+func (a Animal) MarshalJSON() ([]byte, error) {
+    var s string
+    switch a {
+    default:
+        s = "unknown"
+    case Gopher:
+        s = "gopher"
+    case Zebra:
+        s = "zebra"
+    }
+
+    return json.Marshal(s)
+}
+
+func Example_customMarshalJSON() {
+    blob := `["gopher","armadillo","zebra","unknown","gopher","bee","gopher","zebra"]`
+    var zoo []Animal
+    if err := json.Unmarshal([]byte(blob), &zoo); err != nil {
+        log.Fatal(err)
+    }
+
+    census := make(map[Animal]int)
+    for _, animal := range zoo {
+        census[animal] += 1
+    }
+
+    fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras:  %d\n* Unknown: %d\n",
+        census[Gopher], census[Zebra], census[Unknown])
+
+    // Output:
+    // Zoo Census:
+    // * Gophers: 3
+    // * Zebras:  2
+    // * Unknown: 3
+}
+

Example (TextMarshalJSON) +

Code:

package json_test
+
+import (
+    "encoding/json"
+    "fmt"
+    "log"
+    "strings"
+)
+
+type Size int
+
+const (
+    Unrecognized Size = iota
+    Small
+    Large
+)
+
+func (s *Size) UnmarshalText(text []byte) error {
+    switch strings.ToLower(string(text)) {
+    default:
+        *s = Unrecognized
+    case "small":
+        *s = Small
+    case "large":
+        *s = Large
+    }
+    return nil
+}
+
+func (s Size) MarshalText() ([]byte, error) {
+    var name string
+    switch s {
+    default:
+        name = "unrecognized"
+    case Small:
+        name = "small"
+    case Large:
+        name = "large"
+    }
+    return []byte(name), nil
+}
+
+func Example_textMarshalJSON() {
+    blob := `["small","regular","large","unrecognized","small","normal","small","large"]`
+    var inventory []Size
+    if err := json.Unmarshal([]byte(blob), &inventory); err != nil {
+        log.Fatal(err)
+    }
+
+    counts := make(map[Size]int)
+    for _, size := range inventory {
+        counts[size] += 1
+    }
+
+    fmt.Printf("Inventory Counts:\n* Small:        %d\n* Large:        %d\n* Unrecognized: %d\n",
+        counts[Small], counts[Large], counts[Unrecognized])
+
+    // Output:
+    // Inventory Counts:
+    // * Small:        3
+    // * Large:        2
+    // * Unrecognized: 3
+}
+

Index

Examples

Decoder
Decoder.Decode (Stream)
Decoder.Token
HTMLEscape
Indent
Marshal
MarshalIndent
RawMessage (Marshal)
RawMessage (Unmarshal)
Unmarshal
Valid
Package (CustomMarshalJSON)
Package (TextMarshalJSON)

Package files

decode.go encode.go fold.go indent.go scanner.go stream.go tables.go tags.go

func Compact

func Compact(dst *bytes.Buffer, src []byte) error

Compact appends to dst the JSON-encoded src with insignificant space characters elided.

+

func HTMLEscape

func HTMLEscape(dst *bytes.Buffer, src []byte)

HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 so that the JSON will be safe to embed inside HTML <script> tags. For historical reasons, web browsers don't honor standard HTML escaping within <script> tags, so an alternative JSON encoding must be used.

Example +

Code:

var out bytes.Buffer
+json.HTMLEscape(&out, []byte(`{"Name":"<b>HTML content</b>"}`))
+out.WriteTo(os.Stdout)
+

Output:

{"Name":"\u003cb\u003eHTML content\u003c/b\u003e"}
+

func Indent

func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error

Indent appends to dst an indented form of the JSON-encoded src. Each element in a JSON object or array begins on a new, indented line beginning with prefix followed by one or more copies of indent according to the indentation nesting. The data appended to dst does not begin with the prefix nor any indentation, to make it easier to embed inside other formatted JSON data. Although leading space characters (space, tab, carriage return, newline) at the beginning of src are dropped, trailing space characters at the end of src are preserved and copied to dst. For example, if src has no trailing spaces, neither will dst; if src ends in a trailing newline, so will dst.

Example +

Code:

type Road struct {
+    Name   string
+    Number int
+}
+roads := []Road{
+    {"Diamond Fork", 29},
+    {"Sheep Creek", 51},
+}
+
+b, err := json.Marshal(roads)
+if err != nil {
+    log.Fatal(err)
+}
+
+var out bytes.Buffer
+json.Indent(&out, b, "=", "\t")
+out.WriteTo(os.Stdout)
+

Output:

[
+=	{
+=		"Name": "Diamond Fork",
+=		"Number": 29
+=	},
+=	{
+=		"Name": "Sheep Creek",
+=		"Number": 51
+=	}
+=]
+

func Marshal

func Marshal(v any) ([]byte, error)

Marshal returns the JSON encoding of v.

+

Marshal traverses the value v recursively. If an encountered value implements Marshaler and is not a nil pointer, Marshal calls [Marshaler.MarshalJSON] to produce JSON. If no [Marshaler.MarshalJSON] method is present but the value implements encoding.TextMarshaler instead, Marshal calls encoding.TextMarshaler.MarshalText and encodes the result as a JSON string. The nil pointer exception is not strictly necessary but mimics a similar, necessary exception in the behavior of [Unmarshaler.UnmarshalJSON].

+

Otherwise, Marshal uses the following type-dependent default encodings:

+

Boolean values encode as JSON booleans.

+

Floating point, integer, and Number values encode as JSON numbers. NaN and +/-Inf values will return an UnsupportedValueError.

+

String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. So that the JSON will be safe to embed inside HTML <script> tags, the string is encoded using HTMLEscape, which replaces "<", ">", "&", U+2028, and U+2029 are escaped to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029". This replacement can be disabled when using an Encoder, by calling Encoder.SetEscapeHTML(false).

+

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

+

Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below.

+

The encoding of each struct field can be customized by the format string stored under the "json" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name.

+

The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

+

As a special case, if the field tag is "-", the field is always omitted. Note that a field with name "-" can still be generated using the tag "-,".

+

Examples of struct field tags and their meanings:

+
// Field appears in JSON as key "myName".
+Field int `json:"myName"`
+
+// Field appears in JSON as key "myName" and
+// the field is omitted from the object if its value is empty,
+// as defined above.
+Field int `json:"myName,omitempty"`
+
+// Field appears in JSON as key "Field" (the default), but
+// the field is skipped if empty.
+// Note the leading comma.
+Field int `json:",omitempty"`
+
+// Field is ignored by this package.
+Field int `json:"-"`
+
+// Field appears in JSON as key "-".
+Field int `json:"-,"`
+

The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:

+
Int64String int64 `json:",string"`
+

The key name will be used if it's a non-empty string consisting of only Unicode letters, digits, and ASCII punctuation except quotation marks, backslash, and comma.

+

Embedded struct fields are usually marshaled as if their inner exported fields were fields in the outer struct, subject to the usual Go visibility rules amended as described in the next paragraph. An anonymous struct field with a name given in its JSON tag is treated as having that name, rather than being anonymous. An anonymous struct field of interface type is treated the same as having that type as its name, rather than being anonymous.

+

The Go visibility rules for struct fields are amended for JSON when deciding which field to marshal or unmarshal. If there are multiple fields at the same level, and that level is the least nested (and would therefore be the nesting level selected by the usual Go rules), the following extra rules apply:

+

1) Of those fields, if any are JSON-tagged, only tagged fields are considered, even if there are multiple untagged fields that would otherwise conflict.

+

2) If there is exactly one field (tagged or not according to the first rule), that is selected.

+

3) Otherwise there are multiple fields, and all are ignored; no error occurs.

+

Handling of anonymous struct fields is new in Go 1.1. Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of an anonymous struct field in both current and earlier versions, give the field a JSON tag of "-".

+

Map values encode as JSON objects. The map's key type must either be a string, an integer type, or implement encoding.TextMarshaler. The map keys are sorted and used as JSON object keys by applying the following rules, subject to the UTF-8 coercion described for string values above:

+

Pointer values encode as the value pointed to. A nil pointer encodes as the null JSON value.

+

Interface values encode as the value contained in the interface. A nil interface value encodes as the null JSON value.

+

Channel, complex, and function values cannot be encoded in JSON. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError.

+

JSON cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an error.

Example +

Code:

type ColorGroup struct {
+    ID     int
+    Name   string
+    Colors []string
+}
+group := ColorGroup{
+    ID:     1,
+    Name:   "Reds",
+    Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
+}
+b, err := json.Marshal(group)
+if err != nil {
+    fmt.Println("error:", err)
+}
+os.Stdout.Write(b)
+

Output:

{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
+

func MarshalIndent

func MarshalIndent(v any, prefix, indent string) ([]byte, error)

MarshalIndent is like Marshal but applies Indent to format the output. Each JSON element in the output will begin on a new line beginning with prefix followed by one or more copies of indent according to the indentation nesting.

Example +

Code:

data := map[string]int{
+    "a": 1,
+    "b": 2,
+}
+
+b, err := json.MarshalIndent(data, "<prefix>", "<indent>")
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Println(string(b))
+

Output:

{
+<prefix><indent>"a": 1,
+<prefix><indent>"b": 2
+<prefix>}
+

func Unmarshal

func Unmarshal(data []byte, v any) error

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

+

Unmarshal uses the inverse of the encodings that Marshal uses, allocating maps, slices, and pointers as necessary, with the following additional rules:

+

To unmarshal JSON into a pointer, Unmarshal first handles the case of the JSON being the JSON literal null. In that case, Unmarshal sets the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into the value pointed at by the pointer. If the pointer is nil, Unmarshal allocates a new value for it to point to.

+

To unmarshal JSON into a value implementing Unmarshaler, Unmarshal calls that value's [Unmarshaler.UnmarshalJSON] method, including when the input is a JSON null. Otherwise, if the value implements encoding.TextUnmarshaler and the input is a JSON quoted string, Unmarshal calls encoding.TextUnmarshaler.UnmarshalText with the unquoted form of the string.

+

To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. By default, object keys which don't have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).

+

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

+

To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice.

+

To unmarshal a JSON array into a Go array, Unmarshal decodes JSON array elements into corresponding Go array elements. If the Go array is smaller than the JSON array, the additional JSON array elements are discarded. If the JSON array is smaller than the Go array, the additional Go array elements are set to zero values.

+

To unmarshal a JSON object into a map, Unmarshal first establishes a map to use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal reuses the existing map, keeping existing entries. Unmarshal then stores key-value pairs from the JSON object into the map. The map's key type must either be any string type, an integer, implement json.Unmarshaler, or implement encoding.TextUnmarshaler.

+

If the JSON-encoded data contain a syntax error, Unmarshal returns a SyntaxError.

+

If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, Unmarshal skips that field and completes the unmarshaling as best it can. If no more serious errors are encountered, Unmarshal returns an UnmarshalTypeError describing the earliest such error. In any case, it's not guaranteed that all the remaining fields following the problematic one will be unmarshaled into the target object.

+

The JSON null value unmarshals into an interface, map, pointer, or slice by setting that Go value to nil. Because null is often used in JSON to mean “not present,” unmarshaling a JSON null into any other Go type has no effect on the value and produces no error.

+

When unmarshaling quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD.

Example +

Code:

var jsonBlob = []byte(`[
+    {"Name": "Platypus", "Order": "Monotremata"},
+    {"Name": "Quoll",    "Order": "Dasyuromorphia"}
+]`)
+type Animal struct {
+    Name  string
+    Order string
+}
+var animals []Animal
+err := json.Unmarshal(jsonBlob, &animals)
+if err != nil {
+    fmt.Println("error:", err)
+}
+fmt.Printf("%+v", animals)
+

Output:

[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
+

func Valid 1.9

func Valid(data []byte) bool

Valid reports whether data is a valid JSON encoding.

Example +

Code:

goodJSON := `{"example": 1}`
+badJSON := `{"example":2:]}}`
+
+fmt.Println(json.Valid([]byte(goodJSON)), json.Valid([]byte(badJSON)))
+

Output:

true false
+

type Decoder

A Decoder reads and decodes JSON values from an input stream.

+
type Decoder struct {
+    // contains filtered or unexported fields
+}
+

Example +

This example uses a Decoder to decode a stream of distinct JSON values.

Code:

const jsonStream = `
+    {"Name": "Ed", "Text": "Knock knock."}
+    {"Name": "Sam", "Text": "Who's there?"}
+    {"Name": "Ed", "Text": "Go fmt."}
+    {"Name": "Sam", "Text": "Go fmt who?"}
+    {"Name": "Ed", "Text": "Go fmt yourself!"}
+`
+type Message struct {
+    Name, Text string
+}
+dec := json.NewDecoder(strings.NewReader(jsonStream))
+for {
+    var m Message
+    if err := dec.Decode(&m); err == io.EOF {
+        break
+    } else if err != nil {
+        log.Fatal(err)
+    }
+    fmt.Printf("%s: %s\n", m.Name, m.Text)
+}
+

Output:

Ed: Knock knock.
+Sam: Who's there?
+Ed: Go fmt.
+Sam: Go fmt who?
+Ed: Go fmt yourself!
+

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads from r.

+

The decoder introduces its own buffering and may read data from r beyond the JSON values requested.

+

func (*Decoder) Buffered 1.1

func (dec *Decoder) Buffered() io.Reader

Buffered returns a reader of the data remaining in the Decoder's buffer. The reader is valid until the next call to Decoder.Decode.

+

func (*Decoder) Decode

func (dec *Decoder) Decode(v any) error

Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.

+

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

Example (Stream) +

This example uses a Decoder to decode a streaming array of JSON objects.

Code:

const jsonStream = `
+    [
+        {"Name": "Ed", "Text": "Knock knock."},
+        {"Name": "Sam", "Text": "Who's there?"},
+        {"Name": "Ed", "Text": "Go fmt."},
+        {"Name": "Sam", "Text": "Go fmt who?"},
+        {"Name": "Ed", "Text": "Go fmt yourself!"}
+    ]
+`
+type Message struct {
+    Name, Text string
+}
+dec := json.NewDecoder(strings.NewReader(jsonStream))
+
+// read open bracket
+t, err := dec.Token()
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%T: %v\n", t, t)
+
+// while the array contains values
+for dec.More() {
+    var m Message
+    // decode an array value (Message)
+    err := dec.Decode(&m)
+    if err != nil {
+        log.Fatal(err)
+    }
+
+    fmt.Printf("%v: %v\n", m.Name, m.Text)
+}
+
+// read closing bracket
+t, err = dec.Token()
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%T: %v\n", t, t)
+
+

Output:

json.Delim: [
+Ed: Knock knock.
+Sam: Who's there?
+Ed: Go fmt.
+Sam: Go fmt who?
+Ed: Go fmt yourself!
+json.Delim: ]
+

func (*Decoder) DisallowUnknownFields 1.10

func (dec *Decoder) DisallowUnknownFields()

DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.

+

func (*Decoder) InputOffset 1.14

func (dec *Decoder) InputOffset() int64

InputOffset returns the input stream byte offset of the current decoder position. The offset gives the location of the end of the most recently returned token and the beginning of the next token.

+

func (*Decoder) More 1.5

func (dec *Decoder) More() bool

More reports whether there is another element in the current array or object being parsed.

+

func (*Decoder) Token 1.5

func (dec *Decoder) Token() (Token, error)

Token returns the next JSON token in the input stream. At the end of the input stream, Token returns nil, io.EOF.

+

Token guarantees that the delimiters [ ] { } it returns are properly nested and matched: if Token encounters an unexpected delimiter in the input, it will return an error.

+

The input stream consists of basic JSON values—bool, string, number, and null—along with delimiters [ ] { } of type Delim to mark the start and end of arrays and objects. Commas and colons are elided.

Example +

This example uses a Decoder to decode a stream of distinct JSON values.

Code:

const jsonStream = `
+    {"Message": "Hello", "Array": [1, 2, 3], "Null": null, "Number": 1.234}
+`
+dec := json.NewDecoder(strings.NewReader(jsonStream))
+for {
+    t, err := dec.Token()
+    if err == io.EOF {
+        break
+    }
+    if err != nil {
+        log.Fatal(err)
+    }
+    fmt.Printf("%T: %v", t, t)
+    if dec.More() {
+        fmt.Printf(" (more)")
+    }
+    fmt.Printf("\n")
+}
+

Output:

json.Delim: { (more)
+string: Message (more)
+string: Hello (more)
+string: Array (more)
+json.Delim: [ (more)
+float64: 1 (more)
+float64: 2 (more)
+float64: 3
+json.Delim: ] (more)
+string: Null (more)
+<nil>: <nil> (more)
+string: Number (more)
+float64: 1.234
+json.Delim: }
+

func (*Decoder) UseNumber 1.1

func (dec *Decoder) UseNumber()

UseNumber causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.

+

type Delim 1.5

A Delim is a JSON array or object delimiter, one of [ ] { or }.

+
type Delim rune

func (Delim) String 1.5

func (d Delim) String() string

type Encoder

An Encoder writes JSON values to an output stream.

+
type Encoder struct {
+    // contains filtered or unexported fields
+}
+

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w.

+

func (*Encoder) Encode

func (enc *Encoder) Encode(v any) error

Encode writes the JSON encoding of v to the stream, followed by a newline character.

+

See the documentation for Marshal for details about the conversion of Go values to JSON.

+

func (*Encoder) SetEscapeHTML 1.7

func (enc *Encoder) SetEscapeHTML(on bool)

SetEscapeHTML specifies whether problematic HTML characters should be escaped inside JSON quoted strings. The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.

+

In non-HTML settings where the escaping interferes with the readability of the output, SetEscapeHTML(false) disables this behavior.

+

func (*Encoder) SetIndent 1.7

func (enc *Encoder) SetIndent(prefix, indent string)

SetIndent instructs the encoder to format each subsequent encoded value as if indented by the package-level function Indent(dst, src, prefix, indent). Calling SetIndent("", "") disables indentation.

+

type InvalidUTF8Error

Before Go 1.2, an InvalidUTF8Error was returned by Marshal when attempting to encode a string value with invalid UTF-8 sequences. As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by replacing invalid bytes with the Unicode replacement rune U+FFFD.

+

Deprecated: No longer used; kept for compatibility.

+
type InvalidUTF8Error struct {
+    S string // the whole string value that caused the error
+}
+

func (*InvalidUTF8Error) Error

func (e *InvalidUTF8Error) Error() string

type InvalidUnmarshalError

An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil pointer.)

+
type InvalidUnmarshalError struct {
+    Type reflect.Type
+}
+

func (*InvalidUnmarshalError) Error

func (e *InvalidUnmarshalError) Error() string

type Marshaler

Marshaler is the interface implemented by types that can marshal themselves into valid JSON.

+
type Marshaler interface {
+    MarshalJSON() ([]byte, error)
+}

type MarshalerError

A MarshalerError represents an error from calling a [Marshaler.MarshalJSON] or encoding.TextMarshaler.MarshalText method.

+
type MarshalerError struct {
+    Type reflect.Type
+    Err  error
+    // contains filtered or unexported fields
+}
+

func (*MarshalerError) Error

func (e *MarshalerError) Error() string

func (*MarshalerError) Unwrap 1.13

func (e *MarshalerError) Unwrap() error

Unwrap returns the underlying error.

+

type Number 1.1

A Number represents a JSON number literal.

+
type Number string

func (Number) Float64 1.1

func (n Number) Float64() (float64, error)

Float64 returns the number as a float64.

+

func (Number) Int64 1.1

func (n Number) Int64() (int64, error)

Int64 returns the number as an int64.

+

func (Number) String 1.1

func (n Number) String() string

String returns the literal text of the number.

+

type RawMessage

RawMessage is a raw encoded JSON value. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.

+
type RawMessage []byte

Example (Marshal) +

This example uses RawMessage to use a precomputed JSON during marshal.

Code:

h := json.RawMessage(`{"precomputed": true}`)
+
+c := struct {
+    Header *json.RawMessage `json:"header"`
+    Body   string           `json:"body"`
+}{Header: &h, Body: "Hello Gophers!"}
+
+b, err := json.MarshalIndent(&c, "", "\t")
+if err != nil {
+    fmt.Println("error:", err)
+}
+os.Stdout.Write(b)
+
+

Output:

{
+	"header": {
+		"precomputed": true
+	},
+	"body": "Hello Gophers!"
+}
+

Example (Unmarshal) +

This example uses RawMessage to delay parsing part of a JSON message.

Code:

type Color struct {
+    Space string
+    Point json.RawMessage // delay parsing until we know the color space
+}
+type RGB struct {
+    R uint8
+    G uint8
+    B uint8
+}
+type YCbCr struct {
+    Y  uint8
+    Cb int8
+    Cr int8
+}
+
+var j = []byte(`[
+    {"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
+    {"Space": "RGB",   "Point": {"R": 98, "G": 218, "B": 255}}
+]`)
+var colors []Color
+err := json.Unmarshal(j, &colors)
+if err != nil {
+    log.Fatalln("error:", err)
+}
+
+for _, c := range colors {
+    var dst any
+    switch c.Space {
+    case "RGB":
+        dst = new(RGB)
+    case "YCbCr":
+        dst = new(YCbCr)
+    }
+    err := json.Unmarshal(c.Point, dst)
+    if err != nil {
+        log.Fatalln("error:", err)
+    }
+    fmt.Println(c.Space, dst)
+}
+

Output:

YCbCr &{255 0 -10}
+RGB &{98 218 255}
+

func (RawMessage) MarshalJSON 1.8

func (m RawMessage) MarshalJSON() ([]byte, error)

MarshalJSON returns m as the JSON encoding of m.

+

func (*RawMessage) UnmarshalJSON

func (m *RawMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON sets *m to a copy of data.

+

type SyntaxError

A SyntaxError is a description of a JSON syntax error. Unmarshal will return a SyntaxError if the JSON can't be parsed.

+
type SyntaxError struct {
+    Offset int64 // error occurred after reading Offset bytes
+    // contains filtered or unexported fields
+}
+

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

type Token 1.5

A Token holds a value of one of these types:

+
type Token any

type UnmarshalFieldError

An UnmarshalFieldError describes a JSON object key that led to an unexported (and therefore unwritable) struct field.

+

Deprecated: No longer used; kept for compatibility.

+
type UnmarshalFieldError struct {
+    Key   string
+    Type  reflect.Type
+    Field reflect.StructField
+}
+

func (*UnmarshalFieldError) Error

func (e *UnmarshalFieldError) Error() string

type UnmarshalTypeError

An UnmarshalTypeError describes a JSON value that was not appropriate for a value of a specific Go type.

+
type UnmarshalTypeError struct {
+    Value  string       // description of JSON value - "bool", "array", "number -5"
+    Type   reflect.Type // type of Go value it could not be assigned to
+    Offset int64        // error occurred after reading Offset bytes; added in Go 1.5
+    Struct string       // name of the struct type containing the field; added in Go 1.8
+    Field  string       // the full path from root node to the field; added in Go 1.8
+}
+

func (*UnmarshalTypeError) Error

func (e *UnmarshalTypeError) Error() string

type Unmarshaler

Unmarshaler is the interface implemented by types that can unmarshal a JSON description of themselves. The input can be assumed to be a valid encoding of a JSON value. UnmarshalJSON must copy the JSON data if it wishes to retain the data after returning.

+

By convention, to approximate the behavior of Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.

+
type Unmarshaler interface {
+    UnmarshalJSON([]byte) error
+}

type UnsupportedTypeError

An UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.

+
type UnsupportedTypeError struct {
+    Type reflect.Type
+}
+

func (*UnsupportedTypeError) Error

func (e *UnsupportedTypeError) Error() string

type UnsupportedValueError

An UnsupportedValueError is returned by Marshal when attempting to encode an unsupported value.

+
type UnsupportedValueError struct {
+    Value reflect.Value
+    Str   string
+}
+

func (*UnsupportedValueError) Error

func (e *UnsupportedValueError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/encoding/json/ +

+
diff --git a/devdocs/go/encoding%2Fpem%2Findex.html b/devdocs/go/encoding%2Fpem%2Findex.html new file mode 100644 index 00000000..1d12d49b --- /dev/null +++ b/devdocs/go/encoding%2Fpem%2Findex.html @@ -0,0 +1,78 @@ +

Package pem

Overview

Package pem implements the PEM data encoding, which originated in Privacy Enhanced Mail. The most common use of PEM encoding today is in TLS keys and certificates. See RFC 1421.

Index

Examples

Decode
Encode

Package files

pem.go

func Encode

func Encode(out io.Writer, b *Block) error

Encode writes the PEM encoding of b to out.

Example +

Code:

block := &pem.Block{
+    Type: "MESSAGE",
+    Headers: map[string]string{
+        "Animal": "Gopher",
+    },
+    Bytes: []byte("test"),
+}
+
+if err := pem.Encode(os.Stdout, block); err != nil {
+    log.Fatal(err)
+}
+

Output:

-----BEGIN MESSAGE-----
+Animal: Gopher
+
+dGVzdA==
+-----END MESSAGE-----
+

func EncodeToMemory

func EncodeToMemory(b *Block) []byte

EncodeToMemory returns the PEM encoding of b.

+

If b has invalid headers and cannot be encoded, EncodeToMemory returns nil. If it is important to report details about this error case, use Encode instead.

+

type Block

A Block represents a PEM encoded structure.

+

The encoded form is:

+
-----BEGIN Type-----
+Headers
+base64-encoded Bytes
+-----END Type-----
+

where [Block.Headers] is a possibly empty sequence of Key: Value lines.

+
type Block struct {
+    Type    string            // The type, taken from the preamble (i.e. "RSA PRIVATE KEY").
+    Headers map[string]string // Optional headers.
+    Bytes   []byte            // The decoded bytes of the contents. Typically a DER encoded ASN.1 structure.
+}
+

func Decode

func Decode(data []byte) (p *Block, rest []byte)

Decode will find the next PEM formatted block (certificate, private key etc) in the input. It returns that block and the remainder of the input. If no PEM data is found, p is nil and the whole of the input is returned in rest.

Example +

Code:

var pubPEMData = []byte(`
+-----BEGIN PUBLIC KEY-----
+MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlRuRnThUjU8/prwYxbty
+WPT9pURI3lbsKMiB6Fn/VHOKE13p4D8xgOCADpdRagdT6n4etr9atzDKUSvpMtR3
+CP5noNc97WiNCggBjVWhs7szEe8ugyqF23XwpHQ6uV1LKH50m92MbOWfCtjU9p/x
+qhNpQQ1AZhqNy5Gevap5k8XzRmjSldNAFZMY7Yv3Gi+nyCwGwpVtBUwhuLzgNFK/
+yDtw2WcWmUU7NuC8Q6MWvPebxVtCfVp/iQU6q60yyt6aGOBkhAX0LpKAEhKidixY
+nP9PNVBvxgu3XZ4P36gZV6+ummKdBVnc3NqwBLu5+CcdRdusmHPHd5pHf4/38Z3/
+6qU2a/fPvWzceVTEgZ47QjFMTCTmCwNt29cvi7zZeQzjtwQgn4ipN9NibRH/Ax/q
+TbIzHfrJ1xa2RteWSdFjwtxi9C20HUkjXSeI4YlzQMH0fPX6KCE7aVePTOnB69I/
+a9/q96DiXZajwlpq3wFctrs1oXqBp5DVrCIj8hU2wNgB7LtQ1mCtsYz//heai0K9
+PhE4X6hiE0YmeAZjR0uHl8M/5aW9xCoJ72+12kKpWAa0SFRWLy6FejNYCYpkupVJ
+yecLk/4L1W0l6jQQZnWErXZYe0PNFcmwGXy1Rep83kfBRNKRy5tvocalLlwXLdUk
+AIU+2GKjyT3iMuzZxxFxPFMCAwEAAQ==
+-----END PUBLIC KEY-----
+and some more`)
+
+block, rest := pem.Decode(pubPEMData)
+if block == nil || block.Type != "PUBLIC KEY" {
+    log.Fatal("failed to decode PEM block containing public key")
+}
+
+pub, err := x509.ParsePKIXPublicKey(block.Bytes)
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("Got a %T, with remaining data: %q", pub, rest)
+

Output:

Got a *rsa.PublicKey, with remaining data: "and some more"
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/encoding/pem/ +

+
diff --git a/devdocs/go/encoding%2Fxml%2Findex.html b/devdocs/go/encoding%2Fxml%2Findex.html new file mode 100644 index 00000000..381d7195 --- /dev/null +++ b/devdocs/go/encoding%2Fxml%2Findex.html @@ -0,0 +1,596 @@ +

Package xml

Overview

Package xml implements a simple XML 1.0 parser that understands XML name spaces.

Example (CustomMarshalXML) +

Code:

package xml_test
+
+import (
+    "encoding/xml"
+    "fmt"
+    "log"
+    "strings"
+)
+
+type Animal int
+
+const (
+    Unknown Animal = iota
+    Gopher
+    Zebra
+)
+
+func (a *Animal) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
+    var s string
+    if err := d.DecodeElement(&s, &start); err != nil {
+        return err
+    }
+    switch strings.ToLower(s) {
+    default:
+        *a = Unknown
+    case "gopher":
+        *a = Gopher
+    case "zebra":
+        *a = Zebra
+    }
+
+    return nil
+}
+
+func (a Animal) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
+    var s string
+    switch a {
+    default:
+        s = "unknown"
+    case Gopher:
+        s = "gopher"
+    case Zebra:
+        s = "zebra"
+    }
+    return e.EncodeElement(s, start)
+}
+
+func Example_customMarshalXML() {
+    blob := `
+    <animals>
+        <animal>gopher</animal>
+        <animal>armadillo</animal>
+        <animal>zebra</animal>
+        <animal>unknown</animal>
+        <animal>gopher</animal>
+        <animal>bee</animal>
+        <animal>gopher</animal>
+        <animal>zebra</animal>
+    </animals>`
+    var zoo struct {
+        Animals []Animal `xml:"animal"`
+    }
+    if err := xml.Unmarshal([]byte(blob), &zoo); err != nil {
+        log.Fatal(err)
+    }
+
+    census := make(map[Animal]int)
+    for _, animal := range zoo.Animals {
+        census[animal] += 1
+    }
+
+    fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras:  %d\n* Unknown: %d\n",
+        census[Gopher], census[Zebra], census[Unknown])
+
+    // Output:
+    // Zoo Census:
+    // * Gophers: 3
+    // * Zebras:  2
+    // * Unknown: 3
+}
+

Example (TextMarshalXML) +

Code:

package xml_test
+
+import (
+    "encoding/xml"
+    "fmt"
+    "log"
+    "strings"
+)
+
+type Size int
+
+const (
+    Unrecognized Size = iota
+    Small
+    Large
+)
+
+func (s *Size) UnmarshalText(text []byte) error {
+    switch strings.ToLower(string(text)) {
+    default:
+        *s = Unrecognized
+    case "small":
+        *s = Small
+    case "large":
+        *s = Large
+    }
+    return nil
+}
+
+func (s Size) MarshalText() ([]byte, error) {
+    var name string
+    switch s {
+    default:
+        name = "unrecognized"
+    case Small:
+        name = "small"
+    case Large:
+        name = "large"
+    }
+    return []byte(name), nil
+}
+
+func Example_textMarshalXML() {
+    blob := `
+    <sizes>
+        <size>small</size>
+        <size>regular</size>
+        <size>large</size>
+        <size>unrecognized</size>
+        <size>small</size>
+        <size>normal</size>
+        <size>small</size>
+        <size>large</size>
+    </sizes>`
+    var inventory struct {
+        Sizes []Size `xml:"size"`
+    }
+    if err := xml.Unmarshal([]byte(blob), &inventory); err != nil {
+        log.Fatal(err)
+    }
+
+    counts := make(map[Size]int)
+    for _, size := range inventory.Sizes {
+        counts[size] += 1
+    }
+
+    fmt.Printf("Inventory Counts:\n* Small:        %d\n* Large:        %d\n* Unrecognized: %d\n",
+        counts[Small], counts[Large], counts[Unrecognized])
+
+    // Output:
+    // Inventory Counts:
+    // * Small:        3
+    // * Large:        2
+    // * Unrecognized: 3
+}
+

Index

Examples

Encoder
MarshalIndent
Unmarshal
Package (CustomMarshalXML)
Package (TextMarshalXML)

Package files

marshal.go read.go typeinfo.go xml.go

Constants

const (
+    // Header is a generic XML header suitable for use with the output of [Marshal].
+    // This is not automatically added to any output of this package,
+    // it is provided as a convenience.
+    Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n"
+)

Variables

HTMLAutoClose is the set of HTML elements that should be considered to close automatically.

+

See the [Decoder.Strict] and [Decoder.Entity] fields' documentation.

+
var HTMLAutoClose []string = htmlAutoClose

HTMLEntity is an entity map containing translations for the standard HTML entity characters.

+

See the [Decoder.Strict] and [Decoder.Entity] fields' documentation.

+
var HTMLEntity map[string]string = htmlEntity

func Escape

func Escape(w io.Writer, s []byte)

Escape is like EscapeText but omits the error return value. It is provided for backwards compatibility with Go 1.0. Code targeting Go 1.1 or later should use EscapeText.

+

func EscapeText 1.1

func EscapeText(w io.Writer, s []byte) error

EscapeText writes to w the properly escaped XML equivalent of the plain text data s.

+

func Marshal

func Marshal(v any) ([]byte, error)

Marshal returns the XML encoding of v.

+

Marshal handles an array or slice by marshaling each of the elements. Marshal handles a pointer by marshaling the value it points at or, if the pointer is nil, by writing nothing. Marshal handles an interface value by marshaling the value it contains or, if the interface value is nil, by writing nothing. Marshal handles all other data by writing one or more XML elements containing the data.

+

The name for the XML elements is taken from, in order of preference:

+

The XML element for a struct contains marshaled elements for each of the exported fields of the struct, with these exceptions:

+

If a field uses a tag "a>b>c", then the element c will be nested inside parent elements a and b. Fields that appear next to each other that name the same parent will be enclosed in one XML element.

+

If the XML name for a struct field is defined by both the field tag and the struct's XMLName field, the names must match.

+

See MarshalIndent for an example.

+

Marshal will return an error if asked to marshal a channel, function, or map.

+

func MarshalIndent

func MarshalIndent(v any, prefix, indent string) ([]byte, error)

MarshalIndent works like Marshal, but each XML element begins on a new indented line that starts with prefix and is followed by one or more copies of indent according to the nesting depth.

Example +

Code:

type Address struct {
+    City, State string
+}
+type Person struct {
+    XMLName   xml.Name `xml:"person"`
+    Id        int      `xml:"id,attr"`
+    FirstName string   `xml:"name>first"`
+    LastName  string   `xml:"name>last"`
+    Age       int      `xml:"age"`
+    Height    float32  `xml:"height,omitempty"`
+    Married   bool
+    Address
+    Comment string `xml:",comment"`
+}
+
+v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
+v.Comment = " Need more details. "
+v.Address = Address{"Hanga Roa", "Easter Island"}
+
+output, err := xml.MarshalIndent(v, "  ", "    ")
+if err != nil {
+    fmt.Printf("error: %v\n", err)
+}
+
+os.Stdout.Write(output)
+

Output:

  <person id="13">
+      <name>
+          <first>John</first>
+          <last>Doe</last>
+      </name>
+      <age>42</age>
+      <Married>false</Married>
+      <City>Hanga Roa</City>
+      <State>Easter Island</State>
+      <!-- Need more details. -->
+  </person>
+

func Unmarshal

func Unmarshal(data []byte, v any) error

Unmarshal parses the XML-encoded data and stores the result in the value pointed to by v, which must be an arbitrary struct, slice, or string. Well-formed data that does not fit into v is discarded.

+

Because Unmarshal uses the reflect package, it can only assign to exported (upper case) fields. Unmarshal uses a case-sensitive comparison to match XML element names to tag values and struct field names.

+

Unmarshal maps an XML element to a struct using the following rules. In the rules, the tag of a field refers to the value associated with the key 'xml' in the struct field's tag (see the example above).

+

If Unmarshal encounters a field type that implements the Unmarshaler interface, Unmarshal calls its UnmarshalXML method to produce the value from the XML element. Otherwise, if the value implements encoding.TextUnmarshaler, Unmarshal calls that value's UnmarshalText method.

+

Unmarshal maps an XML element to a string or []byte by saving the concatenation of that element's character data in the string or []byte. The saved []byte is never nil.

+

Unmarshal maps an attribute value to a string or []byte by saving the value in the string or slice.

+

Unmarshal maps an attribute value to an Attr by saving the attribute, including its name, in the Attr.

+

Unmarshal maps an XML element or attribute value to a slice by extending the length of the slice and mapping the element or attribute to the newly created value.

+

Unmarshal maps an XML element or attribute value to a bool by setting it to the boolean value represented by the string. Whitespace is trimmed and ignored.

+

Unmarshal maps an XML element or attribute value to an integer or floating-point field by setting the field to the result of interpreting the string value in decimal. There is no check for overflow. Whitespace is trimmed and ignored.

+

Unmarshal maps an XML element to a Name by recording the element name.

+

Unmarshal maps an XML element to a pointer by setting the pointer to a freshly allocated value and then mapping the element to that value.

+

A missing element or empty attribute value will be unmarshaled as a zero value. If the field is a slice, a zero value will be appended to the field. Otherwise, the field will be set to its zero value.

Example +

This example demonstrates unmarshaling an XML excerpt into a value with some preset fields. Note that the Phone field isn't modified and that the XML <Company> element is ignored. Also, the Groups field is assigned considering the element path provided in its tag.

Code:

type Email struct {
+    Where string `xml:"where,attr"`
+    Addr  string
+}
+type Address struct {
+    City, State string
+}
+type Result struct {
+    XMLName xml.Name `xml:"Person"`
+    Name    string   `xml:"FullName"`
+    Phone   string
+    Email   []Email
+    Groups  []string `xml:"Group>Value"`
+    Address
+}
+v := Result{Name: "none", Phone: "none"}
+
+data := `
+        <Person>
+            <FullName>Grace R. Emlin</FullName>
+            <Company>Example Inc.</Company>
+            <Email where="home">
+                <Addr>gre@example.com</Addr>
+            </Email>
+            <Email where='work'>
+                <Addr>gre@work.com</Addr>
+            </Email>
+            <Group>
+                <Value>Friends</Value>
+                <Value>Squash</Value>
+            </Group>
+            <City>Hanga Roa</City>
+            <State>Easter Island</State>
+        </Person>
+    `
+err := xml.Unmarshal([]byte(data), &v)
+if err != nil {
+    fmt.Printf("error: %v", err)
+    return
+}
+fmt.Printf("XMLName: %#v\n", v.XMLName)
+fmt.Printf("Name: %q\n", v.Name)
+fmt.Printf("Phone: %q\n", v.Phone)
+fmt.Printf("Email: %v\n", v.Email)
+fmt.Printf("Groups: %v\n", v.Groups)
+fmt.Printf("Address: %v\n", v.Address)
+

Output:

XMLName: xml.Name{Space:"", Local:"Person"}
+Name: "Grace R. Emlin"
+Phone: "none"
+Email: [{home gre@example.com} {work gre@work.com}]
+Groups: [Friends Squash]
+Address: {Hanga Roa Easter Island}
+

type Attr

An Attr represents an attribute in an XML element (Name=Value).

+
type Attr struct {
+    Name  Name
+    Value string
+}
+

type CharData

A CharData represents XML character data (raw text), in which XML escape sequences have been replaced by the characters they represent.

+
type CharData []byte

func (CharData) Copy

func (c CharData) Copy() CharData

Copy creates a new copy of CharData.

+

type Comment

A Comment represents an XML comment of the form <!--comment-->. The bytes do not include the <!-- and --> comment markers.

+
type Comment []byte

func (Comment) Copy

func (c Comment) Copy() Comment

Copy creates a new copy of Comment.

+

type Decoder

A Decoder represents an XML parser reading a particular input stream. The parser assumes that its input is encoded in UTF-8.

+
type Decoder struct {
+    // Strict defaults to true, enforcing the requirements
+    // of the XML specification.
+    // If set to false, the parser allows input containing common
+    // mistakes:
+    //	* If an element is missing an end tag, the parser invents
+    //	  end tags as necessary to keep the return values from Token
+    //	  properly balanced.
+    //	* In attribute values and character data, unknown or malformed
+    //	  character entities (sequences beginning with &) are left alone.
+    //
+    // Setting:
+    //
+    //	d.Strict = false
+    //	d.AutoClose = xml.HTMLAutoClose
+    //	d.Entity = xml.HTMLEntity
+    //
+    // creates a parser that can handle typical HTML.
+    //
+    // Strict mode does not enforce the requirements of the XML name spaces TR.
+    // In particular it does not reject name space tags using undefined prefixes.
+    // Such tags are recorded with the unknown prefix as the name space URL.
+    Strict bool
+
+    // When Strict == false, AutoClose indicates a set of elements to
+    // consider closed immediately after they are opened, regardless
+    // of whether an end element is present.
+    AutoClose []string
+
+    // Entity can be used to map non-standard entity names to string replacements.
+    // The parser behaves as if these standard mappings are present in the map,
+    // regardless of the actual map content:
+    //
+    //	"lt": "<",
+    //	"gt": ">",
+    //	"amp": "&",
+    //	"apos": "'",
+    //	"quot": `"`,
+    Entity map[string]string
+
+    // CharsetReader, if non-nil, defines a function to generate
+    // charset-conversion readers, converting from the provided
+    // non-UTF-8 charset into UTF-8. If CharsetReader is nil or
+    // returns an error, parsing stops with an error. One of the
+    // CharsetReader's result values must be non-nil.
+    CharsetReader func(charset string, input io.Reader) (io.Reader, error)
+
+    // DefaultSpace sets the default name space used for unadorned tags,
+    // as if the entire XML stream were wrapped in an element containing
+    // the attribute xmlns="DefaultSpace".
+    DefaultSpace string // Go 1.1
+    // contains filtered or unexported fields
+}
+

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder creates a new XML parser reading from r. If r does not implement io.ByteReader, NewDecoder will do its own buffering.

+

func NewTokenDecoder 1.10

func NewTokenDecoder(t TokenReader) *Decoder

NewTokenDecoder creates a new XML parser using an underlying token stream.

+

func (*Decoder) Decode

func (d *Decoder) Decode(v any) error

Decode works like Unmarshal, except it reads the decoder stream to find the start element.

+

func (*Decoder) DecodeElement

func (d *Decoder) DecodeElement(v any, start *StartElement) error

DecodeElement works like Unmarshal except that it takes a pointer to the start XML element to decode into v. It is useful when a client reads some raw XML tokens itself but also wants to defer to Unmarshal for some elements.

+

func (*Decoder) InputOffset 1.4

func (d *Decoder) InputOffset() int64

InputOffset returns the input stream byte offset of the current decoder position. The offset gives the location of the end of the most recently returned token and the beginning of the next token.

+

func (*Decoder) InputPos 1.19

func (d *Decoder) InputPos() (line, column int)

InputPos returns the line of the current decoder position and the 1 based input position of the line. The position gives the location of the end of the most recently returned token.

+

func (*Decoder) RawToken

func (d *Decoder) RawToken() (Token, error)

RawToken is like Decoder.Token but does not verify that start and end elements match and does not translate name space prefixes to their corresponding URLs.

+

func (*Decoder) Skip

func (d *Decoder) Skip() error

Skip reads tokens until it has consumed the end element matching the most recent start element already consumed, skipping nested structures. It returns nil if it finds an end element matching the start element; otherwise it returns an error describing the problem.

+

func (*Decoder) Token

func (d *Decoder) Token() (Token, error)

Token returns the next XML token in the input stream. At the end of the input stream, Token returns nil, io.EOF.

+

Slices of bytes in the returned token data refer to the parser's internal buffer and remain valid only until the next call to Token. To acquire a copy of the bytes, call CopyToken or the token's Copy method.

+

Token expands self-closing elements such as <br> into separate start and end elements returned by successive calls.

+

Token guarantees that the StartElement and EndElement tokens it returns are properly nested and matched: if Token encounters an unexpected end element or EOF before all expected end elements, it will return an error.

+

If [Decoder.CharsetReader] is called and returns an error, the error is wrapped and returned.

+

Token implements XML name spaces as described by https://www.w3.org/TR/REC-xml-names/. Each of the Name structures contained in the Token has the Space set to the URL identifying its name space when known. If Token encounters an unrecognized name space prefix, it uses the prefix as the Space rather than report an error.

+

type Directive

A Directive represents an XML directive of the form <!text>. The bytes do not include the <! and > markers.

+
type Directive []byte

func (Directive) Copy

func (d Directive) Copy() Directive

Copy creates a new copy of Directive.

+

type Encoder

An Encoder writes XML data to an output stream.

+
type Encoder struct {
+    // contains filtered or unexported fields
+}
+

Example +

Code:

type Address struct {
+    City, State string
+}
+type Person struct {
+    XMLName   xml.Name `xml:"person"`
+    Id        int      `xml:"id,attr"`
+    FirstName string   `xml:"name>first"`
+    LastName  string   `xml:"name>last"`
+    Age       int      `xml:"age"`
+    Height    float32  `xml:"height,omitempty"`
+    Married   bool
+    Address
+    Comment string `xml:",comment"`
+}
+
+v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
+v.Comment = " Need more details. "
+v.Address = Address{"Hanga Roa", "Easter Island"}
+
+enc := xml.NewEncoder(os.Stdout)
+enc.Indent("  ", "    ")
+if err := enc.Encode(v); err != nil {
+    fmt.Printf("error: %v\n", err)
+}
+
+

Output:

  <person id="13">
+      <name>
+          <first>John</first>
+          <last>Doe</last>
+      </name>
+      <age>42</age>
+      <Married>false</Married>
+      <City>Hanga Roa</City>
+      <State>Easter Island</State>
+      <!-- Need more details. -->
+  </person>
+

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w.

+

func (*Encoder) Close 1.20

func (enc *Encoder) Close() error

Close the Encoder, indicating that no more data will be written. It flushes any buffered XML to the underlying writer and returns an error if the written XML is invalid (e.g. by containing unclosed elements).

+

func (*Encoder) Encode

func (enc *Encoder) Encode(v any) error

Encode writes the XML encoding of v to the stream.

+

See the documentation for Marshal for details about the conversion of Go values to XML.

+

Encode calls Encoder.Flush before returning.

+

func (*Encoder) EncodeElement 1.2

func (enc *Encoder) EncodeElement(v any, start StartElement) error

EncodeElement writes the XML encoding of v to the stream, using start as the outermost tag in the encoding.

+

See the documentation for Marshal for details about the conversion of Go values to XML.

+

EncodeElement calls Encoder.Flush before returning.

+

func (*Encoder) EncodeToken 1.2

func (enc *Encoder) EncodeToken(t Token) error

EncodeToken writes the given XML token to the stream. It returns an error if StartElement and EndElement tokens are not properly matched.

+

EncodeToken does not call Encoder.Flush, because usually it is part of a larger operation such as Encoder.Encode or Encoder.EncodeElement (or a custom Marshaler's MarshalXML invoked during those), and those will call Flush when finished. Callers that create an Encoder and then invoke EncodeToken directly, without using Encode or EncodeElement, need to call Flush when finished to ensure that the XML is written to the underlying writer.

+

EncodeToken allows writing a ProcInst with Target set to "xml" only as the first token in the stream.

+

func (*Encoder) Flush 1.2

func (enc *Encoder) Flush() error

Flush flushes any buffered XML to the underlying writer. See the Encoder.EncodeToken documentation for details about when it is necessary.

+

func (*Encoder) Indent 1.1

func (enc *Encoder) Indent(prefix, indent string)

Indent sets the encoder to generate XML in which each element begins on a new indented line that starts with prefix and is followed by one or more copies of indent according to the nesting depth.

+

type EndElement

An EndElement represents an XML end element.

+
type EndElement struct {
+    Name Name
+}
+

type Marshaler 1.2

Marshaler is the interface implemented by objects that can marshal themselves into valid XML elements.

+

MarshalXML encodes the receiver as zero or more XML elements. By convention, arrays or slices are typically encoded as a sequence of elements, one per entry. Using start as the element tag is not required, but doing so will enable Unmarshal to match the XML elements to the correct struct field. One common implementation strategy is to construct a separate value with a layout corresponding to the desired XML and then to encode it using e.EncodeElement. Another common strategy is to use repeated calls to e.EncodeToken to generate the XML output one token at a time. The sequence of encoded tokens must make up zero or more valid XML elements.

+
type Marshaler interface {
+    MarshalXML(e *Encoder, start StartElement) error
+}

type MarshalerAttr 1.2

MarshalerAttr is the interface implemented by objects that can marshal themselves into valid XML attributes.

+

MarshalXMLAttr returns an XML attribute with the encoded value of the receiver. Using name as the attribute name is not required, but doing so will enable Unmarshal to match the attribute to the correct struct field. If MarshalXMLAttr returns the zero attribute Attr{}, no attribute will be generated in the output. MarshalXMLAttr is used only for struct fields with the "attr" option in the field tag.

+
type MarshalerAttr interface {
+    MarshalXMLAttr(name Name) (Attr, error)
+}

type Name

A Name represents an XML name (Local) annotated with a name space identifier (Space). In tokens returned by Decoder.Token, the Space identifier is given as a canonical URL, not the short prefix used in the document being parsed.

+
type Name struct {
+    Space, Local string
+}
+

type ProcInst

A ProcInst represents an XML processing instruction of the form <?target inst?>

+
type ProcInst struct {
+    Target string
+    Inst   []byte
+}
+

func (ProcInst) Copy

func (p ProcInst) Copy() ProcInst

Copy creates a new copy of ProcInst.

+

type StartElement

A StartElement represents an XML start element.

+
type StartElement struct {
+    Name Name
+    Attr []Attr
+}
+

func (StartElement) Copy

func (e StartElement) Copy() StartElement

Copy creates a new copy of StartElement.

+

func (StartElement) End 1.2

func (e StartElement) End() EndElement

End returns the corresponding XML end element.

+

type SyntaxError

A SyntaxError represents a syntax error in the XML input stream.

+
type SyntaxError struct {
+    Msg  string
+    Line int
+}
+

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

type TagPathError

A TagPathError represents an error in the unmarshaling process caused by the use of field tags with conflicting paths.

+
type TagPathError struct {
+    Struct       reflect.Type
+    Field1, Tag1 string
+    Field2, Tag2 string
+}
+

func (*TagPathError) Error

func (e *TagPathError) Error() string

type Token

A Token is an interface holding one of the token types: StartElement, EndElement, CharData, Comment, ProcInst, or Directive.

+
type Token any

func CopyToken

func CopyToken(t Token) Token

CopyToken returns a copy of a Token.

+

type TokenReader 1.10

A TokenReader is anything that can decode a stream of XML tokens, including a Decoder.

+

When Token encounters an error or end-of-file condition after successfully reading a token, it returns the token. It may return the (non-nil) error from the same call or return the error (and a nil token) from a subsequent call. An instance of this general case is that a TokenReader returning a non-nil token at the end of the token stream may return either io.EOF or a nil error. The next Read should return nil, io.EOF.

+

Implementations of Token are discouraged from returning a nil token with a nil error. Callers should treat a return of nil, nil as indicating that nothing happened; in particular it does not indicate EOF.

+
type TokenReader interface {
+    Token() (Token, error)
+}

type UnmarshalError

An UnmarshalError represents an error in the unmarshaling process.

+
type UnmarshalError string

func (UnmarshalError) Error

func (e UnmarshalError) Error() string

type Unmarshaler 1.2

Unmarshaler is the interface implemented by objects that can unmarshal an XML element description of themselves.

+

UnmarshalXML decodes a single XML element beginning with the given start element. If it returns an error, the outer call to Unmarshal stops and returns that error. UnmarshalXML must consume exactly one XML element. One common implementation strategy is to unmarshal into a separate value with a layout matching the expected XML using d.DecodeElement, and then to copy the data from that value into the receiver. Another common strategy is to use d.Token to process the XML object one token at a time. UnmarshalXML may not use d.RawToken.

+
type Unmarshaler interface {
+    UnmarshalXML(d *Decoder, start StartElement) error
+}

type UnmarshalerAttr 1.2

UnmarshalerAttr is the interface implemented by objects that can unmarshal an XML attribute description of themselves.

+

UnmarshalXMLAttr decodes a single XML attribute. If it returns an error, the outer call to Unmarshal stops and returns that error. UnmarshalXMLAttr is used only for struct fields with the "attr" option in the field tag.

+
type UnmarshalerAttr interface {
+    UnmarshalXMLAttr(attr Attr) error
+}

type UnsupportedTypeError

UnsupportedTypeError is returned when Marshal encounters a type that cannot be converted into XML.

+
type UnsupportedTypeError struct {
+    Type reflect.Type
+}
+

func (*UnsupportedTypeError) Error

func (e *UnsupportedTypeError) Error() string

Bugs

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/encoding/xml/ +

+
diff --git a/devdocs/go/errors%2Findex.html b/devdocs/go/errors%2Findex.html new file mode 100644 index 00000000..3eb8f8a2 --- /dev/null +++ b/devdocs/go/errors%2Findex.html @@ -0,0 +1,118 @@ +

Package errors

Overview

Package errors implements functions to manipulate errors.

+

The New function creates errors whose only content is a text message.

+

An error e wraps another error if e's type has one of the methods

+
Unwrap() error
+Unwrap() []error
+

If e.Unwrap() returns a non-nil error w or a slice containing w, then we say that e wraps w. A nil error returned from e.Unwrap() indicates that e does not wrap any error. It is invalid for an Unwrap method to return an []error containing a nil error value.

+

An easy way to create wrapped errors is to call fmt.Errorf and apply the %w verb to the error argument:

+
wrapsErr := fmt.Errorf("... %w ...", ..., err, ...)
+

Successive unwrapping of an error creates a tree. The Is and As functions inspect an error's tree by examining first the error itself followed by the tree of each of its children in turn (pre-order, depth-first traversal).

+

Is examines the tree of its first argument looking for an error that matches the second. It reports whether it finds a match. It should be used in preference to simple equality checks:

+
if errors.Is(err, fs.ErrExist)
+

is preferable to

+
if err == fs.ErrExist
+

because the former will succeed if err wraps io/fs.ErrExist.

+

As examines the tree of its first argument looking for an error that can be assigned to its second argument, which must be a pointer. If it succeeds, it performs the assignment and returns true. Otherwise, it returns false. The form

+
var perr *fs.PathError
+if errors.As(err, &perr) {
+	fmt.Println(perr.Path)
+}
+

is preferable to

+
if perr, ok := err.(*fs.PathError); ok {
+	fmt.Println(perr.Path)
+}
+

because the former will succeed if err wraps an *io/fs.PathError.

Example +

Code:

if err := oops(); err != nil {
+    fmt.Println(err)
+}
+

Output:

1989-03-15 22:30:00 +0000 UTC: the file system has gone away
+

Index

Examples

Package
As
Is
Join
New
New (Errorf)
Unwrap

Package files

errors.go join.go wrap.go

Variables

ErrUnsupported indicates that a requested operation cannot be performed, because it is unsupported. For example, a call to os.Link when using a file system that does not support hard links.

+

Functions and methods should not return this error but should instead return an error including appropriate context that satisfies

+
errors.Is(err, errors.ErrUnsupported)
+

either by directly wrapping ErrUnsupported or by implementing an Is method.

+

Functions and methods should document the cases in which an error wrapping this will be returned.

+
var ErrUnsupported = New("unsupported operation")

func As 1.13

func As(err error, target any) bool

As finds the first error in err's tree that matches target, and if one is found, sets target to that error value and returns true. Otherwise, it returns false.

+

The tree consists of err itself, followed by the errors obtained by repeatedly calling its Unwrap() error or Unwrap() []error method. When err wraps multiple errors, As examines err followed by a depth-first traversal of its children.

+

An error matches target if the error's concrete value is assignable to the value pointed to by target, or if the error has a method As(interface{}) bool such that As(target) returns true. In the latter case, the As method is responsible for setting target.

+

An error type might provide an As method so it can be treated as if it were a different error type.

+

As panics if target is not a non-nil pointer to either a type that implements error, or to any interface type.

Example +

Code:

if _, err := os.Open("non-existing"); err != nil {
+    var pathError *fs.PathError
+    if errors.As(err, &pathError) {
+        fmt.Println("Failed at path:", pathError.Path)
+    } else {
+        fmt.Println(err)
+    }
+}
+
+

Output:

Failed at path: non-existing
+

func Is 1.13

func Is(err, target error) bool

Is reports whether any error in err's tree matches target.

+

The tree consists of err itself, followed by the errors obtained by repeatedly calling its Unwrap() error or Unwrap() []error method. When err wraps multiple errors, Is examines err followed by a depth-first traversal of its children.

+

An error is considered to match a target if it is equal to that target or if it implements a method Is(error) bool such that Is(target) returns true.

+

An error type might provide an Is method so it can be treated as equivalent to an existing error. For example, if MyError defines

+
func (m MyError) Is(target error) bool { return target == fs.ErrExist }
+

then Is(MyError{}, fs.ErrExist) returns true. See syscall.Errno.Is for an example in the standard library. An Is method should only shallowly compare err and the target and not call Unwrap on either.

Example +

Code:

if _, err := os.Open("non-existing"); err != nil {
+    if errors.Is(err, fs.ErrNotExist) {
+        fmt.Println("file does not exist")
+    } else {
+        fmt.Println(err)
+    }
+}
+
+

Output:

file does not exist
+

func Join 1.20

func Join(errs ...error) error

Join returns an error that wraps the given errors. Any nil error values are discarded. Join returns nil if every value in errs is nil. The error formats as the concatenation of the strings obtained by calling the Error method of each element of errs, with a newline between each string.

+

A non-nil error returned by Join implements the Unwrap() []error method.

Example +

Code:

err1 := errors.New("err1")
+err2 := errors.New("err2")
+err := errors.Join(err1, err2)
+fmt.Println(err)
+if errors.Is(err, err1) {
+    fmt.Println("err is err1")
+}
+if errors.Is(err, err2) {
+    fmt.Println("err is err2")
+}
+

Output:

err1
+err2
+err is err1
+err is err2
+

func New

func New(text string) error

New returns an error that formats as the given text. Each call to New returns a distinct error value even if the text is identical.

Example +

Code:

err := errors.New("emit macho dwarf: elf header corrupted")
+if err != nil {
+    fmt.Print(err)
+}
+

Output:

emit macho dwarf: elf header corrupted
+

Example (Errorf) +

The fmt package's Errorf function lets us use the package's formatting features to create descriptive error messages.

Code:

const name, id = "bimmler", 17
+err := fmt.Errorf("user %q (id %d) not found", name, id)
+if err != nil {
+    fmt.Print(err)
+}
+

Output:

user "bimmler" (id 17) not found
+

func Unwrap 1.13

func Unwrap(err error) error

Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.

+

Unwrap only calls a method of the form "Unwrap() error". In particular Unwrap does not unwrap errors returned by Join.

Example +

Code:

err1 := errors.New("error1")
+err2 := fmt.Errorf("error2: [%w]", err1)
+fmt.Println(err2)
+fmt.Println(errors.Unwrap(err2))
+

Output:

error2: [error1]
+error1
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/errors/ +

+
diff --git a/devdocs/go/expvar%2Findex.html b/devdocs/go/expvar%2Findex.html new file mode 100644 index 00000000..fed3e6d1 --- /dev/null +++ b/devdocs/go/expvar%2Findex.html @@ -0,0 +1,120 @@ +

Package expvar

Overview

Package expvar provides a standardized interface to public variables, such as operation counters in servers. It exposes these variables via HTTP at /debug/vars in JSON format.

+

Operations to set or modify these public variables are atomic.

+

In addition to adding the HTTP handler, this package registers the following variables:

+
cmdline   os.Args
+memstats  runtime.Memstats
+

The package is sometimes only imported for the side effect of registering its HTTP handler and the above variables. To use it this way, link this package into your program:

+
import _ "expvar"
+

Index

Package files

expvar.go

func Do

func Do(f func(KeyValue))

Do calls f for each exported variable. The global variable map is locked during the iteration, but existing entries may be concurrently updated.

+

func Handler 1.8

func Handler() http.Handler

Handler returns the expvar HTTP Handler.

+

This is only needed to install the handler in a non-standard location.

+

func Publish

func Publish(name string, v Var)

Publish declares a named exported variable. This should be called from a package's init function when it creates its Vars. If the name is already registered then this will log.Panic.

+

type Float

Float is a 64-bit float variable that satisfies the Var interface.

+
type Float struct {
+    // contains filtered or unexported fields
+}
+

func NewFloat

func NewFloat(name string) *Float

func (*Float) Add

func (v *Float) Add(delta float64)

Add adds delta to v.

+

func (*Float) Set

func (v *Float) Set(value float64)

Set sets v to value.

+

func (*Float) String

func (v *Float) String() string

func (*Float) Value 1.8

func (v *Float) Value() float64

type Func

Func implements Var by calling the function and formatting the returned value using JSON.

+
type Func func() any

func (Func) String

func (f Func) String() string

func (Func) Value 1.8

func (f Func) Value() any

type Int

Int is a 64-bit integer variable that satisfies the Var interface.

+
type Int struct {
+    // contains filtered or unexported fields
+}
+

func NewInt

func NewInt(name string) *Int

func (*Int) Add

func (v *Int) Add(delta int64)

func (*Int) Set

func (v *Int) Set(value int64)

func (*Int) String

func (v *Int) String() string

func (*Int) Value 1.8

func (v *Int) Value() int64

type KeyValue

KeyValue represents a single entry in a Map.

+
type KeyValue struct {
+    Key   string
+    Value Var
+}
+

type Map

Map is a string-to-Var map variable that satisfies the Var interface.

+
type Map struct {
+    // contains filtered or unexported fields
+}
+

func NewMap

func NewMap(name string) *Map

func (*Map) Add

func (v *Map) Add(key string, delta int64)

Add adds delta to the *Int value stored under the given map key.

+

func (*Map) AddFloat

func (v *Map) AddFloat(key string, delta float64)

AddFloat adds delta to the *Float value stored under the given map key.

+

func (*Map) Delete 1.12

func (v *Map) Delete(key string)

Delete deletes the given key from the map.

+

func (*Map) Do

func (v *Map) Do(f func(KeyValue))

Do calls f for each entry in the map. The map is locked during the iteration, but existing entries may be concurrently updated.

+

func (*Map) Get

func (v *Map) Get(key string) Var

func (*Map) Init

func (v *Map) Init() *Map

Init removes all keys from the map.

+

func (*Map) Set

func (v *Map) Set(key string, av Var)

func (*Map) String

func (v *Map) String() string

type String

String is a string variable, and satisfies the Var interface.

+
type String struct {
+    // contains filtered or unexported fields
+}
+

func NewString

func NewString(name string) *String

func (*String) Set

func (v *String) Set(value string)

func (*String) String

func (v *String) String() string

String implements the Var interface. To get the unquoted string use String.Value.

+

func (*String) Value 1.8

func (v *String) Value() string

type Var

Var is an abstract type for all exported variables.

+
type Var interface {
+    // String returns a valid JSON value for the variable.
+    // Types with String methods that do not return valid JSON
+    // (such as time.Time) must not be used as a Var.
+    String() string
+}

func Get

func Get(name string) Var

Get retrieves a named exported variable. It returns nil if the name has not been registered.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/expvar/ +

+
diff --git a/devdocs/go/flag%2Findex.html b/devdocs/go/flag%2Findex.html new file mode 100644 index 00000000..e8f9a4df --- /dev/null +++ b/devdocs/go/flag%2Findex.html @@ -0,0 +1,452 @@ +

Package flag

Overview

Package flag implements command-line flag parsing.

+

Usage

Define flags using flag.String, Bool, Int, etc.

+

This declares an integer flag, -n, stored in the pointer nFlag, with type *int:

+
import "flag"
+var nFlag = flag.Int("n", 1234, "help message for flag n")
+

If you like, you can bind the flag to a variable using the Var() functions.

+
var flagvar int
+func init() {
+	flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
+}
+

Or you can create custom flags that satisfy the Value interface (with pointer receivers) and couple them to flag parsing by

+
flag.Var(&flagVal, "name", "help message for flagname")
+

For such flags, the default value is just the initial value of the variable.

+

After all flags are defined, call

+
flag.Parse()
+

to parse the command line into the defined flags.

+

Flags may then be used directly. If you're using the flags themselves, they are all pointers; if you bind to variables, they're values.

+
fmt.Println("ip has value ", *ip)
+fmt.Println("flagvar has value ", flagvar)
+

After parsing, the arguments following the flags are available as the slice flag.Args or individually as flag.Arg(i). The arguments are indexed from 0 through flag.NArg-1.

+

Command line flag syntax

The following forms are permitted:

+
-flag
+--flag   // double dashes are also permitted
+-flag=x
+-flag x  // non-boolean flags only
+

One or two dashes may be used; they are equivalent. The last form is not permitted for boolean flags because the meaning of the command

+
cmd -x *
+

where * is a Unix shell wildcard, will change if there is a file called 0, false, etc. You must use the -flag=false form to turn off a boolean flag.

+

Flag parsing stops just before the first non-flag argument ("-" is a non-flag argument) or after the terminator "--".

+

Integer flags accept 1234, 0664, 0x1234 and may be negative. Boolean flags may be:

+
1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
+

Duration flags accept any input valid for time.ParseDuration.

+

The default set of command-line flags is controlled by top-level functions. The FlagSet type allows one to define independent sets of flags, such as to implement subcommands in a command-line interface. The methods of FlagSet are analogous to the top-level functions for the command-line flag set.

Example +

Code:

// These examples demonstrate more intricate uses of the flag package.
+package flag_test
+
+import (
+    "errors"
+    "flag"
+    "fmt"
+    "strings"
+    "time"
+)
+
+// Example 1: A single string flag called "species" with default value "gopher".
+var species = flag.String("species", "gopher", "the species we are studying")
+
+// Example 2: Two flags sharing a variable, so we can have a shorthand.
+// The order of initialization is undefined, so make sure both use the
+// same default value. They must be set up with an init function.
+var gopherType string
+
+func init() {
+    const (
+        defaultGopher = "pocket"
+        usage         = "the variety of gopher"
+    )
+    flag.StringVar(&gopherType, "gopher_type", defaultGopher, usage)
+    flag.StringVar(&gopherType, "g", defaultGopher, usage+" (shorthand)")
+}
+
+// Example 3: A user-defined flag type, a slice of durations.
+type interval []time.Duration
+
+// String is the method to format the flag's value, part of the flag.Value interface.
+// The String method's output will be used in diagnostics.
+func (i *interval) String() string {
+    return fmt.Sprint(*i)
+}
+
+// Set is the method to set the flag value, part of the flag.Value interface.
+// Set's argument is a string to be parsed to set the flag.
+// It's a comma-separated list, so we split it.
+func (i *interval) Set(value string) error {
+    // If we wanted to allow the flag to be set multiple times,
+    // accumulating values, we would delete this if statement.
+    // That would permit usages such as
+    //	-deltaT 10s -deltaT 15s
+    // and other combinations.
+    if len(*i) > 0 {
+        return errors.New("interval flag already set")
+    }
+    for _, dt := range strings.Split(value, ",") {
+        duration, err := time.ParseDuration(dt)
+        if err != nil {
+            return err
+        }
+        *i = append(*i, duration)
+    }
+    return nil
+}
+
+// Define a flag to accumulate durations. Because it has a special type,
+// we need to use the Var function and therefore create the flag during
+// init.
+
+var intervalFlag interval
+
+func init() {
+    // Tie the command-line flag to the intervalFlag variable and
+    // set a usage message.
+    flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events")
+}
+
+func Example() {
+    // All the interesting pieces are with the variables declared above, but
+    // to enable the flag package to see the flags defined there, one must
+    // execute, typically at the start of main (not init!):
+    //	flag.Parse()
+    // We don't call it here because this code is a function called "Example"
+    // that is part of the testing suite for the package, which has already
+    // parsed the flags. When viewed at pkg.go.dev, however, the function is
+    // renamed to "main" and it could be run as a standalone example.
+}
+

Index

Examples

Package
BoolFunc
Func
TextVar
Value

Package files

flag.go

Variables

CommandLine is the default set of command-line flags, parsed from os.Args. The top-level functions such as BoolVar, Arg, and so on are wrappers for the methods of CommandLine.

+
var CommandLine = NewFlagSet(os.Args[0], ExitOnError)

ErrHelp is the error returned if the -help or -h flag is invoked but no such flag is defined.

+
var ErrHelp = errors.New("flag: help requested")

Usage prints a usage message documenting all defined command-line flags to CommandLine's output, which by default is os.Stderr. It is called when an error occurs while parsing flags. The function is a variable that may be changed to point to a custom function. By default it prints a simple header and calls PrintDefaults; for details about the format of the output and how to control it, see the documentation for PrintDefaults. Custom usage functions may choose to exit the program; by default exiting happens anyway as the command line's error handling strategy is set to ExitOnError.

+
var Usage = func() {
+    fmt.Fprintf(CommandLine.Output(), "Usage of %s:\n", os.Args[0])
+    PrintDefaults()
+}

func Arg

func Arg(i int) string

Arg returns the i'th command-line argument. Arg(0) is the first remaining argument after flags have been processed. Arg returns an empty string if the requested element does not exist.

+

func Args

func Args() []string

Args returns the non-flag command-line arguments.

+

func Bool

func Bool(name string, value bool, usage string) *bool

Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.

+

func BoolFunc 1.21

func BoolFunc(name, usage string, fn func(string) error)

BoolFunc defines a flag with the specified name and usage string without requiring values. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.

Example +

Code:

fs := flag.NewFlagSet("ExampleBoolFunc", flag.ContinueOnError)
+fs.SetOutput(os.Stdout)
+
+fs.BoolFunc("log", "logs a dummy message", func(s string) error {
+    fmt.Println("dummy message:", s)
+    return nil
+})
+fs.Parse([]string{"-log"})
+fs.Parse([]string{"-log=0"})
+
+

Output:

dummy message: true
+dummy message: 0
+

func BoolVar

func BoolVar(p *bool, name string, value bool, usage string)

BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.

+

func Duration

func Duration(name string, value time.Duration, usage string) *time.Duration

Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag. The flag accepts a value acceptable to time.ParseDuration.

+

func DurationVar

func DurationVar(p *time.Duration, name string, value time.Duration, usage string)

DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag. The flag accepts a value acceptable to time.ParseDuration.

+

func Float64

func Float64(name string, value float64, usage string) *float64

Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.

+

func Float64Var

func Float64Var(p *float64, name string, value float64, usage string)

Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.

+

func Func 1.16

func Func(name, usage string, fn func(string) error)

Func defines a flag with the specified name and usage string. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.

Example +

Code:

fs := flag.NewFlagSet("ExampleFunc", flag.ContinueOnError)
+fs.SetOutput(os.Stdout)
+var ip net.IP
+fs.Func("ip", "`IP address` to parse", func(s string) error {
+    ip = net.ParseIP(s)
+    if ip == nil {
+        return errors.New("could not parse IP")
+    }
+    return nil
+})
+fs.Parse([]string{"-ip", "127.0.0.1"})
+fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback())
+
+// 256 is not a valid IPv4 component
+fs.Parse([]string{"-ip", "256.0.0.1"})
+fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback())
+
+

Output:

{ip: 127.0.0.1, loopback: true}
+
+invalid value "256.0.0.1" for flag -ip: could not parse IP
+Usage of ExampleFunc:
+  -ip IP address
+    	IP address to parse
+{ip: <nil>, loopback: false}
+

func Int

func Int(name string, value int, usage string) *int

Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.

+

func Int64

func Int64(name string, value int64, usage string) *int64

Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.

+

func Int64Var

func Int64Var(p *int64, name string, value int64, usage string)

Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.

+

func IntVar

func IntVar(p *int, name string, value int, usage string)

IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.

+

func NArg

func NArg() int

NArg is the number of arguments remaining after flags have been processed.

+

func NFlag

func NFlag() int

NFlag returns the number of command-line flags that have been set.

+

func Parse

func Parse()

Parse parses the command-line flags from os.Args[1:]. Must be called after all flags are defined and before flags are accessed by the program.

+

func Parsed

func Parsed() bool

Parsed reports whether the command-line flags have been parsed.

+

func PrintDefaults

func PrintDefaults()

PrintDefaults prints, to standard error unless configured otherwise, a usage message showing the default settings of all defined command-line flags. For an integer valued flag x, the default output has the form

+
-x int
+	usage-message-for-x (default 7)
+

The usage message will appear on a separate line for anything but a bool flag with a one-byte name. For bool flags, the type is omitted and if the flag name is one byte the usage message appears on the same line. The parenthetical default is omitted if the default is the zero value for the type. The listed type, here int, can be changed by placing a back-quoted name in the flag's usage string; the first such item in the message is taken to be a parameter name to show in the message and the back quotes are stripped from the message when displayed. For instance, given

+
flag.String("I", "", "search `directory` for include files")
+

the output will be

+
-I directory
+	search directory for include files.
+

To change the destination for flag messages, call CommandLine.SetOutput.

+

func Set

func Set(name, value string) error

Set sets the value of the named command-line flag.

+

func String

func String(name string, value string, usage string) *string

String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.

+

func StringVar

func StringVar(p *string, name string, value string, usage string)

StringVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.

+

func TextVar 1.19

func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string)

TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p.

Example +

Code:

fs := flag.NewFlagSet("ExampleTextVar", flag.ContinueOnError)
+fs.SetOutput(os.Stdout)
+var ip net.IP
+fs.TextVar(&ip, "ip", net.IPv4(192, 168, 0, 100), "`IP address` to parse")
+fs.Parse([]string{"-ip", "127.0.0.1"})
+fmt.Printf("{ip: %v}\n\n", ip)
+
+// 256 is not a valid IPv4 component
+ip = nil
+fs.Parse([]string{"-ip", "256.0.0.1"})
+fmt.Printf("{ip: %v}\n\n", ip)
+
+

Output:

{ip: 127.0.0.1}
+
+invalid value "256.0.0.1" for flag -ip: invalid IP address: 256.0.0.1
+Usage of ExampleTextVar:
+  -ip IP address
+    	IP address to parse (default 192.168.0.100)
+{ip: <nil>}
+

func Uint

func Uint(name string, value uint, usage string) *uint

Uint defines a uint flag with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the flag.

+

func Uint64

func Uint64(name string, value uint64, usage string) *uint64

Uint64 defines a uint64 flag with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the flag.

+

func Uint64Var

func Uint64Var(p *uint64, name string, value uint64, usage string)

Uint64Var defines a uint64 flag with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the flag.

+

func UintVar

func UintVar(p *uint, name string, value uint, usage string)

UintVar defines a uint flag with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the flag.

+

func UnquoteUsage 1.5

func UnquoteUsage(flag *Flag) (name string, usage string)

UnquoteUsage extracts a back-quoted name from the usage string for a flag and returns it and the un-quoted usage. Given "a `name` to show" it returns ("name", "a name to show"). If there are no back quotes, the name is an educated guess of the type of the flag's value, or the empty string if the flag is boolean.

+

func Var

func Var(value Value, name string, usage string)

Var defines a flag with the specified name and usage string. The type and value of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.

+

func Visit

func Visit(fn func(*Flag))

Visit visits the command-line flags in lexicographical order, calling fn for each. It visits only those flags that have been set.

+

func VisitAll

func VisitAll(fn func(*Flag))

VisitAll visits the command-line flags in lexicographical order, calling fn for each. It visits all flags, even those not set.

+

type ErrorHandling

ErrorHandling defines how FlagSet.Parse behaves if the parse fails.

+
type ErrorHandling int

These constants cause FlagSet.Parse to behave as described if the parse fails.

+
const (
+    ContinueOnError ErrorHandling = iota // Return a descriptive error.
+    ExitOnError                          // Call os.Exit(2) or for -h/-help Exit(0).
+    PanicOnError                         // Call panic with a descriptive error.
+)

type Flag

A Flag represents the state of a flag.

+
type Flag struct {
+    Name     string // name as it appears on command line
+    Usage    string // help message
+    Value    Value  // value as set
+    DefValue string // default value (as text); for usage message
+}
+

func Lookup

func Lookup(name string) *Flag

Lookup returns the Flag structure of the named command-line flag, returning nil if none exists.

+

type FlagSet

A FlagSet represents a set of defined flags. The zero value of a FlagSet has no name and has ContinueOnError error handling.

+

Flag names must be unique within a FlagSet. An attempt to define a flag whose name is already in use will cause a panic.

+
type FlagSet struct {
+    // Usage is the function called when an error occurs while parsing flags.
+    // The field is a function (not a method) that may be changed to point to
+    // a custom error handler. What happens after Usage is called depends
+    // on the ErrorHandling setting; for the command line, this defaults
+    // to ExitOnError, which exits the program after calling Usage.
+    Usage func()
+    // contains filtered or unexported fields
+}
+

func NewFlagSet

func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet

NewFlagSet returns a new, empty flag set with the specified name and error handling property. If the name is not empty, it will be printed in the default usage message and in error messages.

+

func (*FlagSet) Arg

func (f *FlagSet) Arg(i int) string

Arg returns the i'th argument. Arg(0) is the first remaining argument after flags have been processed. Arg returns an empty string if the requested element does not exist.

+

func (*FlagSet) Args

func (f *FlagSet) Args() []string

Args returns the non-flag arguments.

+

func (*FlagSet) Bool

func (f *FlagSet) Bool(name string, value bool, usage string) *bool

Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.

+

func (*FlagSet) BoolFunc 1.21

func (f *FlagSet) BoolFunc(name, usage string, fn func(string) error)

BoolFunc defines a flag with the specified name and usage string without requiring values. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.

+

func (*FlagSet) BoolVar

func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string)

BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.

+

func (*FlagSet) Duration

func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration

Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag. The flag accepts a value acceptable to time.ParseDuration.

+

func (*FlagSet) DurationVar

func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string)

DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag. The flag accepts a value acceptable to time.ParseDuration.

+

func (*FlagSet) ErrorHandling 1.10

func (f *FlagSet) ErrorHandling() ErrorHandling

ErrorHandling returns the error handling behavior of the flag set.

+

func (*FlagSet) Float64

func (f *FlagSet) Float64(name string, value float64, usage string) *float64

Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.

+

func (*FlagSet) Float64Var

func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string)

Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.

+

func (*FlagSet) Func 1.16

func (f *FlagSet) Func(name, usage string, fn func(string) error)

Func defines a flag with the specified name and usage string. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.

+

func (*FlagSet) Init

func (f *FlagSet) Init(name string, errorHandling ErrorHandling)

Init sets the name and error handling property for a flag set. By default, the zero FlagSet uses an empty name and the ContinueOnError error handling policy.

+

func (*FlagSet) Int

func (f *FlagSet) Int(name string, value int, usage string) *int

Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.

+

func (*FlagSet) Int64

func (f *FlagSet) Int64(name string, value int64, usage string) *int64

Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.

+

func (*FlagSet) Int64Var

func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string)

Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.

+

func (*FlagSet) IntVar

func (f *FlagSet) IntVar(p *int, name string, value int, usage string)

IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.

+

func (*FlagSet) Lookup

func (f *FlagSet) Lookup(name string) *Flag

Lookup returns the Flag structure of the named flag, returning nil if none exists.

+

func (*FlagSet) NArg

func (f *FlagSet) NArg() int

NArg is the number of arguments remaining after flags have been processed.

+

func (*FlagSet) NFlag

func (f *FlagSet) NFlag() int

NFlag returns the number of flags that have been set.

+

func (*FlagSet) Name 1.10

func (f *FlagSet) Name() string

Name returns the name of the flag set.

+

func (*FlagSet) Output 1.10

func (f *FlagSet) Output() io.Writer

Output returns the destination for usage and error messages. os.Stderr is returned if output was not set or was set to nil.

+

func (*FlagSet) Parse

func (f *FlagSet) Parse(arguments []string) error

Parse parses flag definitions from the argument list, which should not include the command name. Must be called after all flags in the FlagSet are defined and before flags are accessed by the program. The return value will be ErrHelp if -help or -h were set but not defined.

+

func (*FlagSet) Parsed

func (f *FlagSet) Parsed() bool

Parsed reports whether f.Parse has been called.

+

func (*FlagSet) PrintDefaults

func (f *FlagSet) PrintDefaults()

PrintDefaults prints, to standard error unless configured otherwise, the default values of all defined command-line flags in the set. See the documentation for the global function PrintDefaults for more information.

+

func (*FlagSet) Set

func (f *FlagSet) Set(name, value string) error

Set sets the value of the named flag.

+

func (*FlagSet) SetOutput

func (f *FlagSet) SetOutput(output io.Writer)

SetOutput sets the destination for usage and error messages. If output is nil, os.Stderr is used.

+

func (*FlagSet) String

func (f *FlagSet) String(name string, value string, usage string) *string

String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.

+

func (*FlagSet) StringVar

func (f *FlagSet) StringVar(p *string, name string, value string, usage string)

StringVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.

+

func (*FlagSet) TextVar 1.19

func (f *FlagSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string)

TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p.

+

func (*FlagSet) Uint

func (f *FlagSet) Uint(name string, value uint, usage string) *uint

Uint defines a uint flag with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the flag.

+

func (*FlagSet) Uint64

func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64

Uint64 defines a uint64 flag with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the flag.

+

func (*FlagSet) Uint64Var

func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string)

Uint64Var defines a uint64 flag with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the flag.

+

func (*FlagSet) UintVar

func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string)

UintVar defines a uint flag with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the flag.

+

func (*FlagSet) Var

func (f *FlagSet) Var(value Value, name string, usage string)

Var defines a flag with the specified name and usage string. The type and value of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.

+

func (*FlagSet) Visit

func (f *FlagSet) Visit(fn func(*Flag))

Visit visits the flags in lexicographical order, calling fn for each. It visits only those flags that have been set.

+

func (*FlagSet) VisitAll

func (f *FlagSet) VisitAll(fn func(*Flag))

VisitAll visits the flags in lexicographical order, calling fn for each. It visits all flags, even those not set.

+

type Getter 1.2

Getter is an interface that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface, except the type used by Func.

+
type Getter interface {
+    Value
+    Get() any
+}

type Value

Value is the interface to the dynamic value stored in a flag. (The default value is represented as a string.)

+

If a Value has an IsBoolFlag() bool method returning true, the command-line parser makes -name equivalent to -name=true rather than using the next command-line argument.

+

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

+
type Value interface {
+    String() string
+    Set(string) error
+}

Example +

Code:

package flag_test
+
+import (
+    "flag"
+    "fmt"
+    "net/url"
+)
+
+type URLValue struct {
+    URL *url.URL
+}
+
+func (v URLValue) String() string {
+    if v.URL != nil {
+        return v.URL.String()
+    }
+    return ""
+}
+
+func (v URLValue) Set(s string) error {
+    if u, err := url.Parse(s); err != nil {
+        return err
+    } else {
+        *v.URL = *u
+    }
+    return nil
+}
+
+var u = &url.URL{}
+
+func ExampleValue() {
+    fs := flag.NewFlagSet("ExampleValue", flag.ExitOnError)
+    fs.Var(&URLValue{u}, "url", "URL to parse")
+
+    fs.Parse([]string{"-url", "https://golang.org/pkg/flag/"})
+    fmt.Printf(`{scheme: %q, host: %q, path: %q}`, u.Scheme, u.Host, u.Path)
+
+    // Output:
+    // {scheme: "https", host: "golang.org", path: "/pkg/flag/"}
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/flag/ +

+
diff --git a/devdocs/go/fmt%2Findex.html b/devdocs/go/fmt%2Findex.html new file mode 100644 index 00000000..f21c9bbf --- /dev/null +++ b/devdocs/go/fmt%2Findex.html @@ -0,0 +1,627 @@ +

Package fmt

Overview

Package fmt implements formatted I/O with functions analogous to C's printf and scanf. The format 'verbs' are derived from C's but are simpler.

+

Printing

The verbs:

+

General:

+
%v	the value in a default format
+	when printing structs, the plus flag (%+v) adds field names
+%#v	a Go-syntax representation of the value
+%T	a Go-syntax representation of the type of the value
+%%	a literal percent sign; consumes no value
+

Boolean:

+
%t	the word true or false
+

Integer:

+
%b	base 2
+%c	the character represented by the corresponding Unicode code point
+%d	base 10
+%o	base 8
+%O	base 8 with 0o prefix
+%q	a single-quoted character literal safely escaped with Go syntax.
+%x	base 16, with lower-case letters for a-f
+%X	base 16, with upper-case letters for A-F
+%U	Unicode format: U+1234; same as "U+%04X"
+

Floating-point and complex constituents:

+
%b	decimalless scientific notation with exponent a power of two,
+	in the manner of strconv.FormatFloat with the 'b' format,
+	e.g. -123456p-78
+%e	scientific notation, e.g. -1.234456e+78
+%E	scientific notation, e.g. -1.234456E+78
+%f	decimal point but no exponent, e.g. 123.456
+%F	synonym for %f
+%g	%e for large exponents, %f otherwise. Precision is discussed below.
+%G	%E for large exponents, %F otherwise
+%x	hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20
+%X	upper-case hexadecimal notation, e.g. -0X1.23ABCP+20
+

String and slice of bytes (treated equivalently with these verbs):

+
%s	the uninterpreted bytes of the string or slice
+%q	a double-quoted string safely escaped with Go syntax
+%x	base 16, lower-case, two characters per byte
+%X	base 16, upper-case, two characters per byte
+

Slice:

+
%p	address of 0th element in base 16 notation, with leading 0x
+

Pointer:

+
%p	base 16 notation, with leading 0x
+The %b, %d, %o, %x and %X verbs also work with pointers,
+formatting the value exactly as if it were an integer.
+

The default format for %v is:

+
bool:                    %t
+int, int8 etc.:          %d
+uint, uint8 etc.:        %d, %#x if printed with %#v
+float32, complex64, etc: %g
+string:                  %s
+chan:                    %p
+pointer:                 %p
+

For compound objects, the elements are printed using these rules, recursively, laid out like this:

+
struct:             {field0 field1 ...}
+array, slice:       [elem0 elem1 ...]
+maps:               map[key1:value1 key2:value2 ...]
+pointer to above:   &{}, &[], &map[]
+

Width is specified by an optional decimal number immediately preceding the verb. If absent, the width is whatever is necessary to represent the value. Precision is specified after the (optional) width by a period followed by a decimal number. If no period is present, a default precision is used. A period with no following number specifies a precision of zero. Examples:

+
%f     default width, default precision
+%9f    width 9, default precision
+%.2f   default width, precision 2
+%9.2f  width 9, precision 2
+%9.f   width 9, precision 0
+

Width and precision are measured in units of Unicode code points, that is, runes. (This differs from C's printf where the units are always measured in bytes.) Either or both of the flags may be replaced with the character '*', causing their values to be obtained from the next operand (preceding the one to format), which must be of type int.

+

For most values, width is the minimum number of runes to output, padding the formatted form with spaces if necessary.

+

For strings, byte slices and byte arrays, however, precision limits the length of the input to be formatted (not the size of the output), truncating if necessary. Normally it is measured in runes, but for these types when formatted with the %x or %X format it is measured in bytes.

+

For floating-point values, width sets the minimum width of the field and precision sets the number of places after the decimal, if appropriate, except that for %g/%G precision sets the maximum number of significant digits (trailing zeros are removed). For example, given 12.345 the format %6.3f prints 12.345 while %.3g prints 12.3. The default precision for %e, %f and %#g is 6; for %g it is the smallest number of digits necessary to identify the value uniquely.

+

For complex numbers, the width and precision apply to the two components independently and the result is parenthesized, so %f applied to 1.2+3.4i produces (1.200000+3.400000i).

+

When formatting a single integer code point or a rune string (type []rune) with %q, invalid Unicode code points are changed to the Unicode replacement character, U+FFFD, as in strconv.QuoteRune.

+

Other flags:

+
'+'	always print a sign for numeric values;
+	guarantee ASCII-only output for %q (%+q)
+'-'	pad with spaces on the right rather than the left (left-justify the field)
+'#'	alternate format: add leading 0b for binary (%#b), 0 for octal (%#o),
+	0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p);
+	for %q, print a raw (backquoted) string if strconv.CanBackquote
+	returns true;
+	always print a decimal point for %e, %E, %f, %F, %g and %G;
+	do not remove trailing zeros for %g and %G;
+	write e.g. U+0078 'x' if the character is printable for %U (%#U).
+' '	(space) leave a space for elided sign in numbers (% d);
+	put spaces between bytes printing strings or slices in hex (% x, % X)
+'0'	pad with leading zeros rather than spaces;
+	for numbers, this moves the padding after the sign;
+	ignored for strings, byte slices and byte arrays
+

Flags are ignored by verbs that do not expect them. For example there is no alternate decimal format, so %#d and %d behave identically.

+

For each Printf-like function, there is also a Print function that takes no format and is equivalent to saying %v for every operand. Another variant Println inserts blanks between operands and appends a newline.

+

Regardless of the verb, if an operand is an interface value, the internal concrete value is used, not the interface itself. Thus:

+
var i interface{} = 23
+fmt.Printf("%v\n", i)
+

will print 23.

+

Except when printed using the verbs %T and %p, special formatting considerations apply for operands that implement certain interfaces. In order of application:

+

1. If the operand is a reflect.Value, the operand is replaced by the concrete value that it holds, and printing continues with the next rule.

+

2. If an operand implements the Formatter interface, it will be invoked. In this case the interpretation of verbs and flags is controlled by that implementation.

+

3. If the %v verb is used with the # flag (%#v) and the operand implements the GoStringer interface, that will be invoked.

+

If the format (which is implicitly %v for Println etc.) is valid for a string (%s %q %x %X), or is %v but not %#v, the following two rules apply:

+

4. If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

+

5. If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

+

For compound operands such as slices and structs, the format applies to the elements of each operand, recursively, not to the operand as a whole. Thus %q will quote each element of a slice of strings, and %6.2f will control formatting for each element of a floating-point array.

+

However, when printing a byte slice with a string-like verb (%s %q %x %X), it is treated identically to a string, as a single item.

+

To avoid recursion in cases such as

+
type X string
+func (x X) String() string { return Sprintf("<%s>", x) }
+

convert the value before recurring:

+
func (x X) String() string { return Sprintf("<%s>", string(x)) }
+

Infinite recursion can also be triggered by self-referential data structures, such as a slice that contains itself as an element, if that type has a String method. Such pathologies are rare, however, and the package does not protect against them.

+

When printing a struct, fmt cannot and therefore does not invoke formatting methods such as Error or String on unexported fields.

+

Explicit argument indexes

In Printf, Sprintf, and Fprintf, the default behavior is for each formatting verb to format successive arguments passed in the call. However, the notation [n] immediately before the verb indicates that the nth one-indexed argument is to be formatted instead. The same notation before a '*' for a width or precision selects the argument index holding the value. After processing a bracketed expression [n], subsequent verbs will use arguments n+1, n+2, etc. unless otherwise directed.

+

For example,

+
fmt.Sprintf("%[2]d %[1]d\n", 11, 22)
+

will yield "22 11", while

+
fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6)
+

equivalent to

+
fmt.Sprintf("%6.2f", 12.0)
+

will yield " 12.00". Because an explicit index affects subsequent verbs, this notation can be used to print the same values multiple times by resetting the index for the first argument to be repeated:

+
fmt.Sprintf("%d %d %#[1]x %#x", 16, 17)
+

will yield "16 17 0x10 0x11".

+

Format errors

If an invalid argument is given for a verb, such as providing a string to %d, the generated string will contain a description of the problem, as in these examples:

+
Wrong type or unknown verb: %!verb(type=value)
+	Printf("%d", "hi"):        %!d(string=hi)
+Too many arguments: %!(EXTRA type=value)
+	Printf("hi", "guys"):      hi%!(EXTRA string=guys)
+Too few arguments: %!verb(MISSING)
+	Printf("hi%d"):            hi%!d(MISSING)
+Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
+	Printf("%*s", 4.5, "hi"):  %!(BADWIDTH)hi
+	Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
+Invalid or invalid use of argument index: %!(BADINDEX)
+	Printf("%*[2]d", 7):       %!d(BADINDEX)
+	Printf("%.[2]d", 7):       %!d(BADINDEX)
+

All errors begin with the string "%!" followed sometimes by a single character (the verb) and end with a parenthesized description.

+

If an Error or String method triggers a panic when called by a print routine, the fmt package reformats the error message from the panic, decorating it with an indication that it came through the fmt package. For example, if a String method calls panic("bad"), the resulting formatted message will look like

+
%!s(PANIC=bad)
+

The %!s just shows the print verb in use when the failure occurred. If the panic is caused by a nil receiver to an Error or String method, however, the output is the undecorated string, "<nil>".

+

Scanning

An analogous set of functions scans formatted text to yield values. Scan, Scanf and Scanln read from os.Stdin; Fscan, Fscanf and Fscanln read from a specified io.Reader; Sscan, Sscanf and Sscanln read from an argument string.

+

Scan, Fscan, Sscan treat newlines in the input as spaces.

+

Scanln, Fscanln and Sscanln stop scanning at a newline and require that the items be followed by a newline or EOF.

+

Scanf, Fscanf, and Sscanf parse the arguments according to a format string, analogous to that of Printf. In the text that follows, 'space' means any Unicode whitespace character except newline.

+

In the format string, a verb introduced by the % character consumes and parses input; these verbs are described in more detail below. A character other than %, space, or newline in the format consumes exactly that input character, which must be present. A newline with zero or more spaces before it in the format string consumes zero or more spaces in the input followed by a single newline or the end of the input. A space following a newline in the format string consumes zero or more spaces in the input. Otherwise, any run of one or more spaces in the format string consumes as many spaces as possible in the input. Unless the run of spaces in the format string appears adjacent to a newline, the run must consume at least one space from the input or find the end of the input.

+

The handling of spaces and newlines differs from that of C's scanf family: in C, newlines are treated as any other space, and it is never an error when a run of spaces in the format string finds no spaces to consume in the input.

+

The verbs behave analogously to those of Printf. For example, %x will scan an integer as a hexadecimal number, and %v will scan the default representation format for the value. The Printf verbs %p and %T and the flags # and + are not implemented. For floating-point and complex values, all valid formatting verbs (%b %e %E %f %F %g %G %x %X and %v) are equivalent and accept both decimal and hexadecimal notation (for example: "2.3e+7", "0x4.5p-8") and digit-separating underscores (for example: "3.14159_26535_89793").

+

Input processed by verbs is implicitly space-delimited: the implementation of every verb except %c starts by discarding leading spaces from the remaining input, and the %s verb (and %v reading into a string) stops consuming input at the first space or newline character.

+

The familiar base-setting prefixes 0b (binary), 0o and 0 (octal), and 0x (hexadecimal) are accepted when scanning integers without a format or with the %v verb, as are digit-separating underscores.

+

Width is interpreted in the input text but there is no syntax for scanning with a precision (no %5.2f, just %5f). If width is provided, it applies after leading spaces are trimmed and specifies the maximum number of runes to read to satisfy the verb. For example,

+
Sscanf(" 1234567 ", "%5s%d", &s, &i)
+

will set s to "12345" and i to 67 while

+
Sscanf(" 12 34 567 ", "%5s%d", &s, &i)
+

will set s to "12" and i to 34.

+

In all the scanning functions, a carriage return followed immediately by a newline is treated as a plain newline (\r\n means the same as \n).

+

In all the scanning functions, if an operand implements method Scan (that is, it implements the Scanner interface) that method will be used to scan the text for that operand. Also, if the number of arguments scanned is less than the number of arguments provided, an error is returned.

+

All arguments to be scanned must be either pointers to basic types or implementations of the Scanner interface.

+

Like Scanf and Fscanf, Sscanf need not consume its entire input. There is no way to recover how much of the input string Sscanf used.

+

Note: Fscan etc. can read one character (rune) past the input they return, which means that a loop calling a scan routine may skip some of the input. This is usually a problem only when there is no space between input values. If the reader provided to Fscan implements ReadRune, that method will be used to read characters. If the reader also implements UnreadRune, that method will be used to save the character and successive calls will not lose data. To attach ReadRune and UnreadRune methods to a reader without that capability, use bufio.NewReader.

Example (Formats) +

These examples demonstrate the basics of printing using a format string. Printf, Sprintf, and Fprintf all take a format string that specifies how to format the subsequent arguments. For example, %d (we call that a 'verb') says to print the corresponding argument, which must be an integer (or something containing an integer, such as a slice of ints) in decimal. The verb %v ('v' for 'value') always formats the argument in its default form, just how Print or Println would show it. The special verb %T ('T' for 'Type') prints the type of the argument rather than its value. The examples are not exhaustive; see the package comment for all the details.

Code:

// A basic set of examples showing that %v is the default format, in this
+// case decimal for integers, which can be explicitly requested with %d;
+// the output is just what Println generates.
+integer := 23
+// Each of these prints "23" (without the quotes).
+fmt.Println(integer)
+fmt.Printf("%v\n", integer)
+fmt.Printf("%d\n", integer)
+
+// The special verb %T shows the type of an item rather than its value.
+fmt.Printf("%T %T\n", integer, &integer)
+// Result: int *int
+
+// Println(x) is the same as Printf("%v\n", x) so we will use only Printf
+// in the following examples. Each one demonstrates how to format values of
+// a particular type, such as integers or strings. We start each format
+// string with %v to show the default output and follow that with one or
+// more custom formats.
+
+// Booleans print as "true" or "false" with %v or %t.
+truth := true
+fmt.Printf("%v %t\n", truth, truth)
+// Result: true true
+
+// Integers print as decimals with %v and %d,
+// or in hex with %x, octal with %o, or binary with %b.
+answer := 42
+fmt.Printf("%v %d %x %o %b\n", answer, answer, answer, answer, answer)
+// Result: 42 42 2a 52 101010
+
+// Floats have multiple formats: %v and %g print a compact representation,
+// while %f prints a decimal point and %e uses exponential notation. The
+// format %6.2f used here shows how to set the width and precision to
+// control the appearance of a floating-point value. In this instance, 6 is
+// the total width of the printed text for the value (note the extra spaces
+// in the output) and 2 is the number of decimal places to show.
+pi := math.Pi
+fmt.Printf("%v %g %.2f (%6.2f) %e\n", pi, pi, pi, pi, pi)
+// Result: 3.141592653589793 3.141592653589793 3.14 (  3.14) 3.141593e+00
+
+// Complex numbers format as parenthesized pairs of floats, with an 'i'
+// after the imaginary part.
+point := 110.7 + 22.5i
+fmt.Printf("%v %g %.2f %.2e\n", point, point, point, point)
+// Result: (110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i)
+
+// Runes are integers but when printed with %c show the character with that
+// Unicode value. The %q verb shows them as quoted characters, %U as a
+// hex Unicode code point, and %#U as both a code point and a quoted
+// printable form if the rune is printable.
+smile := '😀'
+fmt.Printf("%v %d %c %q %U %#U\n", smile, smile, smile, smile, smile, smile)
+// Result: 128512 128512 😀 '😀' U+1F600 U+1F600 '😀'
+
+// Strings are formatted with %v and %s as-is, with %q as quoted strings,
+// and %#q as backquoted strings.
+placeholders := `foo "bar"`
+fmt.Printf("%v %s %q %#q\n", placeholders, placeholders, placeholders, placeholders)
+// Result: foo "bar" foo "bar" "foo \"bar\"" `foo "bar"`
+
+// Maps formatted with %v show keys and values in their default formats.
+// The %#v form (the # is called a "flag" in this context) shows the map in
+// the Go source format. Maps are printed in a consistent order, sorted
+// by the values of the keys.
+isLegume := map[string]bool{
+    "peanut":    true,
+    "dachshund": false,
+}
+fmt.Printf("%v %#v\n", isLegume, isLegume)
+// Result: map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true}
+
+// Structs formatted with %v show field values in their default formats.
+// The %+v form shows the fields by name, while %#v formats the struct in
+// Go source format.
+person := struct {
+    Name string
+    Age  int
+}{"Kim", 22}
+fmt.Printf("%v %+v %#v\n", person, person, person)
+// Result: {Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22}
+
+// The default format for a pointer shows the underlying value preceded by
+// an ampersand. The %p verb prints the pointer value in hex. We use a
+// typed nil for the argument to %p here because the value of any non-nil
+// pointer would change from run to run; run the commented-out Printf
+// call yourself to see.
+pointer := &person
+fmt.Printf("%v %p\n", pointer, (*int)(nil))
+// Result: &{Kim 22} 0x0
+// fmt.Printf("%v %p\n", pointer, pointer)
+// Result: &{Kim 22} 0x010203 // See comment above.
+
+// Arrays and slices are formatted by applying the format to each element.
+greats := [5]string{"Kitano", "Kobayashi", "Kurosawa", "Miyazaki", "Ozu"}
+fmt.Printf("%v %q\n", greats, greats)
+// Result: [Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"]
+
+kGreats := greats[:3]
+fmt.Printf("%v %q %#v\n", kGreats, kGreats, kGreats)
+// Result: [Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"}
+
+// Byte slices are special. Integer verbs like %d print the elements in
+// that format. The %s and %q forms treat the slice like a string. The %x
+// verb has a special form with the space flag that puts a space between
+// the bytes.
+cmd := []byte("a⌘")
+fmt.Printf("%v %d %s %q %x % x\n", cmd, cmd, cmd, cmd, cmd, cmd)
+// Result: [97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98
+
+// Types that implement Stringer are printed the same as strings. Because
+// Stringers return a string, we can print them using a string-specific
+// verb such as %q.
+now := time.Unix(123456789, 0).UTC() // time.Time implements fmt.Stringer.
+fmt.Printf("%v %q\n", now, now)
+// Result: 1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC"
+
+

Output:

23
+23
+23
+int *int
+true true
+42 42 2a 52 101010
+3.141592653589793 3.141592653589793 3.14 (  3.14) 3.141593e+00
+(110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i)
+128512 128512 😀 '😀' U+1F600 U+1F600 '😀'
+foo "bar" foo "bar" "foo \"bar\"" `foo "bar"`
+map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true}
+{Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22}
+&{Kim 22} 0x0
+[Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"]
+[Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"}
+[97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98
+1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC"
+

Example (Printers) +

Print, Println, and Printf lay out their arguments differently. In this example we can compare their behaviors. Println always adds blanks between the items it prints, while Print adds blanks only between non-string arguments and Printf does exactly what it is told. Sprint, Sprintln, Sprintf, Fprint, Fprintln, and Fprintf behave the same as their corresponding Print, Println, and Printf functions shown here.

Code:

a, b := 3.0, 4.0
+h := math.Hypot(a, b)
+
+// Print inserts blanks between arguments when neither is a string.
+// It does not add a newline to the output, so we add one explicitly.
+fmt.Print("The vector (", a, b, ") has length ", h, ".\n")
+
+// Println always inserts spaces between its arguments,
+// so it cannot be used to produce the same output as Print in this case;
+// its output has extra spaces.
+// Also, Println always adds a newline to the output.
+fmt.Println("The vector (", a, b, ") has length", h, ".")
+
+// Printf provides complete control but is more complex to use.
+// It does not add a newline to the output, so we add one explicitly
+// at the end of the format specifier string.
+fmt.Printf("The vector (%g %g) has length %g.\n", a, b, h)
+
+

Output:

The vector (3 4) has length 5.
+The vector ( 3 4 ) has length 5 .
+The vector (3 4) has length 5.
+

Index

Examples

Errorf
Fprint
Fprintf
Fprintln
Fscanf
Fscanln
GoStringer
Print
Printf
Println
Sprint
Sprintf
Sprintln
Sscanf
Stringer
Package (Formats)
Package (Printers)

Package files

doc.go errors.go format.go print.go scan.go

func Append 1.19

func Append(b []byte, a ...any) []byte

Append formats using the default formats for its operands, appends the result to the byte slice, and returns the updated slice.

+

func Appendf 1.19

func Appendf(b []byte, format string, a ...any) []byte

Appendf formats according to a format specifier, appends the result to the byte slice, and returns the updated slice.

+

func Appendln 1.19

func Appendln(b []byte, a ...any) []byte

Appendln formats using the default formats for its operands, appends the result to the byte slice, and returns the updated slice. Spaces are always added between operands and a newline is appended.

+

func Errorf

func Errorf(format string, a ...any) error

Errorf formats according to a format specifier and returns the string as a value that satisfies error.

+

If the format specifier includes a %w verb with an error operand, the returned error will implement an Unwrap method returning the operand. If there is more than one %w verb, the returned error will implement an Unwrap method returning a []error containing all the %w operands in the order they appear in the arguments. It is invalid to supply the %w verb with an operand that does not implement the error interface. The %w verb is otherwise a synonym for %v.

Example +

The Errorf function lets us use formatting features to create descriptive error messages.

Code:

const name, id = "bueller", 17
+err := fmt.Errorf("user %q (id %d) not found", name, id)
+fmt.Println(err.Error())
+
+

Output:

user "bueller" (id 17) not found
+

func FormatString 1.20

func FormatString(state State, verb rune) string

FormatString returns a string representing the fully qualified formatting directive captured by the State, followed by the argument verb. (State does not itself contain the verb.) The result has a leading percent sign followed by any flags, the width, and the precision. Missing flags, width, and precision are omitted. This function allows a Formatter to reconstruct the original directive triggering the call to Format.

+

func Fprint

func Fprint(w io.Writer, a ...any) (n int, err error)

Fprint formats using the default formats for its operands and writes to w. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.

Example +

Code:

const name, age = "Kim", 22
+n, err := fmt.Fprint(os.Stdout, name, " is ", age, " years old.\n")
+
+// The n and err return values from Fprint are
+// those returned by the underlying io.Writer.
+if err != nil {
+    fmt.Fprintf(os.Stderr, "Fprint: %v\n", err)
+}
+fmt.Print(n, " bytes written.\n")
+
+

Output:

Kim is 22 years old.
+21 bytes written.
+

func Fprintf

func Fprintf(w io.Writer, format string, a ...any) (n int, err error)

Fprintf formats according to a format specifier and writes to w. It returns the number of bytes written and any write error encountered.

Example +

Code:

const name, age = "Kim", 22
+n, err := fmt.Fprintf(os.Stdout, "%s is %d years old.\n", name, age)
+
+// The n and err return values from Fprintf are
+// those returned by the underlying io.Writer.
+if err != nil {
+    fmt.Fprintf(os.Stderr, "Fprintf: %v\n", err)
+}
+fmt.Printf("%d bytes written.\n", n)
+
+

Output:

Kim is 22 years old.
+21 bytes written.
+

func Fprintln

func Fprintln(w io.Writer, a ...any) (n int, err error)

Fprintln formats using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

Example +

Code:

const name, age = "Kim", 22
+n, err := fmt.Fprintln(os.Stdout, name, "is", age, "years old.")
+
+// The n and err return values from Fprintln are
+// those returned by the underlying io.Writer.
+if err != nil {
+    fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err)
+}
+fmt.Println(n, "bytes written.")
+
+

Output:

Kim is 22 years old.
+21 bytes written.
+

func Fscan

func Fscan(r io.Reader, a ...any) (n int, err error)

Fscan scans text read from r, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

+

func Fscanf

func Fscanf(r io.Reader, format string, a ...any) (n int, err error)

Fscanf scans text read from r, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully parsed. Newlines in the input must match newlines in the format.

Example +

Code:

var (
+    i int
+    b bool
+    s string
+)
+r := strings.NewReader("5 true gophers")
+n, err := fmt.Fscanf(r, "%d %t %s", &i, &b, &s)
+if err != nil {
+    fmt.Fprintf(os.Stderr, "Fscanf: %v\n", err)
+}
+fmt.Println(i, b, s)
+fmt.Println(n)
+

Output:

5 true gophers
+3
+

func Fscanln

func Fscanln(r io.Reader, a ...any) (n int, err error)

Fscanln is similar to Fscan, but stops scanning at a newline and after the final item there must be a newline or EOF.

Example +

Code:

s := `dmr 1771 1.61803398875
+    ken 271828 3.14159`
+r := strings.NewReader(s)
+var a string
+var b int
+var c float64
+for {
+    n, err := fmt.Fscanln(r, &a, &b, &c)
+    if err == io.EOF {
+        break
+    }
+    if err != nil {
+        panic(err)
+    }
+    fmt.Printf("%d: %s, %d, %f\n", n, a, b, c)
+}
+

Output:

3: dmr, 1771, 1.618034
+3: ken, 271828, 3.141590
+

func Print

func Print(a ...any) (n int, err error)

Print formats using the default formats for its operands and writes to standard output. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.

Example +

Code:

const name, age = "Kim", 22
+fmt.Print(name, " is ", age, " years old.\n")
+
+// It is conventional not to worry about any
+// error returned by Print.
+
+

Output:

Kim is 22 years old.
+

func Printf

func Printf(format string, a ...any) (n int, err error)

Printf formats according to a format specifier and writes to standard output. It returns the number of bytes written and any write error encountered.

Example +

Code:

const name, age = "Kim", 22
+fmt.Printf("%s is %d years old.\n", name, age)
+
+// It is conventional not to worry about any
+// error returned by Printf.
+
+

Output:

Kim is 22 years old.
+

func Println

func Println(a ...any) (n int, err error)

Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

Example +

Code:

const name, age = "Kim", 22
+fmt.Println(name, "is", age, "years old.")
+
+// It is conventional not to worry about any
+// error returned by Println.
+
+

Output:

Kim is 22 years old.
+

func Scan

func Scan(a ...any) (n int, err error)

Scan scans text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

+

func Scanf

func Scanf(format string, a ...any) (n int, err error)

Scanf scans text read from standard input, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why. Newlines in the input must match newlines in the format. The one exception: the verb %c always scans the next rune in the input, even if it is a space (or tab etc.) or newline.

+

func Scanln

func Scanln(a ...any) (n int, err error)

Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.

+

func Sprint

func Sprint(a ...any) string

Sprint formats using the default formats for its operands and returns the resulting string. Spaces are added between operands when neither is a string.

Example +

Code:

const name, age = "Kim", 22
+s := fmt.Sprint(name, " is ", age, " years old.\n")
+
+io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
+
+

Output:

Kim is 22 years old.
+

func Sprintf

func Sprintf(format string, a ...any) string

Sprintf formats according to a format specifier and returns the resulting string.

Example +

Code:

const name, age = "Kim", 22
+s := fmt.Sprintf("%s is %d years old.\n", name, age)
+
+io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
+
+

Output:

Kim is 22 years old.
+

func Sprintln

func Sprintln(a ...any) string

Sprintln formats using the default formats for its operands and returns the resulting string. Spaces are always added between operands and a newline is appended.

Example +

Code:

const name, age = "Kim", 22
+s := fmt.Sprintln(name, "is", age, "years old.")
+
+io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
+
+

Output:

Kim is 22 years old.
+

func Sscan

func Sscan(str string, a ...any) (n int, err error)

Sscan scans the argument string, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

+

func Sscanf

func Sscanf(str string, format string, a ...any) (n int, err error)

Sscanf scans the argument string, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully parsed. Newlines in the input must match newlines in the format.

Example +

Code:

var name string
+var age int
+n, err := fmt.Sscanf("Kim is 22 years old", "%s is %d years old", &name, &age)
+if err != nil {
+    panic(err)
+}
+fmt.Printf("%d: %s, %d\n", n, name, age)
+
+

Output:

2: Kim, 22
+

func Sscanln

func Sscanln(str string, a ...any) (n int, err error)

Sscanln is similar to Sscan, but stops scanning at a newline and after the final item there must be a newline or EOF.

+

type Formatter

Formatter is implemented by any value that has a Format method. The implementation controls how State and rune are interpreted, and may call Sprint() or Fprint(f) etc. to generate its output.

+
type Formatter interface {
+    Format(f State, verb rune)
+}

type GoStringer

GoStringer is implemented by any value that has a GoString method, which defines the Go syntax for that value. The GoString method is used to print values passed as an operand to a %#v format.

+
type GoStringer interface {
+    GoString() string
+}

Example +

Code:

package fmt_test
+
+import (
+    "fmt"
+)
+
+// Address has a City, State and a Country.
+type Address struct {
+    City    string
+    State   string
+    Country string
+}
+
+// Person has a Name, Age and Address.
+type Person struct {
+    Name string
+    Age  uint
+    Addr *Address
+}
+
+// GoString makes Person satisfy the GoStringer interface.
+// The return value is valid Go code that can be used to reproduce the Person struct.
+func (p Person) GoString() string {
+    if p.Addr != nil {
+        return fmt.Sprintf("Person{Name: %q, Age: %d, Addr: &Address{City: %q, State: %q, Country: %q}}", p.Name, int(p.Age), p.Addr.City, p.Addr.State, p.Addr.Country)
+    }
+    return fmt.Sprintf("Person{Name: %q, Age: %d}", p.Name, int(p.Age))
+}
+
+func ExampleGoStringer() {
+    p1 := Person{
+        Name: "Warren",
+        Age:  31,
+        Addr: &Address{
+            City:    "Denver",
+            State:   "CO",
+            Country: "U.S.A.",
+        },
+    }
+    // If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p1)` would be similar to
+    // Person{Name:"Warren", Age:0x1f, Addr:(*main.Address)(0x10448240)}
+    fmt.Printf("%#v\n", p1)
+
+    p2 := Person{
+        Name: "Theia",
+        Age:  4,
+    }
+    // If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p2)` would be similar to
+    // Person{Name:"Theia", Age:0x4, Addr:(*main.Address)(nil)}
+    fmt.Printf("%#v\n", p2)
+
+    // Output:
+    // Person{Name: "Warren", Age: 31, Addr: &Address{City: "Denver", State: "CO", Country: "U.S.A."}}
+    // Person{Name: "Theia", Age: 4}
+}
+

type ScanState

ScanState represents the scanner state passed to custom scanners. Scanners may do rune-at-a-time scanning or ask the ScanState to discover the next space-delimited token.

+
type ScanState interface {
+    // ReadRune reads the next rune (Unicode code point) from the input.
+    // If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will
+    // return EOF after returning the first '\n' or when reading beyond
+    // the specified width.
+    ReadRune() (r rune, size int, err error)
+    // UnreadRune causes the next call to ReadRune to return the same rune.
+    UnreadRune() error
+    // SkipSpace skips space in the input. Newlines are treated appropriately
+    // for the operation being performed; see the package documentation
+    // for more information.
+    SkipSpace()
+    // Token skips space in the input if skipSpace is true, then returns the
+    // run of Unicode code points c satisfying f(c).  If f is nil,
+    // !unicode.IsSpace(c) is used; that is, the token will hold non-space
+    // characters. Newlines are treated appropriately for the operation being
+    // performed; see the package documentation for more information.
+    // The returned slice points to shared data that may be overwritten
+    // by the next call to Token, a call to a Scan function using the ScanState
+    // as input, or when the calling Scan method returns.
+    Token(skipSpace bool, f func(rune) bool) (token []byte, err error)
+    // Width returns the value of the width option and whether it has been set.
+    // The unit is Unicode code points.
+    Width() (wid int, ok bool)
+    // Because ReadRune is implemented by the interface, Read should never be
+    // called by the scanning routines and a valid implementation of
+    // ScanState may choose always to return an error from Read.
+    Read(buf []byte) (n int, err error)
+}

type Scanner

Scanner is implemented by any value that has a Scan method, which scans the input for the representation of a value and stores the result in the receiver, which must be a pointer to be useful. The Scan method is called for any argument to Scan, Scanf, or Scanln that implements it.

+
type Scanner interface {
+    Scan(state ScanState, verb rune) error
+}

type State

State represents the printer state passed to custom formatters. It provides access to the io.Writer interface plus information about the flags and options for the operand's format specifier.

+
type State interface {
+    // Write is the function to call to emit formatted output to be printed.
+    Write(b []byte) (n int, err error)
+    // Width returns the value of the width option and whether it has been set.
+    Width() (wid int, ok bool)
+    // Precision returns the value of the precision option and whether it has been set.
+    Precision() (prec int, ok bool)
+
+    // Flag reports whether the flag c, a character, has been set.
+    Flag(c int) bool
+}

type Stringer

Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print.

+
type Stringer interface {
+    String() string
+}

Example +

Code:

package fmt_test
+
+import (
+    "fmt"
+)
+
+// Animal has a Name and an Age to represent an animal.
+type Animal struct {
+    Name string
+    Age  uint
+}
+
+// String makes Animal satisfy the Stringer interface.
+func (a Animal) String() string {
+    return fmt.Sprintf("%v (%d)", a.Name, a.Age)
+}
+
+func ExampleStringer() {
+    a := Animal{
+        Name: "Gopher",
+        Age:  2,
+    }
+    fmt.Println(a)
+    // Output: Gopher (2)
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/fmt/ +

+
diff --git a/devdocs/go/go%2Fast%2Findex.html b/devdocs/go/go%2Fast%2Findex.html new file mode 100644 index 00000000..9bd381b0 --- /dev/null +++ b/devdocs/go/go%2Fast%2Findex.html @@ -0,0 +1,1031 @@ +

Package ast

Overview

Package ast declares the types used to represent syntax trees for Go packages.

Index

Examples

CommentMap
Inspect
Print

Package files

ast.go commentmap.go filter.go import.go print.go resolve.go scope.go walk.go

func FileExports

func FileExports(src *File) bool

FileExports trims the AST for a Go source file in place such that only exported nodes remain: all top-level identifiers which are not exported and their associated information (such as type, initial value, or function body) are removed. Non-exported fields and methods of exported types are stripped. The [File.Comments] list is not changed.

+

FileExports reports whether there are exported declarations.

+

func FilterDecl

func FilterDecl(decl Decl, f Filter) bool

FilterDecl trims the AST for a Go declaration in place by removing all names (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f.

+

FilterDecl reports whether there are any declared names left after filtering.

+

func FilterFile

func FilterFile(src *File, f Filter) bool

FilterFile trims the AST for a Go file in place by removing all names from top-level declarations (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f. If the declaration is empty afterwards, the declaration is removed from the AST. Import declarations are always removed. The [File.Comments] list is not changed.

+

FilterFile reports whether there are any top-level declarations left after filtering.

+

func FilterPackage

func FilterPackage(pkg *Package, f Filter) bool

FilterPackage trims the AST for a Go package in place by removing all names from top-level declarations (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f. If the declaration is empty afterwards, the declaration is removed from the AST. The pkg.Files list is not changed, so that file names and top-level package comments don't get lost.

+

FilterPackage reports whether there are any top-level declarations left after filtering.

+

func Fprint

func Fprint(w io.Writer, fset *token.FileSet, x any, f FieldFilter) error

Fprint prints the (sub-)tree starting at AST node x to w. If fset != nil, position information is interpreted relative to that file set. Otherwise positions are printed as integer values (file set specific offsets).

+

A non-nil FieldFilter f may be provided to control the output: struct fields for which f(fieldname, fieldvalue) is true are printed; all others are filtered from the output. Unexported struct fields are never printed.

+

func Inspect

func Inspect(node Node, f func(Node) bool)

Inspect traverses an AST in depth-first order: It starts by calling f(node); node must not be nil. If f returns true, Inspect invokes f recursively for each of the non-nil children of node, followed by a call of f(nil).

Example +

This example demonstrates how to inspect the AST of a Go program.

Code:

// src is the input for which we want to inspect the AST.
+src := `
+package p
+const c = 1.0
+var X = f(3.14)*2 + c
+`
+
+// Create the AST by parsing src.
+fset := token.NewFileSet() // positions are relative to fset
+f, err := parser.ParseFile(fset, "src.go", src, 0)
+if err != nil {
+    panic(err)
+}
+
+// Inspect the AST and print all identifiers and literals.
+ast.Inspect(f, func(n ast.Node) bool {
+    var s string
+    switch x := n.(type) {
+    case *ast.BasicLit:
+        s = x.Value
+    case *ast.Ident:
+        s = x.Name
+    }
+    if s != "" {
+        fmt.Printf("%s:\t%s\n", fset.Position(n.Pos()), s)
+    }
+    return true
+})
+
+

Output:

src.go:2:9:	p
+src.go:3:7:	c
+src.go:3:11:	1.0
+src.go:4:5:	X
+src.go:4:9:	f
+src.go:4:11:	3.14
+src.go:4:17:	2
+src.go:4:21:	c
+

func IsExported

func IsExported(name string) bool

IsExported reports whether name starts with an upper-case letter.

+

func IsGenerated 1.21

func IsGenerated(file *File) bool

IsGenerated reports whether the file was generated by a program, not handwritten, by detecting the special comment described at https://go.dev/s/generatedcode.

+

The syntax tree must have been parsed with the ParseComments flag. Example:

+
f, err := parser.ParseFile(fset, filename, src, parser.ParseComments|parser.PackageClauseOnly)
+if err != nil { ... }
+gen := ast.IsGenerated(f)
+

func NotNilFilter

func NotNilFilter(_ string, v reflect.Value) bool

NotNilFilter returns true for field values that are not nil; it returns false otherwise.

+

func PackageExports

func PackageExports(pkg *Package) bool

PackageExports trims the AST for a Go package in place such that only exported nodes remain. The pkg.Files list is not changed, so that file names and top-level package comments don't get lost.

+

PackageExports reports whether there are exported declarations; it returns false otherwise.

+

func Print

func Print(fset *token.FileSet, x any) error

Print prints x to standard output, skipping nil fields. Print(fset, x) is the same as Fprint(os.Stdout, fset, x, NotNilFilter).

Example +

This example shows what an AST looks like when printed for debugging.

Code:

// src is the input for which we want to print the AST.
+src := `
+package main
+func main() {
+    println("Hello, World!")
+}
+`
+
+// Create the AST by parsing src.
+fset := token.NewFileSet() // positions are relative to fset
+f, err := parser.ParseFile(fset, "", src, 0)
+if err != nil {
+    panic(err)
+}
+
+// Print the AST.
+ast.Print(fset, f)
+
+

Output:

     0  *ast.File {
+     1  .  Package: 2:1
+     2  .  Name: *ast.Ident {
+     3  .  .  NamePos: 2:9
+     4  .  .  Name: "main"
+     5  .  }
+     6  .  Decls: []ast.Decl (len = 1) {
+     7  .  .  0: *ast.FuncDecl {
+     8  .  .  .  Name: *ast.Ident {
+     9  .  .  .  .  NamePos: 3:6
+    10  .  .  .  .  Name: "main"
+    11  .  .  .  .  Obj: *ast.Object {
+    12  .  .  .  .  .  Kind: func
+    13  .  .  .  .  .  Name: "main"
+    14  .  .  .  .  .  Decl: *(obj @ 7)
+    15  .  .  .  .  }
+    16  .  .  .  }
+    17  .  .  .  Type: *ast.FuncType {
+    18  .  .  .  .  Func: 3:1
+    19  .  .  .  .  Params: *ast.FieldList {
+    20  .  .  .  .  .  Opening: 3:10
+    21  .  .  .  .  .  Closing: 3:11
+    22  .  .  .  .  }
+    23  .  .  .  }
+    24  .  .  .  Body: *ast.BlockStmt {
+    25  .  .  .  .  Lbrace: 3:13
+    26  .  .  .  .  List: []ast.Stmt (len = 1) {
+    27  .  .  .  .  .  0: *ast.ExprStmt {
+    28  .  .  .  .  .  .  X: *ast.CallExpr {
+    29  .  .  .  .  .  .  .  Fun: *ast.Ident {
+    30  .  .  .  .  .  .  .  .  NamePos: 4:2
+    31  .  .  .  .  .  .  .  .  Name: "println"
+    32  .  .  .  .  .  .  .  }
+    33  .  .  .  .  .  .  .  Lparen: 4:9
+    34  .  .  .  .  .  .  .  Args: []ast.Expr (len = 1) {
+    35  .  .  .  .  .  .  .  .  0: *ast.BasicLit {
+    36  .  .  .  .  .  .  .  .  .  ValuePos: 4:10
+    37  .  .  .  .  .  .  .  .  .  Kind: STRING
+    38  .  .  .  .  .  .  .  .  .  Value: "\"Hello, World!\""
+    39  .  .  .  .  .  .  .  .  }
+    40  .  .  .  .  .  .  .  }
+    41  .  .  .  .  .  .  .  Ellipsis: -
+    42  .  .  .  .  .  .  .  Rparen: 4:25
+    43  .  .  .  .  .  .  }
+    44  .  .  .  .  .  }
+    45  .  .  .  .  }
+    46  .  .  .  .  Rbrace: 5:1
+    47  .  .  .  }
+    48  .  .  }
+    49  .  }
+    50  .  FileStart: 1:1
+    51  .  FileEnd: 5:3
+    52  .  Scope: *ast.Scope {
+    53  .  .  Objects: map[string]*ast.Object (len = 1) {
+    54  .  .  .  "main": *(obj @ 11)
+    55  .  .  }
+    56  .  }
+    57  .  Unresolved: []*ast.Ident (len = 1) {
+    58  .  .  0: *(obj @ 29)
+    59  .  }
+    60  .  GoVersion: ""
+    61  }
+

func SortImports

func SortImports(fset *token.FileSet, f *File)

SortImports sorts runs of consecutive import lines in import blocks in f. It also removes duplicate imports when it is possible to do so without data loss.

+

func Walk

func Walk(v Visitor, node Node)

Walk traverses an AST in depth-first order: It starts by calling v.Visit(node); node must not be nil. If the visitor w returned by v.Visit(node) is not nil, Walk is invoked recursively with visitor w for each of the non-nil children of node, followed by a call of w.Visit(nil).

+

type ArrayType

An ArrayType node represents an array or slice type.

+
type ArrayType struct {
+    Lbrack token.Pos // position of "["
+    Len    Expr      // Ellipsis node for [...]T array types, nil for slice types
+    Elt    Expr      // element type
+}
+

func (*ArrayType) End

func (x *ArrayType) End() token.Pos

func (*ArrayType) Pos

func (x *ArrayType) Pos() token.Pos

type AssignStmt

An AssignStmt node represents an assignment or a short variable declaration.

+
type AssignStmt struct {
+    Lhs    []Expr
+    TokPos token.Pos   // position of Tok
+    Tok    token.Token // assignment token, DEFINE
+    Rhs    []Expr
+}
+

func (*AssignStmt) End

func (s *AssignStmt) End() token.Pos

func (*AssignStmt) Pos

func (s *AssignStmt) Pos() token.Pos

type BadDecl

A BadDecl node is a placeholder for a declaration containing syntax errors for which a correct declaration node cannot be created.

+
type BadDecl struct {
+    From, To token.Pos // position range of bad declaration
+}
+

func (*BadDecl) End

func (d *BadDecl) End() token.Pos

func (*BadDecl) Pos

func (d *BadDecl) Pos() token.Pos

type BadExpr

A BadExpr node is a placeholder for an expression containing syntax errors for which a correct expression node cannot be created.

+
type BadExpr struct {
+    From, To token.Pos // position range of bad expression
+}
+

func (*BadExpr) End

func (x *BadExpr) End() token.Pos

func (*BadExpr) Pos

func (x *BadExpr) Pos() token.Pos

type BadStmt

A BadStmt node is a placeholder for statements containing syntax errors for which no correct statement nodes can be created.

+
type BadStmt struct {
+    From, To token.Pos // position range of bad statement
+}
+

func (*BadStmt) End

func (s *BadStmt) End() token.Pos

func (*BadStmt) Pos

func (s *BadStmt) Pos() token.Pos

type BasicLit

A BasicLit node represents a literal of basic type.

+
type BasicLit struct {
+    ValuePos token.Pos   // literal position
+    Kind     token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING
+    Value    string      // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f', "foo" or `\m\n\o`
+}
+

func (*BasicLit) End

func (x *BasicLit) End() token.Pos

func (*BasicLit) Pos

func (x *BasicLit) Pos() token.Pos

type BinaryExpr

A BinaryExpr node represents a binary expression.

+
type BinaryExpr struct {
+    X     Expr        // left operand
+    OpPos token.Pos   // position of Op
+    Op    token.Token // operator
+    Y     Expr        // right operand
+}
+

func (*BinaryExpr) End

func (x *BinaryExpr) End() token.Pos

func (*BinaryExpr) Pos

func (x *BinaryExpr) Pos() token.Pos

type BlockStmt

A BlockStmt node represents a braced statement list.

+
type BlockStmt struct {
+    Lbrace token.Pos // position of "{"
+    List   []Stmt
+    Rbrace token.Pos // position of "}", if any (may be absent due to syntax error)
+}
+

func (*BlockStmt) End

func (s *BlockStmt) End() token.Pos

func (*BlockStmt) Pos

func (s *BlockStmt) Pos() token.Pos

type BranchStmt

A BranchStmt node represents a break, continue, goto, or fallthrough statement.

+
type BranchStmt struct {
+    TokPos token.Pos   // position of Tok
+    Tok    token.Token // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH)
+    Label  *Ident      // label name; or nil
+}
+

func (*BranchStmt) End

func (s *BranchStmt) End() token.Pos

func (*BranchStmt) Pos

func (s *BranchStmt) Pos() token.Pos

type CallExpr

A CallExpr node represents an expression followed by an argument list.

+
type CallExpr struct {
+    Fun      Expr      // function expression
+    Lparen   token.Pos // position of "("
+    Args     []Expr    // function arguments; or nil
+    Ellipsis token.Pos // position of "..." (token.NoPos if there is no "...")
+    Rparen   token.Pos // position of ")"
+}
+

func (*CallExpr) End

func (x *CallExpr) End() token.Pos

func (*CallExpr) Pos

func (x *CallExpr) Pos() token.Pos

type CaseClause

A CaseClause represents a case of an expression or type switch statement.

+
type CaseClause struct {
+    Case  token.Pos // position of "case" or "default" keyword
+    List  []Expr    // list of expressions or types; nil means default case
+    Colon token.Pos // position of ":"
+    Body  []Stmt    // statement list; or nil
+}
+

func (*CaseClause) End

func (s *CaseClause) End() token.Pos

func (*CaseClause) Pos

func (s *CaseClause) Pos() token.Pos

type ChanDir

The direction of a channel type is indicated by a bit mask including one or both of the following constants.

+
type ChanDir int
const (
+    SEND ChanDir = 1 << iota
+    RECV
+)

type ChanType

A ChanType node represents a channel type.

+
type ChanType struct {
+    Begin token.Pos // position of "chan" keyword or "<-" (whichever comes first)
+    Arrow token.Pos // position of "<-" (token.NoPos if there is no "<-"); added in Go 1.1
+    Dir   ChanDir   // channel direction
+    Value Expr      // value type
+}
+

func (*ChanType) End

func (x *ChanType) End() token.Pos

func (*ChanType) Pos

func (x *ChanType) Pos() token.Pos

type CommClause

A CommClause node represents a case of a select statement.

+
type CommClause struct {
+    Case  token.Pos // position of "case" or "default" keyword
+    Comm  Stmt      // send or receive statement; nil means default case
+    Colon token.Pos // position of ":"
+    Body  []Stmt    // statement list; or nil
+}
+

func (*CommClause) End

func (s *CommClause) End() token.Pos

func (*CommClause) Pos

func (s *CommClause) Pos() token.Pos

type Comment

A Comment node represents a single //-style or /*-style comment.

+

The Text field contains the comment text without carriage returns (\r) that may have been present in the source. Because a comment's end position is computed using len(Text), the position reported by Comment.End does not match the true source end position for comments containing carriage returns.

+
type Comment struct {
+    Slash token.Pos // position of "/" starting the comment
+    Text  string    // comment text (excluding '\n' for //-style comments)
+}
+

func (*Comment) End

func (c *Comment) End() token.Pos

func (*Comment) Pos

func (c *Comment) Pos() token.Pos

type CommentGroup

A CommentGroup represents a sequence of comments with no other tokens and no empty lines between.

+
type CommentGroup struct {
+    List []*Comment // len(List) > 0
+}
+

func (*CommentGroup) End

func (g *CommentGroup) End() token.Pos

func (*CommentGroup) Pos

func (g *CommentGroup) Pos() token.Pos

func (*CommentGroup) Text

func (g *CommentGroup) Text() string

Text returns the text of the comment. Comment markers (//, /*, and */), the first space of a line comment, and leading and trailing empty lines are removed. Comment directives like "//line" and "//go:noinline" are also removed. Multiple empty lines are reduced to one, and trailing space on lines is trimmed. Unless the result is empty, it is newline-terminated.

+

type CommentMap 1.1

A CommentMap maps an AST node to a list of comment groups associated with it. See NewCommentMap for a description of the association.

+
type CommentMap map[Node][]*CommentGroup

Example +

This example illustrates how to remove a variable declaration in a Go program while maintaining correct comment association using an ast.CommentMap.

Code:

// src is the input for which we create the AST that we
+// are going to manipulate.
+src := `
+// This is the package comment.
+package main
+
+// This comment is associated with the hello constant.
+const hello = "Hello, World!" // line comment 1
+
+// This comment is associated with the foo variable.
+var foo = hello // line comment 2
+
+// This comment is associated with the main function.
+func main() {
+    fmt.Println(hello) // line comment 3
+}
+`
+
+// Create the AST by parsing src.
+fset := token.NewFileSet() // positions are relative to fset
+f, err := parser.ParseFile(fset, "src.go", src, parser.ParseComments)
+if err != nil {
+    panic(err)
+}
+
+// Create an ast.CommentMap from the ast.File's comments.
+// This helps keeping the association between comments
+// and AST nodes.
+cmap := ast.NewCommentMap(fset, f, f.Comments)
+
+// Remove the first variable declaration from the list of declarations.
+for i, decl := range f.Decls {
+    if gen, ok := decl.(*ast.GenDecl); ok && gen.Tok == token.VAR {
+        copy(f.Decls[i:], f.Decls[i+1:])
+        f.Decls = f.Decls[:len(f.Decls)-1]
+        break
+    }
+}
+
+// Use the comment map to filter comments that don't belong anymore
+// (the comments associated with the variable declaration), and create
+// the new comments list.
+f.Comments = cmap.Filter(f).Comments()
+
+// Print the modified AST.
+var buf strings.Builder
+if err := format.Node(&buf, fset, f); err != nil {
+    panic(err)
+}
+fmt.Printf("%s", buf.String())
+
+

Output:

// This is the package comment.
+package main
+
+// This comment is associated with the hello constant.
+const hello = "Hello, World!" // line comment 1
+
+// This comment is associated with the main function.
+func main() {
+	fmt.Println(hello) // line comment 3
+}
+

func NewCommentMap 1.1

func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap

NewCommentMap creates a new comment map by associating comment groups of the comments list with the nodes of the AST specified by node.

+

A comment group g is associated with a node n if:

+

NewCommentMap tries to associate a comment group to the "largest" node possible: For instance, if the comment is a line comment trailing an assignment, the comment is associated with the entire assignment rather than just the last operand in the assignment.

+

func (CommentMap) Comments 1.1

func (cmap CommentMap) Comments() []*CommentGroup

Comments returns the list of comment groups in the comment map. The result is sorted in source order.

+

func (CommentMap) Filter 1.1

func (cmap CommentMap) Filter(node Node) CommentMap

Filter returns a new comment map consisting of only those entries of cmap for which a corresponding node exists in the AST specified by node.

+

func (CommentMap) String 1.1

func (cmap CommentMap) String() string

func (CommentMap) Update 1.1

func (cmap CommentMap) Update(old, new Node) Node

Update replaces an old node in the comment map with the new node and returns the new node. Comments that were associated with the old node are associated with the new node.

+

type CompositeLit

A CompositeLit node represents a composite literal.

+
type CompositeLit struct {
+    Type       Expr      // literal type; or nil
+    Lbrace     token.Pos // position of "{"
+    Elts       []Expr    // list of composite elements; or nil
+    Rbrace     token.Pos // position of "}"
+    Incomplete bool      // true if (source) expressions are missing in the Elts list; added in Go 1.11
+}
+

func (*CompositeLit) End

func (x *CompositeLit) End() token.Pos

func (*CompositeLit) Pos

func (x *CompositeLit) Pos() token.Pos

type Decl

All declaration nodes implement the Decl interface.

+
type Decl interface {
+    Node
+    // contains filtered or unexported methods
+}

type DeclStmt

A DeclStmt node represents a declaration in a statement list.

+
type DeclStmt struct {
+    Decl Decl // *GenDecl with CONST, TYPE, or VAR token
+}
+

func (*DeclStmt) End

func (s *DeclStmt) End() token.Pos

func (*DeclStmt) Pos

func (s *DeclStmt) Pos() token.Pos

type DeferStmt

A DeferStmt node represents a defer statement.

+
type DeferStmt struct {
+    Defer token.Pos // position of "defer" keyword
+    Call  *CallExpr
+}
+

func (*DeferStmt) End

func (s *DeferStmt) End() token.Pos

func (*DeferStmt) Pos

func (s *DeferStmt) Pos() token.Pos

type Ellipsis

An Ellipsis node stands for the "..." type in a parameter list or the "..." length in an array type.

+
type Ellipsis struct {
+    Ellipsis token.Pos // position of "..."
+    Elt      Expr      // ellipsis element type (parameter lists only); or nil
+}
+

func (*Ellipsis) End

func (x *Ellipsis) End() token.Pos

func (*Ellipsis) Pos

func (x *Ellipsis) Pos() token.Pos

type EmptyStmt

An EmptyStmt node represents an empty statement. The "position" of the empty statement is the position of the immediately following (explicit or implicit) semicolon.

+
type EmptyStmt struct {
+    Semicolon token.Pos // position of following ";"
+    Implicit  bool      // if set, ";" was omitted in the source; added in Go 1.5
+}
+

func (*EmptyStmt) End

func (s *EmptyStmt) End() token.Pos

func (*EmptyStmt) Pos

func (s *EmptyStmt) Pos() token.Pos

type Expr

All expression nodes implement the Expr interface.

+
type Expr interface {
+    Node
+    // contains filtered or unexported methods
+}

func Unparen 1.22

func Unparen(e Expr) Expr

Unparen returns the expression with any enclosing parentheses removed.

+

type ExprStmt

An ExprStmt node represents a (stand-alone) expression in a statement list.

+
type ExprStmt struct {
+    X Expr // expression
+}
+

func (*ExprStmt) End

func (s *ExprStmt) End() token.Pos

func (*ExprStmt) Pos

func (s *ExprStmt) Pos() token.Pos

type Field

A Field represents a Field declaration list in a struct type, a method list in an interface type, or a parameter/result declaration in a signature. [Field.Names] is nil for unnamed parameters (parameter lists which only contain types) and embedded struct fields. In the latter case, the field name is the type name.

+
type Field struct {
+    Doc     *CommentGroup // associated documentation; or nil
+    Names   []*Ident      // field/method/(type) parameter names; or nil
+    Type    Expr          // field/method/parameter type; or nil
+    Tag     *BasicLit     // field tag; or nil
+    Comment *CommentGroup // line comments; or nil
+}
+

func (*Field) End

func (f *Field) End() token.Pos

func (*Field) Pos

func (f *Field) Pos() token.Pos

type FieldFilter

A FieldFilter may be provided to Fprint to control the output.

+
type FieldFilter func(name string, value reflect.Value) bool

type FieldList

A FieldList represents a list of Fields, enclosed by parentheses, curly braces, or square brackets.

+
type FieldList struct {
+    Opening token.Pos // position of opening parenthesis/brace/bracket, if any
+    List    []*Field  // field list; or nil
+    Closing token.Pos // position of closing parenthesis/brace/bracket, if any
+}
+

func (*FieldList) End

func (f *FieldList) End() token.Pos

func (*FieldList) NumFields

func (f *FieldList) NumFields() int

NumFields returns the number of parameters or struct fields represented by a FieldList.

+

func (*FieldList) Pos

func (f *FieldList) Pos() token.Pos

type File

A File node represents a Go source file.

+

The Comments list contains all comments in the source file in order of appearance, including the comments that are pointed to from other nodes via Doc and Comment fields.

+

For correct printing of source code containing comments (using packages go/format and go/printer), special care must be taken to update comments when a File's syntax tree is modified: For printing, comments are interspersed between tokens based on their position. If syntax tree nodes are removed or moved, relevant comments in their vicinity must also be removed (from the [File.Comments] list) or moved accordingly (by updating their positions). A CommentMap may be used to facilitate some of these operations.

+

Whether and how a comment is associated with a node depends on the interpretation of the syntax tree by the manipulating program: Except for Doc and Comment comments directly associated with nodes, the remaining comments are "free-floating" (see also issues #18593, #20744).

+
type File struct {
+    Doc     *CommentGroup // associated documentation; or nil
+    Package token.Pos     // position of "package" keyword
+    Name    *Ident        // package name
+    Decls   []Decl        // top-level declarations; or nil
+
+    FileStart, FileEnd token.Pos       // start and end of entire file; added in Go 1.20
+    Scope              *Scope          // package scope (this file only). Deprecated: see Object
+    Imports            []*ImportSpec   // imports in this file
+    Unresolved         []*Ident        // unresolved identifiers in this file. Deprecated: see Object
+    Comments           []*CommentGroup // list of all comments in the source file
+    GoVersion          string          // minimum Go version required by //go:build or // +build directives; added in Go 1.21
+}
+

func MergePackageFiles

func MergePackageFiles(pkg *Package, mode MergeMode) *File

MergePackageFiles creates a file AST by merging the ASTs of the files belonging to a package. The mode flags control merging behavior.

+

func (*File) End

func (f *File) End() token.Pos

End returns the end of the last declaration in the file. (Use FileEnd for the end of the entire file.)

+

func (*File) Pos

func (f *File) Pos() token.Pos

Pos returns the position of the package declaration. (Use FileStart for the start of the entire file.)

+

type Filter

type Filter func(string) bool

type ForStmt

A ForStmt represents a for statement.

+
type ForStmt struct {
+    For  token.Pos // position of "for" keyword
+    Init Stmt      // initialization statement; or nil
+    Cond Expr      // condition; or nil
+    Post Stmt      // post iteration statement; or nil
+    Body *BlockStmt
+}
+

func (*ForStmt) End

func (s *ForStmt) End() token.Pos

func (*ForStmt) Pos

func (s *ForStmt) Pos() token.Pos

type FuncDecl

A FuncDecl node represents a function declaration.

+
type FuncDecl struct {
+    Doc  *CommentGroup // associated documentation; or nil
+    Recv *FieldList    // receiver (methods); or nil (functions)
+    Name *Ident        // function/method name
+    Type *FuncType     // function signature: type and value parameters, results, and position of "func" keyword
+    Body *BlockStmt    // function body; or nil for external (non-Go) function
+}
+

func (*FuncDecl) End

func (d *FuncDecl) End() token.Pos

func (*FuncDecl) Pos

func (d *FuncDecl) Pos() token.Pos

type FuncLit

A FuncLit node represents a function literal.

+
type FuncLit struct {
+    Type *FuncType  // function type
+    Body *BlockStmt // function body
+}
+

func (*FuncLit) End

func (x *FuncLit) End() token.Pos

func (*FuncLit) Pos

func (x *FuncLit) Pos() token.Pos

type FuncType

A FuncType node represents a function type.

+
type FuncType struct {
+    Func       token.Pos  // position of "func" keyword (token.NoPos if there is no "func")
+    TypeParams *FieldList // type parameters; or nil; added in Go 1.18
+    Params     *FieldList // (incoming) parameters; non-nil
+    Results    *FieldList // (outgoing) results; or nil
+}
+

func (*FuncType) End

func (x *FuncType) End() token.Pos

func (*FuncType) Pos

func (x *FuncType) Pos() token.Pos

type GenDecl

A GenDecl node (generic declaration node) represents an import, constant, type or variable declaration. A valid Lparen position (Lparen.IsValid()) indicates a parenthesized declaration.

+

Relationship between Tok value and Specs element type:

+
token.IMPORT  *ImportSpec
+token.CONST   *ValueSpec
+token.TYPE    *TypeSpec
+token.VAR     *ValueSpec
+
type GenDecl struct {
+    Doc    *CommentGroup // associated documentation; or nil
+    TokPos token.Pos     // position of Tok
+    Tok    token.Token   // IMPORT, CONST, TYPE, or VAR
+    Lparen token.Pos     // position of '(', if any
+    Specs  []Spec
+    Rparen token.Pos // position of ')', if any
+}
+

func (*GenDecl) End

func (d *GenDecl) End() token.Pos

func (*GenDecl) Pos

func (d *GenDecl) Pos() token.Pos

type GoStmt

A GoStmt node represents a go statement.

+
type GoStmt struct {
+    Go   token.Pos // position of "go" keyword
+    Call *CallExpr
+}
+

func (*GoStmt) End

func (s *GoStmt) End() token.Pos

func (*GoStmt) Pos

func (s *GoStmt) Pos() token.Pos

type Ident

An Ident node represents an identifier.

+
type Ident struct {
+    NamePos token.Pos // identifier position
+    Name    string    // identifier name
+    Obj     *Object   // denoted object, or nil. Deprecated: see Object.
+}
+

func NewIdent

func NewIdent(name string) *Ident

NewIdent creates a new Ident without position. Useful for ASTs generated by code other than the Go parser.

+

func (*Ident) End

func (x *Ident) End() token.Pos

func (*Ident) IsExported

func (id *Ident) IsExported() bool

IsExported reports whether id starts with an upper-case letter.

+

func (*Ident) Pos

func (x *Ident) Pos() token.Pos

func (*Ident) String

func (id *Ident) String() string

type IfStmt

An IfStmt node represents an if statement.

+
type IfStmt struct {
+    If   token.Pos // position of "if" keyword
+    Init Stmt      // initialization statement; or nil
+    Cond Expr      // condition
+    Body *BlockStmt
+    Else Stmt // else branch; or nil
+}
+

func (*IfStmt) End

func (s *IfStmt) End() token.Pos

func (*IfStmt) Pos

func (s *IfStmt) Pos() token.Pos

type ImportSpec

An ImportSpec node represents a single package import.

+
type ImportSpec struct {
+    Doc     *CommentGroup // associated documentation; or nil
+    Name    *Ident        // local package name (including "."); or nil
+    Path    *BasicLit     // import path
+    Comment *CommentGroup // line comments; or nil
+    EndPos  token.Pos     // end of spec (overrides Path.Pos if nonzero)
+}
+

func (*ImportSpec) End

func (s *ImportSpec) End() token.Pos

func (*ImportSpec) Pos

func (s *ImportSpec) Pos() token.Pos

type Importer

An Importer resolves import paths to package Objects. The imports map records the packages already imported, indexed by package id (canonical import path). An Importer must determine the canonical import path and check the map to see if it is already present in the imports map. If so, the Importer can return the map entry. Otherwise, the Importer should load the package data for the given path into a new *Object (pkg), record pkg in the imports map, and then return pkg.

+

Deprecated: use the type checker go/types instead; see Object.

+
type Importer func(imports map[string]*Object, path string) (pkg *Object, err error)

type IncDecStmt

An IncDecStmt node represents an increment or decrement statement.

+
type IncDecStmt struct {
+    X      Expr
+    TokPos token.Pos   // position of Tok
+    Tok    token.Token // INC or DEC
+}
+

func (*IncDecStmt) End

func (s *IncDecStmt) End() token.Pos

func (*IncDecStmt) Pos

func (s *IncDecStmt) Pos() token.Pos

type IndexExpr

An IndexExpr node represents an expression followed by an index.

+
type IndexExpr struct {
+    X      Expr      // expression
+    Lbrack token.Pos // position of "["
+    Index  Expr      // index expression
+    Rbrack token.Pos // position of "]"
+}
+

func (*IndexExpr) End

func (x *IndexExpr) End() token.Pos

func (*IndexExpr) Pos

func (x *IndexExpr) Pos() token.Pos

type IndexListExpr 1.18

An IndexListExpr node represents an expression followed by multiple indices.

+
type IndexListExpr struct {
+    X       Expr      // expression
+    Lbrack  token.Pos // position of "["
+    Indices []Expr    // index expressions
+    Rbrack  token.Pos // position of "]"
+}
+

func (*IndexListExpr) End 1.18

func (x *IndexListExpr) End() token.Pos

func (*IndexListExpr) Pos 1.18

func (x *IndexListExpr) Pos() token.Pos

type InterfaceType

An InterfaceType node represents an interface type.

+
type InterfaceType struct {
+    Interface  token.Pos  // position of "interface" keyword
+    Methods    *FieldList // list of embedded interfaces, methods, or types
+    Incomplete bool       // true if (source) methods or types are missing in the Methods list
+}
+

func (*InterfaceType) End

func (x *InterfaceType) End() token.Pos

func (*InterfaceType) Pos

func (x *InterfaceType) Pos() token.Pos

type KeyValueExpr

A KeyValueExpr node represents (key : value) pairs in composite literals.

+
type KeyValueExpr struct {
+    Key   Expr
+    Colon token.Pos // position of ":"
+    Value Expr
+}
+

func (*KeyValueExpr) End

func (x *KeyValueExpr) End() token.Pos

func (*KeyValueExpr) Pos

func (x *KeyValueExpr) Pos() token.Pos

type LabeledStmt

A LabeledStmt node represents a labeled statement.

+
type LabeledStmt struct {
+    Label *Ident
+    Colon token.Pos // position of ":"
+    Stmt  Stmt
+}
+

func (*LabeledStmt) End

func (s *LabeledStmt) End() token.Pos

func (*LabeledStmt) Pos

func (s *LabeledStmt) Pos() token.Pos

type MapType

A MapType node represents a map type.

+
type MapType struct {
+    Map   token.Pos // position of "map" keyword
+    Key   Expr
+    Value Expr
+}
+

func (*MapType) End

func (x *MapType) End() token.Pos

func (*MapType) Pos

func (x *MapType) Pos() token.Pos

type MergeMode

The MergeMode flags control the behavior of MergePackageFiles.

+
type MergeMode uint
const (
+    // If set, duplicate function declarations are excluded.
+    FilterFuncDuplicates MergeMode = 1 << iota
+    // If set, comments that are not associated with a specific
+    // AST node (as Doc or Comment) are excluded.
+    FilterUnassociatedComments
+    // If set, duplicate import declarations are excluded.
+    FilterImportDuplicates
+)

type Node

All node types implement the Node interface.

+
type Node interface {
+    Pos() token.Pos // position of first character belonging to the node
+    End() token.Pos // position of first character immediately after the node
+}

type ObjKind

ObjKind describes what an object represents.

+
type ObjKind int

The list of possible Object kinds.

+
const (
+    Bad ObjKind = iota // for error handling
+    Pkg                // package
+    Con                // constant
+    Typ                // type
+    Var                // variable
+    Fun                // function or method
+    Lbl                // label
+)

func (ObjKind) String

func (kind ObjKind) String() string

type Object

An Object describes a named language entity such as a package, constant, type, variable, function (incl. methods), or label.

+

The Data fields contains object-specific data:

+
Kind    Data type         Data value
+Pkg     *Scope            package scope
+Con     int               iota for the respective declaration
+

Deprecated: The relationship between Idents and Objects cannot be correctly computed without type information. For example, the expression T{K: 0} may denote a struct, map, slice, or array literal, depending on the type of T. If T is a struct, then K refers to a field of T, whereas for the other types it refers to a value in the environment.

+

New programs should set the [parser.SkipObjectResolution] parser flag to disable syntactic object resolution (which also saves CPU and memory), and instead use the type checker go/types if object resolution is desired. See the Defs, Uses, and Implicits fields of the [types.Info] struct for details.

+
type Object struct {
+    Kind ObjKind
+    Name string // declared name
+    Decl any    // corresponding Field, XxxSpec, FuncDecl, LabeledStmt, AssignStmt, Scope; or nil
+    Data any    // object-specific data; or nil
+    Type any    // placeholder for type information; may be nil
+}
+

func NewObj

func NewObj(kind ObjKind, name string) *Object

NewObj creates a new object of a given kind and name.

+

func (*Object) Pos

func (obj *Object) Pos() token.Pos

Pos computes the source position of the declaration of an object name. The result may be an invalid position if it cannot be computed (obj.Decl may be nil or not correct).

+

type Package

A Package node represents a set of source files collectively building a Go package.

+

Deprecated: use the type checker go/types instead; see Object.

+
type Package struct {
+    Name    string             // package name
+    Scope   *Scope             // package scope across all files
+    Imports map[string]*Object // map of package id -> package object
+    Files   map[string]*File   // Go source files by filename
+}
+

func NewPackage

func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error)

NewPackage creates a new Package node from a set of File nodes. It resolves unresolved identifiers across files and updates each file's Unresolved list accordingly. If a non-nil importer and universe scope are provided, they are used to resolve identifiers not declared in any of the package files. Any remaining unresolved identifiers are reported as undeclared. If the files belong to different packages, one package name is selected and files with different package names are reported and then ignored. The result is a package node and a scanner.ErrorList if there were errors.

+

Deprecated: use the type checker go/types instead; see Object.

+

func (*Package) End

func (p *Package) End() token.Pos

func (*Package) Pos

func (p *Package) Pos() token.Pos

type ParenExpr

A ParenExpr node represents a parenthesized expression.

+
type ParenExpr struct {
+    Lparen token.Pos // position of "("
+    X      Expr      // parenthesized expression
+    Rparen token.Pos // position of ")"
+}
+

func (*ParenExpr) End

func (x *ParenExpr) End() token.Pos

func (*ParenExpr) Pos

func (x *ParenExpr) Pos() token.Pos

type RangeStmt

A RangeStmt represents a for statement with a range clause.

+
type RangeStmt struct {
+    For        token.Pos   // position of "for" keyword
+    Key, Value Expr        // Key, Value may be nil
+    TokPos     token.Pos   // position of Tok; invalid if Key == nil
+    Tok        token.Token // ILLEGAL if Key == nil, ASSIGN, DEFINE
+    Range      token.Pos   // position of "range" keyword; added in Go 1.20
+    X          Expr        // value to range over
+    Body       *BlockStmt
+}
+

func (*RangeStmt) End

func (s *RangeStmt) End() token.Pos

func (*RangeStmt) Pos

func (s *RangeStmt) Pos() token.Pos

type ReturnStmt

A ReturnStmt node represents a return statement.

+
type ReturnStmt struct {
+    Return  token.Pos // position of "return" keyword
+    Results []Expr    // result expressions; or nil
+}
+

func (*ReturnStmt) End

func (s *ReturnStmt) End() token.Pos

func (*ReturnStmt) Pos

func (s *ReturnStmt) Pos() token.Pos

type Scope

A Scope maintains the set of named language entities declared in the scope and a link to the immediately surrounding (outer) scope.

+

Deprecated: use the type checker go/types instead; see Object.

+
type Scope struct {
+    Outer   *Scope
+    Objects map[string]*Object
+}
+

func NewScope

func NewScope(outer *Scope) *Scope

NewScope creates a new scope nested in the outer scope.

+

func (*Scope) Insert

func (s *Scope) Insert(obj *Object) (alt *Object)

Insert attempts to insert a named object obj into the scope s. If the scope already contains an object alt with the same name, Insert leaves the scope unchanged and returns alt. Otherwise it inserts obj and returns nil.

+

func (*Scope) Lookup

func (s *Scope) Lookup(name string) *Object

Lookup returns the object with the given name if it is found in scope s, otherwise it returns nil. Outer scopes are ignored.

+

func (*Scope) String

func (s *Scope) String() string

Debugging support

+

type SelectStmt

A SelectStmt node represents a select statement.

+
type SelectStmt struct {
+    Select token.Pos  // position of "select" keyword
+    Body   *BlockStmt // CommClauses only
+}
+

func (*SelectStmt) End

func (s *SelectStmt) End() token.Pos

func (*SelectStmt) Pos

func (s *SelectStmt) Pos() token.Pos

type SelectorExpr

A SelectorExpr node represents an expression followed by a selector.

+
type SelectorExpr struct {
+    X   Expr   // expression
+    Sel *Ident // field selector
+}
+

func (*SelectorExpr) End

func (x *SelectorExpr) End() token.Pos

func (*SelectorExpr) Pos

func (x *SelectorExpr) Pos() token.Pos

type SendStmt

A SendStmt node represents a send statement.

+
type SendStmt struct {
+    Chan  Expr
+    Arrow token.Pos // position of "<-"
+    Value Expr
+}
+

func (*SendStmt) End

func (s *SendStmt) End() token.Pos

func (*SendStmt) Pos

func (s *SendStmt) Pos() token.Pos

type SliceExpr

A SliceExpr node represents an expression followed by slice indices.

+
type SliceExpr struct {
+    X      Expr      // expression
+    Lbrack token.Pos // position of "["
+    Low    Expr      // begin of slice range; or nil
+    High   Expr      // end of slice range; or nil
+    Max    Expr      // maximum capacity of slice; or nil; added in Go 1.2
+    Slice3 bool      // true if 3-index slice (2 colons present); added in Go 1.2
+    Rbrack token.Pos // position of "]"
+}
+

func (*SliceExpr) End

func (x *SliceExpr) End() token.Pos

func (*SliceExpr) Pos

func (x *SliceExpr) Pos() token.Pos

type Spec

The Spec type stands for any of *ImportSpec, *ValueSpec, and *TypeSpec.

+
type Spec interface {
+    Node
+    // contains filtered or unexported methods
+}

type StarExpr

A StarExpr node represents an expression of the form "*" Expression. Semantically it could be a unary "*" expression, or a pointer type.

+
type StarExpr struct {
+    Star token.Pos // position of "*"
+    X    Expr      // operand
+}
+

func (*StarExpr) End

func (x *StarExpr) End() token.Pos

func (*StarExpr) Pos

func (x *StarExpr) Pos() token.Pos

type Stmt

All statement nodes implement the Stmt interface.

+
type Stmt interface {
+    Node
+    // contains filtered or unexported methods
+}

type StructType

A StructType node represents a struct type.

+
type StructType struct {
+    Struct     token.Pos  // position of "struct" keyword
+    Fields     *FieldList // list of field declarations
+    Incomplete bool       // true if (source) fields are missing in the Fields list
+}
+

func (*StructType) End

func (x *StructType) End() token.Pos

func (*StructType) Pos

func (x *StructType) Pos() token.Pos

type SwitchStmt

A SwitchStmt node represents an expression switch statement.

+
type SwitchStmt struct {
+    Switch token.Pos  // position of "switch" keyword
+    Init   Stmt       // initialization statement; or nil
+    Tag    Expr       // tag expression; or nil
+    Body   *BlockStmt // CaseClauses only
+}
+

func (*SwitchStmt) End

func (s *SwitchStmt) End() token.Pos

func (*SwitchStmt) Pos

func (s *SwitchStmt) Pos() token.Pos

type TypeAssertExpr

A TypeAssertExpr node represents an expression followed by a type assertion.

+
type TypeAssertExpr struct {
+    X      Expr      // expression
+    Lparen token.Pos // position of "("; added in Go 1.2
+    Type   Expr      // asserted type; nil means type switch X.(type)
+    Rparen token.Pos // position of ")"; added in Go 1.2
+}
+

func (*TypeAssertExpr) End

func (x *TypeAssertExpr) End() token.Pos

func (*TypeAssertExpr) Pos

func (x *TypeAssertExpr) Pos() token.Pos

type TypeSpec

A TypeSpec node represents a type declaration (TypeSpec production).

+
type TypeSpec struct {
+    Doc        *CommentGroup // associated documentation; or nil
+    Name       *Ident        // type name
+    TypeParams *FieldList    // type parameters; or nil; added in Go 1.18
+    Assign     token.Pos     // position of '=', if any; added in Go 1.9
+    Type       Expr          // *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes
+    Comment    *CommentGroup // line comments; or nil
+}
+

func (*TypeSpec) End

func (s *TypeSpec) End() token.Pos

func (*TypeSpec) Pos

func (s *TypeSpec) Pos() token.Pos

type TypeSwitchStmt

A TypeSwitchStmt node represents a type switch statement.

+
type TypeSwitchStmt struct {
+    Switch token.Pos  // position of "switch" keyword
+    Init   Stmt       // initialization statement; or nil
+    Assign Stmt       // x := y.(type) or y.(type)
+    Body   *BlockStmt // CaseClauses only
+}
+

func (*TypeSwitchStmt) End

func (s *TypeSwitchStmt) End() token.Pos

func (*TypeSwitchStmt) Pos

func (s *TypeSwitchStmt) Pos() token.Pos

type UnaryExpr

A UnaryExpr node represents a unary expression. Unary "*" expressions are represented via StarExpr nodes.

+
type UnaryExpr struct {
+    OpPos token.Pos   // position of Op
+    Op    token.Token // operator
+    X     Expr        // operand
+}
+

func (*UnaryExpr) End

func (x *UnaryExpr) End() token.Pos

func (*UnaryExpr) Pos

func (x *UnaryExpr) Pos() token.Pos

type ValueSpec

A ValueSpec node represents a constant or variable declaration (ConstSpec or VarSpec production).

+
type ValueSpec struct {
+    Doc     *CommentGroup // associated documentation; or nil
+    Names   []*Ident      // value names (len(Names) > 0)
+    Type    Expr          // value type; or nil
+    Values  []Expr        // initial values; or nil
+    Comment *CommentGroup // line comments; or nil
+}
+

func (*ValueSpec) End

func (s *ValueSpec) End() token.Pos

func (*ValueSpec) Pos

func (s *ValueSpec) Pos() token.Pos

type Visitor

A Visitor's Visit method is invoked for each node encountered by Walk. If the result visitor w is not nil, Walk visits each of the children of node with the visitor w, followed by a call of w.Visit(nil).

+
type Visitor interface {
+    Visit(node Node) (w Visitor)
+}
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/ast/ +

+
diff --git a/devdocs/go/go%2Fbuild%2Fconstraint%2Findex.html b/devdocs/go/go%2Fbuild%2Fconstraint%2Findex.html new file mode 100644 index 00000000..1a648460 --- /dev/null +++ b/devdocs/go/go%2Fbuild%2Fconstraint%2Findex.html @@ -0,0 +1,88 @@ +

Package constraint

Overview

Package constraint implements parsing and evaluation of build constraint lines. See https://golang.org/cmd/go/#hdr-Build_constraints for documentation about build constraints themselves.

+

This package parses both the original “// +build” syntax and the “//go:build” syntax that was added in Go 1.17. See https://golang.org/design/draft-gobuild for details about the “//go:build” syntax.

Index

Package files

expr.go vers.go

func GoVersion 1.21

func GoVersion(x Expr) string

GoVersion returns the minimum Go version implied by a given build expression. If the expression can be satisfied without any Go version tags, GoVersion returns an empty string.

+

For example:

+
GoVersion(linux && go1.22) = "go1.22"
+GoVersion((linux && go1.22) || (windows && go1.20)) = "go1.20" => go1.20
+GoVersion(linux) = ""
+GoVersion(linux || (windows && go1.22)) = ""
+GoVersion(!go1.22) = ""
+

GoVersion assumes that any tag or negated tag may independently be true, so that its analysis can be purely structural, without SAT solving. “Impossible” subexpressions may therefore affect the result.

+

For example:

+
GoVersion((linux && !linux && go1.20) || go1.21) = "go1.20"
+

func IsGoBuild 1.16

func IsGoBuild(line string) bool

IsGoBuild reports whether the line of text is a “//go:build” constraint. It only checks the prefix of the text, not that the expression itself parses.

+

func IsPlusBuild 1.16

func IsPlusBuild(line string) bool

IsPlusBuild reports whether the line of text is a “// +build” constraint. It only checks the prefix of the text, not that the expression itself parses.

+

func PlusBuildLines 1.16

func PlusBuildLines(x Expr) ([]string, error)

PlusBuildLines returns a sequence of “// +build” lines that evaluate to the build expression x. If the expression is too complex to convert directly to “// +build” lines, PlusBuildLines returns an error.

+

type AndExpr 1.16

An AndExpr represents the expression X && Y.

+
type AndExpr struct {
+    X, Y Expr
+}
+

func (*AndExpr) Eval 1.16

func (x *AndExpr) Eval(ok func(tag string) bool) bool

func (*AndExpr) String 1.16

func (x *AndExpr) String() string

type Expr 1.16

An Expr is a build tag constraint expression. The underlying concrete type is *AndExpr, *OrExpr, *NotExpr, or *TagExpr.

+
type Expr interface {
+    // String returns the string form of the expression,
+    // using the boolean syntax used in //go:build lines.
+    String() string
+
+    // Eval reports whether the expression evaluates to true.
+    // It calls ok(tag) as needed to find out whether a given build tag
+    // is satisfied by the current build configuration.
+    Eval(ok func(tag string) bool) bool
+    // contains filtered or unexported methods
+}

func Parse 1.16

func Parse(line string) (Expr, error)

Parse parses a single build constraint line of the form “//go:build ...” or “// +build ...” and returns the corresponding boolean expression.

+

type NotExpr 1.16

A NotExpr represents the expression !X (the negation of X).

+
type NotExpr struct {
+    X Expr
+}
+

func (*NotExpr) Eval 1.16

func (x *NotExpr) Eval(ok func(tag string) bool) bool

func (*NotExpr) String 1.16

func (x *NotExpr) String() string

type OrExpr 1.16

An OrExpr represents the expression X || Y.

+
type OrExpr struct {
+    X, Y Expr
+}
+

func (*OrExpr) Eval 1.16

func (x *OrExpr) Eval(ok func(tag string) bool) bool

func (*OrExpr) String 1.16

func (x *OrExpr) String() string

type SyntaxError 1.16

A SyntaxError reports a syntax error in a parsed build expression.

+
type SyntaxError struct {
+    Offset int    // byte offset in input where error was detected
+    Err    string // description of error
+}
+

func (*SyntaxError) Error 1.16

func (e *SyntaxError) Error() string

type TagExpr 1.16

A TagExpr is an Expr for the single tag Tag.

+
type TagExpr struct {
+    Tag string // for example, “linux” or “cgo”
+}
+

func (*TagExpr) Eval 1.16

func (x *TagExpr) Eval(ok func(tag string) bool) bool

func (*TagExpr) String 1.16

func (x *TagExpr) String() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/build/constraint/ +

+
diff --git a/devdocs/go/go%2Fbuild%2Findex.html b/devdocs/go/go%2Fbuild%2Findex.html new file mode 100644 index 00000000..68a204ff --- /dev/null +++ b/devdocs/go/go%2Fbuild%2Findex.html @@ -0,0 +1,293 @@ +

Package build

Overview

Package build gathers information about Go packages.

+

Go Path

The Go path is a list of directory trees containing Go source code. It is consulted to resolve imports that cannot be found in the standard Go tree. The default path is the value of the GOPATH environment variable, interpreted as a path list appropriate to the operating system (on Unix, the variable is a colon-separated string; on Windows, a semicolon-separated string; on Plan 9, a list).

+

Each directory listed in the Go path must have a prescribed structure:

+

The src/ directory holds source code. The path below 'src' determines the import path or executable name.

+

The pkg/ directory holds installed package objects. As in the Go tree, each target operating system and architecture pair has its own subdirectory of pkg (pkg/GOOS_GOARCH).

+

If DIR is a directory listed in the Go path, a package with source in DIR/src/foo/bar can be imported as "foo/bar" and has its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a" (or, for gccgo, "DIR/pkg/gccgo/foo/libbar.a").

+

The bin/ directory holds compiled commands. Each command is named for its source directory, but only using the final element, not the entire path. That is, the command with source in DIR/src/foo/quux is installed into DIR/bin/quux, not DIR/bin/foo/quux. The foo/ is stripped so that you can add DIR/bin to your PATH to get at the installed commands.

+

Here's an example directory layout:

+
GOPATH=/home/user/gocode
+
+/home/user/gocode/
+    src/
+        foo/
+            bar/               (go code in package bar)
+                x.go
+            quux/              (go code in package main)
+                y.go
+    bin/
+        quux                   (installed command)
+    pkg/
+        linux_amd64/
+            foo/
+                bar.a          (installed package object)
+

Build Constraints

A build constraint, also known as a build tag, is a condition under which a file should be included in the package. Build constraints are given by a line comment that begins

+
//go:build
+

Build constraints may also be part of a file's name (for example, source_windows.go will only be included if the target operating system is windows).

+

See 'go help buildconstraint' (https://golang.org/cmd/go/#hdr-Build_constraints) for details.

+

Binary-Only Packages

In Go 1.12 and earlier, it was possible to distribute packages in binary form without including the source code used for compiling the package. The package was distributed with a source file not excluded by build constraints and containing a "//go:binary-only-package" comment. Like a build constraint, this comment appeared at the top of a file, preceded only by blank lines and other line comments and with a blank line following the comment, to separate it from the package documentation. Unlike build constraints, this comment is only recognized in non-test Go source files.

+

The minimal source code for a binary-only package was therefore:

+
//go:binary-only-package
+
+package mypkg
+

The source code could include additional Go code. That code was never compiled but would be processed by tools like godoc and might be useful as end-user documentation.

+

"go build" and other commands no longer support binary-only-packages. Import and ImportDir will still set the BinaryOnly flag in packages containing these comments for use in tools and error messages.

Index

Package files

build.go doc.go gc.go read.go syslist.go zcgo.go

Variables

ToolDir is the directory containing build tools.

+
var ToolDir = getToolDir()

func ArchChar

func ArchChar(goarch string) (string, error)

ArchChar returns "?" and an error. In earlier versions of Go, the returned string was used to derive the compiler and linker tool names, the default object file suffix, and the default linker output name. As of Go 1.5, those strings no longer vary by architecture; they are compile, link, .o, and a.out, respectively.

+

func IsLocalImport

func IsLocalImport(path string) bool

IsLocalImport reports whether the import path is a local import path, like ".", "..", "./foo", or "../foo".

+

type Context

A Context specifies the supporting context for a build.

+
type Context struct {
+    GOARCH string // target architecture
+    GOOS   string // target operating system
+    GOROOT string // Go root
+    GOPATH string // Go paths
+
+    // Dir is the caller's working directory, or the empty string to use
+    // the current directory of the running process. In module mode, this is used
+    // to locate the main module.
+    //
+    // If Dir is non-empty, directories passed to Import and ImportDir must
+    // be absolute.
+    Dir string // Go 1.14
+
+    CgoEnabled  bool   // whether cgo files are included
+    UseAllFiles bool   // use files regardless of go:build lines, file names
+    Compiler    string // compiler to assume when computing target paths
+
+    // The build, tool, and release tags specify build constraints
+    // that should be considered satisfied when processing go:build lines.
+    // Clients creating a new context may customize BuildTags, which
+    // defaults to empty, but it is usually an error to customize ToolTags or ReleaseTags.
+    // ToolTags defaults to build tags appropriate to the current Go toolchain configuration.
+    // ReleaseTags defaults to the list of Go releases the current release is compatible with.
+    // BuildTags is not set for the Default build Context.
+    // In addition to the BuildTags, ToolTags, and ReleaseTags, build constraints
+    // consider the values of GOARCH and GOOS as satisfied tags.
+    // The last element in ReleaseTags is assumed to be the current release.
+    BuildTags   []string
+    ToolTags    []string // Go 1.17
+    ReleaseTags []string // Go 1.1
+
+    // The install suffix specifies a suffix to use in the name of the installation
+    // directory. By default it is empty, but custom builds that need to keep
+    // their outputs separate can set InstallSuffix to do so. For example, when
+    // using the race detector, the go command uses InstallSuffix = "race", so
+    // that on a Linux/386 system, packages are written to a directory named
+    // "linux_386_race" instead of the usual "linux_386".
+    InstallSuffix string // Go 1.1
+
+    // JoinPath joins the sequence of path fragments into a single path.
+    // If JoinPath is nil, Import uses filepath.Join.
+    JoinPath func(elem ...string) string
+
+    // SplitPathList splits the path list into a slice of individual paths.
+    // If SplitPathList is nil, Import uses filepath.SplitList.
+    SplitPathList func(list string) []string
+
+    // IsAbsPath reports whether path is an absolute path.
+    // If IsAbsPath is nil, Import uses filepath.IsAbs.
+    IsAbsPath func(path string) bool
+
+    // IsDir reports whether the path names a directory.
+    // If IsDir is nil, Import calls os.Stat and uses the result's IsDir method.
+    IsDir func(path string) bool
+
+    // HasSubdir reports whether dir is lexically a subdirectory of
+    // root, perhaps multiple levels below. It does not try to check
+    // whether dir exists.
+    // If so, HasSubdir sets rel to a slash-separated path that
+    // can be joined to root to produce a path equivalent to dir.
+    // If HasSubdir is nil, Import uses an implementation built on
+    // filepath.EvalSymlinks.
+    HasSubdir func(root, dir string) (rel string, ok bool)
+
+    // ReadDir returns a slice of fs.FileInfo, sorted by Name,
+    // describing the content of the named directory.
+    // If ReadDir is nil, Import uses os.ReadDir.
+    ReadDir func(dir string) ([]fs.FileInfo, error)
+
+    // OpenFile opens a file (not a directory) for reading.
+    // If OpenFile is nil, Import uses os.Open.
+    OpenFile func(path string) (io.ReadCloser, error)
+}
+

Default is the default Context for builds. It uses the GOARCH, GOOS, GOROOT, and GOPATH environment variables if set, or else the compiled code's GOARCH, GOOS, and GOROOT.

+
var Default Context = defaultContext()

func (*Context) Import

func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error)

Import returns details about the Go package named by the import path, interpreting local import paths relative to the srcDir directory. If the path is a local import path naming a package that can be imported using a standard import path, the returned package will set p.ImportPath to that path.

+

In the directory containing the package, .go, .c, .h, and .s files are considered part of the package except for:

+

If an error occurs, Import returns a non-nil error and a non-nil *Package containing partial information.

+

func (*Context) ImportDir

func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error)

ImportDir is like Import but processes the Go package found in the named directory.

+

func (*Context) MatchFile 1.2

func (ctxt *Context) MatchFile(dir, name string) (match bool, err error)

MatchFile reports whether the file with the given name in the given directory matches the context and would be included in a Package created by ImportDir of that directory.

+

MatchFile considers the name of the file and may use ctxt.OpenFile to read some or all of the file's content.

+

func (*Context) SrcDirs

func (ctxt *Context) SrcDirs() []string

SrcDirs returns a list of package source root directories. It draws from the current Go root and Go path but omits directories that do not exist.

+

type Directive 1.21

A Directive is a Go directive comment (//go:zzz...) found in a source file.

+
type Directive struct {
+    Text string         // full line comment including leading slashes
+    Pos  token.Position // position of comment
+}
+

type ImportMode

An ImportMode controls the behavior of the Import method.

+
type ImportMode uint
const (
+    // If FindOnly is set, Import stops after locating the directory
+    // that should contain the sources for a package. It does not
+    // read any files in the directory.
+    FindOnly ImportMode = 1 << iota
+
+    // If AllowBinary is set, Import can be satisfied by a compiled
+    // package object without corresponding sources.
+    //
+    // Deprecated:
+    // The supported way to create a compiled-only package is to
+    // write source code containing a //go:binary-only-package comment at
+    // the top of the file. Such a package will be recognized
+    // regardless of this flag setting (because it has source code)
+    // and will have BinaryOnly set to true in the returned Package.
+    AllowBinary
+
+    // If ImportComment is set, parse import comments on package statements.
+    // Import returns an error if it finds a comment it cannot understand
+    // or finds conflicting comments in multiple source files.
+    // See golang.org/s/go14customimport for more information.
+    ImportComment
+
+    // By default, Import searches vendor directories
+    // that apply in the given source directory before searching
+    // the GOROOT and GOPATH roots.
+    // If an Import finds and returns a package using a vendor
+    // directory, the resulting ImportPath is the complete path
+    // to the package, including the path elements leading up
+    // to and including "vendor".
+    // For example, if Import("y", "x/subdir", 0) finds
+    // "x/vendor/y", the returned package's ImportPath is "x/vendor/y",
+    // not plain "y".
+    // See golang.org/s/go15vendor for more information.
+    //
+    // Setting IgnoreVendor ignores vendor directories.
+    //
+    // In contrast to the package's ImportPath,
+    // the returned package's Imports, TestImports, and XTestImports
+    // are always the exact import paths from the source files:
+    // Import makes no attempt to resolve or check those paths.
+    IgnoreVendor
+)

type MultiplePackageError 1.4

MultiplePackageError describes a directory containing multiple buildable Go source files for multiple packages.

+
type MultiplePackageError struct {
+    Dir      string   // directory containing files
+    Packages []string // package names found
+    Files    []string // corresponding files: Files[i] declares package Packages[i]
+}
+

func (*MultiplePackageError) Error 1.4

func (e *MultiplePackageError) Error() string

type NoGoError

NoGoError is the error used by Import to describe a directory containing no buildable Go source files. (It may still contain test files, files hidden by build tags, and so on.)

+
type NoGoError struct {
+    Dir string
+}
+

func (*NoGoError) Error

func (e *NoGoError) Error() string

type Package

A Package describes the Go package found in a directory.

+
type Package struct {
+    Dir           string   // directory containing package sources
+    Name          string   // package name
+    ImportComment string   // path in import comment on package statement; added in Go 1.4
+    Doc           string   // documentation synopsis
+    ImportPath    string   // import path of package ("" if unknown)
+    Root          string   // root of Go tree where this package lives
+    SrcRoot       string   // package source root directory ("" if unknown)
+    PkgRoot       string   // package install root directory ("" if unknown)
+    PkgTargetRoot string   // architecture dependent install root directory ("" if unknown); added in Go 1.5
+    BinDir        string   // command install directory ("" if unknown)
+    Goroot        bool     // package found in Go root
+    PkgObj        string   // installed .a file
+    AllTags       []string // tags that can influence file selection in this directory; added in Go 1.2
+    ConflictDir   string   // this directory shadows Dir in $GOPATH; added in Go 1.2
+    BinaryOnly    bool     // cannot be rebuilt from source (has //go:binary-only-package comment); added in Go 1.7
+
+    // Source files
+    GoFiles           []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
+    CgoFiles          []string // .go source files that import "C"
+    IgnoredGoFiles    []string // .go source files ignored for this build (including ignored _test.go files); added in Go 1.1
+    InvalidGoFiles    []string // .go source files with detected problems (parse error, wrong package name, and so on); added in Go 1.6
+    IgnoredOtherFiles []string // non-.go source files ignored for this build; added in Go 1.16
+    CFiles            []string // .c source files
+    CXXFiles          []string // .cc, .cpp and .cxx source files; added in Go 1.2
+    MFiles            []string // .m (Objective-C) source files; added in Go 1.3
+    HFiles            []string // .h, .hh, .hpp and .hxx source files
+    FFiles            []string // .f, .F, .for and .f90 Fortran source files; added in Go 1.7
+    SFiles            []string // .s source files
+    SwigFiles         []string // .swig files; added in Go 1.1
+    SwigCXXFiles      []string // .swigcxx files; added in Go 1.1
+    SysoFiles         []string // .syso system object files to add to archive
+
+    // Cgo directives
+    CgoCFLAGS    []string // Cgo CFLAGS directives
+    CgoCPPFLAGS  []string // Cgo CPPFLAGS directives; added in Go 1.2
+    CgoCXXFLAGS  []string // Cgo CXXFLAGS directives; added in Go 1.2
+    CgoFFLAGS    []string // Cgo FFLAGS directives; added in Go 1.7
+    CgoLDFLAGS   []string // Cgo LDFLAGS directives
+    CgoPkgConfig []string // Cgo pkg-config directives
+
+    // Test information
+    TestGoFiles  []string // _test.go files in package
+    XTestGoFiles []string // _test.go files outside package
+
+    // Go directive comments (//go:zzz...) found in source files.
+    Directives      []Directive // Go 1.21
+    TestDirectives  []Directive // Go 1.21
+    XTestDirectives []Directive // Go 1.21
+
+    // Dependency information
+    Imports        []string                    // import paths from GoFiles, CgoFiles
+    ImportPos      map[string][]token.Position // line information for Imports
+    TestImports    []string                    // import paths from TestGoFiles
+    TestImportPos  map[string][]token.Position // line information for TestImports
+    XTestImports   []string                    // import paths from XTestGoFiles
+    XTestImportPos map[string][]token.Position // line information for XTestImports
+
+    // //go:embed patterns found in Go source files
+    // For example, if a source file says
+    //	//go:embed a* b.c
+    // then the list will contain those two strings as separate entries.
+    // (See package embed for more details about //go:embed.)
+    EmbedPatterns        []string                    // patterns from GoFiles, CgoFiles; added in Go 1.16
+    EmbedPatternPos      map[string][]token.Position // line information for EmbedPatterns; added in Go 1.16
+    TestEmbedPatterns    []string                    // patterns from TestGoFiles; added in Go 1.16
+    TestEmbedPatternPos  map[string][]token.Position // line information for TestEmbedPatterns; added in Go 1.16
+    XTestEmbedPatterns   []string                    // patterns from XTestGoFiles; added in Go 1.16
+    XTestEmbedPatternPos map[string][]token.Position // line information for XTestEmbedPatternPos; added in Go 1.16
+}
+

func Import

func Import(path, srcDir string, mode ImportMode) (*Package, error)

Import is shorthand for Default.Import.

+

func ImportDir

func ImportDir(dir string, mode ImportMode) (*Package, error)

ImportDir is shorthand for Default.ImportDir.

+

func (*Package) IsCommand

func (p *Package) IsCommand() bool

IsCommand reports whether the package is considered a command to be installed (not just a library). Packages named "main" are treated as commands.

+

Subdirectories

Name Synopsis
..
constraint Package constraint implements parsing and evaluation of build constraint lines.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/build/ +

+
diff --git a/devdocs/go/go%2Fconstant%2Findex.html b/devdocs/go/go%2Fconstant%2Findex.html new file mode 100644 index 00000000..817a4dcc --- /dev/null +++ b/devdocs/go/go%2Fconstant%2Findex.html @@ -0,0 +1,290 @@ +

Package constant

Overview

Package constant implements Values representing untyped Go constants and their corresponding operations.

+

A special Unknown value may be used when a value is unknown due to an error. Operations on unknown values produce unknown values unless specified otherwise.

Example (ComplexNumbers) +

Code:

// Create the complex number 2.3 + 5i.
+ar := constant.MakeFloat64(2.3)
+ai := constant.MakeImag(constant.MakeInt64(5))
+a := constant.BinaryOp(ar, token.ADD, ai)
+
+// Compute (2.3 + 5i) * 11.
+b := constant.MakeUint64(11)
+c := constant.BinaryOp(a, token.MUL, b)
+
+// Convert c into a complex128.
+Ar, exact := constant.Float64Val(constant.Real(c))
+if !exact {
+    fmt.Printf("Could not represent real part %s exactly as float64\n", constant.Real(c))
+}
+Ai, exact := constant.Float64Val(constant.Imag(c))
+if !exact {
+    fmt.Printf("Could not represent imaginary part %s as exactly as float64\n", constant.Imag(c))
+}
+C := complex(Ar, Ai)
+
+fmt.Println("literal", 25.3+55i)
+fmt.Println("go/constant", c)
+fmt.Println("complex128", C)
+
+

Output:

+Could not represent real part 25.3 exactly as float64
+literal (25.3+55i)
+go/constant (25.3 + 55i)
+complex128 (25.299999999999997+55i)
+

Index

Examples

BinaryOp
Compare
Sign
UnaryOp
Val
Package (ComplexNumbers)

Package files

kind_string.go value.go

func BitLen 1.5

func BitLen(x Value) int

BitLen returns the number of bits required to represent the absolute value x in binary representation; x must be an Int or an Unknown. If x is Unknown, the result is 0.

+

func BoolVal 1.5

func BoolVal(x Value) bool

BoolVal returns the Go boolean value of x, which must be a Bool or an Unknown. If x is Unknown, the result is false.

+

func Bytes 1.5

func Bytes(x Value) []byte

Bytes returns the bytes for the absolute value of x in little- endian binary representation; x must be an Int.

+

func Compare 1.5

func Compare(x_ Value, op token.Token, y_ Value) bool

Compare returns the result of the comparison x op y. The comparison must be defined for the operands. If one of the operands is Unknown, the result is false.

Example +

Code:

vs := []constant.Value{
+    constant.MakeString("Z"),
+    constant.MakeString("bacon"),
+    constant.MakeString("go"),
+    constant.MakeString("Frame"),
+    constant.MakeString("defer"),
+    constant.MakeFromLiteral(`"a"`, token.STRING, 0),
+}
+
+sort.Slice(vs, func(i, j int) bool {
+    // Equivalent to vs[i] <= vs[j].
+    return constant.Compare(vs[i], token.LEQ, vs[j])
+})
+
+for _, v := range vs {
+    fmt.Println(constant.StringVal(v))
+}
+
+

Output:

+Frame
+Z
+a
+bacon
+defer
+go
+

func Float32Val 1.5

func Float32Val(x Value) (float32, bool)

Float32Val is like Float64Val but for float32 instead of float64.

+

func Float64Val 1.5

func Float64Val(x Value) (float64, bool)

Float64Val returns the nearest Go float64 value of x and whether the result is exact; x must be numeric or an Unknown, but not Complex. For values too small (too close to 0) to represent as float64, Float64Val silently underflows to 0. The result sign always matches the sign of x, even for 0. If x is Unknown, the result is (0, false).

+

func Int64Val 1.5

func Int64Val(x Value) (int64, bool)

Int64Val returns the Go int64 value of x and whether the result is exact; x must be an Int or an Unknown. If the result is not exact, its value is undefined. If x is Unknown, the result is (0, false).

+

func Sign 1.5

func Sign(x Value) int

Sign returns -1, 0, or 1 depending on whether x < 0, x == 0, or x > 0; x must be numeric or Unknown. For complex values x, the sign is 0 if x == 0, otherwise it is != 0. If x is Unknown, the result is 1.

Example +

Code:

zero := constant.MakeInt64(0)
+one := constant.MakeInt64(1)
+negOne := constant.MakeInt64(-1)
+
+mkComplex := func(a, b constant.Value) constant.Value {
+    b = constant.MakeImag(b)
+    return constant.BinaryOp(a, token.ADD, b)
+}
+
+vs := []constant.Value{
+    negOne,
+    mkComplex(zero, negOne),
+    mkComplex(one, negOne),
+    mkComplex(negOne, one),
+    mkComplex(negOne, negOne),
+    zero,
+    mkComplex(zero, zero),
+    one,
+    mkComplex(zero, one),
+    mkComplex(one, one),
+}
+
+for _, v := range vs {
+    fmt.Printf("% d %s\n", constant.Sign(v), v)
+}
+
+

Output:

+-1 -1
+-1 (0 + -1i)
+-1 (1 + -1i)
+-1 (-1 + 1i)
+-1 (-1 + -1i)
+ 0 0
+ 0 (0 + 0i)
+ 1 1
+ 1 (0 + 1i)
+ 1 (1 + 1i)
+

func StringVal 1.5

func StringVal(x Value) string

StringVal returns the Go string value of x, which must be a String or an Unknown. If x is Unknown, the result is "".

+

func Uint64Val 1.5

func Uint64Val(x Value) (uint64, bool)

Uint64Val returns the Go uint64 value of x and whether the result is exact; x must be an Int or an Unknown. If the result is not exact, its value is undefined. If x is Unknown, the result is (0, false).

+

func Val 1.13

func Val(x Value) any

Val returns the underlying value for a given constant. Since it returns an interface, it is up to the caller to type assert the result to the expected type. The possible dynamic return types are:

+
x Kind             type of result
+-----------------------------------------
+Bool               bool
+String             string
+Int                int64 or *big.Int
+Float              *big.Float or *big.Rat
+everything else    nil
+

Example +

Code:

maxint := constant.MakeInt64(math.MaxInt64)
+fmt.Printf("%v\n", constant.Val(maxint))
+
+e := constant.MakeFloat64(math.E)
+fmt.Printf("%v\n", constant.Val(e))
+
+b := constant.MakeBool(true)
+fmt.Printf("%v\n", constant.Val(b))
+
+b = constant.Make(false)
+fmt.Printf("%v\n", constant.Val(b))
+
+

Output:

+9223372036854775807
+6121026514868073/2251799813685248
+true
+false
+

type Kind 1.5

Kind specifies the kind of value represented by a Value.

+
type Kind int
const (
+    // unknown values
+    Unknown Kind = iota
+
+    // non-numeric values
+    Bool
+    String
+
+    // numeric values
+    Int
+    Float
+    Complex
+)

func (Kind) String 1.18

func (i Kind) String() string

type Value 1.5

A Value represents the value of a Go constant.

+
type Value interface {
+    // Kind returns the value kind.
+    Kind() Kind
+
+    // String returns a short, quoted (human-readable) form of the value.
+    // For numeric values, the result may be an approximation;
+    // for String values the result may be a shortened string.
+    // Use ExactString for a string representing a value exactly.
+    String() string
+
+    // ExactString returns an exact, quoted (human-readable) form of the value.
+    // If the Value is of Kind String, use StringVal to obtain the unquoted string.
+    ExactString() string
+    // contains filtered or unexported methods
+}

func BinaryOp 1.5

func BinaryOp(x_ Value, op token.Token, y_ Value) Value

BinaryOp returns the result of the binary expression x op y. The operation must be defined for the operands. If one of the operands is Unknown, the result is Unknown. BinaryOp doesn't handle comparisons or shifts; use Compare or Shift instead.

+

To force integer division of Int operands, use op == token.QUO_ASSIGN instead of token.QUO; the result is guaranteed to be Int in this case. Division by zero leads to a run-time panic.

Example +

Code:

// 11 / 0.5
+a := constant.MakeUint64(11)
+b := constant.MakeFloat64(0.5)
+c := constant.BinaryOp(a, token.QUO, b)
+fmt.Println(c)
+
+

Output:

22
+

func Denom 1.5

func Denom(x Value) Value

Denom returns the denominator of x; x must be Int, Float, or Unknown. If x is Unknown, or if it is too large or small to represent as a fraction, the result is Unknown. Otherwise the result is an Int >= 1.

+

func Imag 1.5

func Imag(x Value) Value

Imag returns the imaginary part of x, which must be a numeric or unknown value. If x is Unknown, the result is Unknown.

+

func Make 1.13

func Make(x any) Value

Make returns the Value for x.

+
type of x        result Kind
+----------------------------
+bool             Bool
+string           String
+int64            Int
+*big.Int         Int
+*big.Float       Float
+*big.Rat         Float
+anything else    Unknown
+

func MakeBool 1.5

func MakeBool(b bool) Value

MakeBool returns the Bool value for b.

+

func MakeFloat64 1.5

func MakeFloat64(x float64) Value

MakeFloat64 returns the Float value for x. If x is -0.0, the result is 0.0. If x is not finite, the result is an Unknown.

+

func MakeFromBytes 1.5

func MakeFromBytes(bytes []byte) Value

MakeFromBytes returns the Int value given the bytes of its little-endian binary representation. An empty byte slice argument represents 0.

+

func MakeFromLiteral 1.5

func MakeFromLiteral(lit string, tok token.Token, zero uint) Value

MakeFromLiteral returns the corresponding integer, floating-point, imaginary, character, or string value for a Go literal string. The tok value must be one of token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING. The final argument must be zero. If the literal string syntax is invalid, the result is an Unknown.

+

func MakeImag 1.5

func MakeImag(x Value) Value

MakeImag returns the Complex value x*i; x must be Int, Float, or Unknown. If x is Unknown, the result is Unknown.

+

func MakeInt64 1.5

func MakeInt64(x int64) Value

MakeInt64 returns the Int value for x.

+

func MakeString 1.5

func MakeString(s string) Value

MakeString returns the String value for s.

+

func MakeUint64 1.5

func MakeUint64(x uint64) Value

MakeUint64 returns the Int value for x.

+

func MakeUnknown 1.5

func MakeUnknown() Value

MakeUnknown returns the Unknown value.

+

func Num 1.5

func Num(x Value) Value

Num returns the numerator of x; x must be Int, Float, or Unknown. If x is Unknown, or if it is too large or small to represent as a fraction, the result is Unknown. Otherwise the result is an Int with the same sign as x.

+

func Real 1.5

func Real(x Value) Value

Real returns the real part of x, which must be a numeric or unknown value. If x is Unknown, the result is Unknown.

+

func Shift 1.5

func Shift(x Value, op token.Token, s uint) Value

Shift returns the result of the shift expression x op s with op == token.SHL or token.SHR (<< or >>). x must be an Int or an Unknown. If x is Unknown, the result is x.

+

func ToComplex 1.6

func ToComplex(x Value) Value

ToComplex converts x to a Complex value if x is representable as a Complex. Otherwise it returns an Unknown.

+

func ToFloat 1.6

func ToFloat(x Value) Value

ToFloat converts x to a Float value if x is representable as a Float. Otherwise it returns an Unknown.

+

func ToInt 1.6

func ToInt(x Value) Value

ToInt converts x to an Int value if x is representable as an Int. Otherwise it returns an Unknown.

+

func UnaryOp 1.5

func UnaryOp(op token.Token, y Value, prec uint) Value

UnaryOp returns the result of the unary expression op y. The operation must be defined for the operand. If prec > 0 it specifies the ^ (xor) result size in bits. If y is Unknown, the result is Unknown.

Example +

Code:

vs := []constant.Value{
+    constant.MakeBool(true),
+    constant.MakeFloat64(2.7),
+    constant.MakeUint64(42),
+}
+
+for i, v := range vs {
+    switch v.Kind() {
+    case constant.Bool:
+        vs[i] = constant.UnaryOp(token.NOT, v, 0)
+
+    case constant.Float:
+        vs[i] = constant.UnaryOp(token.SUB, v, 0)
+
+    case constant.Int:
+        // Use 16-bit precision.
+        // This would be equivalent to ^uint16(v).
+        vs[i] = constant.UnaryOp(token.XOR, v, 16)
+    }
+}
+
+for _, v := range vs {
+    fmt.Println(v)
+}
+
+

Output:

+false
+-2.7
+65493
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/constant/ +

+
diff --git a/devdocs/go/go%2Fdoc%2Fcomment%2Findex.html b/devdocs/go/go%2Fdoc%2Fcomment%2Findex.html new file mode 100644 index 00000000..00978525 --- /dev/null +++ b/devdocs/go/go%2Fdoc%2Fcomment%2Findex.html @@ -0,0 +1,256 @@ +

Package comment

Overview

Package comment implements parsing and reformatting of Go doc comments, (documentation comments), which are comments that immediately precede a top-level declaration of a package, const, func, type, or var.

+

Go doc comment syntax is a simplified subset of Markdown that supports links, headings, paragraphs, lists (without nesting), and preformatted text blocks. The details of the syntax are documented at https://go.dev/doc/comment.

+

To parse the text associated with a doc comment (after removing comment markers), use a Parser:

+
var p comment.Parser
+doc := p.Parse(text)
+

The result is a *Doc. To reformat it as a doc comment, HTML, Markdown, or plain text, use a Printer:

+
var pr comment.Printer
+os.Stdout.Write(pr.Text(doc))
+

The Parser and Printer types are structs whose fields can be modified to customize the operations. For details, see the documentation for those types.

+

Use cases that need additional control over reformatting can implement their own logic by inspecting the parsed syntax itself. See the documentation for Doc, Block, Text for an overview and links to additional types.

Index

Package files

doc.go html.go markdown.go parse.go print.go std.go text.go

func DefaultLookupPackage 1.19

func DefaultLookupPackage(name string) (importPath string, ok bool)

DefaultLookupPackage is the default package lookup function, used when [Parser.LookupPackage] is nil. It recognizes names of the packages from the standard library with single-element import paths, such as math, which would otherwise be impossible to name.

+

Note that the go/doc package provides a more sophisticated lookup based on the imports used in the current package.

+

type Block 1.19

A Block is block-level content in a doc comment, one of *Code, *Heading, *List, or *Paragraph.

+
type Block interface {
+    // contains filtered or unexported methods
+}

type Code 1.19

A Code is a preformatted code block.

+
type Code struct {
+    // Text is the preformatted text, ending with a newline character.
+    // It may be multiple lines, each of which ends with a newline character.
+    // It is never empty, nor does it start or end with a blank line.
+    Text string
+}
+

type Doc 1.19

A Doc is a parsed Go doc comment.

+
type Doc struct {
+    // Content is the sequence of content blocks in the comment.
+    Content []Block
+
+    // Links is the link definitions in the comment.
+    Links []*LinkDef
+}
+

A DocLink is a link to documentation for a Go package or symbol.

+
type DocLink struct {
+    Text []Text // text of link
+
+    // ImportPath, Recv, and Name identify the Go package or symbol
+    // that is the link target. The potential combinations of
+    // non-empty fields are:
+    //  - ImportPath: a link to another package
+    //  - ImportPath, Name: a link to a const, func, type, or var in another package
+    //  - ImportPath, Recv, Name: a link to a method in another package
+    //  - Name: a link to a const, func, type, or var in this package
+    //  - Recv, Name: a link to a method in this package
+    ImportPath string // import path
+    Recv       string // receiver type, without any pointer star, for methods
+    Name       string // const, func, type, var, or method name
+}
+

func (*DocLink) DefaultURL 1.19

func (l *DocLink) DefaultURL(baseURL string) string

DefaultURL constructs and returns the documentation URL for l, using baseURL as a prefix for links to other packages.

+

The possible forms returned by DefaultURL are:

+

If baseURL ends in a trailing slash, then DefaultURL inserts a slash between ImportPath and # in the anchored forms. For example, here are some baseURL values and URLs they can generate:

+
"/pkg/" → "/pkg/math/#Sqrt"
+"/pkg"  → "/pkg/math#Sqrt"
+"/"     → "/math/#Sqrt"
+""      → "/math#Sqrt"
+

type Heading 1.19

A Heading is a doc comment heading.

+
type Heading struct {
+    Text []Text // the heading text
+}
+

func (*Heading) DefaultID 1.19

func (h *Heading) DefaultID() string

DefaultID returns the default anchor ID for the heading h.

+

The default anchor ID is constructed by converting every rune that is not alphanumeric ASCII to an underscore and then adding the prefix “hdr-”. For example, if the heading text is “Go Doc Comments”, the default ID is “hdr-Go_Doc_Comments”.

+

type Italic 1.19

An Italic is a string rendered as italicized text.

+
type Italic string

A Link is a link to a specific URL.

+
type Link struct {
+    Auto bool   // is this an automatic (implicit) link of a literal URL?
+    Text []Text // text of link
+    URL  string // target URL of link
+}
+

type LinkDef 1.19

A LinkDef is a single link definition.

+
type LinkDef struct {
+    Text string // the link text
+    URL  string // the link URL
+    Used bool   // whether the comment uses the definition
+}
+

type List 1.19

A List is a numbered or bullet list. Lists are always non-empty: len(Items) > 0. In a numbered list, every Items[i].Number is a non-empty string. In a bullet list, every Items[i].Number is an empty string.

+
type List struct {
+    // Items is the list items.
+    Items []*ListItem
+
+    // ForceBlankBefore indicates that the list must be
+    // preceded by a blank line when reformatting the comment,
+    // overriding the usual conditions. See the BlankBefore method.
+    //
+    // The comment parser sets ForceBlankBefore for any list
+    // that is preceded by a blank line, to make sure
+    // the blank line is preserved when printing.
+    ForceBlankBefore bool
+
+    // ForceBlankBetween indicates that list items must be
+    // separated by blank lines when reformatting the comment,
+    // overriding the usual conditions. See the BlankBetween method.
+    //
+    // The comment parser sets ForceBlankBetween for any list
+    // that has a blank line between any two of its items, to make sure
+    // the blank lines are preserved when printing.
+    ForceBlankBetween bool
+}
+

func (*List) BlankBefore 1.19

func (l *List) BlankBefore() bool

BlankBefore reports whether a reformatting of the comment should include a blank line before the list. The default rule is the same as for [BlankBetween]: if the list item content contains any blank lines (meaning at least one item has multiple paragraphs) then the list itself must be preceded by a blank line. A preceding blank line can be forced by setting List.ForceBlankBefore.

+

func (*List) BlankBetween 1.19

func (l *List) BlankBetween() bool

BlankBetween reports whether a reformatting of the comment should include a blank line between each pair of list items. The default rule is that if the list item content contains any blank lines (meaning at least one item has multiple paragraphs) then list items must themselves be separated by blank lines. Blank line separators can be forced by setting List.ForceBlankBetween.

+

type ListItem 1.19

A ListItem is a single item in a numbered or bullet list.

+
type ListItem struct {
+    // Number is a decimal string in a numbered list
+    // or an empty string in a bullet list.
+    Number string // "1", "2", ...; "" for bullet list
+
+    // Content is the list content.
+    // Currently, restrictions in the parser and printer
+    // require every element of Content to be a *Paragraph.
+    Content []Block // Content of this item.
+}
+

type Paragraph 1.19

A Paragraph is a paragraph of text.

+
type Paragraph struct {
+    Text []Text
+}
+

type Parser 1.19

A Parser is a doc comment parser. The fields in the struct can be filled in before calling Parser.Parse in order to customize the details of the parsing process.

+
type Parser struct {
+    // Words is a map of Go identifier words that
+    // should be italicized and potentially linked.
+    // If Words[w] is the empty string, then the word w
+    // is only italicized. Otherwise it is linked, using
+    // Words[w] as the link target.
+    // Words corresponds to the [go/doc.ToHTML] words parameter.
+    Words map[string]string
+
+    // LookupPackage resolves a package name to an import path.
+    //
+    // If LookupPackage(name) returns ok == true, then [name]
+    // (or [name.Sym] or [name.Sym.Method])
+    // is considered a documentation link to importPath's package docs.
+    // It is valid to return "", true, in which case name is considered
+    // to refer to the current package.
+    //
+    // If LookupPackage(name) returns ok == false,
+    // then [name] (or [name.Sym] or [name.Sym.Method])
+    // will not be considered a documentation link,
+    // except in the case where name is the full (but single-element) import path
+    // of a package in the standard library, such as in [math] or [io.Reader].
+    // LookupPackage is still called for such names,
+    // in order to permit references to imports of other packages
+    // with the same package names.
+    //
+    // Setting LookupPackage to nil is equivalent to setting it to
+    // a function that always returns "", false.
+    LookupPackage func(name string) (importPath string, ok bool)
+
+    // LookupSym reports whether a symbol name or method name
+    // exists in the current package.
+    //
+    // If LookupSym("", "Name") returns true, then [Name]
+    // is considered a documentation link for a const, func, type, or var.
+    //
+    // Similarly, if LookupSym("Recv", "Name") returns true,
+    // then [Recv.Name] is considered a documentation link for
+    // type Recv's method Name.
+    //
+    // Setting LookupSym to nil is equivalent to setting it to a function
+    // that always returns false.
+    LookupSym func(recv, name string) (ok bool)
+}
+

func (*Parser) Parse 1.19

func (p *Parser) Parse(text string) *Doc

Parse parses the doc comment text and returns the *Doc form. Comment markers (/* // and */) in the text must have already been removed.

+

type Plain 1.19

A Plain is a string rendered as plain text (not italicized).

+
type Plain string

type Printer 1.19

A Printer is a doc comment printer. The fields in the struct can be filled in before calling any of the printing methods in order to customize the details of the printing process.

+
type Printer struct {
+    // HeadingLevel is the nesting level used for
+    // HTML and Markdown headings.
+    // If HeadingLevel is zero, it defaults to level 3,
+    // meaning to use <h3> and ###.
+    HeadingLevel int
+
+    // HeadingID is a function that computes the heading ID
+    // (anchor tag) to use for the heading h when generating
+    // HTML and Markdown. If HeadingID returns an empty string,
+    // then the heading ID is omitted.
+    // If HeadingID is nil, h.DefaultID is used.
+    HeadingID func(h *Heading) string
+
+    // DocLinkURL is a function that computes the URL for the given DocLink.
+    // If DocLinkURL is nil, then link.DefaultURL(p.DocLinkBaseURL) is used.
+    DocLinkURL func(link *DocLink) string
+
+    // DocLinkBaseURL is used when DocLinkURL is nil,
+    // passed to [DocLink.DefaultURL] to construct a DocLink's URL.
+    // See that method's documentation for details.
+    DocLinkBaseURL string
+
+    // TextPrefix is a prefix to print at the start of every line
+    // when generating text output using the Text method.
+    TextPrefix string
+
+    // TextCodePrefix is the prefix to print at the start of each
+    // preformatted (code block) line when generating text output,
+    // instead of (not in addition to) TextPrefix.
+    // If TextCodePrefix is the empty string, it defaults to TextPrefix+"\t".
+    TextCodePrefix string
+
+    // TextWidth is the maximum width text line to generate,
+    // measured in Unicode code points,
+    // excluding TextPrefix and the newline character.
+    // If TextWidth is zero, it defaults to 80 minus the number of code points in TextPrefix.
+    // If TextWidth is negative, there is no limit.
+    TextWidth int
+}
+

func (*Printer) Comment 1.19

func (p *Printer) Comment(d *Doc) []byte

Comment returns the standard Go formatting of the Doc, without any comment markers.

+

func (*Printer) HTML 1.19

func (p *Printer) HTML(d *Doc) []byte

HTML returns an HTML formatting of the Doc. See the Printer documentation for ways to customize the HTML output.

+

func (*Printer) Markdown 1.19

func (p *Printer) Markdown(d *Doc) []byte

Markdown returns a Markdown formatting of the Doc. See the Printer documentation for ways to customize the Markdown output.

+

func (*Printer) Text 1.19

func (p *Printer) Text(d *Doc) []byte

Text returns a textual formatting of the Doc. See the Printer documentation for ways to customize the text output.

+

type Text 1.19

A Text is text-level content in a doc comment, one of Plain, Italic, *Link, or *DocLink.

+
type Text interface {
+    // contains filtered or unexported methods
+}
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/doc/comment/ +

+
diff --git a/devdocs/go/go%2Fdoc%2Findex.html b/devdocs/go/go%2Fdoc%2Findex.html new file mode 100644 index 00000000..1402067d --- /dev/null +++ b/devdocs/go/go%2Fdoc%2Findex.html @@ -0,0 +1,237 @@ +

Package doc

Overview

Package doc extracts source code documentation from a Go AST.

Index

Examples

NewFromFiles

Package files

comment.go doc.go example.go exports.go filter.go reader.go synopsis.go

Variables

IllegalPrefixes is a list of lower-case prefixes that identify a comment as not being a doc comment. This helps to avoid misinterpreting the common mistake of a copyright notice immediately before a package statement as being a doc comment.

+
var IllegalPrefixes = []string{
+    "copyright",
+    "all rights",
+    "author",
+}

func IsPredeclared 1.8

func IsPredeclared(s string) bool

IsPredeclared reports whether s is a predeclared identifier.

+

func Synopsis

func Synopsis(text string) string

Synopsis returns a cleaned version of the first sentence in text.

+

Deprecated: New programs should use Package.Synopsis instead, which handles links in text properly.

+

func ToHTML

func ToHTML(w io.Writer, text string, words map[string]string)

ToHTML converts comment text to formatted HTML.

+

Deprecated: ToHTML cannot identify documentation links in the doc comment, because they depend on knowing what package the text came from, which is not included in this API.

+

Given the *doc.Package p where text was found, ToHTML(w, text, nil) can be replaced by:

+
w.Write(p.HTML(text))
+

which is in turn shorthand for:

+
w.Write(p.Printer().HTML(p.Parser().Parse(text)))
+

If words may be non-nil, the longer replacement is:

+
parser := p.Parser()
+parser.Words = words
+w.Write(p.Printer().HTML(parser.Parse(d)))
+

func ToText

func ToText(w io.Writer, text string, prefix, codePrefix string, width int)

ToText converts comment text to formatted text.

+

Deprecated: ToText cannot identify documentation links in the doc comment, because they depend on knowing what package the text came from, which is not included in this API.

+

Given the *doc.Package p where text was found, ToText(w, text, "", "\t", 80) can be replaced by:

+
w.Write(p.Text(text))
+

In the general case, ToText(w, text, prefix, codePrefix, width) can be replaced by:

+
d := p.Parser().Parse(text)
+pr := p.Printer()
+pr.TextPrefix = prefix
+pr.TextCodePrefix = codePrefix
+pr.TextWidth = width
+w.Write(pr.Text(d))
+

See the documentation for Package.Text and comment.Printer.Text for more details.

+

type Example

An Example represents an example function found in a test source file.

+
type Example struct {
+    Name        string // name of the item being exemplified (including optional suffix)
+    Suffix      string // example suffix, without leading '_' (only populated by NewFromFiles); added in Go 1.14
+    Doc         string // example function doc string
+    Code        ast.Node
+    Play        *ast.File // a whole program version of the example; added in Go 1.1
+    Comments    []*ast.CommentGroup
+    Output      string // expected output
+    Unordered   bool // Go 1.7
+    EmptyOutput bool // expect empty output; added in Go 1.1
+    Order       int  // original source code order; added in Go 1.1
+}
+

func Examples

func Examples(testFiles ...*ast.File) []*Example

Examples returns the examples found in testFiles, sorted by Name field. The Order fields record the order in which the examples were encountered. The Suffix field is not populated when Examples is called directly, it is only populated by NewFromFiles for examples it finds in _test.go files.

+

Playable Examples must be in a package whose name ends in "_test". An Example is "playable" (the Play field is non-nil) in either of these circumstances:

+

type Filter

type Filter func(string) bool

type Func

Func is the documentation for a func declaration.

+
type Func struct {
+    Doc  string
+    Name string
+    Decl *ast.FuncDecl
+
+    // methods
+    // (for functions, these fields have the respective zero value)
+    Recv  string // actual   receiver "T" or "*T" possibly followed by type parameters [P1, ..., Pn]
+    Orig  string // original receiver "T" or "*T"
+    Level int    // embedding level; 0 means not embedded
+
+    // Examples is a sorted list of examples associated with this
+    // function or method. Examples are extracted from _test.go files
+    // provided to NewFromFiles.
+    Examples []*Example // Go 1.14
+}
+

type Mode

Mode values control the operation of New and NewFromFiles.

+
type Mode int
const (
+    // AllDecls says to extract documentation for all package-level
+    // declarations, not just exported ones.
+    AllDecls Mode = 1 << iota
+
+    // AllMethods says to show all embedded methods, not just the ones of
+    // invisible (unexported) anonymous fields.
+    AllMethods
+
+    // PreserveAST says to leave the AST unmodified. Originally, pieces of
+    // the AST such as function bodies were nil-ed out to save memory in
+    // godoc, but not all programs want that behavior.
+    PreserveAST
+)

type Note 1.1

A Note represents a marked comment starting with "MARKER(uid): note body". Any note with a marker of 2 or more upper case [A-Z] letters and a uid of at least one character is recognized. The ":" following the uid is optional. Notes are collected in the Package.Notes map indexed by the notes marker.

+
type Note struct {
+    Pos, End token.Pos // position range of the comment containing the marker
+    UID      string    // uid found with the marker
+    Body     string    // note body text
+}
+

type Package

Package is the documentation for an entire package.

+
type Package struct {
+    Doc        string
+    Name       string
+    ImportPath string
+    Imports    []string
+    Filenames  []string
+    Notes      map[string][]*Note // Go 1.1
+
+    // Deprecated: For backward compatibility Bugs is still populated,
+    // but all new code should use Notes instead.
+    Bugs []string
+
+    // declarations
+    Consts []*Value
+    Types  []*Type
+    Vars   []*Value
+    Funcs  []*Func
+
+    // Examples is a sorted list of examples associated with
+    // the package. Examples are extracted from _test.go files
+    // provided to NewFromFiles.
+    Examples []*Example // Go 1.14
+    // contains filtered or unexported fields
+}
+

func New

func New(pkg *ast.Package, importPath string, mode Mode) *Package

New computes the package documentation for the given package AST. New takes ownership of the AST pkg and may edit or overwrite it. To have the Examples fields populated, use NewFromFiles and include the package's _test.go files.

+

func NewFromFiles 1.14

func NewFromFiles(fset *token.FileSet, files []*ast.File, importPath string, opts ...any) (*Package, error)

NewFromFiles computes documentation for a package.

+

The package is specified by a list of *ast.Files and corresponding file set, which must not be nil. NewFromFiles uses all provided files when computing documentation, so it is the caller's responsibility to provide only the files that match the desired build context. "go/build".Context.MatchFile can be used for determining whether a file matches a build context with the desired GOOS and GOARCH values, and other build constraints. The import path of the package is specified by importPath.

+

Examples found in _test.go files are associated with the corresponding type, function, method, or the package, based on their name. If the example has a suffix in its name, it is set in the [Example.Suffix] field. Examples with malformed names are skipped.

+

Optionally, a single extra argument of type Mode can be provided to control low-level aspects of the documentation extraction behavior.

+

NewFromFiles takes ownership of the AST files and may edit them, unless the PreserveAST Mode bit is on.

Example +

This example illustrates how to use NewFromFiles to compute package documentation with examples.

Code:

// src and test are two source files that make up
+// a package whose documentation will be computed.
+const src = `
+// This is the package comment.
+package p
+
+import "fmt"
+
+// This comment is associated with the Greet function.
+func Greet(who string) {
+    fmt.Printf("Hello, %s!\n", who)
+}
+`
+const test = `
+package p_test
+
+// This comment is associated with the ExampleGreet_world example.
+func ExampleGreet_world() {
+    Greet("world")
+}
+`
+
+// Create the AST by parsing src and test.
+fset := token.NewFileSet()
+files := []*ast.File{
+    mustParse(fset, "src.go", src),
+    mustParse(fset, "src_test.go", test),
+}
+
+// Compute package documentation with examples.
+p, err := doc.NewFromFiles(fset, files, "example.com/p")
+if err != nil {
+    panic(err)
+}
+
+fmt.Printf("package %s - %s", p.Name, p.Doc)
+fmt.Printf("func %s - %s", p.Funcs[0].Name, p.Funcs[0].Doc)
+fmt.Printf(" ⤷ example with suffix %q - %s", p.Funcs[0].Examples[0].Suffix, p.Funcs[0].Examples[0].Doc)
+
+

Output:

package p - This is the package comment.
+func Greet - This comment is associated with the Greet function.
+ ⤷ example with suffix "world" - This comment is associated with the ExampleGreet_world example.
+

func (*Package) Filter

func (p *Package) Filter(f Filter)

Filter eliminates documentation for names that don't pass through the filter f. TODO(gri): Recognize "Type.Method" as a name.

+

func (*Package) HTML 1.19

func (p *Package) HTML(text string) []byte

HTML returns formatted HTML for the doc comment text.

+

To customize details of the HTML, use Package.Printer to obtain a comment.Printer, and configure it before calling its HTML method.

+

func (*Package) Markdown 1.19

func (p *Package) Markdown(text string) []byte

Markdown returns formatted Markdown for the doc comment text.

+

To customize details of the Markdown, use Package.Printer to obtain a comment.Printer, and configure it before calling its Markdown method.

+

func (*Package) Parser 1.19

func (p *Package) Parser() *comment.Parser

Parser returns a doc comment parser configured for parsing doc comments from package p. Each call returns a new parser, so that the caller may customize it before use.

+

func (*Package) Printer 1.19

func (p *Package) Printer() *comment.Printer

Printer returns a doc comment printer configured for printing doc comments from package p. Each call returns a new printer, so that the caller may customize it before use.

+

func (*Package) Synopsis 1.19

func (p *Package) Synopsis(text string) string

Synopsis returns a cleaned version of the first sentence in text. That sentence ends after the first period followed by space and not preceded by exactly one uppercase letter, or at the first paragraph break. The result string has no \n, \r, or \t characters and uses only single spaces between words. If text starts with any of the IllegalPrefixes, the result is the empty string.

+

func (*Package) Text 1.19

func (p *Package) Text(text string) []byte

Text returns formatted text for the doc comment text, wrapped to 80 Unicode code points and using tabs for code block indentation.

+

To customize details of the formatting, use Package.Printer to obtain a comment.Printer, and configure it before calling its Text method.

+

type Type

Type is the documentation for a type declaration.

+
type Type struct {
+    Doc  string
+    Name string
+    Decl *ast.GenDecl
+
+    // associated declarations
+    Consts  []*Value // sorted list of constants of (mostly) this type
+    Vars    []*Value // sorted list of variables of (mostly) this type
+    Funcs   []*Func  // sorted list of functions returning this type
+    Methods []*Func  // sorted list of methods (including embedded ones) of this type
+
+    // Examples is a sorted list of examples associated with
+    // this type. Examples are extracted from _test.go files
+    // provided to NewFromFiles.
+    Examples []*Example // Go 1.14
+}
+

type Value

Value is the documentation for a (possibly grouped) var or const declaration.

+
type Value struct {
+    Doc   string
+    Names []string // var or const names in declaration order
+    Decl  *ast.GenDecl
+    // contains filtered or unexported fields
+}
+

Subdirectories

Name Synopsis
..
comment Package comment implements parsing and reformatting of Go doc comments, (documentation comments), which are comments that immediately precede a top-level declaration of a package, const, func, type, or var.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/doc/ +

+
diff --git a/devdocs/go/go%2Fformat%2Findex.html b/devdocs/go/go%2Fformat%2Findex.html new file mode 100644 index 00000000..bda6f84d --- /dev/null +++ b/devdocs/go/go%2Fformat%2Findex.html @@ -0,0 +1,42 @@ +

Package format

Overview

Package format implements standard formatting of Go source.

+

Note that formatting of Go source code changes over time, so tools relying on consistent formatting should execute a specific version of the gofmt binary instead of using this package. That way, the formatting will be stable, and the tools won't need to be recompiled each time gofmt changes.

+

For example, pre-submit checks that use this package directly would behave differently depending on what Go version each developer uses, causing the check to be inherently fragile.

Index

Examples

Node

Package files

format.go internal.go

func Node 1.1

func Node(dst io.Writer, fset *token.FileSet, node any) error

Node formats node in canonical gofmt style and writes the result to dst.

+

The node type must be *ast.File, *printer.CommentedNode, []ast.Decl, []ast.Stmt, or assignment-compatible to ast.Expr, ast.Decl, ast.Spec, or ast.Stmt. Node does not modify node. Imports are not sorted for nodes representing partial source files (for instance, if the node is not an *ast.File or a *printer.CommentedNode not wrapping an *ast.File).

+

The function may return early (before the entire result is written) and return a formatting error, for instance due to an incorrect AST.

Example +

Code:

const expr = "(6+2*3)/4"
+
+// parser.ParseExpr parses the argument and returns the
+// corresponding ast.Node.
+node, err := parser.ParseExpr(expr)
+if err != nil {
+    log.Fatal(err)
+}
+
+// Create a FileSet for node. Since the node does not come
+// from a real source file, fset will be empty.
+fset := token.NewFileSet()
+
+var buf bytes.Buffer
+err = format.Node(&buf, fset, node)
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Println(buf.String())
+
+

Output:

(6 + 2*3) / 4
+

func Source 1.1

func Source(src []byte) ([]byte, error)

Source formats src in canonical gofmt style and returns the result or an (I/O or syntax) error. src is expected to be a syntactically correct Go source file, or a list of Go declarations or statements.

+

If src is a partial source file, the leading and trailing space of src is applied to the result (such that it has the same leading and trailing space as src), and the result is indented by the same amount as the first line of src containing code. Imports are not sorted for partial source files.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/format/ +

+
diff --git a/devdocs/go/go%2Fimporter%2Findex.html b/devdocs/go/go%2Fimporter%2Findex.html new file mode 100644 index 00000000..57e52794 --- /dev/null +++ b/devdocs/go/go%2Fimporter%2Findex.html @@ -0,0 +1,22 @@ +

Package importer

Overview

Package importer provides access to export data importers.

Index

Package files

importer.go

func Default 1.5

func Default() types.Importer

Default returns an Importer for the compiler that built the running binary. If available, the result implements types.ImporterFrom.

+

func For 1.5

func For(compiler string, lookup Lookup) types.Importer

For calls ForCompiler with a new FileSet.

+

Deprecated: Use ForCompiler, which populates a FileSet with the positions of objects created by the importer.

+

func ForCompiler 1.12

func ForCompiler(fset *token.FileSet, compiler string, lookup Lookup) types.Importer

ForCompiler returns an Importer for importing from installed packages for the compilers "gc" and "gccgo", or for importing directly from the source if the compiler argument is "source". In this latter case, importing may fail under circumstances where the exported API is not entirely defined in pure Go source code (if the package API depends on cgo-defined entities, the type checker won't have access to those).

+

The lookup function is called each time the resulting importer needs to resolve an import path. In this mode the importer can only be invoked with canonical import paths (not relative or absolute ones); it is assumed that the translation to canonical import paths is being done by the client of the importer.

+

A lookup function must be provided for correct module-aware operation. Deprecated: If lookup is nil, for backwards-compatibility, the importer will attempt to resolve imports in the $GOPATH workspace.

+

type Lookup 1.5

A Lookup function returns a reader to access package data for a given import path, or an error if no matching package is found.

+
type Lookup func(path string) (io.ReadCloser, error)
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/importer/ +

+
diff --git a/devdocs/go/go%2Fparser%2Findex.html b/devdocs/go/go%2Fparser%2Findex.html new file mode 100644 index 00000000..8a527fed --- /dev/null +++ b/devdocs/go/go%2Fparser%2Findex.html @@ -0,0 +1,68 @@ +

Package parser

Overview

Package parser implements a parser for Go source files. Input may be provided in a variety of forms (see the various Parse* functions); the output is an abstract syntax tree (AST) representing the Go source. The parser is invoked through one of the Parse* functions.

+

The parser accepts a larger language than is syntactically permitted by the Go spec, for simplicity, and for improved robustness in the presence of syntax errors. For instance, in method declarations, the receiver is treated like an ordinary parameter list and thus may contain multiple entries where the spec permits exactly one. Consequently, the corresponding field in the AST (ast.FuncDecl.Recv) field is not restricted to one entry.

Index

Examples

ParseFile

Package files

interface.go parser.go resolver.go

func ParseDir

func ParseDir(fset *token.FileSet, path string, filter func(fs.FileInfo) bool, mode Mode) (pkgs map[string]*ast.Package, first error)

ParseDir calls ParseFile for all files with names ending in ".go" in the directory specified by path and returns a map of package name -> package AST with all the packages found.

+

If filter != nil, only the files with fs.FileInfo entries passing through the filter (and ending in ".go") are considered. The mode bits are passed to ParseFile unchanged. Position information is recorded in fset, which must not be nil.

+

If the directory couldn't be read, a nil map and the respective error are returned. If a parse error occurred, a non-nil but incomplete map and the first error encountered are returned.

+

func ParseExpr

func ParseExpr(x string) (ast.Expr, error)

ParseExpr is a convenience function for obtaining the AST of an expression x. The position information recorded in the AST is undefined. The filename used in error messages is the empty string.

+

If syntax errors were found, the result is a partial AST (with ast.Bad* nodes representing the fragments of erroneous source code). Multiple errors are returned via a scanner.ErrorList which is sorted by source position.

+

func ParseExprFrom 1.5

func ParseExprFrom(fset *token.FileSet, filename string, src any, mode Mode) (expr ast.Expr, err error)

ParseExprFrom is a convenience function for parsing an expression. The arguments have the same meaning as for ParseFile, but the source must be a valid Go (type or value) expression. Specifically, fset must not be nil.

+

If the source couldn't be read, the returned AST is nil and the error indicates the specific failure. If the source was read but syntax errors were found, the result is a partial AST (with ast.Bad* nodes representing the fragments of erroneous source code). Multiple errors are returned via a scanner.ErrorList which is sorted by source position.

+

func ParseFile

func ParseFile(fset *token.FileSet, filename string, src any, mode Mode) (f *ast.File, err error)

ParseFile parses the source code of a single Go source file and returns the corresponding ast.File node. The source code may be provided via the filename of the source file, or via the src parameter.

+

If src != nil, ParseFile parses the source from src and the filename is only used when recording position information. The type of the argument for the src parameter must be string, []byte, or io.Reader. If src == nil, ParseFile parses the file specified by filename.

+

The mode parameter controls the amount of source text parsed and other optional parser functionality. If the SkipObjectResolution mode bit is set (recommended), the object resolution phase of parsing will be skipped, causing File.Scope, File.Unresolved, and all Ident.Obj fields to be nil. Those fields are deprecated; see ast.Object for details.

+

Position information is recorded in the file set fset, which must not be nil.

+

If the source couldn't be read, the returned AST is nil and the error indicates the specific failure. If the source was read but syntax errors were found, the result is a partial AST (with ast.Bad* nodes representing the fragments of erroneous source code). Multiple errors are returned via a scanner.ErrorList which is sorted by source position.

Example +

Code:

fset := token.NewFileSet() // positions are relative to fset
+
+src := `package foo
+
+import (
+    "fmt"
+    "time"
+)
+
+func bar() {
+    fmt.Println(time.Now())
+}`
+
+// Parse src but stop after processing the imports.
+f, err := parser.ParseFile(fset, "", src, parser.ImportsOnly)
+if err != nil {
+    fmt.Println(err)
+    return
+}
+
+// Print the imports from the file's AST.
+for _, s := range f.Imports {
+    fmt.Println(s.Path.Value)
+}
+
+

Output:

+"fmt"
+"time"
+

type Mode

A Mode value is a set of flags (or 0). They control the amount of source code parsed and other optional parser functionality.

+
type Mode uint
const (
+    PackageClauseOnly    Mode             = 1 << iota // stop parsing after package clause
+    ImportsOnly                                       // stop parsing after import declarations
+    ParseComments                                     // parse comments and add them to AST
+    Trace                                             // print a trace of parsed productions
+    DeclarationErrors                                 // report declaration errors
+    SpuriousErrors                                    // same as AllErrors, for backward-compatibility
+    SkipObjectResolution                              // skip deprecated identifier resolution; see ParseFile
+    AllErrors            = SpuriousErrors             // report all errors (not just the first 10 on different lines)
+)
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/parser/ +

+
diff --git a/devdocs/go/go%2Fprinter%2Findex.html b/devdocs/go/go%2Fprinter%2Findex.html new file mode 100644 index 00000000..b801c989 --- /dev/null +++ b/devdocs/go/go%2Fprinter%2Findex.html @@ -0,0 +1,100 @@ +

Package printer

Overview

Package printer implements printing of AST nodes.

Index

Examples

Fprint

Package files

comment.go gobuild.go nodes.go printer.go

func Fprint

func Fprint(output io.Writer, fset *token.FileSet, node any) error

Fprint "pretty-prints" an AST node to output. It calls Config.Fprint with default settings. Note that gofmt uses tabs for indentation but spaces for alignment; use format.Node (package go/format) for output that matches gofmt.

Example +

Code:

package printer_test
+
+import (
+    "bytes"
+    "fmt"
+    "go/ast"
+    "go/parser"
+    "go/printer"
+    "go/token"
+    "strings"
+)
+
+func parseFunc(filename, functionname string) (fun *ast.FuncDecl, fset *token.FileSet) {
+    fset = token.NewFileSet()
+    if file, err := parser.ParseFile(fset, filename, nil, 0); err == nil {
+        for _, d := range file.Decls {
+            if f, ok := d.(*ast.FuncDecl); ok && f.Name.Name == functionname {
+                fun = f
+                return
+            }
+        }
+    }
+    panic("function not found")
+}
+
+func printSelf() {
+    // Parse source file and extract the AST without comments for
+    // this function, with position information referring to the
+    // file set fset.
+    funcAST, fset := parseFunc("example_test.go", "printSelf")
+
+    // Print the function body into buffer buf.
+    // The file set is provided to the printer so that it knows
+    // about the original source formatting and can add additional
+    // line breaks where they were present in the source.
+    var buf bytes.Buffer
+    printer.Fprint(&buf, fset, funcAST.Body)
+
+    // Remove braces {} enclosing the function body, unindent,
+    // and trim leading and trailing white space.
+    s := buf.String()
+    s = s[1 : len(s)-1]
+    s = strings.TrimSpace(strings.ReplaceAll(s, "\n\t", "\n"))
+
+    // Print the cleaned-up body text to stdout.
+    fmt.Println(s)
+}
+
+func ExampleFprint() {
+    printSelf()
+
+    // Output:
+    // funcAST, fset := parseFunc("example_test.go", "printSelf")
+    //
+    // var buf bytes.Buffer
+    // printer.Fprint(&buf, fset, funcAST.Body)
+    //
+    // s := buf.String()
+    // s = s[1 : len(s)-1]
+    // s = strings.TrimSpace(strings.ReplaceAll(s, "\n\t", "\n"))
+    //
+    // fmt.Println(s)
+}
+

type CommentedNode

A CommentedNode bundles an AST node and corresponding comments. It may be provided as argument to any of the Fprint functions.

+
type CommentedNode struct {
+    Node     any // *ast.File, or ast.Expr, ast.Decl, ast.Spec, or ast.Stmt
+    Comments []*ast.CommentGroup
+}
+

type Config

A Config node controls the output of Fprint.

+
type Config struct {
+    Mode     Mode // default: 0
+    Tabwidth int  // default: 8
+    Indent   int  // default: 0 (all code is indented at least by this much); added in Go 1.1
+}
+

func (*Config) Fprint

func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node any) error

Fprint "pretty-prints" an AST node to output for a given configuration cfg. Position information is interpreted relative to the file set fset. The node type must be *ast.File, *CommentedNode, []ast.Decl, []ast.Stmt, or assignment-compatible to ast.Expr, ast.Decl, ast.Spec, or ast.Stmt.

+

type Mode

A Mode value is a set of flags (or 0). They control printing.

+
type Mode uint
const (
+    RawFormat Mode = 1 << iota // do not use a tabwriter; if set, UseSpaces is ignored
+    TabIndent                  // use tabs for indentation independent of UseSpaces
+    UseSpaces                  // use spaces instead of tabs for alignment
+    SourcePos                  // emit //line directives to preserve original source positions
+)
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/printer/ +

+
diff --git a/devdocs/go/go%2Fscanner%2Findex.html b/devdocs/go/go%2Fscanner%2Findex.html new file mode 100644 index 00000000..1b6566bc --- /dev/null +++ b/devdocs/go/go%2Fscanner%2Findex.html @@ -0,0 +1,111 @@ +

Package scanner

Overview

Package scanner implements a scanner for Go source text. It takes a []byte as source which can then be tokenized through repeated calls to the Scan method.

Index

Examples

Scanner.Scan

Package files

errors.go scanner.go

func PrintError

func PrintError(w io.Writer, err error)

PrintError is a utility function that prints a list of errors to w, one error per line, if the err parameter is an ErrorList. Otherwise it prints the err string.

+

type Error

In an ErrorList, an error is represented by an *Error. The position Pos, if valid, points to the beginning of the offending token, and the error condition is described by Msg.

+
type Error struct {
+    Pos token.Position
+    Msg string
+}
+

func (Error) Error

func (e Error) Error() string

Error implements the error interface.

+

type ErrorHandler

An ErrorHandler may be provided to Scanner.Init. If a syntax error is encountered and a handler was installed, the handler is called with a position and an error message. The position points to the beginning of the offending token.

+
type ErrorHandler func(pos token.Position, msg string)

type ErrorList

ErrorList is a list of *Errors. The zero value for an ErrorList is an empty ErrorList ready to use.

+
type ErrorList []*Error

func (*ErrorList) Add

func (p *ErrorList) Add(pos token.Position, msg string)

Add adds an Error with given position and error message to an ErrorList.

+

func (ErrorList) Err

func (p ErrorList) Err() error

Err returns an error equivalent to this error list. If the list is empty, Err returns nil.

+

func (ErrorList) Error

func (p ErrorList) Error() string

An ErrorList implements the error interface.

+

func (ErrorList) Len

func (p ErrorList) Len() int

ErrorList implements the sort Interface.

+

func (ErrorList) Less

func (p ErrorList) Less(i, j int) bool

func (*ErrorList) RemoveMultiples

func (p *ErrorList) RemoveMultiples()

RemoveMultiples sorts an ErrorList and removes all but the first error per line.

+

func (*ErrorList) Reset

func (p *ErrorList) Reset()

Reset resets an ErrorList to no errors.

+

func (ErrorList) Sort

func (p ErrorList) Sort()

Sort sorts an ErrorList. *Error entries are sorted by position, other errors are sorted by error message, and before any *Error entry.

+

func (ErrorList) Swap

func (p ErrorList) Swap(i, j int)

type Mode

A mode value is a set of flags (or 0). They control scanner behavior.

+
type Mode uint
const (
+    ScanComments Mode = 1 << iota // return comments as COMMENT tokens
+
+)

type Scanner

A Scanner holds the scanner's internal state while processing a given text. It can be allocated as part of another data structure but must be initialized via Scanner.Init before use.

+
type Scanner struct {
+
+    // public state - ok to modify
+    ErrorCount int // number of errors encountered
+    // contains filtered or unexported fields
+}
+

func (*Scanner) Init

func (s *Scanner) Init(file *token.File, src []byte, err ErrorHandler, mode Mode)

Init prepares the scanner s to tokenize the text src by setting the scanner at the beginning of src. The scanner uses the file set file for position information and it adds line information for each line. It is ok to re-use the same file when re-scanning the same file as line information which is already present is ignored. Init causes a panic if the file size does not match the src size.

+

Calls to Scanner.Scan will invoke the error handler err if they encounter a syntax error and err is not nil. Also, for each error encountered, the Scanner field ErrorCount is incremented by one. The mode parameter determines how comments are handled.

+

Note that Init may call err if there is an error in the first character of the file.

+

func (*Scanner) Scan

func (s *Scanner) Scan() (pos token.Pos, tok token.Token, lit string)

Scan scans the next token and returns the token position, the token, and its literal string if applicable. The source end is indicated by token.EOF.

+

If the returned token is a literal (token.IDENT, token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING) or token.COMMENT, the literal string has the corresponding value.

+

If the returned token is a keyword, the literal string is the keyword.

+

If the returned token is token.SEMICOLON, the corresponding literal string is ";" if the semicolon was present in the source, and "\n" if the semicolon was inserted because of a newline or at EOF.

+

If the returned token is token.ILLEGAL, the literal string is the offending character.

+

In all other cases, Scan returns an empty literal string.

+

For more tolerant parsing, Scan will return a valid token if possible even if a syntax error was encountered. Thus, even if the resulting token sequence contains no illegal tokens, a client may not assume that no error occurred. Instead it must check the scanner's ErrorCount or the number of calls of the error handler, if there was one installed.

+

Scan adds line information to the file added to the file set with Init. Token positions are relative to that file and thus relative to the file set.

Example +

Code:

// src is the input that we want to tokenize.
+src := []byte("cos(x) + 1i*sin(x) // Euler")
+
+// Initialize the scanner.
+var s scanner.Scanner
+fset := token.NewFileSet()                      // positions are relative to fset
+file := fset.AddFile("", fset.Base(), len(src)) // register input "file"
+s.Init(file, src, nil /* no error handler */, scanner.ScanComments)
+
+// Repeated calls to Scan yield the token sequence found in the input.
+for {
+    pos, tok, lit := s.Scan()
+    if tok == token.EOF {
+        break
+    }
+    fmt.Printf("%s\t%s\t%q\n", fset.Position(pos), tok, lit)
+}
+
+

Output:

1:1	IDENT	"cos"
+1:4	(	""
+1:5	IDENT	"x"
+1:6	)	""
+1:8	+	""
+1:10	IMAG	"1i"
+1:12	*	""
+1:13	IDENT	"sin"
+1:16	(	""
+1:17	IDENT	"x"
+1:18	)	""
+1:20	COMMENT	"// Euler"
+1:28	;	"\n"
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/scanner/ +

+
diff --git a/devdocs/go/go%2Ftoken%2Findex.html b/devdocs/go/go%2Ftoken%2Findex.html new file mode 100644 index 00000000..0140e91b --- /dev/null +++ b/devdocs/go/go%2Ftoken%2Findex.html @@ -0,0 +1,339 @@ +

Package token

Overview

Package token defines constants representing the lexical tokens of the Go programming language and basic operations on tokens (printing, predicates).

Example (RetrievePositionInfo) +

Code:

fset := token.NewFileSet()
+
+const src = `package main
+
+import "fmt"
+
+import "go/token"
+
+
+type p = token.Pos
+
+const bad = token.NoPos
+
+
+func ok(pos p) bool {
+    return pos != bad
+}
+
+/*line :7:9*/func main() {
+    fmt.Println(ok(bad) == bad.IsValid())
+}
+`
+
+f, err := parser.ParseFile(fset, "main.go", src, 0)
+if err != nil {
+    fmt.Println(err)
+    return
+}
+
+// Print the location and kind of each declaration in f.
+for _, decl := range f.Decls {
+    // Get the filename, line, and column back via the file set.
+    // We get both the relative and absolute position.
+    // The relative position is relative to the last line directive.
+    // The absolute position is the exact position in the source.
+    pos := decl.Pos()
+    relPosition := fset.Position(pos)
+    absPosition := fset.PositionFor(pos, false)
+
+    // Either a FuncDecl or GenDecl, since we exit on error.
+    kind := "func"
+    if gen, ok := decl.(*ast.GenDecl); ok {
+        kind = gen.Tok.String()
+    }
+
+    // If the relative and absolute positions differ, show both.
+    fmtPosition := relPosition.String()
+    if relPosition != absPosition {
+        fmtPosition += "[" + absPosition.String() + "]"
+    }
+
+    fmt.Printf("%s: %s\n", fmtPosition, kind)
+}
+
+

Output:

+main.go:3:1: import
+main.go:5:1: import
+main.go:1:5[main.go:8:1]: type
+main.go:3:1[main.go:10:1]: const
+fake.go:42:11[main.go:13:1]: func
+fake.go:7:9[main.go:17:14]: func
+

Index

Examples

Package (RetrievePositionInfo)

Package files

position.go serialize.go token.go

Constants

A set of constants for precedence-based expression parsing. Non-operators have lowest precedence, followed by operators starting with precedence 1 up to unary operators. The highest precedence serves as "catch-all" precedence for selector, indexing, and other operator and delimiter tokens.

+
const (
+    LowestPrec  = 0 // non-operators
+    UnaryPrec   = 6
+    HighestPrec = 7
+)

func IsExported 1.13

func IsExported(name string) bool

IsExported reports whether name starts with an upper-case letter.

+

func IsIdentifier 1.13

func IsIdentifier(name string) bool

IsIdentifier reports whether name is a Go identifier, that is, a non-empty string made up of letters, digits, and underscores, where the first character is not a digit. Keywords are not identifiers.

+

func IsKeyword 1.13

func IsKeyword(name string) bool

IsKeyword reports whether name is a Go keyword, such as "func" or "return".

+

type File

A File is a handle for a file belonging to a FileSet. A File has a name, size, and line offset table.

+
type File struct {
+    // contains filtered or unexported fields
+}
+

func (*File) AddLine

func (f *File) AddLine(offset int)

AddLine adds the line offset for a new line. The line offset must be larger than the offset for the previous line and smaller than the file size; otherwise the line offset is ignored.

+

func (*File) AddLineColumnInfo 1.11

func (f *File) AddLineColumnInfo(offset int, filename string, line, column int)

AddLineColumnInfo adds alternative file, line, and column number information for a given file offset. The offset must be larger than the offset for the previously added alternative line info and smaller than the file size; otherwise the information is ignored.

+

AddLineColumnInfo is typically used to register alternative position information for line directives such as //line filename:line:column.

+

func (*File) AddLineInfo

func (f *File) AddLineInfo(offset int, filename string, line int)

AddLineInfo is like File.AddLineColumnInfo with a column = 1 argument. It is here for backward-compatibility for code prior to Go 1.11.

+

func (*File) Base

func (f *File) Base() int

Base returns the base offset of file f as registered with AddFile.

+

func (*File) Line

func (f *File) Line(p Pos) int

Line returns the line number for the given file position p; p must be a Pos value in that file or NoPos.

+

func (*File) LineCount

func (f *File) LineCount() int

LineCount returns the number of lines in file f.

+

func (*File) LineStart 1.12

func (f *File) LineStart(line int) Pos

LineStart returns the Pos value of the start of the specified line. It ignores any alternative positions set using File.AddLineColumnInfo. LineStart panics if the 1-based line number is invalid.

+

func (*File) Lines 1.21

func (f *File) Lines() []int

Lines returns the effective line offset table of the form described by File.SetLines. Callers must not mutate the result.

+

func (*File) MergeLine 1.2

func (f *File) MergeLine(line int)

MergeLine merges a line with the following line. It is akin to replacing the newline character at the end of the line with a space (to not change the remaining offsets). To obtain the line number, consult e.g. [Position.Line]. MergeLine will panic if given an invalid line number.

+

func (*File) Name

func (f *File) Name() string

Name returns the file name of file f as registered with AddFile.

+

func (*File) Offset

func (f *File) Offset(p Pos) int

Offset returns the offset for the given file position p; p must be a valid Pos value in that file. f.Offset(f.Pos(offset)) == offset.

+

func (*File) Pos

func (f *File) Pos(offset int) Pos

Pos returns the Pos value for the given file offset; the offset must be <= f.Size(). f.Pos(f.Offset(p)) == p.

+

func (*File) Position

func (f *File) Position(p Pos) (pos Position)

Position returns the Position value for the given file position p. Calling f.Position(p) is equivalent to calling f.PositionFor(p, true).

+

func (*File) PositionFor 1.4

func (f *File) PositionFor(p Pos, adjusted bool) (pos Position)

PositionFor returns the Position value for the given file position p. If adjusted is set, the position may be adjusted by position-altering //line comments; otherwise those comments are ignored. p must be a Pos value in f or NoPos.

+

func (*File) SetLines

func (f *File) SetLines(lines []int) bool

SetLines sets the line offsets for a file and reports whether it succeeded. The line offsets are the offsets of the first character of each line; for instance for the content "ab\nc\n" the line offsets are {0, 3}. An empty file has an empty line offset table. Each line offset must be larger than the offset for the previous line and smaller than the file size; otherwise SetLines fails and returns false. Callers must not mutate the provided slice after SetLines returns.

+

func (*File) SetLinesForContent

func (f *File) SetLinesForContent(content []byte)

SetLinesForContent sets the line offsets for the given file content. It ignores position-altering //line comments.

+

func (*File) Size

func (f *File) Size() int

Size returns the size of file f as registered with AddFile.

+

type FileSet

A FileSet represents a set of source files. Methods of file sets are synchronized; multiple goroutines may invoke them concurrently.

+

The byte offsets for each file in a file set are mapped into distinct (integer) intervals, one interval [base, base+size] per file. FileSet.Base represents the first byte in the file, and size is the corresponding file size. A Pos value is a value in such an interval. By determining the interval a Pos value belongs to, the file, its file base, and thus the byte offset (position) the Pos value is representing can be computed.

+

When adding a new file, a file base must be provided. That can be any integer value that is past the end of any interval of any file already in the file set. For convenience, FileSet.Base provides such a value, which is simply the end of the Pos interval of the most recently added file, plus one. Unless there is a need to extend an interval later, using the FileSet.Base should be used as argument for FileSet.AddFile.

+

A File may be removed from a FileSet when it is no longer needed. This may reduce memory usage in a long-running application.

+
type FileSet struct {
+    // contains filtered or unexported fields
+}
+

func NewFileSet

func NewFileSet() *FileSet

NewFileSet creates a new file set.

+

func (*FileSet) AddFile

func (s *FileSet) AddFile(filename string, base, size int) *File

AddFile adds a new file with a given filename, base offset, and file size to the file set s and returns the file. Multiple files may have the same name. The base offset must not be smaller than the FileSet.Base, and size must not be negative. As a special case, if a negative base is provided, the current value of the FileSet.Base is used instead.

+

Adding the file will set the file set's FileSet.Base value to base + size + 1 as the minimum base value for the next file. The following relationship exists between a Pos value p for a given file offset offs:

+
int(p) = base + offs
+

with offs in the range [0, size] and thus p in the range [base, base+size]. For convenience, File.Pos may be used to create file-specific position values from a file offset.

+

func (*FileSet) Base

func (s *FileSet) Base() int

Base returns the minimum base offset that must be provided to FileSet.AddFile when adding the next file.

+

func (*FileSet) File

func (s *FileSet) File(p Pos) (f *File)

File returns the file that contains the position p. If no such file is found (for instance for p == NoPos), the result is nil.

+

func (*FileSet) Iterate

func (s *FileSet) Iterate(f func(*File) bool)

Iterate calls f for the files in the file set in the order they were added until f returns false.

+

func (*FileSet) Position

func (s *FileSet) Position(p Pos) (pos Position)

Position converts a Pos p in the fileset into a Position value. Calling s.Position(p) is equivalent to calling s.PositionFor(p, true).

+

func (*FileSet) PositionFor 1.4

func (s *FileSet) PositionFor(p Pos, adjusted bool) (pos Position)

PositionFor converts a Pos p in the fileset into a Position value. If adjusted is set, the position may be adjusted by position-altering //line comments; otherwise those comments are ignored. p must be a Pos value in s or NoPos.

+

func (*FileSet) Read

func (s *FileSet) Read(decode func(any) error) error

Read calls decode to deserialize a file set into s; s must not be nil.

+

func (*FileSet) RemoveFile 1.20

func (s *FileSet) RemoveFile(file *File)

RemoveFile removes a file from the FileSet so that subsequent queries for its Pos interval yield a negative result. This reduces the memory usage of a long-lived FileSet that encounters an unbounded stream of files.

+

Removing a file that does not belong to the set has no effect.

+

func (*FileSet) Write

func (s *FileSet) Write(encode func(any) error) error

Write calls encode to serialize the file set s.

+

type Pos

Pos is a compact encoding of a source position within a file set. It can be converted into a Position for a more convenient, but much larger, representation.

+

The Pos value for a given file is a number in the range [base, base+size], where base and size are specified when a file is added to the file set. The difference between a Pos value and the corresponding file base corresponds to the byte offset of that position (represented by the Pos value) from the beginning of the file. Thus, the file base offset is the Pos value representing the first byte in the file.

+

To create the Pos value for a specific source offset (measured in bytes), first add the respective file to the current file set using FileSet.AddFile and then call File.Pos(offset) for that file. Given a Pos value p for a specific file set fset, the corresponding Position value is obtained by calling fset.Position(p).

+

Pos values can be compared directly with the usual comparison operators: If two Pos values p and q are in the same file, comparing p and q is equivalent to comparing the respective source file offsets. If p and q are in different files, p < q is true if the file implied by p was added to the respective file set before the file implied by q.

+
type Pos int

The zero value for Pos is NoPos; there is no file and line information associated with it, and NoPos.IsValid() is false. NoPos is always smaller than any other Pos value. The corresponding Position value for NoPos is the zero value for Position.

+
const NoPos Pos = 0

func (Pos) IsValid

func (p Pos) IsValid() bool

IsValid reports whether the position is valid.

+

type Position

Position describes an arbitrary source position including the file, line, and column location. A Position is valid if the line number is > 0.

+
type Position struct {
+    Filename string // filename, if any
+    Offset   int    // offset, starting at 0
+    Line     int    // line number, starting at 1
+    Column   int    // column number, starting at 1 (byte count)
+}
+

func (*Position) IsValid

func (pos *Position) IsValid() bool

IsValid reports whether the position is valid.

+

func (Position) String

func (pos Position) String() string

String returns a string in one of several forms:

+
file:line:column    valid position with file name
+file:line           valid position with file name but no column (column == 0)
+line:column         valid position without file name
+line                valid position without file name and no column (column == 0)
+file                invalid position with file name
+-                   invalid position without file name
+

type Token

Token is the set of lexical tokens of the Go programming language.

+
type Token int

The list of tokens.

+
const (
+    // Special tokens
+    ILLEGAL Token = iota
+    EOF
+    COMMENT
+
+    // Identifiers and basic type literals
+    // (these tokens stand for classes of literals)
+    IDENT  // main
+    INT    // 12345
+    FLOAT  // 123.45
+    IMAG   // 123.45i
+    CHAR   // 'a'
+    STRING // "abc"
+
+    // Operators and delimiters
+    ADD // +
+    SUB // -
+    MUL // *
+    QUO // /
+    REM // %
+
+    AND     // &
+    OR      // |
+    XOR     // ^
+    SHL     // <<
+    SHR     // >>
+    AND_NOT // &^
+
+    ADD_ASSIGN // +=
+    SUB_ASSIGN // -=
+    MUL_ASSIGN // *=
+    QUO_ASSIGN // /=
+    REM_ASSIGN // %=
+
+    AND_ASSIGN     // &=
+    OR_ASSIGN      // |=
+    XOR_ASSIGN     // ^=
+    SHL_ASSIGN     // <<=
+    SHR_ASSIGN     // >>=
+    AND_NOT_ASSIGN // &^=
+
+    LAND  // &&
+    LOR   // ||
+    ARROW // <-
+    INC   // ++
+    DEC   // --
+
+    EQL    // ==
+    LSS    // <
+    GTR    // >
+    ASSIGN // =
+    NOT    // !
+
+    NEQ      // !=
+    LEQ      // <=
+    GEQ      // >=
+    DEFINE   // :=
+    ELLIPSIS // ...
+
+    LPAREN // (
+    LBRACK // [
+    LBRACE // {
+    COMMA  // ,
+    PERIOD // .
+
+    RPAREN    // )
+    RBRACK    // ]
+    RBRACE    // }
+    SEMICOLON // ;
+    COLON     // :
+
+    // Keywords
+    BREAK
+    CASE
+    CHAN
+    CONST
+    CONTINUE
+
+    DEFAULT
+    DEFER
+    ELSE
+    FALLTHROUGH
+    FOR
+
+    FUNC
+    GO
+    GOTO
+    IF
+    IMPORT
+
+    INTERFACE
+    MAP
+    PACKAGE
+    RANGE
+    RETURN
+
+    SELECT
+    STRUCT
+    SWITCH
+    TYPE
+    VAR
+
+    // additional tokens, handled in an ad-hoc manner
+    TILDE
+)

func Lookup

func Lookup(ident string) Token

Lookup maps an identifier to its keyword token or IDENT (if not a keyword).

+

func (Token) IsKeyword

func (tok Token) IsKeyword() bool

IsKeyword returns true for tokens corresponding to keywords; it returns false otherwise.

+

func (Token) IsLiteral

func (tok Token) IsLiteral() bool

IsLiteral returns true for tokens corresponding to identifiers and basic type literals; it returns false otherwise.

+

func (Token) IsOperator

func (tok Token) IsOperator() bool

IsOperator returns true for tokens corresponding to operators and delimiters; it returns false otherwise.

+

func (Token) Precedence

func (op Token) Precedence() int

Precedence returns the operator precedence of the binary operator op. If op is not a binary operator, the result is LowestPrecedence.

+

func (Token) String

func (tok Token) String() string

String returns the string corresponding to the token tok. For operators, delimiters, and keywords the string is the actual token character sequence (e.g., for the token ADD, the string is "+"). For all other tokens the string corresponds to the token constant name (e.g. for the token IDENT, the string is "IDENT").

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/token/ +

+
diff --git a/devdocs/go/go%2Ftypes%2Findex.html b/devdocs/go/go%2Ftypes%2Findex.html new file mode 100644 index 00000000..fed28de7 --- /dev/null +++ b/devdocs/go/go%2Ftypes%2Findex.html @@ -0,0 +1,1630 @@ +

Package types

Overview

Package types declares the data types and implements the algorithms for type-checking of Go packages. Use Config.Check to invoke the type checker for a package. Alternatively, create a new type checker with NewChecker and invoke it incrementally by calling Checker.Files.

+

Type-checking consists of several interdependent phases:

+

Name resolution maps each identifier (ast.Ident) in the program to the language object (Object) it denotes. Use Info.{Defs,Uses,Implicits} for the results of name resolution.

+

Constant folding computes the exact constant value (constant.Value) for every expression (ast.Expr) that is a compile-time constant. Use Info.Types[expr].Value for the results of constant folding.

+

Type inference computes the type (Type) of every expression (ast.Expr) and checks for compliance with the language specification. Use [Info.Types][expr].Type for the results of type inference.

+

For a tutorial, see https://golang.org/s/types-tutorial.

Index

Examples

Info
MethodSet
Scope

Package files

alias.go api.go api_predicates.go array.go assignments.go basic.go builtins.go call.go chan.go check.go const.go context.go conversions.go decl.go errors.go eval.go expr.go exprstring.go gccgosizes.go gcsizes.go generate.go index.go infer.go initorder.go instantiate.go interface.go labels.go lookup.go map.go methodset.go mono.go named.go object.go objset.go operand.go package.go pointer.go predicates.go resolver.go return.go scope.go selection.go signature.go sizes.go slice.go stmt.go struct.go subst.go termlist.go tuple.go type.go typelists.go typeparam.go typeset.go typestring.go typeterm.go typexpr.go under.go unify.go union.go universe.go util.go validtype.go version.go

Variables

Typ contains the predeclared *Basic types indexed by their corresponding BasicKind.

+

The *Basic type for Typ[Byte] will have the name "uint8". Use Universe.Lookup("byte").Type() to obtain the specific alias basic type named "byte" (and analogous for "rune").

+
var Typ = []*Basic{
+    Invalid: {Invalid, 0, "invalid type"},
+
+    Bool:          {Bool, IsBoolean, "bool"},
+    Int:           {Int, IsInteger, "int"},
+    Int8:          {Int8, IsInteger, "int8"},
+    Int16:         {Int16, IsInteger, "int16"},
+    Int32:         {Int32, IsInteger, "int32"},
+    Int64:         {Int64, IsInteger, "int64"},
+    Uint:          {Uint, IsInteger | IsUnsigned, "uint"},
+    Uint8:         {Uint8, IsInteger | IsUnsigned, "uint8"},
+    Uint16:        {Uint16, IsInteger | IsUnsigned, "uint16"},
+    Uint32:        {Uint32, IsInteger | IsUnsigned, "uint32"},
+    Uint64:        {Uint64, IsInteger | IsUnsigned, "uint64"},
+    Uintptr:       {Uintptr, IsInteger | IsUnsigned, "uintptr"},
+    Float32:       {Float32, IsFloat, "float32"},
+    Float64:       {Float64, IsFloat, "float64"},
+    Complex64:     {Complex64, IsComplex, "complex64"},
+    Complex128:    {Complex128, IsComplex, "complex128"},
+    String:        {String, IsString, "string"},
+    UnsafePointer: {UnsafePointer, 0, "Pointer"},
+
+    UntypedBool:    {UntypedBool, IsBoolean | IsUntyped, "untyped bool"},
+    UntypedInt:     {UntypedInt, IsInteger | IsUntyped, "untyped int"},
+    UntypedRune:    {UntypedRune, IsInteger | IsUntyped, "untyped rune"},
+    UntypedFloat:   {UntypedFloat, IsFloat | IsUntyped, "untyped float"},
+    UntypedComplex: {UntypedComplex, IsComplex | IsUntyped, "untyped complex"},
+    UntypedString:  {UntypedString, IsString | IsUntyped, "untyped string"},
+    UntypedNil:     {UntypedNil, IsUntyped, "untyped nil"},
+}

func AssertableTo 1.5

func AssertableTo(V *Interface, T Type) bool

AssertableTo reports whether a value of type V can be asserted to have type T.

+

The behavior of AssertableTo is unspecified in three cases:

+

func AssignableTo 1.5

func AssignableTo(V, T Type) bool

AssignableTo reports whether a value of type V is assignable to a variable of type T.

+

The behavior of AssignableTo is unspecified if V or T is Typ[Invalid] or an uninstantiated generic type.

+

func CheckExpr 1.13

func CheckExpr(fset *token.FileSet, pkg *Package, pos token.Pos, expr ast.Expr, info *Info) (err error)

CheckExpr type checks the expression expr as if it had appeared at position pos of package pkg. Type information about the expression is recorded in info. The expression may be an identifier denoting an uninstantiated generic function or type.

+

If pkg == nil, the Universe scope is used and the provided position pos is ignored. If pkg != nil, and pos is invalid, the package scope is used. Otherwise, pos must belong to the package.

+

An error is returned if pos is not within the package or if the node cannot be type-checked.

+

Note: Eval and CheckExpr should not be used instead of running Check to compute types and values, but in addition to Check, as these functions ignore the context in which an expression is used (e.g., an assignment). Thus, top-level untyped constants will return an untyped type rather than the respective context-specific type.

+

func Comparable 1.5

func Comparable(T Type) bool

Comparable reports whether values of type T are comparable.

+

func ConvertibleTo 1.5

func ConvertibleTo(V, T Type) bool

ConvertibleTo reports whether a value of type V is convertible to a value of type T.

+

The behavior of ConvertibleTo is unspecified if V or T is Typ[Invalid] or an uninstantiated generic type.

+

func DefPredeclaredTestFuncs 1.5

func DefPredeclaredTestFuncs()

DefPredeclaredTestFuncs defines the assert and trace built-ins. These built-ins are intended for debugging and testing of this package only.

+

func ExprString 1.5

func ExprString(x ast.Expr) string

ExprString returns the (possibly shortened) string representation for x. Shortened representations are suitable for user interfaces but may not necessarily follow Go syntax.

+

func Id 1.5

func Id(pkg *Package, name string) string

Id returns name if it is exported, otherwise it returns the name qualified with the package path.

+

func Identical 1.5

func Identical(x, y Type) bool

Identical reports whether x and y are identical types. Receivers of Signature types are ignored.

+

func IdenticalIgnoreTags 1.8

func IdenticalIgnoreTags(x, y Type) bool

IdenticalIgnoreTags reports whether x and y are identical types if tags are ignored. Receivers of Signature types are ignored.

+

func Implements 1.5

func Implements(V Type, T *Interface) bool

Implements reports whether type V implements interface T.

+

The behavior of Implements is unspecified if V is Typ[Invalid] or an uninstantiated generic type.

+

func IsInterface 1.5

func IsInterface(t Type) bool

IsInterface reports whether t is an interface type.

+

func ObjectString 1.5

func ObjectString(obj Object, qf Qualifier) string

ObjectString returns the string form of obj. The Qualifier controls the printing of package-level objects, and may be nil.

+

func Satisfies 1.20

func Satisfies(V Type, T *Interface) bool

Satisfies reports whether type V satisfies the constraint T.

+

The behavior of Satisfies is unspecified if V is Typ[Invalid] or an uninstantiated generic type.

+

func SelectionString 1.5

func SelectionString(s *Selection, qf Qualifier) string

SelectionString returns the string form of s. The Qualifier controls the printing of package-level objects, and may be nil.

+

Examples:

+
"field (T) f int"
+"method (T) f(X) Y"
+"method expr (T) f(X) Y"
+

func TypeString 1.5

func TypeString(typ Type, qf Qualifier) string

TypeString returns the string representation of typ. The Qualifier controls the printing of package-level objects, and may be nil.

+

func WriteExpr 1.5

func WriteExpr(buf *bytes.Buffer, x ast.Expr)

WriteExpr writes the (possibly shortened) string representation for x to buf. Shortened representations are suitable for user interfaces but may not necessarily follow Go syntax.

+

func WriteSignature 1.5

func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier)

WriteSignature writes the representation of the signature sig to buf, without a leading "func" keyword. The Qualifier controls the printing of package-level objects, and may be nil.

+

func WriteType 1.5

func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier)

WriteType writes the string representation of typ to buf. The Qualifier controls the printing of package-level objects, and may be nil.

+

type Alias 1.22

An Alias represents an alias type. Whether or not Alias types are created is controlled by the gotypesalias setting with the GODEBUG environment variable. For gotypesalias=1, alias declarations produce an Alias type. Otherwise, the alias information is only in the type name, which points directly to the actual (aliased) type.

+
type Alias struct {
+    // contains filtered or unexported fields
+}
+

func NewAlias 1.22

func NewAlias(obj *TypeName, rhs Type) *Alias

NewAlias creates a new Alias type with the given type name and rhs. rhs must not be nil.

+

func (*Alias) Obj 1.22

func (a *Alias) Obj() *TypeName

func (*Alias) String 1.22

func (a *Alias) String() string

func (*Alias) Underlying 1.22

func (a *Alias) Underlying() Type

type ArgumentError 1.18

An ArgumentError holds an error associated with an argument index.

+
type ArgumentError struct {
+    Index int
+    Err   error
+}
+

func (*ArgumentError) Error 1.18

func (e *ArgumentError) Error() string

func (*ArgumentError) Unwrap 1.18

func (e *ArgumentError) Unwrap() error

type Array 1.5

An Array represents an array type.

+
type Array struct {
+    // contains filtered or unexported fields
+}
+

func NewArray 1.5

func NewArray(elem Type, len int64) *Array

NewArray returns a new array type for the given element type and length. A negative length indicates an unknown length.

+

func (*Array) Elem 1.5

func (a *Array) Elem() Type

Elem returns element type of array a.

+

func (*Array) Len 1.5

func (a *Array) Len() int64

Len returns the length of array a. A negative result indicates an unknown length.

+

func (*Array) String 1.5

func (a *Array) String() string

func (*Array) Underlying 1.5

func (a *Array) Underlying() Type

type Basic 1.5

A Basic represents a basic type.

+
type Basic struct {
+    // contains filtered or unexported fields
+}
+

func (*Basic) Info 1.5

func (b *Basic) Info() BasicInfo

Info returns information about properties of basic type b.

+

func (*Basic) Kind 1.5

func (b *Basic) Kind() BasicKind

Kind returns the kind of basic type b.

+

func (*Basic) Name 1.5

func (b *Basic) Name() string

Name returns the name of basic type b.

+

func (*Basic) String 1.5

func (b *Basic) String() string

func (*Basic) Underlying 1.5

func (b *Basic) Underlying() Type

type BasicInfo 1.5

BasicInfo is a set of flags describing properties of a basic type.

+
type BasicInfo int

Properties of basic types.

+
const (
+    IsBoolean BasicInfo = 1 << iota
+    IsInteger
+    IsUnsigned
+    IsFloat
+    IsComplex
+    IsString
+    IsUntyped
+
+    IsOrdered   = IsInteger | IsFloat | IsString
+    IsNumeric   = IsInteger | IsFloat | IsComplex
+    IsConstType = IsBoolean | IsNumeric | IsString
+)

type BasicKind 1.5

BasicKind describes the kind of basic type.

+
type BasicKind int
const (
+    Invalid BasicKind = iota // type is invalid
+
+    // predeclared types
+    Bool
+    Int
+    Int8
+    Int16
+    Int32
+    Int64
+    Uint
+    Uint8
+    Uint16
+    Uint32
+    Uint64
+    Uintptr
+    Float32
+    Float64
+    Complex64
+    Complex128
+    String
+    UnsafePointer
+
+    // types for untyped values
+    UntypedBool
+    UntypedInt
+    UntypedRune
+    UntypedFloat
+    UntypedComplex
+    UntypedString
+    UntypedNil
+
+    // aliases
+    Byte = Uint8
+    Rune = Int32
+)

type Builtin 1.5

A Builtin represents a built-in function. Builtins don't have a valid type.

+
type Builtin struct {
+    // contains filtered or unexported fields
+}
+

func (*Builtin) Exported 1.5

func (obj *Builtin) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

+

func (*Builtin) Id 1.5

func (obj *Builtin) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

+

func (*Builtin) Name 1.5

func (obj *Builtin) Name() string

Name returns the object's (package-local, unqualified) name.

+

func (*Builtin) Parent 1.5

func (obj *Builtin) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

+

func (*Builtin) Pkg 1.5

func (obj *Builtin) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

+

func (*Builtin) Pos 1.5

func (obj *Builtin) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

+

func (*Builtin) String 1.5

func (obj *Builtin) String() string

func (*Builtin) Type 1.5

func (obj *Builtin) Type() Type

Type returns the object's type.

+

type Chan 1.5

A Chan represents a channel type.

+
type Chan struct {
+    // contains filtered or unexported fields
+}
+

func NewChan 1.5

func NewChan(dir ChanDir, elem Type) *Chan

NewChan returns a new channel type for the given direction and element type.

+

func (*Chan) Dir 1.5

func (c *Chan) Dir() ChanDir

Dir returns the direction of channel c.

+

func (*Chan) Elem 1.5

func (c *Chan) Elem() Type

Elem returns the element type of channel c.

+

func (*Chan) String 1.5

func (c *Chan) String() string

func (*Chan) Underlying 1.5

func (c *Chan) Underlying() Type

type ChanDir 1.5

A ChanDir value indicates a channel direction.

+
type ChanDir int

The direction of a channel is indicated by one of these constants.

+
const (
+    SendRecv ChanDir = iota
+    SendOnly
+    RecvOnly
+)

type Checker 1.5

A Checker maintains the state of the type checker. It must be created with NewChecker.

+
type Checker struct {
+    *Info
+    // contains filtered or unexported fields
+}
+

func NewChecker 1.5

func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker

NewChecker returns a new Checker instance for a given package. Package files may be added incrementally via checker.Files.

+

func (*Checker) Files 1.5

func (check *Checker) Files(files []*ast.File) error

Files checks the provided files as part of the checker's package.

+

type Config 1.5

A Config specifies the configuration for type checking. The zero value for Config is a ready-to-use default configuration.

+
type Config struct {
+    // Context is the context used for resolving global identifiers. If nil, the
+    // type checker will initialize this field with a newly created context.
+    Context *Context // Go 1.18
+
+    // GoVersion describes the accepted Go language version. The string must
+    // start with a prefix of the form "go%d.%d" (e.g. "go1.20", "go1.21rc1", or
+    // "go1.21.0") or it must be empty; an empty string disables Go language
+    // version checks. If the format is invalid, invoking the type checker will
+    // result in an error.
+    GoVersion string // Go 1.18
+
+    // If IgnoreFuncBodies is set, function bodies are not
+    // type-checked.
+    IgnoreFuncBodies bool
+
+    // If FakeImportC is set, `import "C"` (for packages requiring Cgo)
+    // declares an empty "C" package and errors are omitted for qualified
+    // identifiers referring to package C (which won't find an object).
+    // This feature is intended for the standard library cmd/api tool.
+    //
+    // Caution: Effects may be unpredictable due to follow-on errors.
+    //          Do not use casually!
+    FakeImportC bool
+
+    // If Error != nil, it is called with each error found
+    // during type checking; err has dynamic type Error.
+    // Secondary errors (for instance, to enumerate all types
+    // involved in an invalid recursive type declaration) have
+    // error strings that start with a '\t' character.
+    // If Error == nil, type-checking stops with the first
+    // error found.
+    Error func(err error)
+
+    // An importer is used to import packages referred to from
+    // import declarations.
+    // If the installed importer implements ImporterFrom, the type
+    // checker calls ImportFrom instead of Import.
+    // The type checker reports an error if an importer is needed
+    // but none was installed.
+    Importer Importer
+
+    // If Sizes != nil, it provides the sizing functions for package unsafe.
+    // Otherwise SizesFor("gc", "amd64") is used instead.
+    Sizes Sizes
+
+    // If DisableUnusedImportCheck is set, packages are not checked
+    // for unused imports.
+    DisableUnusedImportCheck bool
+    // contains filtered or unexported fields
+}
+

func (*Config) Check 1.5

func (conf *Config) Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error)

Check type-checks a package and returns the resulting package object and the first error if any. Additionally, if info != nil, Check populates each of the non-nil maps in the Info struct.

+

The package is marked as complete if no errors occurred, otherwise it is incomplete. See [Config.Error] for controlling behavior in the presence of errors.

+

The package is specified by a list of *ast.Files and corresponding file set, and the package path the package is identified with. The clean path must not be empty or dot (".").

+

type Const 1.5

A Const represents a declared constant.

+
type Const struct {
+    // contains filtered or unexported fields
+}
+

func NewConst 1.5

func NewConst(pos token.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const

NewConst returns a new constant with value val. The remaining arguments set the attributes found with all Objects.

+

func (*Const) Exported 1.5

func (obj *Const) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

+

func (*Const) Id 1.5

func (obj *Const) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

+

func (*Const) Name 1.5

func (obj *Const) Name() string

Name returns the object's (package-local, unqualified) name.

+

func (*Const) Parent 1.5

func (obj *Const) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

+

func (*Const) Pkg 1.5

func (obj *Const) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

+

func (*Const) Pos 1.5

func (obj *Const) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

+

func (*Const) String 1.5

func (obj *Const) String() string

func (*Const) Type 1.5

func (obj *Const) Type() Type

Type returns the object's type.

+

func (*Const) Val 1.5

func (obj *Const) Val() constant.Value

Val returns the constant's value.

+

type Context 1.18

A Context is an opaque type checking context. It may be used to share identical type instances across type-checked packages or calls to Instantiate. Contexts are safe for concurrent use.

+

The use of a shared context does not guarantee that identical instances are deduplicated in all cases.

+
type Context struct {
+    // contains filtered or unexported fields
+}
+

func NewContext 1.18

func NewContext() *Context

NewContext creates a new Context.

+

type Error 1.5

An Error describes a type-checking error; it implements the error interface. A "soft" error is an error that still permits a valid interpretation of a package (such as "unused variable"); "hard" errors may lead to unpredictable behavior if ignored.

+
type Error struct {
+    Fset *token.FileSet // file set for interpretation of Pos
+    Pos  token.Pos      // error position
+    Msg  string         // error message
+    Soft bool           // if set, error is "soft"
+    // contains filtered or unexported fields
+}
+

func (Error) Error 1.5

func (err Error) Error() string

Error returns an error string formatted as follows: filename:line:column: message

+

type Func 1.5

A Func represents a declared function, concrete method, or abstract (interface) method. Its Type() is always a *Signature. An abstract method may belong to many interfaces due to embedding.

+
type Func struct {
+    // contains filtered or unexported fields
+}
+

func MissingMethod 1.5

func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)

MissingMethod returns (nil, false) if V implements T, otherwise it returns a missing method required by T and whether it is missing or just has the wrong type: either a pointer receiver or wrong signature.

+

For non-interface types V, or if static is set, V implements T if all methods of T are present in V. Otherwise (V is an interface and static is not set), MissingMethod only checks that methods of T which are also present in V have matching types (e.g., for a type assertion x.(T) where x is of interface type V).

+

func NewFunc 1.5

func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func

NewFunc returns a new function with the given signature, representing the function's type.

+

func (*Func) Exported 1.5

func (obj *Func) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

+

func (*Func) FullName 1.5

func (obj *Func) FullName() string

FullName returns the package- or receiver-type-qualified name of function or method obj.

+

func (*Func) Id 1.5

func (obj *Func) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

+

func (*Func) Name 1.5

func (obj *Func) Name() string

Name returns the object's (package-local, unqualified) name.

+

func (*Func) Origin 1.19

func (obj *Func) Origin() *Func

Origin returns the canonical Func for its receiver, i.e. the Func object recorded in Info.Defs.

+

For synthetic functions created during instantiation (such as methods on an instantiated Named type or interface methods that depend on type arguments), this will be the corresponding Func on the generic (uninstantiated) type. For all other Funcs Origin returns the receiver.

+

func (*Func) Parent 1.5

func (obj *Func) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

+

func (*Func) Pkg 1.5

func (obj *Func) Pkg() *Package

Pkg returns the package to which the function belongs.

+

The result is nil for methods of types in the Universe scope, like method Error of the error built-in interface type.

+

func (*Func) Pos 1.5

func (obj *Func) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

+

func (*Func) Scope 1.5

func (obj *Func) Scope() *Scope

Scope returns the scope of the function's body block. The result is nil for imported or instantiated functions and methods (but there is also no mechanism to get to an instantiated function).

+

func (*Func) String 1.5

func (obj *Func) String() string

func (*Func) Type 1.5

func (obj *Func) Type() Type

Type returns the object's type.

+

type ImportMode 1.6

ImportMode is reserved for future use.

+
type ImportMode int

type Importer 1.5

An Importer resolves import paths to Packages.

+

CAUTION: This interface does not support the import of locally vendored packages. See https://golang.org/s/go15vendor. If possible, external implementations should implement ImporterFrom.

+
type Importer interface {
+    // Import returns the imported package for the given import path.
+    // The semantics is like for ImporterFrom.ImportFrom except that
+    // dir and mode are ignored (since they are not present).
+    Import(path string) (*Package, error)
+}

type ImporterFrom 1.6

An ImporterFrom resolves import paths to packages; it supports vendoring per https://golang.org/s/go15vendor. Use go/importer to obtain an ImporterFrom implementation.

+
type ImporterFrom interface {
+    // Importer is present for backward-compatibility. Calling
+    // Import(path) is the same as calling ImportFrom(path, "", 0);
+    // i.e., locally vendored packages may not be found.
+    // The types package does not call Import if an ImporterFrom
+    // is present.
+    Importer
+
+    // ImportFrom returns the imported package for the given import
+    // path when imported by a package file located in dir.
+    // If the import failed, besides returning an error, ImportFrom
+    // is encouraged to cache and return a package anyway, if one
+    // was created. This will reduce package inconsistencies and
+    // follow-on type checker errors due to the missing package.
+    // The mode value must be 0; it is reserved for future use.
+    // Two calls to ImportFrom with the same path and dir must
+    // return the same package.
+    ImportFrom(path, dir string, mode ImportMode) (*Package, error)
+}

type Info 1.5

Info holds result type information for a type-checked package. Only the information for which a map is provided is collected. If the package has type errors, the collected information may be incomplete.

+
type Info struct {
+    // Types maps expressions to their types, and for constant
+    // expressions, also their values. Invalid expressions are
+    // omitted.
+    //
+    // For (possibly parenthesized) identifiers denoting built-in
+    // functions, the recorded signatures are call-site specific:
+    // if the call result is not a constant, the recorded type is
+    // an argument-specific signature. Otherwise, the recorded type
+    // is invalid.
+    //
+    // The Types map does not record the type of every identifier,
+    // only those that appear where an arbitrary expression is
+    // permitted. For instance, the identifier f in a selector
+    // expression x.f is found only in the Selections map, the
+    // identifier z in a variable declaration 'var z int' is found
+    // only in the Defs map, and identifiers denoting packages in
+    // qualified identifiers are collected in the Uses map.
+    Types map[ast.Expr]TypeAndValue
+
+    // Instances maps identifiers denoting generic types or functions to their
+    // type arguments and instantiated type.
+    //
+    // For example, Instances will map the identifier for 'T' in the type
+    // instantiation T[int, string] to the type arguments [int, string] and
+    // resulting instantiated *Named type. Given a generic function
+    // func F[A any](A), Instances will map the identifier for 'F' in the call
+    // expression F(int(1)) to the inferred type arguments [int], and resulting
+    // instantiated *Signature.
+    //
+    // Invariant: Instantiating Uses[id].Type() with Instances[id].TypeArgs
+    // results in an equivalent of Instances[id].Type.
+    Instances map[*ast.Ident]Instance // Go 1.18
+
+    // Defs maps identifiers to the objects they define (including
+    // package names, dots "." of dot-imports, and blank "_" identifiers).
+    // For identifiers that do not denote objects (e.g., the package name
+    // in package clauses, or symbolic variables t in t := x.(type) of
+    // type switch headers), the corresponding objects are nil.
+    //
+    // For an embedded field, Defs returns the field *Var it defines.
+    //
+    // Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos()
+    Defs map[*ast.Ident]Object
+
+    // Uses maps identifiers to the objects they denote.
+    //
+    // For an embedded field, Uses returns the *TypeName it denotes.
+    //
+    // Invariant: Uses[id].Pos() != id.Pos()
+    Uses map[*ast.Ident]Object
+
+    // Implicits maps nodes to their implicitly declared objects, if any.
+    // The following node and object types may appear:
+    //
+    //     node               declared object
+    //
+    //     *ast.ImportSpec    *PkgName for imports without renames
+    //     *ast.CaseClause    type-specific *Var for each type switch case clause (incl. default)
+    //     *ast.Field         anonymous parameter *Var (incl. unnamed results)
+    //
+    Implicits map[ast.Node]Object
+
+    // Selections maps selector expressions (excluding qualified identifiers)
+    // to their corresponding selections.
+    Selections map[*ast.SelectorExpr]*Selection
+
+    // Scopes maps ast.Nodes to the scopes they define. Package scopes are not
+    // associated with a specific node but with all files belonging to a package.
+    // Thus, the package scope can be found in the type-checked Package object.
+    // Scopes nest, with the Universe scope being the outermost scope, enclosing
+    // the package scope, which contains (one or more) files scopes, which enclose
+    // function scopes which in turn enclose statement and function literal scopes.
+    // Note that even though package-level functions are declared in the package
+    // scope, the function scopes are embedded in the file scope of the file
+    // containing the function declaration.
+    //
+    // The Scope of a function contains the declarations of any
+    // type parameters, parameters, and named results, plus any
+    // local declarations in the body block.
+    // It is coextensive with the complete extent of the
+    // function's syntax ([*ast.FuncDecl] or [*ast.FuncLit]).
+    // The Scopes mapping does not contain an entry for the
+    // function body ([*ast.BlockStmt]); the function's scope is
+    // associated with the [*ast.FuncType].
+    //
+    // The following node types may appear in Scopes:
+    //
+    //     *ast.File
+    //     *ast.FuncType
+    //     *ast.TypeSpec
+    //     *ast.BlockStmt
+    //     *ast.IfStmt
+    //     *ast.SwitchStmt
+    //     *ast.TypeSwitchStmt
+    //     *ast.CaseClause
+    //     *ast.CommClause
+    //     *ast.ForStmt
+    //     *ast.RangeStmt
+    //
+    Scopes map[ast.Node]*Scope
+
+    // InitOrder is the list of package-level initializers in the order in which
+    // they must be executed. Initializers referring to variables related by an
+    // initialization dependency appear in topological order, the others appear
+    // in source order. Variables without an initialization expression do not
+    // appear in this list.
+    InitOrder []*Initializer
+
+    // FileVersions maps a file to its Go version string.
+    // If the file doesn't specify a version, the reported
+    // string is Config.GoVersion.
+    // Version strings begin with “go”, like “go1.21”, and
+    // are suitable for use with the [go/version] package.
+    FileVersions map[*ast.File]string // Go 1.22
+}
+

Example +

ExampleInfo prints various facts recorded by the type checker in a types.Info struct: definitions of and references to each named object, and the type, value, and mode of every expression in the package.

Code:

// Parse a single source file.
+const input = `
+package fib
+
+type S string
+
+var a, b, c = len(b), S(c), "hello"
+
+func fib(x int) int {
+    if x < 2 {
+        return x
+    }
+    return fib(x-1) - fib(x-2)
+}`
+// We need a specific fileset in this test below for positions.
+// Cannot use typecheck helper.
+fset := token.NewFileSet()
+f := mustParse(fset, input)
+
+// Type-check the package.
+// We create an empty map for each kind of input
+// we're interested in, and Check populates them.
+info := types.Info{
+    Types: make(map[ast.Expr]types.TypeAndValue),
+    Defs:  make(map[*ast.Ident]types.Object),
+    Uses:  make(map[*ast.Ident]types.Object),
+}
+var conf types.Config
+pkg, err := conf.Check("fib", fset, []*ast.File{f}, &info)
+if err != nil {
+    log.Fatal(err)
+}
+
+// Print package-level variables in initialization order.
+fmt.Printf("InitOrder: %v\n\n", info.InitOrder)
+
+// For each named object, print the line and
+// column of its definition and each of its uses.
+fmt.Println("Defs and Uses of each named object:")
+usesByObj := make(map[types.Object][]string)
+for id, obj := range info.Uses {
+    posn := fset.Position(id.Pos())
+    lineCol := fmt.Sprintf("%d:%d", posn.Line, posn.Column)
+    usesByObj[obj] = append(usesByObj[obj], lineCol)
+}
+var items []string
+for obj, uses := range usesByObj {
+    sort.Strings(uses)
+    item := fmt.Sprintf("%s:\n  defined at %s\n  used at %s",
+        types.ObjectString(obj, types.RelativeTo(pkg)),
+        fset.Position(obj.Pos()),
+        strings.Join(uses, ", "))
+    items = append(items, item)
+}
+sort.Strings(items) // sort by line:col, in effect
+fmt.Println(strings.Join(items, "\n"))
+fmt.Println()
+
+fmt.Println("Types and Values of each expression:")
+items = nil
+for expr, tv := range info.Types {
+    var buf strings.Builder
+    posn := fset.Position(expr.Pos())
+    tvstr := tv.Type.String()
+    if tv.Value != nil {
+        tvstr += " = " + tv.Value.String()
+    }
+    // line:col | expr | mode : type = value
+    fmt.Fprintf(&buf, "%2d:%2d | %-19s | %-7s : %s",
+        posn.Line, posn.Column, exprString(fset, expr),
+        mode(tv), tvstr)
+    items = append(items, buf.String())
+}
+sort.Strings(items)
+fmt.Println(strings.Join(items, "\n"))
+
+

Output:

InitOrder: [c = "hello" b = S(c) a = len(b)]
+
+Defs and Uses of each named object:
+builtin len:
+  defined at -
+  used at 6:15
+func fib(x int) int:
+  defined at fib:8:6
+  used at 12:20, 12:9
+type S string:
+  defined at fib:4:6
+  used at 6:23
+type int:
+  defined at -
+  used at 8:12, 8:17
+type string:
+  defined at -
+  used at 4:8
+var b S:
+  defined at fib:6:8
+  used at 6:19
+var c string:
+  defined at fib:6:11
+  used at 6:25
+var x int:
+  defined at fib:8:10
+  used at 10:10, 12:13, 12:24, 9:5
+
+Types and Values of each expression:
+ 4: 8 | string              | type    : string
+ 6:15 | len                 | builtin : func(fib.S) int
+ 6:15 | len(b)              | value   : int
+ 6:19 | b                   | var     : fib.S
+ 6:23 | S                   | type    : fib.S
+ 6:23 | S(c)                | value   : fib.S
+ 6:25 | c                   | var     : string
+ 6:29 | "hello"             | value   : string = "hello"
+ 8:12 | int                 | type    : int
+ 8:17 | int                 | type    : int
+ 9: 5 | x                   | var     : int
+ 9: 5 | x < 2               | value   : untyped bool
+ 9: 9 | 2                   | value   : int = 2
+10:10 | x                   | var     : int
+12: 9 | fib                 | value   : func(x int) int
+12: 9 | fib(x - 1)          | value   : int
+12: 9 | fib(x-1) - fib(x-2) | value   : int
+12:13 | x                   | var     : int
+12:13 | x - 1               | value   : int
+12:15 | 1                   | value   : int = 1
+12:20 | fib                 | value   : func(x int) int
+12:20 | fib(x - 2)          | value   : int
+12:24 | x                   | var     : int
+12:24 | x - 2               | value   : int
+12:26 | 2                   | value   : int = 2
+

func (*Info) ObjectOf 1.5

func (info *Info) ObjectOf(id *ast.Ident) Object

ObjectOf returns the object denoted by the specified id, or nil if not found.

+

If id is an embedded struct field, Info.ObjectOf returns the field (*Var) it defines, not the type (*TypeName) it uses.

+

Precondition: the Uses and Defs maps are populated.

+

func (*Info) PkgNameOf 1.22

func (info *Info) PkgNameOf(imp *ast.ImportSpec) *PkgName

PkgNameOf returns the local package name defined by the import, or nil if not found.

+

For dot-imports, the package name is ".".

+

Precondition: the Defs and Implicts maps are populated.

+

func (*Info) TypeOf 1.5

func (info *Info) TypeOf(e ast.Expr) Type

TypeOf returns the type of expression e, or nil if not found. Precondition: the Types, Uses and Defs maps are populated.

+

type Initializer 1.5

An Initializer describes a package-level variable, or a list of variables in case of a multi-valued initialization expression, and the corresponding initialization expression.

+
type Initializer struct {
+    Lhs []*Var // var Lhs = Rhs
+    Rhs ast.Expr
+}
+

func (*Initializer) String 1.5

func (init *Initializer) String() string

type Instance 1.18

Instance reports the type arguments and instantiated type for type and function instantiations. For type instantiations, Type will be of dynamic type *Named. For function instantiations, Type will be of dynamic type *Signature.

+
type Instance struct {
+    TypeArgs *TypeList
+    Type     Type
+}
+

type Interface 1.5

An Interface represents an interface type.

+
type Interface struct {
+    // contains filtered or unexported fields
+}
+

func NewInterface 1.5

func NewInterface(methods []*Func, embeddeds []*Named) *Interface

NewInterface returns a new interface for the given methods and embedded types. NewInterface takes ownership of the provided methods and may modify their types by setting missing receivers.

+

Deprecated: Use NewInterfaceType instead which allows arbitrary embedded types.

+

func NewInterfaceType 1.11

func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface

NewInterfaceType returns a new interface for the given methods and embedded types. NewInterfaceType takes ownership of the provided methods and may modify their types by setting missing receivers.

+

To avoid race conditions, the interface's type set should be computed before concurrent use of the interface, by explicitly calling Complete.

+

func (*Interface) Complete 1.5

func (t *Interface) Complete() *Interface

Complete computes the interface's type set. It must be called by users of NewInterfaceType and NewInterface after the interface's embedded types are fully defined and before using the interface type in any way other than to form other types. The interface must not contain duplicate methods or a panic occurs. Complete returns the receiver.

+

Interface types that have been completed are safe for concurrent use.

+

func (*Interface) Embedded 1.5

func (t *Interface) Embedded(i int) *Named

Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds(). The result is nil if the i'th embedded type is not a defined type.

+

Deprecated: Use Interface.EmbeddedType which is not restricted to defined (*Named) types.

+

func (*Interface) EmbeddedType 1.11

func (t *Interface) EmbeddedType(i int) Type

EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().

+

func (*Interface) Empty 1.5

func (t *Interface) Empty() bool

Empty reports whether t is the empty interface.

+

func (*Interface) ExplicitMethod 1.5

func (t *Interface) ExplicitMethod(i int) *Func

ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods(). The methods are ordered by their unique Id.

+

func (*Interface) IsComparable 1.18

func (t *Interface) IsComparable() bool

IsComparable reports whether each type in interface t's type set is comparable.

+

func (*Interface) IsImplicit 1.18

func (t *Interface) IsImplicit() bool

IsImplicit reports whether the interface t is a wrapper for a type set literal.

+

func (*Interface) IsMethodSet 1.18

func (t *Interface) IsMethodSet() bool

IsMethodSet reports whether the interface t is fully described by its method set.

+

func (*Interface) MarkImplicit 1.18

func (t *Interface) MarkImplicit()

MarkImplicit marks the interface t as implicit, meaning this interface corresponds to a constraint literal such as ~T or A|B without explicit interface embedding. MarkImplicit should be called before any concurrent use of implicit interfaces.

+

func (*Interface) Method 1.5

func (t *Interface) Method(i int) *Func

Method returns the i'th method of interface t for 0 <= i < t.NumMethods(). The methods are ordered by their unique Id.

+

func (*Interface) NumEmbeddeds 1.5

func (t *Interface) NumEmbeddeds() int

NumEmbeddeds returns the number of embedded types in interface t.

+

func (*Interface) NumExplicitMethods 1.5

func (t *Interface) NumExplicitMethods() int

NumExplicitMethods returns the number of explicitly declared methods of interface t.

+

func (*Interface) NumMethods 1.5

func (t *Interface) NumMethods() int

NumMethods returns the total number of methods of interface t.

+

func (*Interface) String 1.5

func (t *Interface) String() string

func (*Interface) Underlying 1.5

func (t *Interface) Underlying() Type

type Label 1.5

A Label represents a declared label. Labels don't have a type.

+
type Label struct {
+    // contains filtered or unexported fields
+}
+

func NewLabel 1.5

func NewLabel(pos token.Pos, pkg *Package, name string) *Label

NewLabel returns a new label.

+

func (*Label) Exported 1.5

func (obj *Label) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

+

func (*Label) Id 1.5

func (obj *Label) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

+

func (*Label) Name 1.5

func (obj *Label) Name() string

Name returns the object's (package-local, unqualified) name.

+

func (*Label) Parent 1.5

func (obj *Label) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

+

func (*Label) Pkg 1.5

func (obj *Label) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

+

func (*Label) Pos 1.5

func (obj *Label) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

+

func (*Label) String 1.5

func (obj *Label) String() string

func (*Label) Type 1.5

func (obj *Label) Type() Type

Type returns the object's type.

+

type Map 1.5

A Map represents a map type.

+
type Map struct {
+    // contains filtered or unexported fields
+}
+

func NewMap 1.5

func NewMap(key, elem Type) *Map

NewMap returns a new map for the given key and element types.

+

func (*Map) Elem 1.5

func (m *Map) Elem() Type

Elem returns the element type of map m.

+

func (*Map) Key 1.5

func (m *Map) Key() Type

Key returns the key type of map m.

+

func (*Map) String 1.5

func (t *Map) String() string

func (*Map) Underlying 1.5

func (t *Map) Underlying() Type

type MethodSet 1.5

A MethodSet is an ordered set of concrete or abstract (interface) methods; a method is a MethodVal selection, and they are ordered by ascending m.Obj().Id(). The zero value for a MethodSet is a ready-to-use empty method set.

+
type MethodSet struct {
+    // contains filtered or unexported fields
+}
+

Example +

ExampleMethodSet prints the method sets of various types.

Code:

// Parse a single source file.
+const input = `
+package temperature
+import "fmt"
+type Celsius float64
+func (c Celsius) String() string  { return fmt.Sprintf("%g°C", c) }
+func (c *Celsius) SetF(f float64) { *c = Celsius(f - 32 / 9 * 5) }
+
+type S struct { I; m int }
+type I interface { m() byte }
+`
+fset := token.NewFileSet()
+f, err := parser.ParseFile(fset, "celsius.go", input, 0)
+if err != nil {
+    log.Fatal(err)
+}
+
+// Type-check a package consisting of this file.
+// Type information for the imported packages
+// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
+conf := types.Config{Importer: importer.Default()}
+pkg, err := conf.Check("temperature", fset, []*ast.File{f}, nil)
+if err != nil {
+    log.Fatal(err)
+}
+
+// Print the method sets of Celsius and *Celsius.
+celsius := pkg.Scope().Lookup("Celsius").Type()
+for _, t := range []types.Type{celsius, types.NewPointer(celsius)} {
+    fmt.Printf("Method set of %s:\n", t)
+    mset := types.NewMethodSet(t)
+    for i := 0; i < mset.Len(); i++ {
+        fmt.Println(mset.At(i))
+    }
+    fmt.Println()
+}
+
+// Print the method set of S.
+styp := pkg.Scope().Lookup("S").Type()
+fmt.Printf("Method set of %s:\n", styp)
+fmt.Println(types.NewMethodSet(styp))
+
+

Output:

Method set of temperature.Celsius:
+method (temperature.Celsius) String() string
+
+Method set of *temperature.Celsius:
+method (*temperature.Celsius) SetF(f float64)
+method (*temperature.Celsius) String() string
+
+Method set of temperature.S:
+MethodSet {}
+

func NewMethodSet 1.5

func NewMethodSet(T Type) *MethodSet

NewMethodSet returns the method set for the given type T. It always returns a non-nil method set, even if it is empty.

+

func (*MethodSet) At 1.5

func (s *MethodSet) At(i int) *Selection

At returns the i'th method in s for 0 <= i < s.Len().

+

func (*MethodSet) Len 1.5

func (s *MethodSet) Len() int

Len returns the number of methods in s.

+

func (*MethodSet) Lookup 1.5

func (s *MethodSet) Lookup(pkg *Package, name string) *Selection

Lookup returns the method with matching package and name, or nil if not found.

+

func (*MethodSet) String 1.5

func (s *MethodSet) String() string

type Named 1.5

A Named represents a named (defined) type.

+
type Named struct {
+    // contains filtered or unexported fields
+}
+

func NewNamed 1.5

func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named

NewNamed returns a new named type for the given type name, underlying type, and associated methods. If the given type name obj doesn't have a type yet, its type is set to the returned named type. The underlying type must not be a *Named.

+

func (*Named) AddMethod 1.5

func (t *Named) AddMethod(m *Func)

AddMethod adds method m unless it is already in the method list. t must not have type arguments.

+

func (*Named) Method 1.5

func (t *Named) Method(i int) *Func

Method returns the i'th method of named type t for 0 <= i < t.NumMethods().

+

For an ordinary or instantiated type t, the receiver base type of this method is the named type t. For an uninstantiated generic type t, each method receiver is instantiated with its receiver type parameters.

+

func (*Named) NumMethods 1.5

func (t *Named) NumMethods() int

NumMethods returns the number of explicit methods defined for t.

+

func (*Named) Obj 1.5

func (t *Named) Obj() *TypeName

Obj returns the type name for the declaration defining the named type t. For instantiated types, this is same as the type name of the origin type.

+

func (*Named) Origin 1.18

func (t *Named) Origin() *Named

Origin returns the generic type from which the named type t is instantiated. If t is not an instantiated type, the result is t.

+

func (*Named) SetTypeParams 1.18

func (t *Named) SetTypeParams(tparams []*TypeParam)

SetTypeParams sets the type parameters of the named type t. t must not have type arguments.

+

func (*Named) SetUnderlying 1.5

func (t *Named) SetUnderlying(underlying Type)

SetUnderlying sets the underlying type and marks t as complete. t must not have type arguments.

+

func (*Named) String 1.5

func (t *Named) String() string

func (*Named) TypeArgs 1.18

func (t *Named) TypeArgs() *TypeList

TypeArgs returns the type arguments used to instantiate the named type t.

+

func (*Named) TypeParams 1.18

func (t *Named) TypeParams() *TypeParamList

TypeParams returns the type parameters of the named type t, or nil. The result is non-nil for an (originally) generic type even if it is instantiated.

+

func (*Named) Underlying 1.5

func (t *Named) Underlying() Type

TODO(gri) Investigate if Unalias can be moved to where underlying is set.

+

type Nil 1.5

Nil represents the predeclared value nil.

+
type Nil struct {
+    // contains filtered or unexported fields
+}
+

func (*Nil) Exported 1.5

func (obj *Nil) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

+

func (*Nil) Id 1.5

func (obj *Nil) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

+

func (*Nil) Name 1.5

func (obj *Nil) Name() string

Name returns the object's (package-local, unqualified) name.

+

func (*Nil) Parent 1.5

func (obj *Nil) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

+

func (*Nil) Pkg 1.5

func (obj *Nil) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

+

func (*Nil) Pos 1.5

func (obj *Nil) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

+

func (*Nil) String 1.5

func (obj *Nil) String() string

func (*Nil) Type 1.5

func (obj *Nil) Type() Type

Type returns the object's type.

+

type Object 1.5

An Object describes a named language entity such as a package, constant, type, variable, function (incl. methods), or label. All objects implement the Object interface.

+
type Object interface {
+    Parent() *Scope // scope in which this object is declared; nil for methods and struct fields
+    Pos() token.Pos // position of object identifier in declaration
+    Pkg() *Package  // package to which this object belongs; nil for labels and objects in the Universe scope
+    Name() string   // package local object name
+    Type() Type     // object type
+    Exported() bool // reports whether the name starts with a capital letter
+    Id() string     // object name if exported, qualified name if not exported (see func Id)
+
+    // String returns a human-readable string of the object.
+    String() string
+    // contains filtered or unexported methods
+}

func LookupFieldOrMethod 1.5

func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool)

LookupFieldOrMethod looks up a field or method with given package and name in T and returns the corresponding *Var or *Func, an index sequence, and a bool indicating if there were any pointer indirections on the path to the field or method. If addressable is set, T is the type of an addressable variable (only matters for method lookups). T must not be nil.

+

The last index entry is the field or method index in the (possibly embedded) type where the entry was found, either:

+
  1. the list of declared methods of a named type; or
  2. +
  3. the list of all methods (method set) of an interface type; or
  4. +
  5. the list of fields of a struct type.
  6. +

The earlier index entries are the indices of the embedded struct fields traversed to get to the found entry, starting at depth 0.

+

If no entry is found, a nil object is returned. In this case, the returned index and indirect values have the following meaning:

+

type Package 1.5

A Package describes a Go package.

+
type Package struct {
+    // contains filtered or unexported fields
+}
+

The Unsafe package is the package returned by an importer for the import path "unsafe".

+
var Unsafe *Package

func NewPackage 1.5

func NewPackage(path, name string) *Package

NewPackage returns a new Package for the given package path and name. The package is not complete and contains no explicit imports.

+

func (*Package) Complete 1.5

func (pkg *Package) Complete() bool

A package is complete if its scope contains (at least) all exported objects; otherwise it is incomplete.

+

func (*Package) GoVersion 1.21

func (pkg *Package) GoVersion() string

GoVersion returns the minimum Go version required by this package. If the minimum version is unknown, GoVersion returns the empty string. Individual source files may specify a different minimum Go version, as reported in the go/ast.File.GoVersion field.

+

func (*Package) Imports 1.5

func (pkg *Package) Imports() []*Package

Imports returns the list of packages directly imported by pkg; the list is in source order.

+

If pkg was loaded from export data, Imports includes packages that provide package-level objects referenced by pkg. This may be more or less than the set of packages directly imported by pkg's source code.

+

If pkg uses cgo and the FakeImportC configuration option was enabled, the imports list may contain a fake "C" package.

+

func (*Package) MarkComplete 1.5

func (pkg *Package) MarkComplete()

MarkComplete marks a package as complete.

+

func (*Package) Name 1.5

func (pkg *Package) Name() string

Name returns the package name.

+

func (*Package) Path 1.5

func (pkg *Package) Path() string

Path returns the package path.

+

func (*Package) Scope 1.5

func (pkg *Package) Scope() *Scope

Scope returns the (complete or incomplete) package scope holding the objects declared at package level (TypeNames, Consts, Vars, and Funcs). For a nil pkg receiver, Scope returns the Universe scope.

+

func (*Package) SetImports 1.5

func (pkg *Package) SetImports(list []*Package)

SetImports sets the list of explicitly imported packages to list. It is the caller's responsibility to make sure list elements are unique.

+

func (*Package) SetName 1.6

func (pkg *Package) SetName(name string)

SetName sets the package name.

+

func (*Package) String 1.5

func (pkg *Package) String() string

type PkgName 1.5

A PkgName represents an imported Go package. PkgNames don't have a type.

+
type PkgName struct {
+    // contains filtered or unexported fields
+}
+

func NewPkgName 1.5

func NewPkgName(pos token.Pos, pkg *Package, name string, imported *Package) *PkgName

NewPkgName returns a new PkgName object representing an imported package. The remaining arguments set the attributes found with all Objects.

+

func (*PkgName) Exported 1.5

func (obj *PkgName) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

+

func (*PkgName) Id 1.5

func (obj *PkgName) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

+

func (*PkgName) Imported 1.5

func (obj *PkgName) Imported() *Package

Imported returns the package that was imported. It is distinct from Pkg(), which is the package containing the import statement.

+

func (*PkgName) Name 1.5

func (obj *PkgName) Name() string

Name returns the object's (package-local, unqualified) name.

+

func (*PkgName) Parent 1.5

func (obj *PkgName) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

+

func (*PkgName) Pkg 1.5

func (obj *PkgName) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

+

func (*PkgName) Pos 1.5

func (obj *PkgName) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

+

func (*PkgName) String 1.5

func (obj *PkgName) String() string

func (*PkgName) Type 1.5

func (obj *PkgName) Type() Type

Type returns the object's type.

+

type Pointer 1.5

A Pointer represents a pointer type.

+
type Pointer struct {
+    // contains filtered or unexported fields
+}
+

func NewPointer 1.5

func NewPointer(elem Type) *Pointer

NewPointer returns a new pointer type for the given element (base) type.

+

func (*Pointer) Elem 1.5

func (p *Pointer) Elem() Type

Elem returns the element type for the given pointer p.

+

func (*Pointer) String 1.5

func (p *Pointer) String() string

func (*Pointer) Underlying 1.5

func (p *Pointer) Underlying() Type

type Qualifier 1.5

A Qualifier controls how named package-level objects are printed in calls to TypeString, ObjectString, and SelectionString.

+

These three formatting routines call the Qualifier for each package-level object O, and if the Qualifier returns a non-empty string p, the object is printed in the form p.O. If it returns an empty string, only the object name O is printed.

+

Using a nil Qualifier is equivalent to using (*Package).Path: the object is qualified by the import path, e.g., "encoding/json.Marshal".

+
type Qualifier func(*Package) string

func RelativeTo 1.5

func RelativeTo(pkg *Package) Qualifier

RelativeTo returns a Qualifier that fully qualifies members of all packages other than pkg.

+

type Scope 1.5

A Scope maintains a set of objects and links to its containing (parent) and contained (children) scopes. Objects may be inserted and looked up by name. The zero value for Scope is a ready-to-use empty scope.

+
type Scope struct {
+    // contains filtered or unexported fields
+}
+

The Universe scope contains all predeclared objects of Go. It is the outermost scope of any chain of nested scopes.

+
var Universe *Scope

Example +

ExampleScope prints the tree of Scopes of a package created from a set of parsed files.

Code:

// Parse the source files for a package.
+fset := token.NewFileSet()
+var files []*ast.File
+for _, src := range []string{
+    `package main
+import "fmt"
+func main() {
+    freezing := FToC(-18)
+    fmt.Println(freezing, Boiling) }
+`,
+    `package main
+import "fmt"
+type Celsius float64
+func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
+func FToC(f float64) Celsius { return Celsius(f - 32 / 9 * 5) }
+const Boiling Celsius = 100
+func Unused() { {}; {{ var x int; _ = x }} } // make sure empty block scopes get printed
+`,
+} {
+    files = append(files, mustParse(fset, src))
+}
+
+// Type-check a package consisting of these files.
+// Type information for the imported "fmt" package
+// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
+conf := types.Config{Importer: importer.Default()}
+pkg, err := conf.Check("temperature", fset, files, nil)
+if err != nil {
+    log.Fatal(err)
+}
+
+// Print the tree of scopes.
+// For determinism, we redact addresses.
+var buf strings.Builder
+pkg.Scope().WriteTo(&buf, 0, true)
+rx := regexp.MustCompile(` 0x[a-fA-F\d]*`)
+fmt.Println(rx.ReplaceAllString(buf.String(), ""))
+
+

Output:

package "temperature" scope {
+.  const temperature.Boiling temperature.Celsius
+.  type temperature.Celsius float64
+.  func temperature.FToC(f float64) temperature.Celsius
+.  func temperature.Unused()
+.  func temperature.main()
+.  main scope {
+.  .  package fmt
+.  .  function scope {
+.  .  .  var freezing temperature.Celsius
+.  .  }
+.  }
+.  main scope {
+.  .  package fmt
+.  .  function scope {
+.  .  .  var c temperature.Celsius
+.  .  }
+.  .  function scope {
+.  .  .  var f float64
+.  .  }
+.  .  function scope {
+.  .  .  block scope {
+.  .  .  }
+.  .  .  block scope {
+.  .  .  .  block scope {
+.  .  .  .  .  var x int
+.  .  .  .  }
+.  .  .  }
+.  .  }
+.  }
+}
+

func NewScope 1.5

func NewScope(parent *Scope, pos, end token.Pos, comment string) *Scope

NewScope returns a new, empty scope contained in the given parent scope, if any. The comment is for debugging only.

+

func (*Scope) Child 1.5

func (s *Scope) Child(i int) *Scope

Child returns the i'th child scope for 0 <= i < NumChildren().

+

func (*Scope) Contains 1.5

func (s *Scope) Contains(pos token.Pos) bool

Contains reports whether pos is within the scope's extent. The result is guaranteed to be valid only if the type-checked AST has complete position information.

+

func (*Scope) End 1.5

func (s *Scope) End() token.Pos

func (*Scope) Innermost 1.5

func (s *Scope) Innermost(pos token.Pos) *Scope

Innermost returns the innermost (child) scope containing pos. If pos is not within any scope, the result is nil. The result is also nil for the Universe scope. The result is guaranteed to be valid only if the type-checked AST has complete position information.

+

func (*Scope) Insert 1.5

func (s *Scope) Insert(obj Object) Object

Insert attempts to insert an object obj into scope s. If s already contains an alternative object alt with the same name, Insert leaves s unchanged and returns alt. Otherwise it inserts obj, sets the object's parent scope if not already set, and returns nil.

+

func (*Scope) Len 1.5

func (s *Scope) Len() int

Len returns the number of scope elements.

+

func (*Scope) Lookup 1.5

func (s *Scope) Lookup(name string) Object

Lookup returns the object in scope s with the given name if such an object exists; otherwise the result is nil.

+

func (*Scope) LookupParent 1.5

func (s *Scope) LookupParent(name string, pos token.Pos) (*Scope, Object)

LookupParent follows the parent chain of scopes starting with s until it finds a scope where Lookup(name) returns a non-nil object, and then returns that scope and object. If a valid position pos is provided, only objects that were declared at or before pos are considered. If no such scope and object exists, the result is (nil, nil).

+

Note that obj.Parent() may be different from the returned scope if the object was inserted into the scope and already had a parent at that time (see Insert). This can only happen for dot-imported objects whose scope is the scope of the package that exported them.

+

func (*Scope) Names 1.5

func (s *Scope) Names() []string

Names returns the scope's element names in sorted order.

+

func (*Scope) NumChildren 1.5

func (s *Scope) NumChildren() int

NumChildren returns the number of scopes nested in s.

+

func (*Scope) Parent 1.5

func (s *Scope) Parent() *Scope

Parent returns the scope's containing (parent) scope.

+

func (*Scope) Pos 1.5

func (s *Scope) Pos() token.Pos

Pos and End describe the scope's source code extent [pos, end). The results are guaranteed to be valid only if the type-checked AST has complete position information. The extent is undefined for Universe and package scopes.

+

func (*Scope) String 1.5

func (s *Scope) String() string

String returns a string representation of the scope, for debugging.

+

func (*Scope) WriteTo 1.5

func (s *Scope) WriteTo(w io.Writer, n int, recurse bool)

WriteTo writes a string representation of the scope to w, with the scope elements sorted by name. The level of indentation is controlled by n >= 0, with n == 0 for no indentation. If recurse is set, it also writes nested (children) scopes.

+

type Selection 1.5

A Selection describes a selector expression x.f. For the declarations:

+
type T struct{ x int; E }
+type E struct{}
+func (e E) m() {}
+var p *T
+

the following relations exist:

+
Selector    Kind          Recv    Obj    Type       Index     Indirect
+
+p.x         FieldVal      T       x      int        {0}       true
+p.m         MethodVal     *T      m      func()     {1, 0}    true
+T.m         MethodExpr    T       m      func(T)    {1, 0}    false
+
type Selection struct {
+    // contains filtered or unexported fields
+}
+

func (*Selection) Index 1.5

func (s *Selection) Index() []int

Index describes the path from x to f in x.f. The last index entry is the field or method index of the type declaring f; either:

+
  1. the list of declared methods of a named type; or
  2. +
  3. the list of methods of an interface type; or
  4. +
  5. the list of fields of a struct type.
  6. +

The earlier index entries are the indices of the embedded fields implicitly traversed to get from (the type of) x to f, starting at embedding depth 0.

+

func (*Selection) Indirect 1.5

func (s *Selection) Indirect() bool

Indirect reports whether any pointer indirection was required to get from x to f in x.f.

+

Beware: Indirect spuriously returns true (Go issue #8353) for a MethodVal selection in which the receiver argument and parameter both have type *T so there is no indirection. Unfortunately, a fix is too risky.

+

func (*Selection) Kind 1.5

func (s *Selection) Kind() SelectionKind

Kind returns the selection kind.

+

func (*Selection) Obj 1.5

func (s *Selection) Obj() Object

Obj returns the object denoted by x.f; a *Var for a field selection, and a *Func in all other cases.

+

func (*Selection) Recv 1.5

func (s *Selection) Recv() Type

Recv returns the type of x in x.f.

+

func (*Selection) String 1.5

func (s *Selection) String() string

func (*Selection) Type 1.5

func (s *Selection) Type() Type

Type returns the type of x.f, which may be different from the type of f. See Selection for more information.

+

type SelectionKind 1.5

SelectionKind describes the kind of a selector expression x.f (excluding qualified identifiers).

+

If x is a struct or *struct, a selector expression x.f may denote a sequence of selection operations x.a.b.c.f. The SelectionKind describes the kind of the final (explicit) operation; all the previous (implicit) operations are always field selections. Each element of Indices specifies an implicit field (a, b, c) by its index in the struct type of the field selection operand.

+

For a FieldVal operation, the final selection refers to the field specified by Selection.Obj.

+

For a MethodVal operation, the final selection refers to a method. If the "pointerness" of the method's declared receiver does not match that of the effective receiver after implicit field selection, then an & or * operation is implicitly applied to the receiver variable or value. So, x.f denotes (&x.a.b.c).f when f requires a pointer receiver but x.a.b.c is a non-pointer variable; and it denotes (*x.a.b.c).f when f requires a non-pointer receiver but x.a.b.c is a pointer value.

+

All pointer indirections, whether due to implicit or explicit field selections or * operations inserted for "pointerness", panic if applied to a nil pointer, so a method call x.f() may panic even before the function call.

+

By contrast, a MethodExpr operation T.f is essentially equivalent to a function literal of the form:

+
func(x T, args) (results) { return x.f(args) }
+

Consequently, any implicit field selections and * operations inserted for "pointerness" are not evaluated until the function is called, so a T.f or (*T).f expression never panics.

+
type SelectionKind int
const (
+    FieldVal   SelectionKind = iota // x.f is a struct field selector
+    MethodVal                       // x.f is a method selector
+    MethodExpr                      // x.f is a method expression
+)

type Signature 1.5

A Signature represents a (non-builtin) function or method type. The receiver is ignored when comparing signatures for identity.

+
type Signature struct {
+    // contains filtered or unexported fields
+}
+

func NewSignature 1.5

func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature

NewSignature returns a new function type for the given receiver, parameters, and results, either of which may be nil. If variadic is set, the function is variadic, it must have at least one parameter, and the last parameter must be of unnamed slice type.

+

Deprecated: Use NewSignatureType instead which allows for type parameters.

+

func NewSignatureType 1.18

func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature

NewSignatureType creates a new function type for the given receiver, receiver type parameters, type parameters, parameters, and results. If variadic is set, params must hold at least one parameter and the last parameter's core type must be of unnamed slice or bytestring type. If recv is non-nil, typeParams must be empty. If recvTypeParams is non-empty, recv must be non-nil.

+

func (*Signature) Params 1.5

func (s *Signature) Params() *Tuple

Params returns the parameters of signature s, or nil.

+

func (*Signature) Recv 1.5

func (s *Signature) Recv() *Var

Recv returns the receiver of signature s (if a method), or nil if a function. It is ignored when comparing signatures for identity.

+

For an abstract method, Recv returns the enclosing interface either as a *Named or an *Interface. Due to embedding, an interface may contain methods whose receiver type is a different interface.

+

func (*Signature) RecvTypeParams 1.18

func (s *Signature) RecvTypeParams() *TypeParamList

RecvTypeParams returns the receiver type parameters of signature s, or nil.

+

func (*Signature) Results 1.5

func (s *Signature) Results() *Tuple

Results returns the results of signature s, or nil.

+

func (*Signature) String 1.5

func (t *Signature) String() string

func (*Signature) TypeParams 1.18

func (s *Signature) TypeParams() *TypeParamList

TypeParams returns the type parameters of signature s, or nil.

+

func (*Signature) Underlying 1.5

func (t *Signature) Underlying() Type

func (*Signature) Variadic 1.5

func (s *Signature) Variadic() bool

Variadic reports whether the signature s is variadic.

+

type Sizes 1.5

Sizes defines the sizing functions for package unsafe.

+
type Sizes interface {
+    // Alignof returns the alignment of a variable of type T.
+    // Alignof must implement the alignment guarantees required by the spec.
+    // The result must be >= 1.
+    Alignof(T Type) int64
+
+    // Offsetsof returns the offsets of the given struct fields, in bytes.
+    // Offsetsof must implement the offset guarantees required by the spec.
+    // A negative entry in the result indicates that the struct is too large.
+    Offsetsof(fields []*Var) []int64
+
+    // Sizeof returns the size of a variable of type T.
+    // Sizeof must implement the size guarantees required by the spec.
+    // A negative result indicates that T is too large.
+    Sizeof(T Type) int64
+}

func SizesFor 1.9

func SizesFor(compiler, arch string) Sizes

SizesFor returns the Sizes used by a compiler for an architecture. The result is nil if a compiler/architecture pair is not known.

+

Supported architectures for compiler "gc": "386", "amd64", "amd64p32", "arm", "arm64", "loong64", "mips", "mipsle", "mips64", "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", "sparc64", "wasm".

+

type Slice 1.5

A Slice represents a slice type.

+
type Slice struct {
+    // contains filtered or unexported fields
+}
+

func NewSlice 1.5

func NewSlice(elem Type) *Slice

NewSlice returns a new slice type for the given element type.

+

func (*Slice) Elem 1.5

func (s *Slice) Elem() Type

Elem returns the element type of slice s.

+

func (*Slice) String 1.5

func (s *Slice) String() string

func (*Slice) Underlying 1.5

func (s *Slice) Underlying() Type

type StdSizes 1.5

StdSizes is a convenience type for creating commonly used Sizes. It makes the following simplifying assumptions:

+

*StdSizes implements Sizes.

+
type StdSizes struct {
+    WordSize int64 // word size in bytes - must be >= 4 (32bits)
+    MaxAlign int64 // maximum alignment in bytes - must be >= 1
+}
+

func (*StdSizes) Alignof 1.5

func (s *StdSizes) Alignof(T Type) (result int64)

func (*StdSizes) Offsetsof 1.5

func (s *StdSizes) Offsetsof(fields []*Var) []int64

func (*StdSizes) Sizeof 1.5

func (s *StdSizes) Sizeof(T Type) int64

type Struct 1.5

A Struct represents a struct type.

+
type Struct struct {
+    // contains filtered or unexported fields
+}
+

func NewStruct 1.5

func NewStruct(fields []*Var, tags []string) *Struct

NewStruct returns a new struct with the given fields and corresponding field tags. If a field with index i has a tag, tags[i] must be that tag, but len(tags) may be only as long as required to hold the tag with the largest index i. Consequently, if no field has a tag, tags may be nil.

+

func (*Struct) Field 1.5

func (s *Struct) Field(i int) *Var

Field returns the i'th field for 0 <= i < NumFields().

+

func (*Struct) NumFields 1.5

func (s *Struct) NumFields() int

NumFields returns the number of fields in the struct (including blank and embedded fields).

+

func (*Struct) String 1.5

func (t *Struct) String() string

func (*Struct) Tag 1.5

func (s *Struct) Tag(i int) string

Tag returns the i'th field tag for 0 <= i < NumFields().

+

func (*Struct) Underlying 1.5

func (t *Struct) Underlying() Type

type Term 1.18

A Term represents a term in a Union.

+
type Term term

func NewTerm 1.18

func NewTerm(tilde bool, typ Type) *Term

NewTerm returns a new union term.

+

func (*Term) String 1.18

func (t *Term) String() string

func (*Term) Tilde 1.18

func (t *Term) Tilde() bool

func (*Term) Type 1.18

func (t *Term) Type() Type

type Tuple 1.5

A Tuple represents an ordered list of variables; a nil *Tuple is a valid (empty) tuple. Tuples are used as components of signatures and to represent the type of multiple assignments; they are not first class types of Go.

+
type Tuple struct {
+    // contains filtered or unexported fields
+}
+

func NewTuple 1.5

func NewTuple(x ...*Var) *Tuple

NewTuple returns a new tuple for the given variables.

+

func (*Tuple) At 1.5

func (t *Tuple) At(i int) *Var

At returns the i'th variable of tuple t.

+

func (*Tuple) Len 1.5

func (t *Tuple) Len() int

Len returns the number variables of tuple t.

+

func (*Tuple) String 1.5

func (t *Tuple) String() string

func (*Tuple) Underlying 1.5

func (t *Tuple) Underlying() Type

type Type 1.5

A Type represents a type of Go. All types implement the Type interface.

+
type Type interface {
+    // Underlying returns the underlying type of a type.
+    Underlying() Type
+
+    // String returns a string representation of a type.
+    String() string
+}

func Default 1.8

func Default(t Type) Type

Default returns the default "typed" type for an "untyped" type; it returns the incoming type for all other types. The default type for untyped nil is untyped nil.

+

func Instantiate 1.18

func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error)

Instantiate instantiates the type orig with the given type arguments targs. orig must be a *Named or a *Signature type. If there is no error, the resulting Type is an instantiated type of the same kind (either a *Named or a *Signature). Methods attached to a *Named type are also instantiated, and associated with a new *Func that has the same position as the original method, but nil function scope.

+

If ctxt is non-nil, it may be used to de-duplicate the instance against previous instances with the same identity. As a special case, generic *Signature origin types are only considered identical if they are pointer equivalent, so that instantiating distinct (but possibly identical) signatures will yield different instances. The use of a shared context does not guarantee that identical instances are deduplicated in all cases.

+

If validate is set, Instantiate verifies that the number of type arguments and parameters match, and that the type arguments satisfy their corresponding type constraints. If verification fails, the resulting error may wrap an *ArgumentError indicating which type argument did not satisfy its corresponding type parameter constraint, and why.

+

If validate is not set, Instantiate does not verify the type argument count or whether the type arguments satisfy their constraints. Instantiate is guaranteed to not return an error, but may panic. Specifically, for *Signature types, Instantiate will panic immediately if the type argument count is incorrect; for *Named types, a panic may occur later inside the *Named API.

+

func Unalias 1.22

func Unalias(t Type) Type

Unalias returns t if it is not an alias type; otherwise it follows t's alias chain until it reaches a non-alias type which is then returned. Consequently, the result is never an alias type.

+

type TypeAndValue 1.5

TypeAndValue reports the type and value (for constants) of the corresponding expression.

+
type TypeAndValue struct {
+    Type  Type
+    Value constant.Value
+    // contains filtered or unexported fields
+}
+

func Eval 1.5

func Eval(fset *token.FileSet, pkg *Package, pos token.Pos, expr string) (_ TypeAndValue, err error)

Eval returns the type and, if constant, the value for the expression expr, evaluated at position pos of package pkg, which must have been derived from type-checking an AST with complete position information relative to the provided file set.

+

The meaning of the parameters fset, pkg, and pos is the same as in CheckExpr. An error is returned if expr cannot be parsed successfully, or the resulting expr AST cannot be type-checked.

+

func (TypeAndValue) Addressable 1.5

func (tv TypeAndValue) Addressable() bool

Addressable reports whether the corresponding expression is addressable (https://golang.org/ref/spec#Address_operators).

+

func (TypeAndValue) Assignable 1.5

func (tv TypeAndValue) Assignable() bool

Assignable reports whether the corresponding expression is assignable to (provided a value of the right type).

+

func (TypeAndValue) HasOk 1.5

func (tv TypeAndValue) HasOk() bool

HasOk reports whether the corresponding expression may be used on the rhs of a comma-ok assignment.

+

func (TypeAndValue) IsBuiltin 1.5

func (tv TypeAndValue) IsBuiltin() bool

IsBuiltin reports whether the corresponding expression denotes a (possibly parenthesized) built-in function.

+

func (TypeAndValue) IsNil 1.5

func (tv TypeAndValue) IsNil() bool

IsNil reports whether the corresponding expression denotes the predeclared value nil.

+

func (TypeAndValue) IsType 1.5

func (tv TypeAndValue) IsType() bool

IsType reports whether the corresponding expression specifies a type.

+

func (TypeAndValue) IsValue 1.5

func (tv TypeAndValue) IsValue() bool

IsValue reports whether the corresponding expression is a value. Builtins are not considered values. Constant values have a non- nil Value.

+

func (TypeAndValue) IsVoid 1.5

func (tv TypeAndValue) IsVoid() bool

IsVoid reports whether the corresponding expression is a function call without results.

+

type TypeList 1.18

TypeList holds a list of types.

+
type TypeList struct {
+    // contains filtered or unexported fields
+}
+

func (*TypeList) At 1.18

func (l *TypeList) At(i int) Type

At returns the i'th type in the list.

+

func (*TypeList) Len 1.18

func (l *TypeList) Len() int

Len returns the number of types in the list. It is safe to call on a nil receiver.

+

type TypeName 1.5

A TypeName represents a name for a (defined or alias) type.

+
type TypeName struct {
+    // contains filtered or unexported fields
+}
+

func NewTypeName 1.5

func NewTypeName(pos token.Pos, pkg *Package, name string, typ Type) *TypeName

NewTypeName returns a new type name denoting the given typ. The remaining arguments set the attributes found with all Objects.

+

The typ argument may be a defined (Named) type or an alias type. It may also be nil such that the returned TypeName can be used as argument for NewNamed, which will set the TypeName's type as a side- effect.

+

func (*TypeName) Exported 1.5

func (obj *TypeName) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

+

func (*TypeName) Id 1.5

func (obj *TypeName) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

+

func (*TypeName) IsAlias 1.9

func (obj *TypeName) IsAlias() bool

IsAlias reports whether obj is an alias name for a type.

+

func (*TypeName) Name 1.5

func (obj *TypeName) Name() string

Name returns the object's (package-local, unqualified) name.

+

func (*TypeName) Parent 1.5

func (obj *TypeName) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

+

func (*TypeName) Pkg 1.5

func (obj *TypeName) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

+

func (*TypeName) Pos 1.5

func (obj *TypeName) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

+

func (*TypeName) String 1.5

func (obj *TypeName) String() string

func (*TypeName) Type 1.5

func (obj *TypeName) Type() Type

Type returns the object's type.

+

type TypeParam 1.18

A TypeParam represents a type parameter type.

+
type TypeParam struct {
+    // contains filtered or unexported fields
+}
+

func NewTypeParam 1.18

func NewTypeParam(obj *TypeName, constraint Type) *TypeParam

NewTypeParam returns a new TypeParam. Type parameters may be set on a Named or Signature type by calling SetTypeParams. Setting a type parameter on more than one type will result in a panic.

+

The constraint argument can be nil, and set later via SetConstraint. If the constraint is non-nil, it must be fully defined.

+

func (*TypeParam) Constraint 1.18

func (t *TypeParam) Constraint() Type

Constraint returns the type constraint specified for t.

+

func (*TypeParam) Index 1.18

func (t *TypeParam) Index() int

Index returns the index of the type param within its param list, or -1 if the type parameter has not yet been bound to a type.

+

func (*TypeParam) Obj 1.18

func (t *TypeParam) Obj() *TypeName

Obj returns the type name for the type parameter t.

+

func (*TypeParam) SetConstraint 1.18

func (t *TypeParam) SetConstraint(bound Type)

SetConstraint sets the type constraint for t.

+

It must be called by users of NewTypeParam after the bound's underlying is fully defined, and before using the type parameter in any way other than to form other types. Once SetConstraint returns the receiver, t is safe for concurrent use.

+

func (*TypeParam) String 1.18

func (t *TypeParam) String() string

func (*TypeParam) Underlying 1.18

func (t *TypeParam) Underlying() Type

type TypeParamList 1.18

TypeParamList holds a list of type parameters.

+
type TypeParamList struct {
+    // contains filtered or unexported fields
+}
+

func (*TypeParamList) At 1.18

func (l *TypeParamList) At(i int) *TypeParam

At returns the i'th type parameter in the list.

+

func (*TypeParamList) Len 1.18

func (l *TypeParamList) Len() int

Len returns the number of type parameters in the list. It is safe to call on a nil receiver.

+

type Union 1.18

A Union represents a union of terms embedded in an interface.

+
type Union struct {
+    // contains filtered or unexported fields
+}
+

func NewUnion 1.18

func NewUnion(terms []*Term) *Union

NewUnion returns a new Union type with the given terms. It is an error to create an empty union; they are syntactically not possible.

+

func (*Union) Len 1.18

func (u *Union) Len() int

func (*Union) String 1.18

func (u *Union) String() string

func (*Union) Term 1.18

func (u *Union) Term(i int) *Term

func (*Union) Underlying 1.18

func (u *Union) Underlying() Type

type Var 1.5

A Variable represents a declared variable (including function parameters and results, and struct fields).

+
type Var struct {
+    // contains filtered or unexported fields
+}
+

func NewField 1.5

func NewField(pos token.Pos, pkg *Package, name string, typ Type, embedded bool) *Var

NewField returns a new variable representing a struct field. For embedded fields, the name is the unqualified type name under which the field is accessible.

+

func NewParam 1.5

func NewParam(pos token.Pos, pkg *Package, name string, typ Type) *Var

NewParam returns a new variable representing a function parameter.

+

func NewVar 1.5

func NewVar(pos token.Pos, pkg *Package, name string, typ Type) *Var

NewVar returns a new variable. The arguments set the attributes found with all Objects.

+

func (*Var) Anonymous 1.5

func (obj *Var) Anonymous() bool

Anonymous reports whether the variable is an embedded field. Same as Embedded; only present for backward-compatibility.

+

func (*Var) Embedded 1.11

func (obj *Var) Embedded() bool

Embedded reports whether the variable is an embedded field.

+

func (*Var) Exported 1.5

func (obj *Var) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

+

func (*Var) Id 1.5

func (obj *Var) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

+

func (*Var) IsField 1.5

func (obj *Var) IsField() bool

IsField reports whether the variable is a struct field.

+

func (*Var) Name 1.5

func (obj *Var) Name() string

Name returns the object's (package-local, unqualified) name.

+

func (*Var) Origin 1.19

func (obj *Var) Origin() *Var

Origin returns the canonical Var for its receiver, i.e. the Var object recorded in Info.Defs.

+

For synthetic Vars created during instantiation (such as struct fields or function parameters that depend on type arguments), this will be the corresponding Var on the generic (uninstantiated) type. For all other Vars Origin returns the receiver.

+

func (*Var) Parent 1.5

func (obj *Var) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

+

func (*Var) Pkg 1.5

func (obj *Var) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

+

func (*Var) Pos 1.5

func (obj *Var) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

+

func (*Var) String 1.5

func (obj *Var) String() string

func (*Var) Type 1.5

func (obj *Var) Type() Type

Type returns the object's type.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/types/ +

+
diff --git a/devdocs/go/go%2Fversion%2Findex.html b/devdocs/go/go%2Fversion%2Findex.html new file mode 100644 index 00000000..88e5dc66 --- /dev/null +++ b/devdocs/go/go%2Fversion%2Findex.html @@ -0,0 +1,23 @@ +

Package version

Overview

Package version provides operations on Go versions in Go toolchain name syntax: strings like "go1.20", "go1.21.0", "go1.22rc2", and "go1.23.4-bigcorp".

Index

Package files

version.go

func Compare 1.22

func Compare(x, y string) int

Compare returns -1, 0, or +1 depending on whether x < y, x == y, or x > y, interpreted as Go versions. The versions x and y must begin with a "go" prefix: "go1.21" not "1.21". Invalid versions, including the empty string, compare less than valid versions and equal to each other. The language version "go1.21" compares less than the release candidate and eventual releases "go1.21rc1" and "go1.21.0".

+

func IsValid 1.22

func IsValid(x string) bool

IsValid reports whether the version x is valid.

+

func Lang 1.22

func Lang(x string) string

Lang returns the Go language version for version x. If x is not a valid version, Lang returns the empty string. For example:

+
Lang("go1.21rc2") = "go1.21"
+Lang("go1.21.2") = "go1.21"
+Lang("go1.21") = "go1.21"
+Lang("go1") = "go1"
+Lang("bad") = ""
+Lang("1.21") = ""
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/go/version/ +

+
diff --git a/devdocs/go/hash%2Fadler32%2Findex.html b/devdocs/go/hash%2Fadler32%2Findex.html new file mode 100644 index 00000000..58786cdd --- /dev/null +++ b/devdocs/go/hash%2Fadler32%2Findex.html @@ -0,0 +1,23 @@ +

Package adler32

Overview

Package adler32 implements the Adler-32 checksum.

+

It is defined in RFC 1950:

+
Adler-32 is composed of two sums accumulated per byte: s1 is
+the sum of all bytes, s2 is the sum of all s1 values. Both sums
+are done modulo 65521. s1 is initialized to 1, s2 to zero.  The
+Adler-32 checksum is stored as s2*65536 + s1 in most-
+significant-byte first (network) order.
+

Index

Package files

adler32.go

Constants

The size of an Adler-32 checksum in bytes.

+
const Size = 4

func Checksum

func Checksum(data []byte) uint32

Checksum returns the Adler-32 checksum of data.

+

func New

func New() hash.Hash32

New returns a new hash.Hash32 computing the Adler-32 checksum. Its Sum method will lay the value out in big-endian byte order. The returned Hash32 also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/hash/adler32/ +

+
diff --git a/devdocs/go/hash%2Fcrc32%2Findex.html b/devdocs/go/hash%2Fcrc32%2Findex.html new file mode 100644 index 00000000..65aed132 --- /dev/null +++ b/devdocs/go/hash%2Fcrc32%2Findex.html @@ -0,0 +1,62 @@ +

Package crc32

Overview

Package crc32 implements the 32-bit cyclic redundancy check, or CRC-32, checksum. See https://en.wikipedia.org/wiki/Cyclic_redundancy_check for information.

+

Polynomials are represented in LSB-first form also known as reversed representation.

+

See https://en.wikipedia.org/wiki/Mathematics_of_cyclic_redundancy_checks#Reversed_representations_and_reciprocal_polynomials for information.

Index

Examples

MakeTable

Package files

crc32.go crc32_amd64.go crc32_generic.go

Constants

Predefined polynomials.

+
const (
+    // IEEE is by far and away the most common CRC-32 polynomial.
+    // Used by ethernet (IEEE 802.3), v.42, fddi, gzip, zip, png, ...
+    IEEE = 0xedb88320
+
+    // Castagnoli's polynomial, used in iSCSI.
+    // Has better error detection characteristics than IEEE.
+    // https://dx.doi.org/10.1109/26.231911
+    Castagnoli = 0x82f63b78
+
+    // Koopman's polynomial.
+    // Also has better error detection characteristics than IEEE.
+    // https://dx.doi.org/10.1109/DSN.2002.1028931
+    Koopman = 0xeb31d82e
+)

The size of a CRC-32 checksum in bytes.

+
const Size = 4

Variables

IEEETable is the table for the IEEE polynomial.

+
var IEEETable = simpleMakeTable(IEEE)

func Checksum

func Checksum(data []byte, tab *Table) uint32

Checksum returns the CRC-32 checksum of data using the polynomial represented by the Table.

+

func ChecksumIEEE

func ChecksumIEEE(data []byte) uint32

ChecksumIEEE returns the CRC-32 checksum of data using the IEEE polynomial.

+

func New

func New(tab *Table) hash.Hash32

New creates a new hash.Hash32 computing the CRC-32 checksum using the polynomial represented by the Table. Its Sum method will lay the value out in big-endian byte order. The returned Hash32 also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

+

func NewIEEE

func NewIEEE() hash.Hash32

NewIEEE creates a new hash.Hash32 computing the CRC-32 checksum using the IEEE polynomial. Its Sum method will lay the value out in big-endian byte order. The returned Hash32 also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

+

func Update

func Update(crc uint32, tab *Table, p []byte) uint32

Update returns the result of adding the bytes in p to the crc.

+

type Table

Table is a 256-word table representing the polynomial for efficient processing.

+
type Table [256]uint32

func MakeTable

func MakeTable(poly uint32) *Table

MakeTable returns a Table constructed from the specified polynomial. The contents of this Table must not be modified.

Example +

Code:

// In this package, the CRC polynomial is represented in reversed notation,
+// or LSB-first representation.
+//
+// LSB-first representation is a hexadecimal number with n bits, in which the
+// most significant bit represents the coefficient of x⁰ and the least significant
+// bit represents the coefficient of xⁿ⁻¹ (the coefficient for xⁿ is implicit).
+//
+// For example, CRC32-Q, as defined by the following polynomial,
+//	x³²+ x³¹+ x²⁴+ x²²+ x¹⁶+ x¹⁴+ x⁸+ x⁷+ x⁵+ x³+ x¹+ x⁰
+// has the reversed notation 0b11010101100000101000001010000001, so the value
+// that should be passed to MakeTable is 0xD5828281.
+crc32q := crc32.MakeTable(0xD5828281)
+fmt.Printf("%08x\n", crc32.Checksum([]byte("Hello world"), crc32q))
+

Output:

2964d064
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/hash/crc32/ +

+
diff --git a/devdocs/go/hash%2Fcrc64%2Findex.html b/devdocs/go/hash%2Fcrc64%2Findex.html new file mode 100644 index 00000000..2a4d782a --- /dev/null +++ b/devdocs/go/hash%2Fcrc64%2Findex.html @@ -0,0 +1,30 @@ +

Package crc64

Overview

Package crc64 implements the 64-bit cyclic redundancy check, or CRC-64, checksum. See https://en.wikipedia.org/wiki/Cyclic_redundancy_check for information.

Index

Package files

crc64.go

Constants

Predefined polynomials.

+
const (
+    // The ISO polynomial, defined in ISO 3309 and used in HDLC.
+    ISO = 0xD800000000000000
+
+    // The ECMA polynomial, defined in ECMA 182.
+    ECMA = 0xC96C5795D7870F42
+)

The size of a CRC-64 checksum in bytes.

+
const Size = 8

func Checksum

func Checksum(data []byte, tab *Table) uint64

Checksum returns the CRC-64 checksum of data using the polynomial represented by the Table.

+

func New

func New(tab *Table) hash.Hash64

New creates a new hash.Hash64 computing the CRC-64 checksum using the polynomial represented by the Table. Its Sum method will lay the value out in big-endian byte order. The returned Hash64 also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

+

func Update

func Update(crc uint64, tab *Table, p []byte) uint64

Update returns the result of adding the bytes in p to the crc.

+

type Table

Table is a 256-word table representing the polynomial for efficient processing.

+
type Table [256]uint64

func MakeTable

func MakeTable(poly uint64) *Table

MakeTable returns a Table constructed from the specified polynomial. The contents of this Table must not be modified.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/hash/crc64/ +

+
diff --git a/devdocs/go/hash%2Ffnv%2Findex.html b/devdocs/go/hash%2Ffnv%2Findex.html new file mode 100644 index 00000000..cd5f2e27 --- /dev/null +++ b/devdocs/go/hash%2Ffnv%2Findex.html @@ -0,0 +1,23 @@ +

Package fnv

Overview

Package fnv implements FNV-1 and FNV-1a, non-cryptographic hash functions created by Glenn Fowler, Landon Curt Noll, and Phong Vo. See https://en.wikipedia.org/wiki/Fowler-Noll-Vo_hash_function.

+

All the hash.Hash implementations returned by this package also implement encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

Index

Package files

fnv.go

func New128 1.9

func New128() hash.Hash

New128 returns a new 128-bit FNV-1 hash.Hash. Its Sum method will lay the value out in big-endian byte order.

+

func New128a 1.9

func New128a() hash.Hash

New128a returns a new 128-bit FNV-1a hash.Hash. Its Sum method will lay the value out in big-endian byte order.

+

func New32

func New32() hash.Hash32

New32 returns a new 32-bit FNV-1 hash.Hash. Its Sum method will lay the value out in big-endian byte order.

+

func New32a

func New32a() hash.Hash32

New32a returns a new 32-bit FNV-1a hash.Hash. Its Sum method will lay the value out in big-endian byte order.

+

func New64

func New64() hash.Hash64

New64 returns a new 64-bit FNV-1 hash.Hash. Its Sum method will lay the value out in big-endian byte order.

+

func New64a

func New64a() hash.Hash64

New64a returns a new 64-bit FNV-1a hash.Hash. Its Sum method will lay the value out in big-endian byte order.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/hash/fnv/ +

+
diff --git a/devdocs/go/hash%2Findex.html b/devdocs/go/hash%2Findex.html new file mode 100644 index 00000000..778f1ee8 --- /dev/null +++ b/devdocs/go/hash%2Findex.html @@ -0,0 +1,82 @@ +

Package hash

Overview

Package hash provides interfaces for hash functions.

Example (BinaryMarshaler) +

Code:

const (
+    input1 = "The tunneling gopher digs downwards, "
+    input2 = "unaware of what he will find."
+)
+
+first := sha256.New()
+first.Write([]byte(input1))
+
+marshaler, ok := first.(encoding.BinaryMarshaler)
+if !ok {
+    log.Fatal("first does not implement encoding.BinaryMarshaler")
+}
+state, err := marshaler.MarshalBinary()
+if err != nil {
+    log.Fatal("unable to marshal hash:", err)
+}
+
+second := sha256.New()
+
+unmarshaler, ok := second.(encoding.BinaryUnmarshaler)
+if !ok {
+    log.Fatal("second does not implement encoding.BinaryUnmarshaler")
+}
+if err := unmarshaler.UnmarshalBinary(state); err != nil {
+    log.Fatal("unable to unmarshal hash:", err)
+}
+
+first.Write([]byte(input2))
+second.Write([]byte(input2))
+
+fmt.Printf("%x\n", first.Sum(nil))
+fmt.Println(bytes.Equal(first.Sum(nil), second.Sum(nil)))
+

Output:

57d51a066f3a39942649cd9a76c77e97ceab246756ff3888659e6aa5a07f4a52
+true
+

Index

Examples

Package (BinaryMarshaler)

Package files

hash.go

type Hash

Hash is the common interface implemented by all hash functions.

+

Hash implementations in the standard library (e.g. hash/crc32 and crypto/sha256) implement the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler interfaces. Marshaling a hash implementation allows its internal state to be saved and used for additional processing later, without having to re-write the data previously written to the hash. The hash state may contain portions of the input in its original form, which users are expected to handle for any possible security implications.

+

Compatibility: Any future changes to hash or crypto packages will endeavor to maintain compatibility with state encoded using previous versions. That is, any released versions of the packages should be able to decode data written with any previously released version, subject to issues such as security fixes. See the Go compatibility document for background: https://golang.org/doc/go1compat

+
type Hash interface {
+    // Write (via the embedded io.Writer interface) adds more data to the running hash.
+    // It never returns an error.
+    io.Writer
+
+    // Sum appends the current hash to b and returns the resulting slice.
+    // It does not change the underlying hash state.
+    Sum(b []byte) []byte
+
+    // Reset resets the Hash to its initial state.
+    Reset()
+
+    // Size returns the number of bytes Sum will return.
+    Size() int
+
+    // BlockSize returns the hash's underlying block size.
+    // The Write method must be able to accept any amount
+    // of data, but it may operate more efficiently if all writes
+    // are a multiple of the block size.
+    BlockSize() int
+}

type Hash32

Hash32 is the common interface implemented by all 32-bit hash functions.

+
type Hash32 interface {
+    Hash
+    Sum32() uint32
+}

type Hash64

Hash64 is the common interface implemented by all 64-bit hash functions.

+
type Hash64 interface {
+    Hash
+    Sum64() uint64
+}

Subdirectories

Name Synopsis
..
adler32 Package adler32 implements the Adler-32 checksum.
crc32 Package crc32 implements the 32-bit cyclic redundancy check, or CRC-32, checksum.
crc64 Package crc64 implements the 64-bit cyclic redundancy check, or CRC-64, checksum.
fnv Package fnv implements FNV-1 and FNV-1a, non-cryptographic hash functions created by Glenn Fowler, Landon Curt Noll, and Phong Vo.
maphash Package maphash provides hash functions on byte sequences.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/hash/ +

+
diff --git a/devdocs/go/hash%2Fmaphash%2Findex.html b/devdocs/go/hash%2Fmaphash%2Findex.html new file mode 100644 index 00000000..290b0289 --- /dev/null +++ b/devdocs/go/hash%2Fmaphash%2Findex.html @@ -0,0 +1,106 @@ +

Package maphash

Overview

Package maphash provides hash functions on byte sequences. These hash functions are intended to be used to implement hash tables or other data structures that need to map arbitrary strings or byte sequences to a uniform distribution on unsigned 64-bit integers. Each different instance of a hash table or data structure should use its own Seed.

+

The hash functions are not cryptographically secure. (See crypto/sha256 and crypto/sha512 for cryptographic use.)

Example +

Code:

+// The zero Hash value is valid and ready to use; setting an
+// initial seed is not necessary.
+var h maphash.Hash
+
+// Add a string to the hash, and print the current hash value.
+h.WriteString("hello, ")
+fmt.Printf("%#x\n", h.Sum64())
+
+// Append additional data (in the form of a byte array).
+h.Write([]byte{'w', 'o', 'r', 'l', 'd'})
+fmt.Printf("%#x\n", h.Sum64())
+
+// Reset discards all data previously added to the Hash, without
+// changing its seed.
+h.Reset()
+
+// Use SetSeed to create a new Hash h2 which will behave
+// identically to h.
+var h2 maphash.Hash
+h2.SetSeed(h.Seed())
+
+h.WriteString("same")
+h2.WriteString("same")
+fmt.Printf("%#x == %#x\n", h.Sum64(), h2.Sum64())
+

Index

Examples

Package

Package files

maphash.go maphash_runtime.go

func Bytes 1.19

func Bytes(seed Seed, b []byte) uint64

Bytes returns the hash of b with the given seed.

+

Bytes is equivalent to, but more convenient and efficient than:

+
var h Hash
+h.SetSeed(seed)
+h.Write(b)
+return h.Sum64()
+

func String 1.19

func String(seed Seed, s string) uint64

String returns the hash of s with the given seed.

+

String is equivalent to, but more convenient and efficient than:

+
var h Hash
+h.SetSeed(seed)
+h.WriteString(s)
+return h.Sum64()
+

type Hash 1.14

A Hash computes a seeded hash of a byte sequence.

+

The zero Hash is a valid Hash ready to use. A zero Hash chooses a random seed for itself during the first call to a Reset, Write, Seed, or Sum64 method. For control over the seed, use SetSeed.

+

The computed hash values depend only on the initial seed and the sequence of bytes provided to the Hash object, not on the way in which the bytes are provided. For example, the three sequences

+
h.Write([]byte{'f','o','o'})
+h.WriteByte('f'); h.WriteByte('o'); h.WriteByte('o')
+h.WriteString("foo")
+

all have the same effect.

+

Hashes are intended to be collision-resistant, even for situations where an adversary controls the byte sequences being hashed.

+

A Hash is not safe for concurrent use by multiple goroutines, but a Seed is. If multiple goroutines must compute the same seeded hash, each can declare its own Hash and call SetSeed with a common Seed.

+
type Hash struct {
+    // contains filtered or unexported fields
+}
+

func (*Hash) BlockSize 1.14

func (h *Hash) BlockSize() int

BlockSize returns h's block size.

+

func (*Hash) Reset 1.14

func (h *Hash) Reset()

Reset discards all bytes added to h. (The seed remains the same.)

+

func (*Hash) Seed 1.14

func (h *Hash) Seed() Seed

Seed returns h's seed value.

+

func (*Hash) SetSeed 1.14

func (h *Hash) SetSeed(seed Seed)

SetSeed sets h to use seed, which must have been returned by MakeSeed or by another Hash.Seed method. Two Hash objects with the same seed behave identically. Two Hash objects with different seeds will very likely behave differently. Any bytes added to h before this call will be discarded.

+

func (*Hash) Size 1.14

func (h *Hash) Size() int

Size returns h's hash value size, 8 bytes.

+

func (*Hash) Sum 1.14

func (h *Hash) Sum(b []byte) []byte

Sum appends the hash's current 64-bit value to b. It exists for implementing hash.Hash. For direct calls, it is more efficient to use Hash.Sum64.

+

func (*Hash) Sum64 1.14

func (h *Hash) Sum64() uint64

Sum64 returns h's current 64-bit value, which depends on h's seed and the sequence of bytes added to h since the last call to Hash.Reset or Hash.SetSeed.

+

All bits of the Sum64 result are close to uniformly and independently distributed, so it can be safely reduced by using bit masking, shifting, or modular arithmetic.

+

func (*Hash) Write 1.14

func (h *Hash) Write(b []byte) (int, error)

Write adds b to the sequence of bytes hashed by h. It always writes all of b and never fails; the count and error result are for implementing io.Writer.

+

func (*Hash) WriteByte 1.14

func (h *Hash) WriteByte(b byte) error

WriteByte adds b to the sequence of bytes hashed by h. It never fails; the error result is for implementing io.ByteWriter.

+

func (*Hash) WriteString 1.14

func (h *Hash) WriteString(s string) (int, error)

WriteString adds the bytes of s to the sequence of bytes hashed by h. It always writes all of s and never fails; the count and error result are for implementing io.StringWriter.

+

type Seed 1.14

A Seed is a random value that selects the specific hash function computed by a Hash. If two Hashes use the same Seeds, they will compute the same hash values for any given input. If two Hashes use different Seeds, they are very likely to compute distinct hash values for any given input.

+

A Seed must be initialized by calling MakeSeed. The zero seed is uninitialized and not valid for use with Hash's SetSeed method.

+

Each Seed value is local to a single process and cannot be serialized or otherwise recreated in a different process.

+
type Seed struct {
+    // contains filtered or unexported fields
+}
+

func MakeSeed 1.14

func MakeSeed() Seed

MakeSeed returns a new random seed.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/hash/maphash/ +

+
diff --git a/devdocs/go/html%2Findex.html b/devdocs/go/html%2Findex.html new file mode 100644 index 00000000..27643e64 --- /dev/null +++ b/devdocs/go/html%2Findex.html @@ -0,0 +1,23 @@ +

Package html

Overview

Package html provides functions for escaping and unescaping HTML text.

Index

Examples

EscapeString
UnescapeString

Package files

entity.go escape.go

func EscapeString

func EscapeString(s string) string

EscapeString escapes special characters like "<" to become "&lt;". It escapes only five such characters: <, >, &, ' and ". UnescapeString(EscapeString(s)) == s always holds, but the converse isn't always true.

Example +

Code:

const s = `"Fran & Freddie's Diner" <tasty@example.com>`
+fmt.Println(html.EscapeString(s))
+

Output:

&#34;Fran &amp; Freddie&#39;s Diner&#34; &lt;tasty@example.com&gt;
+

func UnescapeString

func UnescapeString(s string) string

UnescapeString unescapes entities like "&lt;" to become "<". It unescapes a larger range of entities than EscapeString escapes. For example, "&aacute;" unescapes to "á", as does "&#225;" and "&#xE1;". UnescapeString(EscapeString(s)) == s always holds, but the converse isn't always true.

Example +

Code:

const s = `&quot;Fran &amp; Freddie&#39;s Diner&quot; &lt;tasty@example.com&gt;`
+fmt.Println(html.UnescapeString(s))
+

Output:

"Fran & Freddie's Diner" <tasty@example.com>
+

Subdirectories

Name Synopsis
..
template Package template (html/template) implements data-driven templates for generating HTML output safe against code injection.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/html/ +

+
diff --git a/devdocs/go/html%2Ftemplate%2Findex.html b/devdocs/go/html%2Ftemplate%2Findex.html new file mode 100644 index 00000000..c5a2b4af --- /dev/null +++ b/devdocs/go/html%2Ftemplate%2Findex.html @@ -0,0 +1,773 @@ +

Package template

Overview

Package template (html/template) implements data-driven templates for generating HTML output safe against code injection. It provides the same interface as text/template and should be used instead of text/template whenever the output is HTML.

+

The documentation here focuses on the security features of the package. For information about how to program the templates themselves, see the documentation for text/template.

+

Introduction

This package wraps text/template so you can share its template API to parse and execute HTML templates safely.

+
tmpl, err := template.New("name").Parse(...)
+// Error checking elided
+err = tmpl.Execute(out, data)
+

If successful, tmpl will now be injection-safe. Otherwise, err is an error defined in the docs for ErrorCode.

+

HTML templates treat data values as plain text which should be encoded so they can be safely embedded in an HTML document. The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts.

+

The security model used by this package assumes that template authors are trusted, while Execute's data parameter is not. More details are provided below.

+

Example

+
import "text/template"
+...
+t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
+err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")
+

produces

+
Hello, <script>alert('you have been pwned')</script>!
+

but the contextual autoescaping in html/template

+
import "html/template"
+...
+t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
+err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")
+

produces safe, escaped HTML output

+
Hello, &lt;script&gt;alert(&#39;you have been pwned&#39;)&lt;/script&gt;!
+

Contexts

This package understands HTML, CSS, JavaScript, and URIs. It adds sanitizing functions to each simple action pipeline, so given the excerpt

+
<a href="/search?q={{.}}">{{.}}</a>
+

At parse time each {{.}} is overwritten to add escaping functions as necessary. In this case it becomes

+
<a href="/search?q={{. | urlescaper | attrescaper}}">{{. | htmlescaper}}</a>
+

where urlescaper, attrescaper, and htmlescaper are aliases for internal escaping functions.

+

For these internal escaping functions, if an action pipeline evaluates to a nil interface value, it is treated as though it were an empty string.

+

Namespaced and data- attributes

Attributes with a namespace are treated as if they had no namespace. Given the excerpt

+
<a my:href="{{.}}"></a>
+

At parse time the attribute will be treated as if it were just "href". So at parse time the template becomes:

+
<a my:href="{{. | urlescaper | attrescaper}}"></a>
+

Similarly to attributes with namespaces, attributes with a "data-" prefix are treated as if they had no "data-" prefix. So given

+
<a data-href="{{.}}"></a>
+

At parse time this becomes

+
<a data-href="{{. | urlescaper | attrescaper}}"></a>
+

If an attribute has both a namespace and a "data-" prefix, only the namespace will be removed when determining the context. For example

+
<a my:data-href="{{.}}"></a>
+

This is handled as if "my:data-href" was just "data-href" and not "href" as it would be if the "data-" prefix were to be ignored too. Thus at parse time this becomes just

+
<a my:data-href="{{. | attrescaper}}"></a>
+

As a special case, attributes with the namespace "xmlns" are always treated as containing URLs. Given the excerpts

+
<a xmlns:title="{{.}}"></a>
+<a xmlns:href="{{.}}"></a>
+<a xmlns:onclick="{{.}}"></a>
+

At parse time they become:

+
<a xmlns:title="{{. | urlescaper | attrescaper}}"></a>
+<a xmlns:href="{{. | urlescaper | attrescaper}}"></a>
+<a xmlns:onclick="{{. | urlescaper | attrescaper}}"></a>
+

Errors

See the documentation of ErrorCode for details.

+

A fuller picture

The rest of this package comment may be skipped on first reading; it includes details necessary to understand escaping contexts and error messages. Most users will not need to understand these details.

+

Contexts

Assuming {{.}} is `O'Reilly: How are <i>you</i>?`, the table below shows how {{.}} appears when used in the context to the left.

+
Context                          {{.}} After
+{{.}}                            O'Reilly: How are &lt;i&gt;you&lt;/i&gt;?
+<a title='{{.}}'>                O&#39;Reilly: How are you?
+<a href="/{{.}}">                O&#39;Reilly: How are %3ci%3eyou%3c/i%3e?
+<a href="?q={{.}}">              O&#39;Reilly%3a%20How%20are%3ci%3e...%3f
+<a onx='f("{{.}}")'>             O\x27Reilly: How are \x3ci\x3eyou...?
+<a onx='f({{.}})'>               "O\x27Reilly: How are \x3ci\x3eyou...?"
+<a onx='pattern = /{{.}}/;'>     O\x27Reilly: How are \x3ci\x3eyou...\x3f
+

If used in an unsafe context, then the value might be filtered out:

+
Context                          {{.}} After
+<a href="{{.}}">                 #ZgotmplZ
+

since "O'Reilly:" is not an allowed protocol like "http:".

+

If {{.}} is the innocuous word, `left`, then it can appear more widely,

+
Context                              {{.}} After
+{{.}}                                left
+<a title='{{.}}'>                    left
+<a href='{{.}}'>                     left
+<a href='/{{.}}'>                    left
+<a href='?dir={{.}}'>                left
+<a style="border-{{.}}: 4px">        left
+<a style="align: {{.}}">             left
+<a style="background: '{{.}}'>       left
+<a style="background: url('{{.}}')>  left
+<style>p.{{.}} {color:red}</style>   left
+

Non-string values can be used in JavaScript contexts. If {{.}} is

+
struct{A,B string}{ "foo", "bar" }
+

in the escaped template

+
<script>var pair = {{.}};</script>
+

then the template output is

+
<script>var pair = {"A": "foo", "B": "bar"};</script>
+

See package json to understand how non-string content is marshaled for embedding in JavaScript contexts.

+

Typed Strings

By default, this package assumes that all pipelines produce a plain text string. It adds escaping pipeline stages necessary to correctly and safely embed that plain text string in the appropriate context.

+

When a data value is not plain text, you can make sure it is not over-escaped by marking it with its type.

+

Types HTML, JS, URL, and others from content.go can carry safe content that is exempted from escaping.

+

The template

+
Hello, {{.}}!
+

can be invoked with

+
tmpl.Execute(out, template.HTML(`<b>World</b>`))
+

to produce

+
Hello, <b>World</b>!
+

instead of the

+
Hello, &lt;b&gt;World&lt;b&gt;!
+

that would have been produced if {{.}} was a regular string.

+

Security Model

https://rawgit.com/mikesamuel/sanitized-jquery-templates/trunk/safetemplate.html#problem_definition defines "safe" as used by this package.

+

This package assumes that template authors are trusted, that Execute's data parameter is not, and seeks to preserve the properties below in the face of untrusted data:

+

Structure Preservation Property: "... when a template author writes an HTML tag in a safe templating language, the browser will interpret the corresponding portion of the output as a tag regardless of the values of untrusted data, and similarly for other structures such as attribute boundaries and JS and CSS string boundaries."

+

Code Effect Property: "... only code specified by the template author should run as a result of injecting the template output into a page and all code specified by the template author should run as a result of the same."

+

Least Surprise Property: "A developer (or code reviewer) familiar with HTML, CSS, and JavaScript, who knows that contextual autoescaping happens should be able to look at a {{.}} and correctly infer what sanitization happens."

+

As a consequence of the Least Surprise Property, template actions within an ECMAScript 6 template literal are disabled by default. Handling string interpolation within these literals is rather complex resulting in no clear safe way to support it. To re-enable template actions within ECMAScript 6 template literals, use the GODEBUG=jstmpllitinterp=1 environment variable.

Example +

Code:

const tpl = `
+<!DOCTYPE html>
+<html>
+    <head>
+        <meta charset="UTF-8">
+        <title>{{.Title}}</title>
+    </head>
+    <body>
+        {{range .Items}}<div>{{ . }}</div>{{else}}<div><strong>no rows</strong></div>{{end}}
+    </body>
+</html>`
+
+check := func(err error) {
+    if err != nil {
+        log.Fatal(err)
+    }
+}
+t, err := template.New("webpage").Parse(tpl)
+check(err)
+
+data := struct {
+    Title string
+    Items []string
+}{
+    Title: "My page",
+    Items: []string{
+        "My photos",
+        "My blog",
+    },
+}
+
+err = t.Execute(os.Stdout, data)
+check(err)
+
+noItems := struct {
+    Title string
+    Items []string
+}{
+    Title: "My another page",
+    Items: []string{},
+}
+
+err = t.Execute(os.Stdout, noItems)
+check(err)
+
+

Output:

<!DOCTYPE html>
+<html>
+	<head>
+		<meta charset="UTF-8">
+		<title>My page</title>
+	</head>
+	<body>
+		<div>My photos</div><div>My blog</div>
+	</body>
+</html>
+<!DOCTYPE html>
+<html>
+	<head>
+		<meta charset="UTF-8">
+		<title>My another page</title>
+	</head>
+	<body>
+		<div><strong>no rows</strong></div>
+	</body>
+</html>
+

Example (Autoescaping) +

Code:

check := func(err error) {
+    if err != nil {
+        log.Fatal(err)
+    }
+}
+t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
+check(err)
+err = t.ExecuteTemplate(os.Stdout, "T", "<script>alert('you have been pwned')</script>")
+check(err)
+

Output:

Hello, &lt;script&gt;alert(&#39;you have been pwned&#39;)&lt;/script&gt;!
+

Example (Escape) +

Code:

const s = `"Fran & Freddie's Diner" <tasty@example.com>`
+v := []any{`"Fran & Freddie's Diner"`, ' ', `<tasty@example.com>`}
+
+fmt.Println(template.HTMLEscapeString(s))
+template.HTMLEscape(os.Stdout, []byte(s))
+fmt.Fprintln(os.Stdout, "")
+fmt.Println(template.HTMLEscaper(v...))
+
+fmt.Println(template.JSEscapeString(s))
+template.JSEscape(os.Stdout, []byte(s))
+fmt.Fprintln(os.Stdout, "")
+fmt.Println(template.JSEscaper(v...))
+
+fmt.Println(template.URLQueryEscaper(v...))
+
+

Output:

&#34;Fran &amp; Freddie&#39;s Diner&#34; &lt;tasty@example.com&gt;
+&#34;Fran &amp; Freddie&#39;s Diner&#34; &lt;tasty@example.com&gt;
+&#34;Fran &amp; Freddie&#39;s Diner&#34;32&lt;tasty@example.com&gt;
+\"Fran \u0026 Freddie\'s Diner\" \u003Ctasty@example.com\u003E
+\"Fran \u0026 Freddie\'s Diner\" \u003Ctasty@example.com\u003E
+\"Fran \u0026 Freddie\'s Diner\"32\u003Ctasty@example.com\u003E
+%22Fran+%26+Freddie%27s+Diner%2232%3Ctasty%40example.com%3E
+

Index

Examples

Package
Template.Delims
Template (Block)
Template (Glob)
Template (Helpers)
Template (Parsefiles)
Template (Share)
Package (Autoescaping)
Package (Escape)

Package files

attr.go attr_string.go content.go context.go css.go delim_string.go doc.go element_string.go error.go escape.go html.go js.go jsctx_string.go state_string.go template.go transition.go url.go urlpart_string.go

func HTMLEscape

func HTMLEscape(w io.Writer, b []byte)

HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.

+

func HTMLEscapeString

func HTMLEscapeString(s string) string

HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.

+

func HTMLEscaper

func HTMLEscaper(args ...any) string

HTMLEscaper returns the escaped HTML equivalent of the textual representation of its arguments.

+

func IsTrue 1.6

func IsTrue(val any) (truth, ok bool)

IsTrue reports whether the value is 'true', in the sense of not the zero of its type, and whether the value has a meaningful truth value. This is the definition of truth used by if and other such actions.

+

func JSEscape

func JSEscape(w io.Writer, b []byte)

JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.

+

func JSEscapeString

func JSEscapeString(s string) string

JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.

+

func JSEscaper

func JSEscaper(args ...any) string

JSEscaper returns the escaped JavaScript equivalent of the textual representation of its arguments.

+

func URLQueryEscaper

func URLQueryEscaper(args ...any) string

URLQueryEscaper returns the escaped value of the textual representation of its arguments in a form suitable for embedding in a URL query.

+

type CSS

CSS encapsulates known safe content that matches any of:

+
  1. The CSS3 stylesheet production, such as `p { color: purple }`.
  2. +
  3. The CSS3 rule production, such as `a[href=~"https:"].foo#bar`.
  4. +
  5. CSS3 declaration productions, such as `color: red; margin: 2px`.
  6. +
  7. The CSS3 value production, such as `rgba(0, 0, 255, 127)`.
  8. +

See https://www.w3.org/TR/css3-syntax/#parsing and https://web.archive.org/web/20090211114933/http://w3.org/TR/css3-syntax#style

+

Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

+
type CSS string

type Error

Error describes a problem encountered during template Escaping.

+
type Error struct {
+    // ErrorCode describes the kind of error.
+    ErrorCode ErrorCode
+    // Node is the node that caused the problem, if known.
+    // If not nil, it overrides Name and Line.
+    Node parse.Node // Go 1.4
+    // Name is the name of the template in which the error was encountered.
+    Name string
+    // Line is the line number of the error in the template source or 0.
+    Line int
+    // Description is a human-readable description of the problem.
+    Description string
+}
+

func (*Error) Error

func (e *Error) Error() string

type ErrorCode

ErrorCode is a code for a kind of error.

+
type ErrorCode int

We define codes for each error that manifests while escaping templates, but escaped templates may also fail at runtime.

+

Output: "ZgotmplZ" Example:

+
<img src="{{.X}}">
+where {{.X}} evaluates to `javascript:...`
+

Discussion:

+
"ZgotmplZ" is a special value that indicates that unsafe content reached a
+CSS or URL context at runtime. The output of the example will be
+  <img src="#ZgotmplZ">
+If the data comes from a trusted source, use content types to exempt it
+from filtering: URL(`javascript:...`).
+
const (
+    // OK indicates the lack of an error.
+    OK ErrorCode = iota
+
+    // ErrAmbigContext: "... appears in an ambiguous context within a URL"
+    // Example:
+    //   <a href="
+    //      {{if .C}}
+    //        /path/
+    //      {{else}}
+    //        /search?q=
+    //      {{end}}
+    //      {{.X}}
+    //   ">
+    // Discussion:
+    //   {{.X}} is in an ambiguous URL context since, depending on {{.C}},
+    //  it may be either a URL suffix or a query parameter.
+    //   Moving {{.X}} into the condition removes the ambiguity:
+    //   <a href="{{if .C}}/path/{{.X}}{{else}}/search?q={{.X}}">
+    ErrAmbigContext
+
+    // ErrBadHTML: "expected space, attr name, or end of tag, but got ...",
+    //   "... in unquoted attr", "... in attribute name"
+    // Example:
+    //   <a href = /search?q=foo>
+    //   <href=foo>
+    //   <form na<e=...>
+    //   <option selected<
+    // Discussion:
+    //   This is often due to a typo in an HTML element, but some runes
+    //   are banned in tag names, attribute names, and unquoted attribute
+    //   values because they can tickle parser ambiguities.
+    //   Quoting all attributes is the best policy.
+    ErrBadHTML
+
+    // ErrBranchEnd: "{{if}} branches end in different contexts"
+    // Example:
+    //   {{if .C}}<a href="{{end}}{{.X}}
+    // Discussion:
+    //   Package html/template statically examines each path through an
+    //   {{if}}, {{range}}, or {{with}} to escape any following pipelines.
+    //   The example is ambiguous since {{.X}} might be an HTML text node,
+    //   or a URL prefix in an HTML attribute. The context of {{.X}} is
+    //   used to figure out how to escape it, but that context depends on
+    //   the run-time value of {{.C}} which is not statically known.
+    //
+    //   The problem is usually something like missing quotes or angle
+    //   brackets, or can be avoided by refactoring to put the two contexts
+    //   into different branches of an if, range or with. If the problem
+    //   is in a {{range}} over a collection that should never be empty,
+    //   adding a dummy {{else}} can help.
+    ErrBranchEnd
+
+    // ErrEndContext: "... ends in a non-text context: ..."
+    // Examples:
+    //   <div
+    //   <div title="no close quote>
+    //   <script>f()
+    // Discussion:
+    //   Executed templates should produce a DocumentFragment of HTML.
+    //   Templates that end without closing tags will trigger this error.
+    //   Templates that should not be used in an HTML context or that
+    //   produce incomplete Fragments should not be executed directly.
+    //
+    //   {{define "main"}} <script>{{template "helper"}}</script> {{end}}
+    //   {{define "helper"}} document.write(' <div title=" ') {{end}}
+    //
+    //   "helper" does not produce a valid document fragment, so should
+    //   not be Executed directly.
+    ErrEndContext
+
+    // ErrNoSuchTemplate: "no such template ..."
+    // Examples:
+    //   {{define "main"}}<div {{template "attrs"}}>{{end}}
+    //   {{define "attrs"}}href="{{.URL}}"{{end}}
+    // Discussion:
+    //   Package html/template looks through template calls to compute the
+    //   context.
+    //   Here the {{.URL}} in "attrs" must be treated as a URL when called
+    //   from "main", but you will get this error if "attrs" is not defined
+    //   when "main" is parsed.
+    ErrNoSuchTemplate
+
+    // ErrOutputContext: "cannot compute output context for template ..."
+    // Examples:
+    //   {{define "t"}}{{if .T}}{{template "t" .T}}{{end}}{{.H}}",{{end}}
+    // Discussion:
+    //   A recursive template does not end in the same context in which it
+    //   starts, and a reliable output context cannot be computed.
+    //   Look for typos in the named template.
+    //   If the template should not be called in the named start context,
+    //   look for calls to that template in unexpected contexts.
+    //   Maybe refactor recursive templates to not be recursive.
+    ErrOutputContext
+
+    // ErrPartialCharset: "unfinished JS regexp charset in ..."
+    // Example:
+    //     <script>var pattern = /foo[{{.Chars}}]/</script>
+    // Discussion:
+    //   Package html/template does not support interpolation into regular
+    //   expression literal character sets.
+    ErrPartialCharset
+
+    // ErrPartialEscape: "unfinished escape sequence in ..."
+    // Example:
+    //   <script>alert("\{{.X}}")</script>
+    // Discussion:
+    //   Package html/template does not support actions following a
+    //   backslash.
+    //   This is usually an error and there are better solutions; for
+    //   example
+    //     <script>alert("{{.X}}")</script>
+    //   should work, and if {{.X}} is a partial escape sequence such as
+    //   "xA0", mark the whole sequence as safe content: JSStr(`\xA0`)
+    ErrPartialEscape
+
+    // ErrRangeLoopReentry: "on range loop re-entry: ..."
+    // Example:
+    //   <script>var x = [{{range .}}'{{.}},{{end}}]</script>
+    // Discussion:
+    //   If an iteration through a range would cause it to end in a
+    //   different context than an earlier pass, there is no single context.
+    //   In the example, there is missing a quote, so it is not clear
+    //   whether {{.}} is meant to be inside a JS string or in a JS value
+    //   context. The second iteration would produce something like
+    //
+    //     <script>var x = ['firstValue,'secondValue]</script>
+    ErrRangeLoopReentry
+
+    // ErrSlashAmbig: '/' could start a division or regexp.
+    // Example:
+    //   <script>
+    //     {{if .C}}var x = 1{{end}}
+    //     /-{{.N}}/i.test(x) ? doThis : doThat();
+    //   </script>
+    // Discussion:
+    //   The example above could produce `var x = 1/-2/i.test(s)...`
+    //   in which the first '/' is a mathematical division operator or it
+    //   could produce `/-2/i.test(s)` in which the first '/' starts a
+    //   regexp literal.
+    //   Look for missing semicolons inside branches, and maybe add
+    //   parentheses to make it clear which interpretation you intend.
+    ErrSlashAmbig
+
+    // ErrPredefinedEscaper: "predefined escaper ... disallowed in template"
+    // Example:
+    //   <div class={{. | html}}>Hello<div>
+    // Discussion:
+    //   Package html/template already contextually escapes all pipelines to
+    //   produce HTML output safe against code injection. Manually escaping
+    //   pipeline output using the predefined escapers "html" or "urlquery" is
+    //   unnecessary, and may affect the correctness or safety of the escaped
+    //   pipeline output in Go 1.8 and earlier.
+    //
+    //   In most cases, such as the given example, this error can be resolved by
+    //   simply removing the predefined escaper from the pipeline and letting the
+    //   contextual autoescaper handle the escaping of the pipeline. In other
+    //   instances, where the predefined escaper occurs in the middle of a
+    //   pipeline where subsequent commands expect escaped input, e.g.
+    //     {{.X | html | makeALink}}
+    //   where makeALink does
+    //     return `<a href="`+input+`">link</a>`
+    //   consider refactoring the surrounding template to make use of the
+    //   contextual autoescaper, i.e.
+    //     <a href="{{.X}}">link</a>
+    //
+    //   To ease migration to Go 1.9 and beyond, "html" and "urlquery" will
+    //   continue to be allowed as the last command in a pipeline. However, if the
+    //   pipeline occurs in an unquoted attribute value context, "html" is
+    //   disallowed. Avoid using "html" and "urlquery" entirely in new templates.
+    ErrPredefinedEscaper
+
+    // ErrJSTemplate: "... appears in a JS template literal"
+    // Example:
+    //     <script>var tmpl = `{{.Interp}}`</script>
+    // Discussion:
+    //   Package html/template does not support actions inside of JS template
+    //   literals.
+    //
+    // Deprecated: ErrJSTemplate is no longer returned when an action is present
+    // in a JS template literal. Actions inside of JS template literals are now
+    // escaped as expected.
+    ErrJSTemplate
+)

type FuncMap

type FuncMap = template.FuncMap

type HTML

HTML encapsulates a known safe HTML document fragment. It should not be used for HTML from a third-party, or HTML with unclosed tags or comments. The outputs of a sound HTML sanitizer and a template escaped by this package are fine for use with HTML.

+

Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

+
type HTML string

type HTMLAttr

HTMLAttr encapsulates an HTML attribute from a trusted source, for example, ` dir="ltr"`.

+

Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

+
type HTMLAttr string

type JS

JS encapsulates a known safe EcmaScript5 Expression, for example, `(x + y * z())`. Template authors are responsible for ensuring that typed expressions do not break the intended precedence and that there is no statement/expression ambiguity as when passing an expression like "{ foo: bar() }\n['foo']()", which is both a valid Expression and a valid Program with a very different meaning.

+

Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

+

Using JS to include valid but untrusted JSON is not safe. A safe alternative is to parse the JSON with json.Unmarshal and then pass the resultant object into the template, where it will be converted to sanitized JSON when presented in a JavaScript context.

+
type JS string

type JSStr

JSStr encapsulates a sequence of characters meant to be embedded between quotes in a JavaScript expression. The string must match a series of StringCharacters:

+
StringCharacter :: SourceCharacter but not `\` or LineTerminator
+                 | EscapeSequence
+

Note that LineContinuations are not allowed. JSStr("foo\\nbar") is fine, but JSStr("foo\\\nbar") is not.

+

Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

+
type JSStr string

type Srcset 1.10

Srcset encapsulates a known safe srcset attribute (see https://w3c.github.io/html/semantics-embedded-content.html#element-attrdef-img-srcset).

+

Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

+
type Srcset string

type Template

Template is a specialized Template from "text/template" that produces a safe HTML document fragment.

+
type Template struct {
+
+    // The underlying template's parse tree, updated to be HTML-safe.
+    Tree *parse.Tree // Go 1.2
+    // contains filtered or unexported fields
+}
+

Example (Block) +

Code:

const (
+    master  = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}`
+    overlay = `{{define "list"}} {{join . ", "}}{{end}} `
+)
+var (
+    funcs     = template.FuncMap{"join": strings.Join}
+    guardians = []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"}
+)
+masterTmpl, err := template.New("master").Funcs(funcs).Parse(master)
+if err != nil {
+    log.Fatal(err)
+}
+overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay)
+if err != nil {
+    log.Fatal(err)
+}
+if err := masterTmpl.Execute(os.Stdout, guardians); err != nil {
+    log.Fatal(err)
+}
+if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil {
+    log.Fatal(err)
+}
+

Output:

Names:
+- Gamora
+- Groot
+- Nebula
+- Rocket
+- Star-Lord
+Names: Gamora, Groot, Nebula, Rocket, Star-Lord
+

Example (Glob) +

Here we demonstrate loading a set of templates from a directory.

Code:

// Here we create a temporary directory and populate it with our sample
+// template definition files; usually the template files would already
+// exist in some location known to the program.
+dir := createTestDir([]templateFile{
+    // T0.tmpl is a plain template file that just invokes T1.
+    {"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`},
+    // T1.tmpl defines a template, T1 that invokes T2.
+    {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
+    // T2.tmpl defines a template T2.
+    {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
+})
+// Clean up after the test; another quirk of running as an example.
+defer os.RemoveAll(dir)
+
+// pattern is the glob pattern used to find all the template files.
+pattern := filepath.Join(dir, "*.tmpl")
+
+// Here starts the example proper.
+// T0.tmpl is the first name matched, so it becomes the starting template,
+// the value returned by ParseGlob.
+tmpl := template.Must(template.ParseGlob(pattern))
+
+err := tmpl.Execute(os.Stdout, nil)
+if err != nil {
+    log.Fatalf("template execution: %s", err)
+}
+

Output:

T0 invokes T1: (T1 invokes T2: (This is T2))
+

Example (Helpers) +

This example demonstrates one way to share some templates and use them in different contexts. In this variant we add multiple driver templates by hand to an existing bundle of templates.

Code:

// Here we create a temporary directory and populate it with our sample
+// template definition files; usually the template files would already
+// exist in some location known to the program.
+dir := createTestDir([]templateFile{
+    // T1.tmpl defines a template, T1 that invokes T2.
+    {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
+    // T2.tmpl defines a template T2.
+    {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
+})
+// Clean up after the test; another quirk of running as an example.
+defer os.RemoveAll(dir)
+
+// pattern is the glob pattern used to find all the template files.
+pattern := filepath.Join(dir, "*.tmpl")
+
+// Here starts the example proper.
+// Load the helpers.
+templates := template.Must(template.ParseGlob(pattern))
+// Add one driver template to the bunch; we do this with an explicit template definition.
+_, err := templates.Parse("{{define `driver1`}}Driver 1 calls T1: ({{template `T1`}})\n{{end}}")
+if err != nil {
+    log.Fatal("parsing driver1: ", err)
+}
+// Add another driver template.
+_, err = templates.Parse("{{define `driver2`}}Driver 2 calls T2: ({{template `T2`}})\n{{end}}")
+if err != nil {
+    log.Fatal("parsing driver2: ", err)
+}
+// We load all the templates before execution. This package does not require
+// that behavior but html/template's escaping does, so it's a good habit.
+err = templates.ExecuteTemplate(os.Stdout, "driver1", nil)
+if err != nil {
+    log.Fatalf("driver1 execution: %s", err)
+}
+err = templates.ExecuteTemplate(os.Stdout, "driver2", nil)
+if err != nil {
+    log.Fatalf("driver2 execution: %s", err)
+}
+

Output:

Driver 1 calls T1: (T1 invokes T2: (This is T2))
+Driver 2 calls T2: (This is T2)
+

Example (Parsefiles) +

Here we demonstrate loading a set of templates from files in different directories

Code:

// Here we create different temporary directories and populate them with our sample
+// template definition files; usually the template files would already
+// exist in some location known to the program.
+dir1 := createTestDir([]templateFile{
+    // T1.tmpl is a plain template file that just invokes T2.
+    {"T1.tmpl", `T1 invokes T2: ({{template "T2"}})`},
+})
+
+dir2 := createTestDir([]templateFile{
+    // T2.tmpl defines a template T2.
+    {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
+})
+
+// Clean up after the test; another quirk of running as an example.
+defer func(dirs ...string) {
+    for _, dir := range dirs {
+        os.RemoveAll(dir)
+    }
+}(dir1, dir2)
+
+// Here starts the example proper.
+// Let's just parse only dir1/T0 and dir2/T2
+paths := []string{
+    filepath.Join(dir1, "T1.tmpl"),
+    filepath.Join(dir2, "T2.tmpl"),
+}
+tmpl := template.Must(template.ParseFiles(paths...))
+
+err := tmpl.Execute(os.Stdout, nil)
+if err != nil {
+    log.Fatalf("template execution: %s", err)
+}
+

Output:

T1 invokes T2: (This is T2)
+

Example (Share) +

This example demonstrates how to use one group of driver templates with distinct sets of helper templates.

Code:

// Here we create a temporary directory and populate it with our sample
+// template definition files; usually the template files would already
+// exist in some location known to the program.
+dir := createTestDir([]templateFile{
+    // T0.tmpl is a plain template file that just invokes T1.
+    {"T0.tmpl", "T0 ({{.}} version) invokes T1: ({{template `T1`}})\n"},
+    // T1.tmpl defines a template, T1 that invokes T2. Note T2 is not defined
+    {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
+})
+// Clean up after the test; another quirk of running as an example.
+defer os.RemoveAll(dir)
+
+// pattern is the glob pattern used to find all the template files.
+pattern := filepath.Join(dir, "*.tmpl")
+
+// Here starts the example proper.
+// Load the drivers.
+drivers := template.Must(template.ParseGlob(pattern))
+
+// We must define an implementation of the T2 template. First we clone
+// the drivers, then add a definition of T2 to the template name space.
+
+// 1. Clone the helper set to create a new name space from which to run them.
+first, err := drivers.Clone()
+if err != nil {
+    log.Fatal("cloning helpers: ", err)
+}
+// 2. Define T2, version A, and parse it.
+_, err = first.Parse("{{define `T2`}}T2, version A{{end}}")
+if err != nil {
+    log.Fatal("parsing T2: ", err)
+}
+
+// Now repeat the whole thing, using a different version of T2.
+// 1. Clone the drivers.
+second, err := drivers.Clone()
+if err != nil {
+    log.Fatal("cloning drivers: ", err)
+}
+// 2. Define T2, version B, and parse it.
+_, err = second.Parse("{{define `T2`}}T2, version B{{end}}")
+if err != nil {
+    log.Fatal("parsing T2: ", err)
+}
+
+// Execute the templates in the reverse order to verify the
+// first is unaffected by the second.
+err = second.ExecuteTemplate(os.Stdout, "T0.tmpl", "second")
+if err != nil {
+    log.Fatalf("second execution: %s", err)
+}
+err = first.ExecuteTemplate(os.Stdout, "T0.tmpl", "first")
+if err != nil {
+    log.Fatalf("first: execution: %s", err)
+}
+
+

Output:

T0 (second version) invokes T1: (T1 invokes T2: (T2, version B))
+T0 (first version) invokes T1: (T1 invokes T2: (T2, version A))
+

func Must

func Must(t *Template, err error) *Template

Must is a helper that wraps a call to a function returning (*Template, error) and panics if the error is non-nil. It is intended for use in variable initializations such as

+
var t = template.Must(template.New("name").Parse("html"))
+

func New

func New(name string) *Template

New allocates a new HTML template with the given name.

+

func ParseFS 1.16

func ParseFS(fs fs.FS, patterns ...string) (*Template, error)

ParseFS is like ParseFiles or ParseGlob but reads from the file system fs instead of the host operating system's file system. It accepts a list of glob patterns. (Note that most file names serve as glob patterns matching only themselves.)

+

func ParseFiles

func ParseFiles(filenames ...string) (*Template, error)

ParseFiles creates a new Template and parses the template definitions from the named files. The returned template's name will have the (base) name and (parsed) contents of the first file. There must be at least one file. If an error occurs, parsing stops and the returned *Template is nil.

+

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results. For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template named "foo", while "a/foo" is unavailable.

+

func ParseGlob

func ParseGlob(pattern string) (*Template, error)

ParseGlob creates a new Template and parses the template definitions from the files identified by the pattern. The files are matched according to the semantics of filepath.Match, and the pattern must match at least one file. The returned template will have the (base) name and (parsed) contents of the first file matched by the pattern. ParseGlob is equivalent to calling ParseFiles with the list of files matched by the pattern.

+

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

+

func (*Template) AddParseTree

func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)

AddParseTree creates a new template with the name and parse tree and associates it with t.

+

It returns an error if t or any associated template has already been executed.

+

func (*Template) Clone

func (t *Template) Clone() (*Template, error)

Clone returns a duplicate of the template, including all associated templates. The actual representation is not copied, but the name space of associated templates is, so further calls to Parse in the copy will add templates to the copy but not to the original. Clone can be used to prepare common templates and use them with variant definitions for other templates by adding the variants after the clone is made.

+

It returns an error if t has already been executed.

+

func (*Template) DefinedTemplates 1.6

func (t *Template) DefinedTemplates() string

DefinedTemplates returns a string listing the defined templates, prefixed by the string "; defined templates are: ". If there are none, it returns the empty string. Used to generate an error message.

+

func (*Template) Delims

func (t *Template) Delims(left, right string) *Template

Delims sets the action delimiters to the specified strings, to be used in subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template definitions will inherit the settings. An empty delimiter stands for the corresponding default: {{ or }}. The return value is the template, so calls can be chained.

Example +

Code:

const text = "<<.Greeting>> {{.Name}}"
+
+data := struct {
+    Greeting string
+    Name     string
+}{
+    Greeting: "Hello",
+    Name:     "Joe",
+}
+
+t := template.Must(template.New("tpl").Delims("<<", ">>").Parse(text))
+
+err := t.Execute(os.Stdout, data)
+if err != nil {
+    log.Fatal(err)
+}
+
+

Output:

Hello {{.Name}}
+

func (*Template) Execute

func (t *Template) Execute(wr io.Writer, data any) error

Execute applies a parsed template to the specified data object, writing the output to wr. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

+

func (*Template) ExecuteTemplate

func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error

ExecuteTemplate applies the template associated with t that has the given name to the specified data object and writes the output to wr. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

+

func (*Template) Funcs

func (t *Template) Funcs(funcMap FuncMap) *Template

Funcs adds the elements of the argument map to the template's function map. It must be called before the template is parsed. It panics if a value in the map is not a function with appropriate return type. However, it is legal to overwrite elements of the map. The return value is the template, so calls can be chained.

+

func (*Template) Lookup

func (t *Template) Lookup(name string) *Template

Lookup returns the template with the given name that is associated with t, or nil if there is no such template.

+

func (*Template) Name

func (t *Template) Name() string

Name returns the name of the template.

+

func (*Template) New

func (t *Template) New(name string) *Template

New allocates a new HTML template associated with the given one and with the same delimiters. The association, which is transitive, allows one template to invoke another with a {{template}} action.

+

If a template with the given name already exists, the new HTML template will replace it. The existing template will be reset and disassociated with t.

+

func (*Template) Option 1.5

func (t *Template) Option(opt ...string) *Template

Option sets options for the template. Options are described by strings, either a simple string or "key=value". There can be at most one equals sign in an option string. If the option string is unrecognized or otherwise invalid, Option panics.

+

Known options:

+

missingkey: Control the behavior during execution if a map is indexed with a key that is not present in the map.

+
"missingkey=default" or "missingkey=invalid"
+	The default behavior: Do nothing and continue execution.
+	If printed, the result of the index operation is the string
+	"<no value>".
+"missingkey=zero"
+	The operation returns the zero value for the map type's element.
+"missingkey=error"
+	Execution stops immediately with an error.
+

func (*Template) Parse

func (t *Template) Parse(text string) (*Template, error)

Parse parses text as a template body for t. Named template definitions ({{define ...}} or {{block ...}} statements) in text define additional templates associated with t and are removed from the definition of t itself.

+

Templates can be redefined in successive calls to Parse, before the first use of Execute on t or any associated template. A template definition with a body containing only white space and comments is considered empty and will not replace an existing template's body. This allows using Parse to add new named template definitions without overwriting the main template body.

+

func (*Template) ParseFS 1.16

func (t *Template) ParseFS(fs fs.FS, patterns ...string) (*Template, error)

ParseFS is like ParseFiles or ParseGlob but reads from the file system fs instead of the host operating system's file system. It accepts a list of glob patterns. (Note that most file names serve as glob patterns matching only themselves.)

+

func (*Template) ParseFiles

func (t *Template) ParseFiles(filenames ...string) (*Template, error)

ParseFiles parses the named files and associates the resulting templates with t. If an error occurs, parsing stops and the returned template is nil; otherwise it is t. There must be at least one file.

+

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

+

ParseFiles returns an error if t or any associated template has already been executed.

+

func (*Template) ParseGlob

func (t *Template) ParseGlob(pattern string) (*Template, error)

ParseGlob parses the template definitions in the files identified by the pattern and associates the resulting templates with t. The files are matched according to the semantics of filepath.Match, and the pattern must match at least one file. ParseGlob is equivalent to calling t.ParseFiles with the list of files matched by the pattern.

+

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

+

ParseGlob returns an error if t or any associated template has already been executed.

+

func (*Template) Templates

func (t *Template) Templates() []*Template

Templates returns a slice of the templates associated with t, including t itself.

+

type URL

URL encapsulates a known safe URL or URL substring (see RFC 3986). A URL like `javascript:checkThatFormNotEditedBeforeLeavingPage()` from a trusted source should go in the page, but by default dynamic `javascript:` URLs are filtered out since they are a frequently exploited injection vector.

+

Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

+
type URL string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/html/template/ +

+
diff --git a/devdocs/go/image%2Fcolor%2Findex.html b/devdocs/go/image%2Fcolor%2Findex.html new file mode 100644 index 00000000..49670864 --- /dev/null +++ b/devdocs/go/image%2Fcolor%2Findex.html @@ -0,0 +1,149 @@ +

Package color

Overview

Package color implements a basic color library.

Index

Package files

color.go ycbcr.go

Variables

Standard colors.

+
var (
+    Black       = Gray16{0}
+    White       = Gray16{0xffff}
+    Transparent = Alpha16{0}
+    Opaque      = Alpha16{0xffff}
+)

func CMYKToRGB 1.5

func CMYKToRGB(c, m, y, k uint8) (uint8, uint8, uint8)

CMYKToRGB converts a CMYK quadruple to an RGB triple.

+

func RGBToCMYK 1.5

func RGBToCMYK(r, g, b uint8) (uint8, uint8, uint8, uint8)

RGBToCMYK converts an RGB triple to a CMYK quadruple.

+

func RGBToYCbCr

func RGBToYCbCr(r, g, b uint8) (uint8, uint8, uint8)

RGBToYCbCr converts an RGB triple to a Y'CbCr triple.

+

func YCbCrToRGB

func YCbCrToRGB(y, cb, cr uint8) (uint8, uint8, uint8)

YCbCrToRGB converts a Y'CbCr triple to an RGB triple.

+

type Alpha

Alpha represents an 8-bit alpha color.

+
type Alpha struct {
+    A uint8
+}
+

func (Alpha) RGBA

func (c Alpha) RGBA() (r, g, b, a uint32)

type Alpha16

Alpha16 represents a 16-bit alpha color.

+
type Alpha16 struct {
+    A uint16
+}
+

func (Alpha16) RGBA

func (c Alpha16) RGBA() (r, g, b, a uint32)

type CMYK 1.5

CMYK represents a fully opaque CMYK color, having 8 bits for each of cyan, magenta, yellow and black.

+

It is not associated with any particular color profile.

+
type CMYK struct {
+    C, M, Y, K uint8
+}
+

func (CMYK) RGBA 1.5

func (c CMYK) RGBA() (uint32, uint32, uint32, uint32)

type Color

Color can convert itself to alpha-premultiplied 16-bits per channel RGBA. The conversion may be lossy.

+
type Color interface {
+    // RGBA returns the alpha-premultiplied red, green, blue and alpha values
+    // for the color. Each value ranges within [0, 0xffff], but is represented
+    // by a uint32 so that multiplying by a blend factor up to 0xffff will not
+    // overflow.
+    //
+    // An alpha-premultiplied color component c has been scaled by alpha (a),
+    // so has valid values 0 <= c <= a.
+    RGBA() (r, g, b, a uint32)
+}

type Gray

Gray represents an 8-bit grayscale color.

+
type Gray struct {
+    Y uint8
+}
+

func (Gray) RGBA

func (c Gray) RGBA() (r, g, b, a uint32)

type Gray16

Gray16 represents a 16-bit grayscale color.

+
type Gray16 struct {
+    Y uint16
+}
+

func (Gray16) RGBA

func (c Gray16) RGBA() (r, g, b, a uint32)

type Model

Model can convert any Color to one from its own color model. The conversion may be lossy.

+
type Model interface {
+    Convert(c Color) Color
+}

Models for the standard color types.

+
var (
+    RGBAModel    Model = ModelFunc(rgbaModel)
+    RGBA64Model  Model = ModelFunc(rgba64Model)
+    NRGBAModel   Model = ModelFunc(nrgbaModel)
+    NRGBA64Model Model = ModelFunc(nrgba64Model)
+    AlphaModel   Model = ModelFunc(alphaModel)
+    Alpha16Model Model = ModelFunc(alpha16Model)
+    GrayModel    Model = ModelFunc(grayModel)
+    Gray16Model  Model = ModelFunc(gray16Model)
+)

CMYKModel is the Model for CMYK colors.

+
var CMYKModel Model = ModelFunc(cmykModel)

NYCbCrAModel is the Model for non-alpha-premultiplied Y'CbCr-with-alpha colors.

+
var NYCbCrAModel Model = ModelFunc(nYCbCrAModel)

YCbCrModel is the Model for Y'CbCr colors.

+
var YCbCrModel Model = ModelFunc(yCbCrModel)

func ModelFunc

func ModelFunc(f func(Color) Color) Model

ModelFunc returns a Model that invokes f to implement the conversion.

+

type NRGBA

NRGBA represents a non-alpha-premultiplied 32-bit color.

+
type NRGBA struct {
+    R, G, B, A uint8
+}
+

func (NRGBA) RGBA

func (c NRGBA) RGBA() (r, g, b, a uint32)

type NRGBA64

NRGBA64 represents a non-alpha-premultiplied 64-bit color, having 16 bits for each of red, green, blue and alpha.

+
type NRGBA64 struct {
+    R, G, B, A uint16
+}
+

func (NRGBA64) RGBA

func (c NRGBA64) RGBA() (r, g, b, a uint32)

type NYCbCrA 1.6

NYCbCrA represents a non-alpha-premultiplied Y'CbCr-with-alpha color, having 8 bits each for one luma, two chroma and one alpha component.

+
type NYCbCrA struct {
+    YCbCr
+    A uint8
+}
+

func (NYCbCrA) RGBA 1.6

func (c NYCbCrA) RGBA() (uint32, uint32, uint32, uint32)

type Palette

Palette is a palette of colors.

+
type Palette []Color

func (Palette) Convert

func (p Palette) Convert(c Color) Color

Convert returns the palette color closest to c in Euclidean R,G,B space.

+

func (Palette) Index

func (p Palette) Index(c Color) int

Index returns the index of the palette color closest to c in Euclidean R,G,B,A space.

+

type RGBA

RGBA represents a traditional 32-bit alpha-premultiplied color, having 8 bits for each of red, green, blue and alpha.

+

An alpha-premultiplied color component C has been scaled by alpha (A), so has valid values 0 <= C <= A.

+
type RGBA struct {
+    R, G, B, A uint8
+}
+

func (RGBA) RGBA

func (c RGBA) RGBA() (r, g, b, a uint32)

type RGBA64

RGBA64 represents a 64-bit alpha-premultiplied color, having 16 bits for each of red, green, blue and alpha.

+

An alpha-premultiplied color component C has been scaled by alpha (A), so has valid values 0 <= C <= A.

+
type RGBA64 struct {
+    R, G, B, A uint16
+}
+

func (RGBA64) RGBA

func (c RGBA64) RGBA() (r, g, b, a uint32)

type YCbCr

YCbCr represents a fully opaque 24-bit Y'CbCr color, having 8 bits each for one luma and two chroma components.

+

JPEG, VP8, the MPEG family and other codecs use this color model. Such codecs often use the terms YUV and Y'CbCr interchangeably, but strictly speaking, the term YUV applies only to analog video signals, and Y' (luma) is Y (luminance) after applying gamma correction.

+

Conversion between RGB and Y'CbCr is lossy and there are multiple, slightly different formulae for converting between the two. This package follows the JFIF specification at https://www.w3.org/Graphics/JPEG/jfif3.pdf.

+
type YCbCr struct {
+    Y, Cb, Cr uint8
+}
+

func (YCbCr) RGBA

func (c YCbCr) RGBA() (uint32, uint32, uint32, uint32)

Subdirectories

Name Synopsis
..
palette Package palette provides standard color palettes.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/image/color/ +

+
diff --git a/devdocs/go/image%2Fcolor%2Fpalette%2Findex.html b/devdocs/go/image%2Fcolor%2Fpalette%2Findex.html new file mode 100644 index 00000000..8f6e60cf --- /dev/null +++ b/devdocs/go/image%2Fcolor%2Fpalette%2Findex.html @@ -0,0 +1,488 @@ +

Package palette

Overview

Package palette provides standard color palettes.

Index

Package files

generate.go palette.go

Variables

Plan9 is a 256-color palette that partitions the 24-bit RGB space into 4×4×4 subdivision, with 4 shades in each subcube. Compared to the WebSafe, the idea is to reduce the color resolution by dicing the color cube into fewer cells, and to use the extra space to increase the intensity resolution. This results in 16 gray shades (4 gray subcubes with 4 samples in each), 13 shades of each primary and secondary color (3 subcubes with 4 samples plus black) and a reasonable selection of colors covering the rest of the color cube. The advantage is better representation of continuous tones.

+

This palette was used in the Plan 9 Operating System, described at https://9p.io/magic/man2html/6/color

+
var Plan9 = []color.Color{
+    color.RGBA{0x00, 0x00, 0x00, 0xff},
+    color.RGBA{0x00, 0x00, 0x44, 0xff},
+    color.RGBA{0x00, 0x00, 0x88, 0xff},
+    color.RGBA{0x00, 0x00, 0xcc, 0xff},
+    color.RGBA{0x00, 0x44, 0x00, 0xff},
+    color.RGBA{0x00, 0x44, 0x44, 0xff},
+    color.RGBA{0x00, 0x44, 0x88, 0xff},
+    color.RGBA{0x00, 0x44, 0xcc, 0xff},
+    color.RGBA{0x00, 0x88, 0x00, 0xff},
+    color.RGBA{0x00, 0x88, 0x44, 0xff},
+    color.RGBA{0x00, 0x88, 0x88, 0xff},
+    color.RGBA{0x00, 0x88, 0xcc, 0xff},
+    color.RGBA{0x00, 0xcc, 0x00, 0xff},
+    color.RGBA{0x00, 0xcc, 0x44, 0xff},
+    color.RGBA{0x00, 0xcc, 0x88, 0xff},
+    color.RGBA{0x00, 0xcc, 0xcc, 0xff},
+    color.RGBA{0x00, 0xdd, 0xdd, 0xff},
+    color.RGBA{0x11, 0x11, 0x11, 0xff},
+    color.RGBA{0x00, 0x00, 0x55, 0xff},
+    color.RGBA{0x00, 0x00, 0x99, 0xff},
+    color.RGBA{0x00, 0x00, 0xdd, 0xff},
+    color.RGBA{0x00, 0x55, 0x00, 0xff},
+    color.RGBA{0x00, 0x55, 0x55, 0xff},
+    color.RGBA{0x00, 0x4c, 0x99, 0xff},
+    color.RGBA{0x00, 0x49, 0xdd, 0xff},
+    color.RGBA{0x00, 0x99, 0x00, 0xff},
+    color.RGBA{0x00, 0x99, 0x4c, 0xff},
+    color.RGBA{0x00, 0x99, 0x99, 0xff},
+    color.RGBA{0x00, 0x93, 0xdd, 0xff},
+    color.RGBA{0x00, 0xdd, 0x00, 0xff},
+    color.RGBA{0x00, 0xdd, 0x49, 0xff},
+    color.RGBA{0x00, 0xdd, 0x93, 0xff},
+    color.RGBA{0x00, 0xee, 0x9e, 0xff},
+    color.RGBA{0x00, 0xee, 0xee, 0xff},
+    color.RGBA{0x22, 0x22, 0x22, 0xff},
+    color.RGBA{0x00, 0x00, 0x66, 0xff},
+    color.RGBA{0x00, 0x00, 0xaa, 0xff},
+    color.RGBA{0x00, 0x00, 0xee, 0xff},
+    color.RGBA{0x00, 0x66, 0x00, 0xff},
+    color.RGBA{0x00, 0x66, 0x66, 0xff},
+    color.RGBA{0x00, 0x55, 0xaa, 0xff},
+    color.RGBA{0x00, 0x4f, 0xee, 0xff},
+    color.RGBA{0x00, 0xaa, 0x00, 0xff},
+    color.RGBA{0x00, 0xaa, 0x55, 0xff},
+    color.RGBA{0x00, 0xaa, 0xaa, 0xff},
+    color.RGBA{0x00, 0x9e, 0xee, 0xff},
+    color.RGBA{0x00, 0xee, 0x00, 0xff},
+    color.RGBA{0x00, 0xee, 0x4f, 0xff},
+    color.RGBA{0x00, 0xff, 0x55, 0xff},
+    color.RGBA{0x00, 0xff, 0xaa, 0xff},
+    color.RGBA{0x00, 0xff, 0xff, 0xff},
+    color.RGBA{0x33, 0x33, 0x33, 0xff},
+    color.RGBA{0x00, 0x00, 0x77, 0xff},
+    color.RGBA{0x00, 0x00, 0xbb, 0xff},
+    color.RGBA{0x00, 0x00, 0xff, 0xff},
+    color.RGBA{0x00, 0x77, 0x00, 0xff},
+    color.RGBA{0x00, 0x77, 0x77, 0xff},
+    color.RGBA{0x00, 0x5d, 0xbb, 0xff},
+    color.RGBA{0x00, 0x55, 0xff, 0xff},
+    color.RGBA{0x00, 0xbb, 0x00, 0xff},
+    color.RGBA{0x00, 0xbb, 0x5d, 0xff},
+    color.RGBA{0x00, 0xbb, 0xbb, 0xff},
+    color.RGBA{0x00, 0xaa, 0xff, 0xff},
+    color.RGBA{0x00, 0xff, 0x00, 0xff},
+    color.RGBA{0x44, 0x00, 0x44, 0xff},
+    color.RGBA{0x44, 0x00, 0x88, 0xff},
+    color.RGBA{0x44, 0x00, 0xcc, 0xff},
+    color.RGBA{0x44, 0x44, 0x00, 0xff},
+    color.RGBA{0x44, 0x44, 0x44, 0xff},
+    color.RGBA{0x44, 0x44, 0x88, 0xff},
+    color.RGBA{0x44, 0x44, 0xcc, 0xff},
+    color.RGBA{0x44, 0x88, 0x00, 0xff},
+    color.RGBA{0x44, 0x88, 0x44, 0xff},
+    color.RGBA{0x44, 0x88, 0x88, 0xff},
+    color.RGBA{0x44, 0x88, 0xcc, 0xff},
+    color.RGBA{0x44, 0xcc, 0x00, 0xff},
+    color.RGBA{0x44, 0xcc, 0x44, 0xff},
+    color.RGBA{0x44, 0xcc, 0x88, 0xff},
+    color.RGBA{0x44, 0xcc, 0xcc, 0xff},
+    color.RGBA{0x44, 0x00, 0x00, 0xff},
+    color.RGBA{0x55, 0x00, 0x00, 0xff},
+    color.RGBA{0x55, 0x00, 0x55, 0xff},
+    color.RGBA{0x4c, 0x00, 0x99, 0xff},
+    color.RGBA{0x49, 0x00, 0xdd, 0xff},
+    color.RGBA{0x55, 0x55, 0x00, 0xff},
+    color.RGBA{0x55, 0x55, 0x55, 0xff},
+    color.RGBA{0x4c, 0x4c, 0x99, 0xff},
+    color.RGBA{0x49, 0x49, 0xdd, 0xff},
+    color.RGBA{0x4c, 0x99, 0x00, 0xff},
+    color.RGBA{0x4c, 0x99, 0x4c, 0xff},
+    color.RGBA{0x4c, 0x99, 0x99, 0xff},
+    color.RGBA{0x49, 0x93, 0xdd, 0xff},
+    color.RGBA{0x49, 0xdd, 0x00, 0xff},
+    color.RGBA{0x49, 0xdd, 0x49, 0xff},
+    color.RGBA{0x49, 0xdd, 0x93, 0xff},
+    color.RGBA{0x49, 0xdd, 0xdd, 0xff},
+    color.RGBA{0x4f, 0xee, 0xee, 0xff},
+    color.RGBA{0x66, 0x00, 0x00, 0xff},
+    color.RGBA{0x66, 0x00, 0x66, 0xff},
+    color.RGBA{0x55, 0x00, 0xaa, 0xff},
+    color.RGBA{0x4f, 0x00, 0xee, 0xff},
+    color.RGBA{0x66, 0x66, 0x00, 0xff},
+    color.RGBA{0x66, 0x66, 0x66, 0xff},
+    color.RGBA{0x55, 0x55, 0xaa, 0xff},
+    color.RGBA{0x4f, 0x4f, 0xee, 0xff},
+    color.RGBA{0x55, 0xaa, 0x00, 0xff},
+    color.RGBA{0x55, 0xaa, 0x55, 0xff},
+    color.RGBA{0x55, 0xaa, 0xaa, 0xff},
+    color.RGBA{0x4f, 0x9e, 0xee, 0xff},
+    color.RGBA{0x4f, 0xee, 0x00, 0xff},
+    color.RGBA{0x4f, 0xee, 0x4f, 0xff},
+    color.RGBA{0x4f, 0xee, 0x9e, 0xff},
+    color.RGBA{0x55, 0xff, 0xaa, 0xff},
+    color.RGBA{0x55, 0xff, 0xff, 0xff},
+    color.RGBA{0x77, 0x00, 0x00, 0xff},
+    color.RGBA{0x77, 0x00, 0x77, 0xff},
+    color.RGBA{0x5d, 0x00, 0xbb, 0xff},
+    color.RGBA{0x55, 0x00, 0xff, 0xff},
+    color.RGBA{0x77, 0x77, 0x00, 0xff},
+    color.RGBA{0x77, 0x77, 0x77, 0xff},
+    color.RGBA{0x5d, 0x5d, 0xbb, 0xff},
+    color.RGBA{0x55, 0x55, 0xff, 0xff},
+    color.RGBA{0x5d, 0xbb, 0x00, 0xff},
+    color.RGBA{0x5d, 0xbb, 0x5d, 0xff},
+    color.RGBA{0x5d, 0xbb, 0xbb, 0xff},
+    color.RGBA{0x55, 0xaa, 0xff, 0xff},
+    color.RGBA{0x55, 0xff, 0x00, 0xff},
+    color.RGBA{0x55, 0xff, 0x55, 0xff},
+    color.RGBA{0x88, 0x00, 0x88, 0xff},
+    color.RGBA{0x88, 0x00, 0xcc, 0xff},
+    color.RGBA{0x88, 0x44, 0x00, 0xff},
+    color.RGBA{0x88, 0x44, 0x44, 0xff},
+    color.RGBA{0x88, 0x44, 0x88, 0xff},
+    color.RGBA{0x88, 0x44, 0xcc, 0xff},
+    color.RGBA{0x88, 0x88, 0x00, 0xff},
+    color.RGBA{0x88, 0x88, 0x44, 0xff},
+    color.RGBA{0x88, 0x88, 0x88, 0xff},
+    color.RGBA{0x88, 0x88, 0xcc, 0xff},
+    color.RGBA{0x88, 0xcc, 0x00, 0xff},
+    color.RGBA{0x88, 0xcc, 0x44, 0xff},
+    color.RGBA{0x88, 0xcc, 0x88, 0xff},
+    color.RGBA{0x88, 0xcc, 0xcc, 0xff},
+    color.RGBA{0x88, 0x00, 0x00, 0xff},
+    color.RGBA{0x88, 0x00, 0x44, 0xff},
+    color.RGBA{0x99, 0x00, 0x4c, 0xff},
+    color.RGBA{0x99, 0x00, 0x99, 0xff},
+    color.RGBA{0x93, 0x00, 0xdd, 0xff},
+    color.RGBA{0x99, 0x4c, 0x00, 0xff},
+    color.RGBA{0x99, 0x4c, 0x4c, 0xff},
+    color.RGBA{0x99, 0x4c, 0x99, 0xff},
+    color.RGBA{0x93, 0x49, 0xdd, 0xff},
+    color.RGBA{0x99, 0x99, 0x00, 0xff},
+    color.RGBA{0x99, 0x99, 0x4c, 0xff},
+    color.RGBA{0x99, 0x99, 0x99, 0xff},
+    color.RGBA{0x93, 0x93, 0xdd, 0xff},
+    color.RGBA{0x93, 0xdd, 0x00, 0xff},
+    color.RGBA{0x93, 0xdd, 0x49, 0xff},
+    color.RGBA{0x93, 0xdd, 0x93, 0xff},
+    color.RGBA{0x93, 0xdd, 0xdd, 0xff},
+    color.RGBA{0x99, 0x00, 0x00, 0xff},
+    color.RGBA{0xaa, 0x00, 0x00, 0xff},
+    color.RGBA{0xaa, 0x00, 0x55, 0xff},
+    color.RGBA{0xaa, 0x00, 0xaa, 0xff},
+    color.RGBA{0x9e, 0x00, 0xee, 0xff},
+    color.RGBA{0xaa, 0x55, 0x00, 0xff},
+    color.RGBA{0xaa, 0x55, 0x55, 0xff},
+    color.RGBA{0xaa, 0x55, 0xaa, 0xff},
+    color.RGBA{0x9e, 0x4f, 0xee, 0xff},
+    color.RGBA{0xaa, 0xaa, 0x00, 0xff},
+    color.RGBA{0xaa, 0xaa, 0x55, 0xff},
+    color.RGBA{0xaa, 0xaa, 0xaa, 0xff},
+    color.RGBA{0x9e, 0x9e, 0xee, 0xff},
+    color.RGBA{0x9e, 0xee, 0x00, 0xff},
+    color.RGBA{0x9e, 0xee, 0x4f, 0xff},
+    color.RGBA{0x9e, 0xee, 0x9e, 0xff},
+    color.RGBA{0x9e, 0xee, 0xee, 0xff},
+    color.RGBA{0xaa, 0xff, 0xff, 0xff},
+    color.RGBA{0xbb, 0x00, 0x00, 0xff},
+    color.RGBA{0xbb, 0x00, 0x5d, 0xff},
+    color.RGBA{0xbb, 0x00, 0xbb, 0xff},
+    color.RGBA{0xaa, 0x00, 0xff, 0xff},
+    color.RGBA{0xbb, 0x5d, 0x00, 0xff},
+    color.RGBA{0xbb, 0x5d, 0x5d, 0xff},
+    color.RGBA{0xbb, 0x5d, 0xbb, 0xff},
+    color.RGBA{0xaa, 0x55, 0xff, 0xff},
+    color.RGBA{0xbb, 0xbb, 0x00, 0xff},
+    color.RGBA{0xbb, 0xbb, 0x5d, 0xff},
+    color.RGBA{0xbb, 0xbb, 0xbb, 0xff},
+    color.RGBA{0xaa, 0xaa, 0xff, 0xff},
+    color.RGBA{0xaa, 0xff, 0x00, 0xff},
+    color.RGBA{0xaa, 0xff, 0x55, 0xff},
+    color.RGBA{0xaa, 0xff, 0xaa, 0xff},
+    color.RGBA{0xcc, 0x00, 0xcc, 0xff},
+    color.RGBA{0xcc, 0x44, 0x00, 0xff},
+    color.RGBA{0xcc, 0x44, 0x44, 0xff},
+    color.RGBA{0xcc, 0x44, 0x88, 0xff},
+    color.RGBA{0xcc, 0x44, 0xcc, 0xff},
+    color.RGBA{0xcc, 0x88, 0x00, 0xff},
+    color.RGBA{0xcc, 0x88, 0x44, 0xff},
+    color.RGBA{0xcc, 0x88, 0x88, 0xff},
+    color.RGBA{0xcc, 0x88, 0xcc, 0xff},
+    color.RGBA{0xcc, 0xcc, 0x00, 0xff},
+    color.RGBA{0xcc, 0xcc, 0x44, 0xff},
+    color.RGBA{0xcc, 0xcc, 0x88, 0xff},
+    color.RGBA{0xcc, 0xcc, 0xcc, 0xff},
+    color.RGBA{0xcc, 0x00, 0x00, 0xff},
+    color.RGBA{0xcc, 0x00, 0x44, 0xff},
+    color.RGBA{0xcc, 0x00, 0x88, 0xff},
+    color.RGBA{0xdd, 0x00, 0x93, 0xff},
+    color.RGBA{0xdd, 0x00, 0xdd, 0xff},
+    color.RGBA{0xdd, 0x49, 0x00, 0xff},
+    color.RGBA{0xdd, 0x49, 0x49, 0xff},
+    color.RGBA{0xdd, 0x49, 0x93, 0xff},
+    color.RGBA{0xdd, 0x49, 0xdd, 0xff},
+    color.RGBA{0xdd, 0x93, 0x00, 0xff},
+    color.RGBA{0xdd, 0x93, 0x49, 0xff},
+    color.RGBA{0xdd, 0x93, 0x93, 0xff},
+    color.RGBA{0xdd, 0x93, 0xdd, 0xff},
+    color.RGBA{0xdd, 0xdd, 0x00, 0xff},
+    color.RGBA{0xdd, 0xdd, 0x49, 0xff},
+    color.RGBA{0xdd, 0xdd, 0x93, 0xff},
+    color.RGBA{0xdd, 0xdd, 0xdd, 0xff},
+    color.RGBA{0xdd, 0x00, 0x00, 0xff},
+    color.RGBA{0xdd, 0x00, 0x49, 0xff},
+    color.RGBA{0xee, 0x00, 0x4f, 0xff},
+    color.RGBA{0xee, 0x00, 0x9e, 0xff},
+    color.RGBA{0xee, 0x00, 0xee, 0xff},
+    color.RGBA{0xee, 0x4f, 0x00, 0xff},
+    color.RGBA{0xee, 0x4f, 0x4f, 0xff},
+    color.RGBA{0xee, 0x4f, 0x9e, 0xff},
+    color.RGBA{0xee, 0x4f, 0xee, 0xff},
+    color.RGBA{0xee, 0x9e, 0x00, 0xff},
+    color.RGBA{0xee, 0x9e, 0x4f, 0xff},
+    color.RGBA{0xee, 0x9e, 0x9e, 0xff},
+    color.RGBA{0xee, 0x9e, 0xee, 0xff},
+    color.RGBA{0xee, 0xee, 0x00, 0xff},
+    color.RGBA{0xee, 0xee, 0x4f, 0xff},
+    color.RGBA{0xee, 0xee, 0x9e, 0xff},
+    color.RGBA{0xee, 0xee, 0xee, 0xff},
+    color.RGBA{0xee, 0x00, 0x00, 0xff},
+    color.RGBA{0xff, 0x00, 0x00, 0xff},
+    color.RGBA{0xff, 0x00, 0x55, 0xff},
+    color.RGBA{0xff, 0x00, 0xaa, 0xff},
+    color.RGBA{0xff, 0x00, 0xff, 0xff},
+    color.RGBA{0xff, 0x55, 0x00, 0xff},
+    color.RGBA{0xff, 0x55, 0x55, 0xff},
+    color.RGBA{0xff, 0x55, 0xaa, 0xff},
+    color.RGBA{0xff, 0x55, 0xff, 0xff},
+    color.RGBA{0xff, 0xaa, 0x00, 0xff},
+    color.RGBA{0xff, 0xaa, 0x55, 0xff},
+    color.RGBA{0xff, 0xaa, 0xaa, 0xff},
+    color.RGBA{0xff, 0xaa, 0xff, 0xff},
+    color.RGBA{0xff, 0xff, 0x00, 0xff},
+    color.RGBA{0xff, 0xff, 0x55, 0xff},
+    color.RGBA{0xff, 0xff, 0xaa, 0xff},
+    color.RGBA{0xff, 0xff, 0xff, 0xff},
+}

WebSafe is a 216-color palette that was popularized by early versions of Netscape Navigator. It is also known as the Netscape Color Cube.

+

See https://en.wikipedia.org/wiki/Web_colors#Web-safe_colors for details.

+
var WebSafe = []color.Color{
+    color.RGBA{0x00, 0x00, 0x00, 0xff},
+    color.RGBA{0x00, 0x00, 0x33, 0xff},
+    color.RGBA{0x00, 0x00, 0x66, 0xff},
+    color.RGBA{0x00, 0x00, 0x99, 0xff},
+    color.RGBA{0x00, 0x00, 0xcc, 0xff},
+    color.RGBA{0x00, 0x00, 0xff, 0xff},
+    color.RGBA{0x00, 0x33, 0x00, 0xff},
+    color.RGBA{0x00, 0x33, 0x33, 0xff},
+    color.RGBA{0x00, 0x33, 0x66, 0xff},
+    color.RGBA{0x00, 0x33, 0x99, 0xff},
+    color.RGBA{0x00, 0x33, 0xcc, 0xff},
+    color.RGBA{0x00, 0x33, 0xff, 0xff},
+    color.RGBA{0x00, 0x66, 0x00, 0xff},
+    color.RGBA{0x00, 0x66, 0x33, 0xff},
+    color.RGBA{0x00, 0x66, 0x66, 0xff},
+    color.RGBA{0x00, 0x66, 0x99, 0xff},
+    color.RGBA{0x00, 0x66, 0xcc, 0xff},
+    color.RGBA{0x00, 0x66, 0xff, 0xff},
+    color.RGBA{0x00, 0x99, 0x00, 0xff},
+    color.RGBA{0x00, 0x99, 0x33, 0xff},
+    color.RGBA{0x00, 0x99, 0x66, 0xff},
+    color.RGBA{0x00, 0x99, 0x99, 0xff},
+    color.RGBA{0x00, 0x99, 0xcc, 0xff},
+    color.RGBA{0x00, 0x99, 0xff, 0xff},
+    color.RGBA{0x00, 0xcc, 0x00, 0xff},
+    color.RGBA{0x00, 0xcc, 0x33, 0xff},
+    color.RGBA{0x00, 0xcc, 0x66, 0xff},
+    color.RGBA{0x00, 0xcc, 0x99, 0xff},
+    color.RGBA{0x00, 0xcc, 0xcc, 0xff},
+    color.RGBA{0x00, 0xcc, 0xff, 0xff},
+    color.RGBA{0x00, 0xff, 0x00, 0xff},
+    color.RGBA{0x00, 0xff, 0x33, 0xff},
+    color.RGBA{0x00, 0xff, 0x66, 0xff},
+    color.RGBA{0x00, 0xff, 0x99, 0xff},
+    color.RGBA{0x00, 0xff, 0xcc, 0xff},
+    color.RGBA{0x00, 0xff, 0xff, 0xff},
+    color.RGBA{0x33, 0x00, 0x00, 0xff},
+    color.RGBA{0x33, 0x00, 0x33, 0xff},
+    color.RGBA{0x33, 0x00, 0x66, 0xff},
+    color.RGBA{0x33, 0x00, 0x99, 0xff},
+    color.RGBA{0x33, 0x00, 0xcc, 0xff},
+    color.RGBA{0x33, 0x00, 0xff, 0xff},
+    color.RGBA{0x33, 0x33, 0x00, 0xff},
+    color.RGBA{0x33, 0x33, 0x33, 0xff},
+    color.RGBA{0x33, 0x33, 0x66, 0xff},
+    color.RGBA{0x33, 0x33, 0x99, 0xff},
+    color.RGBA{0x33, 0x33, 0xcc, 0xff},
+    color.RGBA{0x33, 0x33, 0xff, 0xff},
+    color.RGBA{0x33, 0x66, 0x00, 0xff},
+    color.RGBA{0x33, 0x66, 0x33, 0xff},
+    color.RGBA{0x33, 0x66, 0x66, 0xff},
+    color.RGBA{0x33, 0x66, 0x99, 0xff},
+    color.RGBA{0x33, 0x66, 0xcc, 0xff},
+    color.RGBA{0x33, 0x66, 0xff, 0xff},
+    color.RGBA{0x33, 0x99, 0x00, 0xff},
+    color.RGBA{0x33, 0x99, 0x33, 0xff},
+    color.RGBA{0x33, 0x99, 0x66, 0xff},
+    color.RGBA{0x33, 0x99, 0x99, 0xff},
+    color.RGBA{0x33, 0x99, 0xcc, 0xff},
+    color.RGBA{0x33, 0x99, 0xff, 0xff},
+    color.RGBA{0x33, 0xcc, 0x00, 0xff},
+    color.RGBA{0x33, 0xcc, 0x33, 0xff},
+    color.RGBA{0x33, 0xcc, 0x66, 0xff},
+    color.RGBA{0x33, 0xcc, 0x99, 0xff},
+    color.RGBA{0x33, 0xcc, 0xcc, 0xff},
+    color.RGBA{0x33, 0xcc, 0xff, 0xff},
+    color.RGBA{0x33, 0xff, 0x00, 0xff},
+    color.RGBA{0x33, 0xff, 0x33, 0xff},
+    color.RGBA{0x33, 0xff, 0x66, 0xff},
+    color.RGBA{0x33, 0xff, 0x99, 0xff},
+    color.RGBA{0x33, 0xff, 0xcc, 0xff},
+    color.RGBA{0x33, 0xff, 0xff, 0xff},
+    color.RGBA{0x66, 0x00, 0x00, 0xff},
+    color.RGBA{0x66, 0x00, 0x33, 0xff},
+    color.RGBA{0x66, 0x00, 0x66, 0xff},
+    color.RGBA{0x66, 0x00, 0x99, 0xff},
+    color.RGBA{0x66, 0x00, 0xcc, 0xff},
+    color.RGBA{0x66, 0x00, 0xff, 0xff},
+    color.RGBA{0x66, 0x33, 0x00, 0xff},
+    color.RGBA{0x66, 0x33, 0x33, 0xff},
+    color.RGBA{0x66, 0x33, 0x66, 0xff},
+    color.RGBA{0x66, 0x33, 0x99, 0xff},
+    color.RGBA{0x66, 0x33, 0xcc, 0xff},
+    color.RGBA{0x66, 0x33, 0xff, 0xff},
+    color.RGBA{0x66, 0x66, 0x00, 0xff},
+    color.RGBA{0x66, 0x66, 0x33, 0xff},
+    color.RGBA{0x66, 0x66, 0x66, 0xff},
+    color.RGBA{0x66, 0x66, 0x99, 0xff},
+    color.RGBA{0x66, 0x66, 0xcc, 0xff},
+    color.RGBA{0x66, 0x66, 0xff, 0xff},
+    color.RGBA{0x66, 0x99, 0x00, 0xff},
+    color.RGBA{0x66, 0x99, 0x33, 0xff},
+    color.RGBA{0x66, 0x99, 0x66, 0xff},
+    color.RGBA{0x66, 0x99, 0x99, 0xff},
+    color.RGBA{0x66, 0x99, 0xcc, 0xff},
+    color.RGBA{0x66, 0x99, 0xff, 0xff},
+    color.RGBA{0x66, 0xcc, 0x00, 0xff},
+    color.RGBA{0x66, 0xcc, 0x33, 0xff},
+    color.RGBA{0x66, 0xcc, 0x66, 0xff},
+    color.RGBA{0x66, 0xcc, 0x99, 0xff},
+    color.RGBA{0x66, 0xcc, 0xcc, 0xff},
+    color.RGBA{0x66, 0xcc, 0xff, 0xff},
+    color.RGBA{0x66, 0xff, 0x00, 0xff},
+    color.RGBA{0x66, 0xff, 0x33, 0xff},
+    color.RGBA{0x66, 0xff, 0x66, 0xff},
+    color.RGBA{0x66, 0xff, 0x99, 0xff},
+    color.RGBA{0x66, 0xff, 0xcc, 0xff},
+    color.RGBA{0x66, 0xff, 0xff, 0xff},
+    color.RGBA{0x99, 0x00, 0x00, 0xff},
+    color.RGBA{0x99, 0x00, 0x33, 0xff},
+    color.RGBA{0x99, 0x00, 0x66, 0xff},
+    color.RGBA{0x99, 0x00, 0x99, 0xff},
+    color.RGBA{0x99, 0x00, 0xcc, 0xff},
+    color.RGBA{0x99, 0x00, 0xff, 0xff},
+    color.RGBA{0x99, 0x33, 0x00, 0xff},
+    color.RGBA{0x99, 0x33, 0x33, 0xff},
+    color.RGBA{0x99, 0x33, 0x66, 0xff},
+    color.RGBA{0x99, 0x33, 0x99, 0xff},
+    color.RGBA{0x99, 0x33, 0xcc, 0xff},
+    color.RGBA{0x99, 0x33, 0xff, 0xff},
+    color.RGBA{0x99, 0x66, 0x00, 0xff},
+    color.RGBA{0x99, 0x66, 0x33, 0xff},
+    color.RGBA{0x99, 0x66, 0x66, 0xff},
+    color.RGBA{0x99, 0x66, 0x99, 0xff},
+    color.RGBA{0x99, 0x66, 0xcc, 0xff},
+    color.RGBA{0x99, 0x66, 0xff, 0xff},
+    color.RGBA{0x99, 0x99, 0x00, 0xff},
+    color.RGBA{0x99, 0x99, 0x33, 0xff},
+    color.RGBA{0x99, 0x99, 0x66, 0xff},
+    color.RGBA{0x99, 0x99, 0x99, 0xff},
+    color.RGBA{0x99, 0x99, 0xcc, 0xff},
+    color.RGBA{0x99, 0x99, 0xff, 0xff},
+    color.RGBA{0x99, 0xcc, 0x00, 0xff},
+    color.RGBA{0x99, 0xcc, 0x33, 0xff},
+    color.RGBA{0x99, 0xcc, 0x66, 0xff},
+    color.RGBA{0x99, 0xcc, 0x99, 0xff},
+    color.RGBA{0x99, 0xcc, 0xcc, 0xff},
+    color.RGBA{0x99, 0xcc, 0xff, 0xff},
+    color.RGBA{0x99, 0xff, 0x00, 0xff},
+    color.RGBA{0x99, 0xff, 0x33, 0xff},
+    color.RGBA{0x99, 0xff, 0x66, 0xff},
+    color.RGBA{0x99, 0xff, 0x99, 0xff},
+    color.RGBA{0x99, 0xff, 0xcc, 0xff},
+    color.RGBA{0x99, 0xff, 0xff, 0xff},
+    color.RGBA{0xcc, 0x00, 0x00, 0xff},
+    color.RGBA{0xcc, 0x00, 0x33, 0xff},
+    color.RGBA{0xcc, 0x00, 0x66, 0xff},
+    color.RGBA{0xcc, 0x00, 0x99, 0xff},
+    color.RGBA{0xcc, 0x00, 0xcc, 0xff},
+    color.RGBA{0xcc, 0x00, 0xff, 0xff},
+    color.RGBA{0xcc, 0x33, 0x00, 0xff},
+    color.RGBA{0xcc, 0x33, 0x33, 0xff},
+    color.RGBA{0xcc, 0x33, 0x66, 0xff},
+    color.RGBA{0xcc, 0x33, 0x99, 0xff},
+    color.RGBA{0xcc, 0x33, 0xcc, 0xff},
+    color.RGBA{0xcc, 0x33, 0xff, 0xff},
+    color.RGBA{0xcc, 0x66, 0x00, 0xff},
+    color.RGBA{0xcc, 0x66, 0x33, 0xff},
+    color.RGBA{0xcc, 0x66, 0x66, 0xff},
+    color.RGBA{0xcc, 0x66, 0x99, 0xff},
+    color.RGBA{0xcc, 0x66, 0xcc, 0xff},
+    color.RGBA{0xcc, 0x66, 0xff, 0xff},
+    color.RGBA{0xcc, 0x99, 0x00, 0xff},
+    color.RGBA{0xcc, 0x99, 0x33, 0xff},
+    color.RGBA{0xcc, 0x99, 0x66, 0xff},
+    color.RGBA{0xcc, 0x99, 0x99, 0xff},
+    color.RGBA{0xcc, 0x99, 0xcc, 0xff},
+    color.RGBA{0xcc, 0x99, 0xff, 0xff},
+    color.RGBA{0xcc, 0xcc, 0x00, 0xff},
+    color.RGBA{0xcc, 0xcc, 0x33, 0xff},
+    color.RGBA{0xcc, 0xcc, 0x66, 0xff},
+    color.RGBA{0xcc, 0xcc, 0x99, 0xff},
+    color.RGBA{0xcc, 0xcc, 0xcc, 0xff},
+    color.RGBA{0xcc, 0xcc, 0xff, 0xff},
+    color.RGBA{0xcc, 0xff, 0x00, 0xff},
+    color.RGBA{0xcc, 0xff, 0x33, 0xff},
+    color.RGBA{0xcc, 0xff, 0x66, 0xff},
+    color.RGBA{0xcc, 0xff, 0x99, 0xff},
+    color.RGBA{0xcc, 0xff, 0xcc, 0xff},
+    color.RGBA{0xcc, 0xff, 0xff, 0xff},
+    color.RGBA{0xff, 0x00, 0x00, 0xff},
+    color.RGBA{0xff, 0x00, 0x33, 0xff},
+    color.RGBA{0xff, 0x00, 0x66, 0xff},
+    color.RGBA{0xff, 0x00, 0x99, 0xff},
+    color.RGBA{0xff, 0x00, 0xcc, 0xff},
+    color.RGBA{0xff, 0x00, 0xff, 0xff},
+    color.RGBA{0xff, 0x33, 0x00, 0xff},
+    color.RGBA{0xff, 0x33, 0x33, 0xff},
+    color.RGBA{0xff, 0x33, 0x66, 0xff},
+    color.RGBA{0xff, 0x33, 0x99, 0xff},
+    color.RGBA{0xff, 0x33, 0xcc, 0xff},
+    color.RGBA{0xff, 0x33, 0xff, 0xff},
+    color.RGBA{0xff, 0x66, 0x00, 0xff},
+    color.RGBA{0xff, 0x66, 0x33, 0xff},
+    color.RGBA{0xff, 0x66, 0x66, 0xff},
+    color.RGBA{0xff, 0x66, 0x99, 0xff},
+    color.RGBA{0xff, 0x66, 0xcc, 0xff},
+    color.RGBA{0xff, 0x66, 0xff, 0xff},
+    color.RGBA{0xff, 0x99, 0x00, 0xff},
+    color.RGBA{0xff, 0x99, 0x33, 0xff},
+    color.RGBA{0xff, 0x99, 0x66, 0xff},
+    color.RGBA{0xff, 0x99, 0x99, 0xff},
+    color.RGBA{0xff, 0x99, 0xcc, 0xff},
+    color.RGBA{0xff, 0x99, 0xff, 0xff},
+    color.RGBA{0xff, 0xcc, 0x00, 0xff},
+    color.RGBA{0xff, 0xcc, 0x33, 0xff},
+    color.RGBA{0xff, 0xcc, 0x66, 0xff},
+    color.RGBA{0xff, 0xcc, 0x99, 0xff},
+    color.RGBA{0xff, 0xcc, 0xcc, 0xff},
+    color.RGBA{0xff, 0xcc, 0xff, 0xff},
+    color.RGBA{0xff, 0xff, 0x00, 0xff},
+    color.RGBA{0xff, 0xff, 0x33, 0xff},
+    color.RGBA{0xff, 0xff, 0x66, 0xff},
+    color.RGBA{0xff, 0xff, 0x99, 0xff},
+    color.RGBA{0xff, 0xff, 0xcc, 0xff},
+    color.RGBA{0xff, 0xff, 0xff, 0xff},
+}
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/image/color/palette/ +

+
diff --git a/devdocs/go/image%2Fdraw%2Findex.html b/devdocs/go/image%2Fdraw%2Findex.html new file mode 100644 index 00000000..b44b2f3c --- /dev/null +++ b/devdocs/go/image%2Fdraw%2Findex.html @@ -0,0 +1,85 @@ +

Package draw

Overview

Package draw provides image composition functions.

+

See "The Go image/draw package" for an introduction to this package: https://golang.org/doc/articles/image_draw.html

Index

Examples

Drawer (FloydSteinberg)

Package files

draw.go

func Draw

func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op)

Draw calls DrawMask with a nil mask.

+

func DrawMask

func DrawMask(dst Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point, op Op)

DrawMask aligns r.Min in dst with sp in src and mp in mask and then replaces the rectangle r in dst with the result of a Porter-Duff composition. A nil mask is treated as opaque.

+

type Drawer 1.2

Drawer contains the Draw method.

+
type Drawer interface {
+    // Draw aligns r.Min in dst with sp in src and then replaces the
+    // rectangle r in dst with the result of drawing src on dst.
+    Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point)
+}

FloydSteinberg is a Drawer that is the Src Op with Floyd-Steinberg error diffusion.

+
var FloydSteinberg Drawer = floydSteinberg{}

Example (FloydSteinberg) +

Code:

+const width = 130
+const height = 50
+
+im := image.NewGray(image.Rectangle{Max: image.Point{X: width, Y: height}})
+for x := 0; x < width; x++ {
+    for y := 0; y < height; y++ {
+        dist := math.Sqrt(math.Pow(float64(x-width/2), 2)/3+math.Pow(float64(y-height/2), 2)) / (height / 1.5) * 255
+        var gray uint8
+        if dist > 255 {
+            gray = 255
+        } else {
+            gray = uint8(dist)
+        }
+        im.SetGray(x, y, color.Gray{Y: 255 - gray})
+    }
+}
+pi := image.NewPaletted(im.Bounds(), []color.Color{
+    color.Gray{Y: 255},
+    color.Gray{Y: 160},
+    color.Gray{Y: 70},
+    color.Gray{Y: 35},
+    color.Gray{Y: 0},
+})
+
+draw.FloydSteinberg.Draw(pi, im.Bounds(), im, image.Point{})
+shade := []string{" ", "░", "▒", "▓", "█"}
+for i, p := range pi.Pix {
+    fmt.Print(shade[p])
+    if (i+1)%width == 0 {
+        fmt.Print("\n")
+    }
+}
+

type Image

Image is an image.Image with a Set method to change a single pixel.

+
type Image interface {
+    image.Image
+    Set(x, y int, c color.Color)
+}

type Op

Op is a Porter-Duff compositing operator.

+
type Op int
const (
+    // Over specifies ``(src in mask) over dst''.
+    Over Op = iota
+    // Src specifies ``src in mask''.
+    Src
+)

func (Op) Draw 1.2

func (op Op) Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point)

Draw implements the Drawer interface by calling the Draw function with this Op.

+

type Quantizer 1.2

Quantizer produces a palette for an image.

+
type Quantizer interface {
+    // Quantize appends up to cap(p) - len(p) colors to p and returns the
+    // updated palette suitable for converting m to a paletted image.
+    Quantize(p color.Palette, m image.Image) color.Palette
+}

type RGBA64Image 1.17

RGBA64Image extends both the Image and image.RGBA64Image interfaces with a SetRGBA64 method to change a single pixel. SetRGBA64 is equivalent to calling Set, but it can avoid allocations from converting concrete color types to the color.Color interface type.

+
type RGBA64Image interface {
+    image.RGBA64Image
+    Set(x, y int, c color.Color)
+    SetRGBA64(x, y int, c color.RGBA64)
+}
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/image/draw/ +

+
diff --git a/devdocs/go/image%2Fgif%2Findex.html b/devdocs/go/image%2Fgif%2Findex.html new file mode 100644 index 00000000..e695fb18 --- /dev/null +++ b/devdocs/go/image%2Fgif%2Findex.html @@ -0,0 +1,74 @@ +

Package gif

Overview

Package gif implements a GIF image decoder and encoder.

+

The GIF specification is at https://www.w3.org/Graphics/GIF/spec-gif89a.txt.

Index

Package files

reader.go writer.go

Constants

Disposal Methods.

+
const (
+    DisposalNone       = 0x01
+    DisposalBackground = 0x02
+    DisposalPrevious   = 0x03
+)

func Decode

func Decode(r io.Reader) (image.Image, error)

Decode reads a GIF image from r and returns the first embedded image as an image.Image.

+

func DecodeConfig

func DecodeConfig(r io.Reader) (image.Config, error)

DecodeConfig returns the global color model and dimensions of a GIF image without decoding the entire image.

+

func Encode 1.2

func Encode(w io.Writer, m image.Image, o *Options) error

Encode writes the Image m to w in GIF format.

+

func EncodeAll 1.2

func EncodeAll(w io.Writer, g *GIF) error

EncodeAll writes the images in g to w in GIF format with the given loop count and delay between frames.

+

type GIF

GIF represents the possibly multiple images stored in a GIF file.

+
type GIF struct {
+    Image []*image.Paletted // The successive images.
+    Delay []int             // The successive delay times, one per frame, in 100ths of a second.
+    // LoopCount controls the number of times an animation will be
+    // restarted during display.
+    // A LoopCount of 0 means to loop forever.
+    // A LoopCount of -1 means to show each frame only once.
+    // Otherwise, the animation is looped LoopCount+1 times.
+    LoopCount int
+    // Disposal is the successive disposal methods, one per frame. For
+    // backwards compatibility, a nil Disposal is valid to pass to EncodeAll,
+    // and implies that each frame's disposal method is 0 (no disposal
+    // specified).
+    Disposal []byte // Go 1.5
+    // Config is the global color table (palette), width and height. A nil or
+    // empty-color.Palette Config.ColorModel means that each frame has its own
+    // color table and there is no global color table. Each frame's bounds must
+    // be within the rectangle defined by the two points (0, 0) and
+    // (Config.Width, Config.Height).
+    //
+    // For backwards compatibility, a zero-valued Config is valid to pass to
+    // EncodeAll, and implies that the overall GIF's width and height equals
+    // the first frame's bounds' Rectangle.Max point.
+    Config image.Config // Go 1.5
+    // BackgroundIndex is the background index in the global color table, for
+    // use with the DisposalBackground disposal method.
+    BackgroundIndex byte // Go 1.5
+}
+

func DecodeAll

func DecodeAll(r io.Reader) (*GIF, error)

DecodeAll reads a GIF image from r and returns the sequential frames and timing information.

+

type Options 1.2

Options are the encoding parameters.

+
type Options struct {
+    // NumColors is the maximum number of colors used in the image.
+    // It ranges from 1 to 256.
+    NumColors int
+
+    // Quantizer is used to produce a palette with size NumColors.
+    // palette.Plan9 is used in place of a nil Quantizer.
+    Quantizer draw.Quantizer
+
+    // Drawer is used to convert the source image to the desired palette.
+    // draw.FloydSteinberg is used in place of a nil Drawer.
+    Drawer draw.Drawer
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/image/gif/ +

+
diff --git a/devdocs/go/image%2Findex.html b/devdocs/go/image%2Findex.html new file mode 100644 index 00000000..d3c4b716 --- /dev/null +++ b/devdocs/go/image%2Findex.html @@ -0,0 +1,721 @@ +

Package image

Overview

Package image implements a basic 2-D image library.

+

The fundamental interface is called Image. An Image contains colors, which are described in the image/color package.

+

Values of the Image interface are created either by calling functions such as NewRGBA and NewPaletted, or by calling Decode on an io.Reader containing image data in a format such as GIF, JPEG or PNG. Decoding any particular image format requires the prior registration of a decoder function. Registration is typically automatic as a side effect of initializing that format's package so that, to decode a PNG image, it suffices to have

+
import _ "image/png"
+

in a program's main package. The _ means to import a package purely for its initialization side effects.

+

See "The Go image package" for more details: https://golang.org/doc/articles/image_package.html

+

Security Considerations

The image package can be used to parse arbitrarily large images, which can cause resource exhaustion on machines which do not have enough memory to store them. When operating on arbitrary images, DecodeConfig should be called before Decode, so that the program can decide whether the image, as defined in the returned header, can be safely decoded with the available resources. A call to Decode which produces an extremely large image, as defined in the header returned by DecodeConfig, is not considered a security issue, regardless of whether the image is itself malformed or not. A call to DecodeConfig which returns a header which does not match the image returned by Decode may be considered a security issue, and should be reported per the [Go Security Policy](https://go.dev/security/policy).

Example +

Code:

// Decode the JPEG data. If reading from file, create a reader with
+//
+// reader, err := os.Open("testdata/video-001.q50.420.jpeg")
+// if err != nil {
+//     log.Fatal(err)
+// }
+// defer reader.Close()
+reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))
+m, _, err := image.Decode(reader)
+if err != nil {
+    log.Fatal(err)
+}
+bounds := m.Bounds()
+
+// Calculate a 16-bin histogram for m's red, green, blue and alpha components.
+//
+// An image's bounds do not necessarily start at (0, 0), so the two loops start
+// at bounds.Min.Y and bounds.Min.X. Looping over Y first and X second is more
+// likely to result in better memory access patterns than X first and Y second.
+var histogram [16][4]int
+for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
+    for x := bounds.Min.X; x < bounds.Max.X; x++ {
+        r, g, b, a := m.At(x, y).RGBA()
+        // A color's RGBA method returns values in the range [0, 65535].
+        // Shifting by 12 reduces this to the range [0, 15].
+        histogram[r>>12][0]++
+        histogram[g>>12][1]++
+        histogram[b>>12][2]++
+        histogram[a>>12][3]++
+    }
+}
+
+// Print the results.
+fmt.Printf("%-14s %6s %6s %6s %6s\n", "bin", "red", "green", "blue", "alpha")
+for i, x := range histogram {
+    fmt.Printf("0x%04x-0x%04x: %6d %6d %6d %6d\n", i<<12, (i+1)<<12-1, x[0], x[1], x[2], x[3])
+}
+

Output:

bin               red  green   blue  alpha
+0x0000-0x0fff:    364    790   7242      0
+0x1000-0x1fff:    645   2967   1039      0
+0x2000-0x2fff:   1072   2299    979      0
+0x3000-0x3fff:    820   2266    980      0
+0x4000-0x4fff:    537   1305    541      0
+0x5000-0x5fff:    319    962    261      0
+0x6000-0x6fff:    322    375    177      0
+0x7000-0x7fff:    601    279    214      0
+0x8000-0x8fff:   3478    227    273      0
+0x9000-0x9fff:   2260    234    329      0
+0xa000-0xafff:    921    282    373      0
+0xb000-0xbfff:    321    335    397      0
+0xc000-0xcfff:    229    388    298      0
+0xd000-0xdfff:    260    414    277      0
+0xe000-0xefff:    516    428    298      0
+0xf000-0xffff:   2785   1899   1772  15450
+

Example (DecodeConfig) +

Code:

+reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))
+config, format, err := image.DecodeConfig(reader)
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println("Width:", config.Width, "Height:", config.Height, "Format:", format)
+

Index

Examples

Package
Package (DecodeConfig)

Package files

format.go geom.go image.go names.go ycbcr.go

Variables

var (
+    // Black is an opaque black uniform image.
+    Black = NewUniform(color.Black)
+    // White is an opaque white uniform image.
+    White = NewUniform(color.White)
+    // Transparent is a fully transparent uniform image.
+    Transparent = NewUniform(color.Transparent)
+    // Opaque is a fully opaque uniform image.
+    Opaque = NewUniform(color.Opaque)
+)

ErrFormat indicates that decoding encountered an unknown format.

+
var ErrFormat = errors.New("image: unknown format")

func RegisterFormat

func RegisterFormat(name, magic string, decode func(io.Reader) (Image, error), decodeConfig func(io.Reader) (Config, error))

RegisterFormat registers an image format for use by Decode. Name is the name of the format, like "jpeg" or "png". Magic is the magic prefix that identifies the format's encoding. The magic string can contain "?" wildcards that each match any one byte. Decode is the function that decodes the encoded image. DecodeConfig is the function that decodes just its configuration.

+

type Alpha

Alpha is an in-memory image whose At method returns color.Alpha values.

+
type Alpha struct {
+    // Pix holds the image's pixels, as alpha values. The pixel at
+    // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
+    Pix []uint8
+    // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+    Stride int
+    // Rect is the image's bounds.
+    Rect Rectangle
+}
+

func NewAlpha

func NewAlpha(r Rectangle) *Alpha

NewAlpha returns a new Alpha image with the given bounds.

+

func (*Alpha) AlphaAt 1.4

func (p *Alpha) AlphaAt(x, y int) color.Alpha

func (*Alpha) At

func (p *Alpha) At(x, y int) color.Color

func (*Alpha) Bounds

func (p *Alpha) Bounds() Rectangle

func (*Alpha) ColorModel

func (p *Alpha) ColorModel() color.Model

func (*Alpha) Opaque

func (p *Alpha) Opaque() bool

Opaque scans the entire image and reports whether it is fully opaque.

+

func (*Alpha) PixOffset

func (p *Alpha) PixOffset(x, y int) int

PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

+

func (*Alpha) RGBA64At 1.17

func (p *Alpha) RGBA64At(x, y int) color.RGBA64

func (*Alpha) Set

func (p *Alpha) Set(x, y int, c color.Color)

func (*Alpha) SetAlpha

func (p *Alpha) SetAlpha(x, y int, c color.Alpha)

func (*Alpha) SetRGBA64 1.17

func (p *Alpha) SetRGBA64(x, y int, c color.RGBA64)

func (*Alpha) SubImage

func (p *Alpha) SubImage(r Rectangle) Image

SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

+

type Alpha16

Alpha16 is an in-memory image whose At method returns color.Alpha16 values.

+
type Alpha16 struct {
+    // Pix holds the image's pixels, as alpha values in big-endian format. The pixel at
+    // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*2].
+    Pix []uint8
+    // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+    Stride int
+    // Rect is the image's bounds.
+    Rect Rectangle
+}
+

func NewAlpha16

func NewAlpha16(r Rectangle) *Alpha16

NewAlpha16 returns a new Alpha16 image with the given bounds.

+

func (*Alpha16) Alpha16At 1.4

func (p *Alpha16) Alpha16At(x, y int) color.Alpha16

func (*Alpha16) At

func (p *Alpha16) At(x, y int) color.Color

func (*Alpha16) Bounds

func (p *Alpha16) Bounds() Rectangle

func (*Alpha16) ColorModel

func (p *Alpha16) ColorModel() color.Model

func (*Alpha16) Opaque

func (p *Alpha16) Opaque() bool

Opaque scans the entire image and reports whether it is fully opaque.

+

func (*Alpha16) PixOffset

func (p *Alpha16) PixOffset(x, y int) int

PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

+

func (*Alpha16) RGBA64At 1.17

func (p *Alpha16) RGBA64At(x, y int) color.RGBA64

func (*Alpha16) Set

func (p *Alpha16) Set(x, y int, c color.Color)

func (*Alpha16) SetAlpha16

func (p *Alpha16) SetAlpha16(x, y int, c color.Alpha16)

func (*Alpha16) SetRGBA64 1.17

func (p *Alpha16) SetRGBA64(x, y int, c color.RGBA64)

func (*Alpha16) SubImage

func (p *Alpha16) SubImage(r Rectangle) Image

SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

+

type CMYK 1.5

CMYK is an in-memory image whose At method returns color.CMYK values.

+
type CMYK struct {
+    // Pix holds the image's pixels, in C, M, Y, K order. The pixel at
+    // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
+    Pix []uint8
+    // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+    Stride int
+    // Rect is the image's bounds.
+    Rect Rectangle
+}
+

func NewCMYK 1.5

func NewCMYK(r Rectangle) *CMYK

NewCMYK returns a new CMYK image with the given bounds.

+

func (*CMYK) At 1.5

func (p *CMYK) At(x, y int) color.Color

func (*CMYK) Bounds 1.5

func (p *CMYK) Bounds() Rectangle

func (*CMYK) CMYKAt 1.5

func (p *CMYK) CMYKAt(x, y int) color.CMYK

func (*CMYK) ColorModel 1.5

func (p *CMYK) ColorModel() color.Model

func (*CMYK) Opaque 1.5

func (p *CMYK) Opaque() bool

Opaque scans the entire image and reports whether it is fully opaque.

+

func (*CMYK) PixOffset 1.5

func (p *CMYK) PixOffset(x, y int) int

PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

+

func (*CMYK) RGBA64At 1.17

func (p *CMYK) RGBA64At(x, y int) color.RGBA64

func (*CMYK) Set 1.5

func (p *CMYK) Set(x, y int, c color.Color)

func (*CMYK) SetCMYK 1.5

func (p *CMYK) SetCMYK(x, y int, c color.CMYK)

func (*CMYK) SetRGBA64 1.17

func (p *CMYK) SetRGBA64(x, y int, c color.RGBA64)

func (*CMYK) SubImage 1.5

func (p *CMYK) SubImage(r Rectangle) Image

SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

+

type Config

Config holds an image's color model and dimensions.

+
type Config struct {
+    ColorModel    color.Model
+    Width, Height int
+}
+

func DecodeConfig

func DecodeConfig(r io.Reader) (Config, string, error)

DecodeConfig decodes the color model and dimensions of an image that has been encoded in a registered format. The string returned is the format name used during format registration. Format registration is typically done by an init function in the codec-specific package.

+

type Gray

Gray is an in-memory image whose At method returns color.Gray values.

+
type Gray struct {
+    // Pix holds the image's pixels, as gray values. The pixel at
+    // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
+    Pix []uint8
+    // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+    Stride int
+    // Rect is the image's bounds.
+    Rect Rectangle
+}
+

func NewGray

func NewGray(r Rectangle) *Gray

NewGray returns a new Gray image with the given bounds.

+

func (*Gray) At

func (p *Gray) At(x, y int) color.Color

func (*Gray) Bounds

func (p *Gray) Bounds() Rectangle

func (*Gray) ColorModel

func (p *Gray) ColorModel() color.Model

func (*Gray) GrayAt 1.4

func (p *Gray) GrayAt(x, y int) color.Gray

func (*Gray) Opaque

func (p *Gray) Opaque() bool

Opaque scans the entire image and reports whether it is fully opaque.

+

func (*Gray) PixOffset

func (p *Gray) PixOffset(x, y int) int

PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

+

func (*Gray) RGBA64At 1.17

func (p *Gray) RGBA64At(x, y int) color.RGBA64

func (*Gray) Set

func (p *Gray) Set(x, y int, c color.Color)

func (*Gray) SetGray

func (p *Gray) SetGray(x, y int, c color.Gray)

func (*Gray) SetRGBA64 1.17

func (p *Gray) SetRGBA64(x, y int, c color.RGBA64)

func (*Gray) SubImage

func (p *Gray) SubImage(r Rectangle) Image

SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

+

type Gray16

Gray16 is an in-memory image whose At method returns color.Gray16 values.

+
type Gray16 struct {
+    // Pix holds the image's pixels, as gray values in big-endian format. The pixel at
+    // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*2].
+    Pix []uint8
+    // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+    Stride int
+    // Rect is the image's bounds.
+    Rect Rectangle
+}
+

func NewGray16

func NewGray16(r Rectangle) *Gray16

NewGray16 returns a new Gray16 image with the given bounds.

+

func (*Gray16) At

func (p *Gray16) At(x, y int) color.Color

func (*Gray16) Bounds

func (p *Gray16) Bounds() Rectangle

func (*Gray16) ColorModel

func (p *Gray16) ColorModel() color.Model

func (*Gray16) Gray16At 1.4

func (p *Gray16) Gray16At(x, y int) color.Gray16

func (*Gray16) Opaque

func (p *Gray16) Opaque() bool

Opaque scans the entire image and reports whether it is fully opaque.

+

func (*Gray16) PixOffset

func (p *Gray16) PixOffset(x, y int) int

PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

+

func (*Gray16) RGBA64At 1.17

func (p *Gray16) RGBA64At(x, y int) color.RGBA64

func (*Gray16) Set

func (p *Gray16) Set(x, y int, c color.Color)

func (*Gray16) SetGray16

func (p *Gray16) SetGray16(x, y int, c color.Gray16)

func (*Gray16) SetRGBA64 1.17

func (p *Gray16) SetRGBA64(x, y int, c color.RGBA64)

func (*Gray16) SubImage

func (p *Gray16) SubImage(r Rectangle) Image

SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

+

type Image

Image is a finite rectangular grid of color.Color values taken from a color model.

+
type Image interface {
+    // ColorModel returns the Image's color model.
+    ColorModel() color.Model
+    // Bounds returns the domain for which At can return non-zero color.
+    // The bounds do not necessarily contain the point (0, 0).
+    Bounds() Rectangle
+    // At returns the color of the pixel at (x, y).
+    // At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid.
+    // At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one.
+    At(x, y int) color.Color
+}

func Decode

func Decode(r io.Reader) (Image, string, error)

Decode decodes an image that has been encoded in a registered format. The string returned is the format name used during format registration. Format registration is typically done by an init function in the codec- specific package.

+

type NRGBA

NRGBA is an in-memory image whose At method returns color.NRGBA values.

+
type NRGBA struct {
+    // Pix holds the image's pixels, in R, G, B, A order. The pixel at
+    // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
+    Pix []uint8
+    // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+    Stride int
+    // Rect is the image's bounds.
+    Rect Rectangle
+}
+

func NewNRGBA

func NewNRGBA(r Rectangle) *NRGBA

NewNRGBA returns a new NRGBA image with the given bounds.

+

func (*NRGBA) At

func (p *NRGBA) At(x, y int) color.Color

func (*NRGBA) Bounds

func (p *NRGBA) Bounds() Rectangle

func (*NRGBA) ColorModel

func (p *NRGBA) ColorModel() color.Model

func (*NRGBA) NRGBAAt 1.4

func (p *NRGBA) NRGBAAt(x, y int) color.NRGBA

func (*NRGBA) Opaque

func (p *NRGBA) Opaque() bool

Opaque scans the entire image and reports whether it is fully opaque.

+

func (*NRGBA) PixOffset

func (p *NRGBA) PixOffset(x, y int) int

PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

+

func (*NRGBA) RGBA64At 1.17

func (p *NRGBA) RGBA64At(x, y int) color.RGBA64

func (*NRGBA) Set

func (p *NRGBA) Set(x, y int, c color.Color)

func (*NRGBA) SetNRGBA

func (p *NRGBA) SetNRGBA(x, y int, c color.NRGBA)

func (*NRGBA) SetRGBA64 1.17

func (p *NRGBA) SetRGBA64(x, y int, c color.RGBA64)

func (*NRGBA) SubImage

func (p *NRGBA) SubImage(r Rectangle) Image

SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

+

type NRGBA64

NRGBA64 is an in-memory image whose At method returns color.NRGBA64 values.

+
type NRGBA64 struct {
+    // Pix holds the image's pixels, in R, G, B, A order and big-endian format. The pixel at
+    // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*8].
+    Pix []uint8
+    // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+    Stride int
+    // Rect is the image's bounds.
+    Rect Rectangle
+}
+

func NewNRGBA64

func NewNRGBA64(r Rectangle) *NRGBA64

NewNRGBA64 returns a new NRGBA64 image with the given bounds.

+

func (*NRGBA64) At

func (p *NRGBA64) At(x, y int) color.Color

func (*NRGBA64) Bounds

func (p *NRGBA64) Bounds() Rectangle

func (*NRGBA64) ColorModel

func (p *NRGBA64) ColorModel() color.Model

func (*NRGBA64) NRGBA64At 1.4

func (p *NRGBA64) NRGBA64At(x, y int) color.NRGBA64

func (*NRGBA64) Opaque

func (p *NRGBA64) Opaque() bool

Opaque scans the entire image and reports whether it is fully opaque.

+

func (*NRGBA64) PixOffset

func (p *NRGBA64) PixOffset(x, y int) int

PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

+

func (*NRGBA64) RGBA64At 1.17

func (p *NRGBA64) RGBA64At(x, y int) color.RGBA64

func (*NRGBA64) Set

func (p *NRGBA64) Set(x, y int, c color.Color)

func (*NRGBA64) SetNRGBA64

func (p *NRGBA64) SetNRGBA64(x, y int, c color.NRGBA64)

func (*NRGBA64) SetRGBA64 1.17

func (p *NRGBA64) SetRGBA64(x, y int, c color.RGBA64)

func (*NRGBA64) SubImage

func (p *NRGBA64) SubImage(r Rectangle) Image

SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

+

type NYCbCrA 1.6

NYCbCrA is an in-memory image of non-alpha-premultiplied Y'CbCr-with-alpha colors. A and AStride are analogous to the Y and YStride fields of the embedded YCbCr.

+
type NYCbCrA struct {
+    YCbCr
+    A       []uint8
+    AStride int
+}
+

func NewNYCbCrA 1.6

func NewNYCbCrA(r Rectangle, subsampleRatio YCbCrSubsampleRatio) *NYCbCrA

NewNYCbCrA returns a new NYCbCrA image with the given bounds and subsample ratio.

+

func (*NYCbCrA) AOffset 1.6

func (p *NYCbCrA) AOffset(x, y int) int

AOffset returns the index of the first element of A that corresponds to the pixel at (x, y).

+

func (*NYCbCrA) At 1.6

func (p *NYCbCrA) At(x, y int) color.Color

func (*NYCbCrA) ColorModel 1.6

func (p *NYCbCrA) ColorModel() color.Model

func (*NYCbCrA) NYCbCrAAt 1.6

func (p *NYCbCrA) NYCbCrAAt(x, y int) color.NYCbCrA

func (*NYCbCrA) Opaque 1.6

func (p *NYCbCrA) Opaque() bool

Opaque scans the entire image and reports whether it is fully opaque.

+

func (*NYCbCrA) RGBA64At 1.17

func (p *NYCbCrA) RGBA64At(x, y int) color.RGBA64

func (*NYCbCrA) SubImage 1.6

func (p *NYCbCrA) SubImage(r Rectangle) Image

SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

+

type Paletted

Paletted is an in-memory image of uint8 indices into a given palette.

+
type Paletted struct {
+    // Pix holds the image's pixels, as palette indices. The pixel at
+    // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
+    Pix []uint8
+    // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+    Stride int
+    // Rect is the image's bounds.
+    Rect Rectangle
+    // Palette is the image's palette.
+    Palette color.Palette
+}
+

func NewPaletted

func NewPaletted(r Rectangle, p color.Palette) *Paletted

NewPaletted returns a new Paletted image with the given width, height and palette.

+

func (*Paletted) At

func (p *Paletted) At(x, y int) color.Color

func (*Paletted) Bounds

func (p *Paletted) Bounds() Rectangle

func (*Paletted) ColorIndexAt

func (p *Paletted) ColorIndexAt(x, y int) uint8

func (*Paletted) ColorModel

func (p *Paletted) ColorModel() color.Model

func (*Paletted) Opaque

func (p *Paletted) Opaque() bool

Opaque scans the entire image and reports whether it is fully opaque.

+

func (*Paletted) PixOffset

func (p *Paletted) PixOffset(x, y int) int

PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

+

func (*Paletted) RGBA64At 1.17

func (p *Paletted) RGBA64At(x, y int) color.RGBA64

func (*Paletted) Set

func (p *Paletted) Set(x, y int, c color.Color)

func (*Paletted) SetColorIndex

func (p *Paletted) SetColorIndex(x, y int, index uint8)

func (*Paletted) SetRGBA64 1.17

func (p *Paletted) SetRGBA64(x, y int, c color.RGBA64)

func (*Paletted) SubImage

func (p *Paletted) SubImage(r Rectangle) Image

SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

+

type PalettedImage

PalettedImage is an image whose colors may come from a limited palette. If m is a PalettedImage and m.ColorModel() returns a color.Palette p, then m.At(x, y) should be equivalent to p[m.ColorIndexAt(x, y)]. If m's color model is not a color.Palette, then ColorIndexAt's behavior is undefined.

+
type PalettedImage interface {
+    // ColorIndexAt returns the palette index of the pixel at (x, y).
+    ColorIndexAt(x, y int) uint8
+    Image
+}

type Point

A Point is an X, Y coordinate pair. The axes increase right and down.

+
type Point struct {
+    X, Y int
+}
+

ZP is the zero Point.

+

Deprecated: Use a literal image.Point instead.

+
var ZP Point

func Pt

func Pt(X, Y int) Point

Pt is shorthand for Point{X, Y}.

+

func (Point) Add

func (p Point) Add(q Point) Point

Add returns the vector p+q.

+

func (Point) Div

func (p Point) Div(k int) Point

Div returns the vector p/k.

+

func (Point) Eq

func (p Point) Eq(q Point) bool

Eq reports whether p and q are equal.

+

func (Point) In

func (p Point) In(r Rectangle) bool

In reports whether p is in r.

+

func (Point) Mod

func (p Point) Mod(r Rectangle) Point

Mod returns the point q in r such that p.X-q.X is a multiple of r's width and p.Y-q.Y is a multiple of r's height.

+

func (Point) Mul

func (p Point) Mul(k int) Point

Mul returns the vector p*k.

+

func (Point) String

func (p Point) String() string

String returns a string representation of p like "(3,4)".

+

func (Point) Sub

func (p Point) Sub(q Point) Point

Sub returns the vector p-q.

+

type RGBA

RGBA is an in-memory image whose At method returns color.RGBA values.

+
type RGBA struct {
+    // Pix holds the image's pixels, in R, G, B, A order. The pixel at
+    // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
+    Pix []uint8
+    // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+    Stride int
+    // Rect is the image's bounds.
+    Rect Rectangle
+}
+

func NewRGBA

func NewRGBA(r Rectangle) *RGBA

NewRGBA returns a new RGBA image with the given bounds.

+

func (*RGBA) At

func (p *RGBA) At(x, y int) color.Color

func (*RGBA) Bounds

func (p *RGBA) Bounds() Rectangle

func (*RGBA) ColorModel

func (p *RGBA) ColorModel() color.Model

func (*RGBA) Opaque

func (p *RGBA) Opaque() bool

Opaque scans the entire image and reports whether it is fully opaque.

+

func (*RGBA) PixOffset

func (p *RGBA) PixOffset(x, y int) int

PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

+

func (*RGBA) RGBA64At 1.17

func (p *RGBA) RGBA64At(x, y int) color.RGBA64

func (*RGBA) RGBAAt 1.4

func (p *RGBA) RGBAAt(x, y int) color.RGBA

func (*RGBA) Set

func (p *RGBA) Set(x, y int, c color.Color)

func (*RGBA) SetRGBA

func (p *RGBA) SetRGBA(x, y int, c color.RGBA)

func (*RGBA) SetRGBA64 1.17

func (p *RGBA) SetRGBA64(x, y int, c color.RGBA64)

func (*RGBA) SubImage

func (p *RGBA) SubImage(r Rectangle) Image

SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

+

type RGBA64

RGBA64 is an in-memory image whose At method returns color.RGBA64 values.

+
type RGBA64 struct {
+    // Pix holds the image's pixels, in R, G, B, A order and big-endian format. The pixel at
+    // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*8].
+    Pix []uint8
+    // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+    Stride int
+    // Rect is the image's bounds.
+    Rect Rectangle
+}
+

func NewRGBA64

func NewRGBA64(r Rectangle) *RGBA64

NewRGBA64 returns a new RGBA64 image with the given bounds.

+

func (*RGBA64) At

func (p *RGBA64) At(x, y int) color.Color

func (*RGBA64) Bounds

func (p *RGBA64) Bounds() Rectangle

func (*RGBA64) ColorModel

func (p *RGBA64) ColorModel() color.Model

func (*RGBA64) Opaque

func (p *RGBA64) Opaque() bool

Opaque scans the entire image and reports whether it is fully opaque.

+

func (*RGBA64) PixOffset

func (p *RGBA64) PixOffset(x, y int) int

PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

+

func (*RGBA64) RGBA64At 1.4

func (p *RGBA64) RGBA64At(x, y int) color.RGBA64

func (*RGBA64) Set

func (p *RGBA64) Set(x, y int, c color.Color)

func (*RGBA64) SetRGBA64

func (p *RGBA64) SetRGBA64(x, y int, c color.RGBA64)

func (*RGBA64) SubImage

func (p *RGBA64) SubImage(r Rectangle) Image

SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

+

type RGBA64Image 1.17

RGBA64Image is an Image whose pixels can be converted directly to a color.RGBA64.

+
type RGBA64Image interface {
+    // RGBA64At returns the RGBA64 color of the pixel at (x, y). It is
+    // equivalent to calling At(x, y).RGBA() and converting the resulting
+    // 32-bit return values to a color.RGBA64, but it can avoid allocations
+    // from converting concrete color types to the color.Color interface type.
+    RGBA64At(x, y int) color.RGBA64
+    Image
+}

type Rectangle

A Rectangle contains the points with Min.X <= X < Max.X, Min.Y <= Y < Max.Y. It is well-formed if Min.X <= Max.X and likewise for Y. Points are always well-formed. A rectangle's methods always return well-formed outputs for well-formed inputs.

+

A Rectangle is also an Image whose bounds are the rectangle itself. At returns color.Opaque for points in the rectangle and color.Transparent otherwise.

+
type Rectangle struct {
+    Min, Max Point
+}
+

ZR is the zero Rectangle.

+

Deprecated: Use a literal image.Rectangle instead.

+
var ZR Rectangle

func Rect

func Rect(x0, y0, x1, y1 int) Rectangle

Rect is shorthand for Rectangle{Pt(x0, y0), Pt(x1, y1)}. The returned rectangle has minimum and maximum coordinates swapped if necessary so that it is well-formed.

+

func (Rectangle) Add

func (r Rectangle) Add(p Point) Rectangle

Add returns the rectangle r translated by p.

+

func (Rectangle) At 1.5

func (r Rectangle) At(x, y int) color.Color

At implements the Image interface.

+

func (Rectangle) Bounds 1.5

func (r Rectangle) Bounds() Rectangle

Bounds implements the Image interface.

+

func (Rectangle) Canon

func (r Rectangle) Canon() Rectangle

Canon returns the canonical version of r. The returned rectangle has minimum and maximum coordinates swapped if necessary so that it is well-formed.

+

func (Rectangle) ColorModel 1.5

func (r Rectangle) ColorModel() color.Model

ColorModel implements the Image interface.

+

func (Rectangle) Dx

func (r Rectangle) Dx() int

Dx returns r's width.

+

func (Rectangle) Dy

func (r Rectangle) Dy() int

Dy returns r's height.

+

func (Rectangle) Empty

func (r Rectangle) Empty() bool

Empty reports whether the rectangle contains no points.

+

func (Rectangle) Eq

func (r Rectangle) Eq(s Rectangle) bool

Eq reports whether r and s contain the same set of points. All empty rectangles are considered equal.

+

func (Rectangle) In

func (r Rectangle) In(s Rectangle) bool

In reports whether every point in r is in s.

+

func (Rectangle) Inset

func (r Rectangle) Inset(n int) Rectangle

Inset returns the rectangle r inset by n, which may be negative. If either of r's dimensions is less than 2*n then an empty rectangle near the center of r will be returned.

+

func (Rectangle) Intersect

func (r Rectangle) Intersect(s Rectangle) Rectangle

Intersect returns the largest rectangle contained by both r and s. If the two rectangles do not overlap then the zero rectangle will be returned.

+

func (Rectangle) Overlaps

func (r Rectangle) Overlaps(s Rectangle) bool

Overlaps reports whether r and s have a non-empty intersection.

+

func (Rectangle) RGBA64At 1.17

func (r Rectangle) RGBA64At(x, y int) color.RGBA64

RGBA64At implements the RGBA64Image interface.

+

func (Rectangle) Size

func (r Rectangle) Size() Point

Size returns r's width and height.

+

func (Rectangle) String

func (r Rectangle) String() string

String returns a string representation of r like "(3,4)-(6,5)".

+

func (Rectangle) Sub

func (r Rectangle) Sub(p Point) Rectangle

Sub returns the rectangle r translated by -p.

+

func (Rectangle) Union

func (r Rectangle) Union(s Rectangle) Rectangle

Union returns the smallest rectangle that contains both r and s.

+

type Uniform

Uniform is an infinite-sized Image of uniform color. It implements the color.Color, color.Model, and Image interfaces.

+
type Uniform struct {
+    C color.Color
+}
+

func NewUniform

func NewUniform(c color.Color) *Uniform

NewUniform returns a new Uniform image of the given color.

+

func (*Uniform) At

func (c *Uniform) At(x, y int) color.Color

func (*Uniform) Bounds

func (c *Uniform) Bounds() Rectangle

func (*Uniform) ColorModel

func (c *Uniform) ColorModel() color.Model

func (*Uniform) Convert

func (c *Uniform) Convert(color.Color) color.Color

func (*Uniform) Opaque

func (c *Uniform) Opaque() bool

Opaque scans the entire image and reports whether it is fully opaque.

+

func (*Uniform) RGBA

func (c *Uniform) RGBA() (r, g, b, a uint32)

func (*Uniform) RGBA64At 1.17

func (c *Uniform) RGBA64At(x, y int) color.RGBA64

type YCbCr

YCbCr is an in-memory image of Y'CbCr colors. There is one Y sample per pixel, but each Cb and Cr sample can span one or more pixels. YStride is the Y slice index delta between vertically adjacent pixels. CStride is the Cb and Cr slice index delta between vertically adjacent pixels that map to separate chroma samples. It is not an absolute requirement, but YStride and len(Y) are typically multiples of 8, and:

+
For 4:4:4, CStride == YStride/1 && len(Cb) == len(Cr) == len(Y)/1.
+For 4:2:2, CStride == YStride/2 && len(Cb) == len(Cr) == len(Y)/2.
+For 4:2:0, CStride == YStride/2 && len(Cb) == len(Cr) == len(Y)/4.
+For 4:4:0, CStride == YStride/1 && len(Cb) == len(Cr) == len(Y)/2.
+For 4:1:1, CStride == YStride/4 && len(Cb) == len(Cr) == len(Y)/4.
+For 4:1:0, CStride == YStride/4 && len(Cb) == len(Cr) == len(Y)/8.
+
type YCbCr struct {
+    Y, Cb, Cr      []uint8
+    YStride        int
+    CStride        int
+    SubsampleRatio YCbCrSubsampleRatio
+    Rect           Rectangle
+}
+

func NewYCbCr

func NewYCbCr(r Rectangle, subsampleRatio YCbCrSubsampleRatio) *YCbCr

NewYCbCr returns a new YCbCr image with the given bounds and subsample ratio.

+

func (*YCbCr) At

func (p *YCbCr) At(x, y int) color.Color

func (*YCbCr) Bounds

func (p *YCbCr) Bounds() Rectangle

func (*YCbCr) COffset

func (p *YCbCr) COffset(x, y int) int

COffset returns the index of the first element of Cb or Cr that corresponds to the pixel at (x, y).

+

func (*YCbCr) ColorModel

func (p *YCbCr) ColorModel() color.Model

func (*YCbCr) Opaque

func (p *YCbCr) Opaque() bool

func (*YCbCr) RGBA64At 1.17

func (p *YCbCr) RGBA64At(x, y int) color.RGBA64

func (*YCbCr) SubImage

func (p *YCbCr) SubImage(r Rectangle) Image

SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

+

func (*YCbCr) YCbCrAt 1.4

func (p *YCbCr) YCbCrAt(x, y int) color.YCbCr

func (*YCbCr) YOffset

func (p *YCbCr) YOffset(x, y int) int

YOffset returns the index of the first element of Y that corresponds to the pixel at (x, y).

+

type YCbCrSubsampleRatio

YCbCrSubsampleRatio is the chroma subsample ratio used in a YCbCr image.

+
type YCbCrSubsampleRatio int
const (
+    YCbCrSubsampleRatio444 YCbCrSubsampleRatio = iota
+    YCbCrSubsampleRatio422
+    YCbCrSubsampleRatio420
+    YCbCrSubsampleRatio440
+    YCbCrSubsampleRatio411
+    YCbCrSubsampleRatio410
+)

func (YCbCrSubsampleRatio) String

func (s YCbCrSubsampleRatio) String() string

Subdirectories

Name Synopsis
..
color Package color implements a basic color library.
palette Package palette provides standard color palettes.
draw Package draw provides image composition functions.
gif Package gif implements a GIF image decoder and encoder.
jpeg Package jpeg implements a JPEG image decoder and encoder.
png Package png implements a PNG image decoder and encoder.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/image/ +

+
diff --git a/devdocs/go/image%2Fjpeg%2Findex.html b/devdocs/go/image%2Fjpeg%2Findex.html new file mode 100644 index 00000000..7b4c616f --- /dev/null +++ b/devdocs/go/image%2Fjpeg%2Findex.html @@ -0,0 +1,38 @@ +

Package jpeg

Overview

Package jpeg implements a JPEG image decoder and encoder.

+

JPEG is defined in ITU-T T.81: https://www.w3.org/Graphics/JPEG/itu-t81.pdf.

Index

Package files

fdct.go huffman.go idct.go reader.go scan.go writer.go

Constants

DefaultQuality is the default quality encoding parameter.

+
const DefaultQuality = 75

func Decode

func Decode(r io.Reader) (image.Image, error)

Decode reads a JPEG image from r and returns it as an image.Image.

+

func DecodeConfig

func DecodeConfig(r io.Reader) (image.Config, error)

DecodeConfig returns the color model and dimensions of a JPEG image without decoding the entire image.

+

func Encode

func Encode(w io.Writer, m image.Image, o *Options) error

Encode writes the Image m to w in JPEG 4:2:0 baseline format with the given options. Default parameters are used if a nil *Options is passed.

+

type FormatError

A FormatError reports that the input is not a valid JPEG.

+
type FormatError string

func (FormatError) Error

func (e FormatError) Error() string

type Options

Options are the encoding parameters. Quality ranges from 1 to 100 inclusive, higher is better.

+
type Options struct {
+    Quality int
+}
+

type Reader

Deprecated: Reader is not used by the image/jpeg package and should not be used by others. It is kept for compatibility.

+
type Reader interface {
+    io.ByteReader
+    io.Reader
+}

type UnsupportedError

An UnsupportedError reports that the input uses a valid but unimplemented JPEG feature.

+
type UnsupportedError string

func (UnsupportedError) Error

func (e UnsupportedError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/image/jpeg/ +

+
diff --git a/devdocs/go/image%2Fpng%2Findex.html b/devdocs/go/image%2Fpng%2Findex.html new file mode 100644 index 00000000..81d127b6 --- /dev/null +++ b/devdocs/go/image%2Fpng%2Findex.html @@ -0,0 +1,104 @@ +

Package png

Overview

Package png implements a PNG image decoder and encoder.

+

The PNG specification is at https://www.w3.org/TR/PNG/.

Index

Examples

Decode
Encode

Package files

paeth.go reader.go writer.go

func Decode

func Decode(r io.Reader) (image.Image, error)

Decode reads a PNG image from r and returns it as an image.Image. The type of Image returned depends on the PNG contents.

Example +

Code:

+// This example uses png.Decode which can only decode PNG images.
+// Consider using the general image.Decode as it can sniff and decode any registered image format.
+img, err := png.Decode(gopherPNG())
+if err != nil {
+    log.Fatal(err)
+}
+
+levels := []string{" ", "░", "▒", "▓", "█"}
+
+for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
+    for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
+        c := color.GrayModel.Convert(img.At(x, y)).(color.Gray)
+        level := c.Y / 51 // 51 * 5 = 255
+        if level == 5 {
+            level--
+        }
+        fmt.Print(levels[level])
+    }
+    fmt.Print("\n")
+}
+

func DecodeConfig

func DecodeConfig(r io.Reader) (image.Config, error)

DecodeConfig returns the color model and dimensions of a PNG image without decoding the entire image.

+

func Encode

func Encode(w io.Writer, m image.Image) error

Encode writes the Image m to w in PNG format. Any Image may be encoded, but images that are not image.NRGBA might be encoded lossily.

Example +

Code:

+const width, height = 256, 256
+
+// Create a colored image of the given width and height.
+img := image.NewNRGBA(image.Rect(0, 0, width, height))
+
+for y := 0; y < height; y++ {
+    for x := 0; x < width; x++ {
+        img.Set(x, y, color.NRGBA{
+            R: uint8((x + y) & 255),
+            G: uint8((x + y) << 1 & 255),
+            B: uint8((x + y) << 2 & 255),
+            A: 255,
+        })
+    }
+}
+
+f, err := os.Create("image.png")
+if err != nil {
+    log.Fatal(err)
+}
+
+if err := png.Encode(f, img); err != nil {
+    f.Close()
+    log.Fatal(err)
+}
+
+if err := f.Close(); err != nil {
+    log.Fatal(err)
+}
+

type CompressionLevel 1.4

CompressionLevel indicates the compression level.

+
type CompressionLevel int
const (
+    DefaultCompression CompressionLevel = 0
+    NoCompression      CompressionLevel = -1
+    BestSpeed          CompressionLevel = -2
+    BestCompression    CompressionLevel = -3
+)

type Encoder 1.4

Encoder configures encoding PNG images.

+
type Encoder struct {
+    CompressionLevel CompressionLevel
+
+    // BufferPool optionally specifies a buffer pool to get temporary
+    // EncoderBuffers when encoding an image.
+    BufferPool EncoderBufferPool // Go 1.9
+}
+

func (*Encoder) Encode 1.4

func (enc *Encoder) Encode(w io.Writer, m image.Image) error

Encode writes the Image m to w in PNG format.

+

type EncoderBuffer 1.9

EncoderBuffer holds the buffers used for encoding PNG images.

+
type EncoderBuffer encoder

type EncoderBufferPool 1.9

EncoderBufferPool is an interface for getting and returning temporary instances of the EncoderBuffer struct. This can be used to reuse buffers when encoding multiple images.

+
type EncoderBufferPool interface {
+    Get() *EncoderBuffer
+    Put(*EncoderBuffer)
+}

type FormatError

A FormatError reports that the input is not a valid PNG.

+
type FormatError string

func (FormatError) Error

func (e FormatError) Error() string

type UnsupportedError

An UnsupportedError reports that the input uses a valid but unimplemented PNG feature.

+
type UnsupportedError string

func (UnsupportedError) Error

func (e UnsupportedError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/image/png/ +

+
diff --git a/devdocs/go/index b/devdocs/go/index new file mode 100644 index 00000000..5166adbf --- /dev/null +++ b/devdocs/go/index @@ -0,0 +1 @@ +((pages . ["index" "arena/index" "builtin/index" "archive/tar/index" "archive/zip/index" "bufio/index" "cmp/index" "compress/bzip2/index" "compress/flate/index" "compress/gzip/index" "compress/lzw/index" "compress/zlib/index" "container/heap/index" "container/list/index" "container/ring/index" "context/index" "crypto/index" "crypto/aes/index" "crypto/boring/index" "crypto/cipher/index" "crypto/des/index" "bytes/index" "crypto/dsa/index" "crypto/ecdh/index" "crypto/ecdsa/index" "crypto/ed25519/index" "crypto/elliptic/index" "crypto/hmac/index" "crypto/md5/index" "crypto/rand/index" "crypto/rc4/index" "crypto/rsa/index" "crypto/sha1/index" "crypto/sha256/index" "crypto/sha512/index" "crypto/subtle/index" "crypto/tls/index" "crypto/tls/fipsonly/index" "crypto/x509/index" "crypto/x509/pkix/index" "database/sql/index" "database/sql/driver/index" "debug/buildinfo/index" "debug/dwarf/index" "debug/elf/index" "debug/gosym/index" "debug/macho/index" "debug/pe/index" "debug/plan9obj/index" "embed/index" "encoding/index" "encoding/ascii85/index" "encoding/asn1/index" "encoding/base32/index" "encoding/base64/index" "encoding/binary/index" "encoding/csv/index" "encoding/gob/index" "encoding/hex/index" "encoding/json/index" "encoding/pem/index" "errors/index" "expvar/index" "flag/index" "fmt/index" "go/build/index" "go/build/constraint/index" "go/constant/index" "go/doc/index" "go/doc/comment/index" "go/format/index" "go/importer/index" "go/parser/index" "go/printer/index" "go/scanner/index" "go/token/index" "encoding/xml/index" "go/ast/index" "go/types/index" "go/version/index" "hash/index" "hash/adler32/index" "hash/crc32/index" "hash/crc64/index" "hash/fnv/index" "hash/maphash/index" "html/index" "html/template/index" "image/index" "image/color/index" "image/color/palette/index" "image/draw/index" "image/gif/index" "image/jpeg/index" "image/png/index" "index/suffixarray/index" "io/index" "io/fs/index" "io/ioutil/index" "iter/index" "log/index" "log/slog/index" "log/syslog/index" "maps/index" "math/index" "math/big/index" "math/bits/index" "math/cmplx/index" "math/rand/index" "math/rand/v2/index" "mime/index" "mime/multipart/index" "mime/quotedprintable/index" "net/index" "net/http/index" "net/http/cgi/index" "net/http/cookiejar/index" "net/http/fcgi/index" "net/http/httptest/index" "net/http/httptrace/index" "net/http/httputil/index" "net/http/pprof/index" "net/mail/index" "net/netip/index" "net/rpc/index" "net/rpc/jsonrpc/index" "net/smtp/index" "net/textproto/index" "net/url/index" "os/index" "os/exec/index" "os/signal/index" "os/user/index" "path/index" "path/filepath/index" "plugin/index" "reflect/index" "regexp/index" "regexp/syntax/index" "runtime/asan/index" "runtime/cgo/index" "runtime/coverage/index" "runtime/debug/index" "runtime/metrics/index" "runtime/pprof/index" "runtime/race/index" "runtime/trace/index" "slices/index" "sort/index" "strconv/index" "strings/index" "sync/index" "sync/atomic/index" "runtime/index" "syscall/index" "syscall/js/index" "testing/index" "testing/fstest/index" "testing/iotest/index" "testing/quick/index" "testing/slogtest/index" "text/scanner/index" "text/tabwriter/index" "text/template/index" "text/template/parse/index" "time/index" "time/tzdata/index" "unicode/index" "unicode/utf16/index" "unicode/utf8/index" "unsafe/index" "net/http/internal/index" "internal/goarch/index" "internal/goos/index"]) (entries . [((name . "adler32.Checksum()") (path . "hash/adler32/index#Checksum") (type . "hash")) ((name . "adler32.New()") (path . "hash/adler32/index#New") (type . "hash")) ((name . "aes.KeySizeError") (path . "crypto/aes/index#KeySizeError") (type . "crypto")) ((name . "aes.KeySizeError.Error()") (path . "crypto/aes/index#KeySizeError.Error") (type . "crypto")) ((name . "aes.NewCipher()") (path . "crypto/aes/index#NewCipher") (type . "crypto")) ((name . "archive/tar") (path . "archive/tar/index") (type . "archive")) ((name . "archive/tar constants") (path . "archive/tar/index#pkg-constants") (type . "archive")) ((name . "archive/tar variables") (path . "archive/tar/index#pkg-variables") (type . "archive")) ((name . "archive/zip") (path . "archive/zip/index") (type . "archive")) ((name . "archive/zip constants") (path . "archive/zip/index#pkg-constants") (type . "archive")) ((name . "archive/zip variables") (path . "archive/zip/index#pkg-variables") (type . "archive")) ((name . "ascii85.CorruptInputError") (path . "encoding/ascii85/index#CorruptInputError") (type . "encoding")) ((name . "ascii85.CorruptInputError.Error()") (path . "encoding/ascii85/index#CorruptInputError.Error") (type . "encoding")) ((name . "ascii85.Decode()") (path . "encoding/ascii85/index#Decode") (type . "encoding")) ((name . "ascii85.Encode()") (path . "encoding/ascii85/index#Encode") (type . "encoding")) ((name . "ascii85.MaxEncodedLen()") (path . "encoding/ascii85/index#MaxEncodedLen") (type . "encoding")) ((name . "ascii85.NewDecoder()") (path . "encoding/ascii85/index#NewDecoder") (type . "encoding")) ((name . "ascii85.NewEncoder()") (path . "encoding/ascii85/index#NewEncoder") (type . "encoding")) ((name . "asn1.BitString") (path . "encoding/asn1/index#BitString") (type . "encoding")) ((name . "asn1.BitString.At()") (path . "encoding/asn1/index#BitString.At") (type . "encoding")) ((name . "asn1.BitString.RightAlign()") (path . "encoding/asn1/index#BitString.RightAlign") (type . "encoding")) ((name . "asn1.Enumerated") (path . "encoding/asn1/index#Enumerated") (type . "encoding")) ((name . "asn1.Flag") (path . "encoding/asn1/index#Flag") (type . "encoding")) ((name . "asn1.Marshal()") (path . "encoding/asn1/index#Marshal") (type . "encoding")) ((name . "asn1.MarshalWithParams()") (path . "encoding/asn1/index#MarshalWithParams") (type . "encoding")) ((name . "asn1.ObjectIdentifier") (path . "encoding/asn1/index#ObjectIdentifier") (type . "encoding")) ((name . "asn1.ObjectIdentifier.Equal()") (path . "encoding/asn1/index#ObjectIdentifier.Equal") (type . "encoding")) ((name . "asn1.ObjectIdentifier.String()") (path . "encoding/asn1/index#ObjectIdentifier.String") (type . "encoding")) ((name . "asn1.RawContent") (path . "encoding/asn1/index#RawContent") (type . "encoding")) ((name . "asn1.RawValue") (path . "encoding/asn1/index#RawValue") (type . "encoding")) ((name . "asn1.StructuralError") (path . "encoding/asn1/index#StructuralError") (type . "encoding")) ((name . "asn1.StructuralError.Error()") (path . "encoding/asn1/index#StructuralError.Error") (type . "encoding")) ((name . "asn1.SyntaxError") (path . "encoding/asn1/index#SyntaxError") (type . "encoding")) ((name . "asn1.SyntaxError.Error()") (path . "encoding/asn1/index#SyntaxError.Error") (type . "encoding")) ((name . "asn1.Unmarshal()") (path . "encoding/asn1/index#Unmarshal") (type . "encoding")) ((name . "asn1.UnmarshalWithParams()") (path . "encoding/asn1/index#UnmarshalWithParams") (type . "encoding")) ((name . "ast.ArrayType") (path . "go/ast/index#ArrayType") (type . "go")) ((name . "ast.ArrayType.End()") (path . "go/ast/index#ArrayType.End") (type . "go")) ((name . "ast.ArrayType.Pos()") (path . "go/ast/index#ArrayType.Pos") (type . "go")) ((name . "ast.AssignStmt") (path . "go/ast/index#AssignStmt") (type . "go")) ((name . "ast.AssignStmt.End()") (path . "go/ast/index#AssignStmt.End") (type . "go")) ((name . "ast.AssignStmt.Pos()") (path . "go/ast/index#AssignStmt.Pos") (type . "go")) ((name . "ast.BadDecl") (path . "go/ast/index#BadDecl") (type . "go")) ((name . "ast.BadDecl.End()") (path . "go/ast/index#BadDecl.End") (type . "go")) ((name . "ast.BadDecl.Pos()") (path . "go/ast/index#BadDecl.Pos") (type . "go")) ((name . "ast.BadExpr") (path . "go/ast/index#BadExpr") (type . "go")) ((name . "ast.BadExpr.End()") (path . "go/ast/index#BadExpr.End") (type . "go")) ((name . "ast.BadExpr.Pos()") (path . "go/ast/index#BadExpr.Pos") (type . "go")) ((name . "ast.BadStmt") (path . "go/ast/index#BadStmt") (type . "go")) ((name . "ast.BadStmt.End()") (path . "go/ast/index#BadStmt.End") (type . "go")) ((name . "ast.BadStmt.Pos()") (path . "go/ast/index#BadStmt.Pos") (type . "go")) ((name . "ast.BasicLit") (path . "go/ast/index#BasicLit") (type . "go")) ((name . "ast.BasicLit.End()") (path . "go/ast/index#BasicLit.End") (type . "go")) ((name . "ast.BasicLit.Pos()") (path . "go/ast/index#BasicLit.Pos") (type . "go")) ((name . "ast.BinaryExpr") (path . "go/ast/index#BinaryExpr") (type . "go")) ((name . "ast.BinaryExpr.End()") (path . "go/ast/index#BinaryExpr.End") (type . "go")) ((name . "ast.BinaryExpr.Pos()") (path . "go/ast/index#BinaryExpr.Pos") (type . "go")) ((name . "ast.BlockStmt") (path . "go/ast/index#BlockStmt") (type . "go")) ((name . "ast.BlockStmt.End()") (path . "go/ast/index#BlockStmt.End") (type . "go")) ((name . "ast.BlockStmt.Pos()") (path . "go/ast/index#BlockStmt.Pos") (type . "go")) ((name . "ast.BranchStmt") (path . "go/ast/index#BranchStmt") (type . "go")) ((name . "ast.BranchStmt.End()") (path . "go/ast/index#BranchStmt.End") (type . "go")) ((name . "ast.BranchStmt.Pos()") (path . "go/ast/index#BranchStmt.Pos") (type . "go")) ((name . "ast.CallExpr") (path . "go/ast/index#CallExpr") (type . "go")) ((name . "ast.CallExpr.End()") (path . "go/ast/index#CallExpr.End") (type . "go")) ((name . "ast.CallExpr.Pos()") (path . "go/ast/index#CallExpr.Pos") (type . "go")) ((name . "ast.CaseClause") (path . "go/ast/index#CaseClause") (type . "go")) ((name . "ast.CaseClause.End()") (path . "go/ast/index#CaseClause.End") (type . "go")) ((name . "ast.CaseClause.Pos()") (path . "go/ast/index#CaseClause.Pos") (type . "go")) ((name . "ast.ChanDir") (path . "go/ast/index#ChanDir") (type . "go")) ((name . "ast.ChanType") (path . "go/ast/index#ChanType") (type . "go")) ((name . "ast.ChanType.End()") (path . "go/ast/index#ChanType.End") (type . "go")) ((name . "ast.ChanType.Pos()") (path . "go/ast/index#ChanType.Pos") (type . "go")) ((name . "ast.CommClause") (path . "go/ast/index#CommClause") (type . "go")) ((name . "ast.CommClause.End()") (path . "go/ast/index#CommClause.End") (type . "go")) ((name . "ast.CommClause.Pos()") (path . "go/ast/index#CommClause.Pos") (type . "go")) ((name . "ast.Comment") (path . "go/ast/index#Comment") (type . "go")) ((name . "ast.Comment.End()") (path . "go/ast/index#Comment.End") (type . "go")) ((name . "ast.Comment.Pos()") (path . "go/ast/index#Comment.Pos") (type . "go")) ((name . "ast.CommentGroup") (path . "go/ast/index#CommentGroup") (type . "go")) ((name . "ast.CommentGroup.End()") (path . "go/ast/index#CommentGroup.End") (type . "go")) ((name . "ast.CommentGroup.Pos()") (path . "go/ast/index#CommentGroup.Pos") (type . "go")) ((name . "ast.CommentGroup.Text()") (path . "go/ast/index#CommentGroup.Text") (type . "go")) ((name . "ast.CommentMap") (path . "go/ast/index#CommentMap") (type . "go")) ((name . "ast.CommentMap.Comments()") (path . "go/ast/index#CommentMap.Comments") (type . "go")) ((name . "ast.CommentMap.Filter()") (path . "go/ast/index#CommentMap.Filter") (type . "go")) ((name . "ast.CommentMap.String()") (path . "go/ast/index#CommentMap.String") (type . "go")) ((name . "ast.CommentMap.Update()") (path . "go/ast/index#CommentMap.Update") (type . "go")) ((name . "ast.CompositeLit") (path . "go/ast/index#CompositeLit") (type . "go")) ((name . "ast.CompositeLit.End()") (path . "go/ast/index#CompositeLit.End") (type . "go")) ((name . "ast.CompositeLit.Pos()") (path . "go/ast/index#CompositeLit.Pos") (type . "go")) ((name . "ast.Decl") (path . "go/ast/index#Decl") (type . "go")) ((name . "ast.DeclStmt") (path . "go/ast/index#DeclStmt") (type . "go")) ((name . "ast.DeclStmt.End()") (path . "go/ast/index#DeclStmt.End") (type . "go")) ((name . "ast.DeclStmt.Pos()") (path . "go/ast/index#DeclStmt.Pos") (type . "go")) ((name . "ast.DeferStmt") (path . "go/ast/index#DeferStmt") (type . "go")) ((name . "ast.DeferStmt.End()") (path . "go/ast/index#DeferStmt.End") (type . "go")) ((name . "ast.DeferStmt.Pos()") (path . "go/ast/index#DeferStmt.Pos") (type . "go")) ((name . "ast.Ellipsis") (path . "go/ast/index#Ellipsis") (type . "go")) ((name . "ast.Ellipsis.End()") (path . "go/ast/index#Ellipsis.End") (type . "go")) ((name . "ast.Ellipsis.Pos()") (path . "go/ast/index#Ellipsis.Pos") (type . "go")) ((name . "ast.EmptyStmt") (path . "go/ast/index#EmptyStmt") (type . "go")) ((name . "ast.EmptyStmt.End()") (path . "go/ast/index#EmptyStmt.End") (type . "go")) ((name . "ast.EmptyStmt.Pos()") (path . "go/ast/index#EmptyStmt.Pos") (type . "go")) ((name . "ast.Expr") (path . "go/ast/index#Expr") (type . "go")) ((name . "ast.ExprStmt") (path . "go/ast/index#ExprStmt") (type . "go")) ((name . "ast.ExprStmt.End()") (path . "go/ast/index#ExprStmt.End") (type . "go")) ((name . "ast.ExprStmt.Pos()") (path . "go/ast/index#ExprStmt.Pos") (type . "go")) ((name . "ast.Field") (path . "go/ast/index#Field") (type . "go")) ((name . "ast.Field.End()") (path . "go/ast/index#Field.End") (type . "go")) ((name . "ast.Field.Pos()") (path . "go/ast/index#Field.Pos") (type . "go")) ((name . "ast.FieldFilter") (path . "go/ast/index#FieldFilter") (type . "go")) ((name . "ast.FieldList") (path . "go/ast/index#FieldList") (type . "go")) ((name . "ast.FieldList.End()") (path . "go/ast/index#FieldList.End") (type . "go")) ((name . "ast.FieldList.NumFields()") (path . "go/ast/index#FieldList.NumFields") (type . "go")) ((name . "ast.FieldList.Pos()") (path . "go/ast/index#FieldList.Pos") (type . "go")) ((name . "ast.File") (path . "go/ast/index#File") (type . "go")) ((name . "ast.File.End()") (path . "go/ast/index#File.End") (type . "go")) ((name . "ast.File.Pos()") (path . "go/ast/index#File.Pos") (type . "go")) ((name . "ast.FileExports()") (path . "go/ast/index#FileExports") (type . "go")) ((name . "ast.Filter") (path . "go/ast/index#Filter") (type . "go")) ((name . "ast.FilterDecl()") (path . "go/ast/index#FilterDecl") (type . "go")) ((name . "ast.FilterFile()") (path . "go/ast/index#FilterFile") (type . "go")) ((name . "ast.FilterPackage()") (path . "go/ast/index#FilterPackage") (type . "go")) ((name . "ast.ForStmt") (path . "go/ast/index#ForStmt") (type . "go")) ((name . "ast.ForStmt.End()") (path . "go/ast/index#ForStmt.End") (type . "go")) ((name . "ast.ForStmt.Pos()") (path . "go/ast/index#ForStmt.Pos") (type . "go")) ((name . "ast.Fprint()") (path . "go/ast/index#Fprint") (type . "go")) ((name . "ast.FuncDecl") (path . "go/ast/index#FuncDecl") (type . "go")) ((name . "ast.FuncDecl.End()") (path . "go/ast/index#FuncDecl.End") (type . "go")) ((name . "ast.FuncDecl.Pos()") (path . "go/ast/index#FuncDecl.Pos") (type . "go")) ((name . "ast.FuncLit") (path . "go/ast/index#FuncLit") (type . "go")) ((name . "ast.FuncLit.End()") (path . "go/ast/index#FuncLit.End") (type . "go")) ((name . "ast.FuncLit.Pos()") (path . "go/ast/index#FuncLit.Pos") (type . "go")) ((name . "ast.FuncType") (path . "go/ast/index#FuncType") (type . "go")) ((name . "ast.FuncType.End()") (path . "go/ast/index#FuncType.End") (type . "go")) ((name . "ast.FuncType.Pos()") (path . "go/ast/index#FuncType.Pos") (type . "go")) ((name . "ast.GenDecl") (path . "go/ast/index#GenDecl") (type . "go")) ((name . "ast.GenDecl.End()") (path . "go/ast/index#GenDecl.End") (type . "go")) ((name . "ast.GenDecl.Pos()") (path . "go/ast/index#GenDecl.Pos") (type . "go")) ((name . "ast.GoStmt") (path . "go/ast/index#GoStmt") (type . "go")) ((name . "ast.GoStmt.End()") (path . "go/ast/index#GoStmt.End") (type . "go")) ((name . "ast.GoStmt.Pos()") (path . "go/ast/index#GoStmt.Pos") (type . "go")) ((name . "ast.Ident") (path . "go/ast/index#Ident") (type . "go")) ((name . "ast.Ident.End()") (path . "go/ast/index#Ident.End") (type . "go")) ((name . "ast.Ident.IsExported()") (path . "go/ast/index#Ident.IsExported") (type . "go")) ((name . "ast.Ident.Pos()") (path . "go/ast/index#Ident.Pos") (type . "go")) ((name . "ast.Ident.String()") (path . "go/ast/index#Ident.String") (type . "go")) ((name . "ast.IfStmt") (path . "go/ast/index#IfStmt") (type . "go")) ((name . "ast.IfStmt.End()") (path . "go/ast/index#IfStmt.End") (type . "go")) ((name . "ast.IfStmt.Pos()") (path . "go/ast/index#IfStmt.Pos") (type . "go")) ((name . "ast.Importer") (path . "go/ast/index#Importer") (type . "go")) ((name . "ast.ImportSpec") (path . "go/ast/index#ImportSpec") (type . "go")) ((name . "ast.ImportSpec.End()") (path . "go/ast/index#ImportSpec.End") (type . "go")) ((name . "ast.ImportSpec.Pos()") (path . "go/ast/index#ImportSpec.Pos") (type . "go")) ((name . "ast.IncDecStmt") (path . "go/ast/index#IncDecStmt") (type . "go")) ((name . "ast.IncDecStmt.End()") (path . "go/ast/index#IncDecStmt.End") (type . "go")) ((name . "ast.IncDecStmt.Pos()") (path . "go/ast/index#IncDecStmt.Pos") (type . "go")) ((name . "ast.IndexExpr") (path . "go/ast/index#IndexExpr") (type . "go")) ((name . "ast.IndexExpr.End()") (path . "go/ast/index#IndexExpr.End") (type . "go")) ((name . "ast.IndexExpr.Pos()") (path . "go/ast/index#IndexExpr.Pos") (type . "go")) ((name . "ast.IndexListExpr") (path . "go/ast/index#IndexListExpr") (type . "go")) ((name . "ast.IndexListExpr.End()") (path . "go/ast/index#IndexListExpr.End") (type . "go")) ((name . "ast.IndexListExpr.Pos()") (path . "go/ast/index#IndexListExpr.Pos") (type . "go")) ((name . "ast.Inspect()") (path . "go/ast/index#Inspect") (type . "go")) ((name . "ast.InterfaceType") (path . "go/ast/index#InterfaceType") (type . "go")) ((name . "ast.InterfaceType.End()") (path . "go/ast/index#InterfaceType.End") (type . "go")) ((name . "ast.InterfaceType.Pos()") (path . "go/ast/index#InterfaceType.Pos") (type . "go")) ((name . "ast.IsExported()") (path . "go/ast/index#IsExported") (type . "go")) ((name . "ast.IsGenerated()") (path . "go/ast/index#IsGenerated") (type . "go")) ((name . "ast.KeyValueExpr") (path . "go/ast/index#KeyValueExpr") (type . "go")) ((name . "ast.KeyValueExpr.End()") (path . "go/ast/index#KeyValueExpr.End") (type . "go")) ((name . "ast.KeyValueExpr.Pos()") (path . "go/ast/index#KeyValueExpr.Pos") (type . "go")) ((name . "ast.LabeledStmt") (path . "go/ast/index#LabeledStmt") (type . "go")) ((name . "ast.LabeledStmt.End()") (path . "go/ast/index#LabeledStmt.End") (type . "go")) ((name . "ast.LabeledStmt.Pos()") (path . "go/ast/index#LabeledStmt.Pos") (type . "go")) ((name . "ast.MapType") (path . "go/ast/index#MapType") (type . "go")) ((name . "ast.MapType.End()") (path . "go/ast/index#MapType.End") (type . "go")) ((name . "ast.MapType.Pos()") (path . "go/ast/index#MapType.Pos") (type . "go")) ((name . "ast.MergeMode") (path . "go/ast/index#MergeMode") (type . "go")) ((name . "ast.MergePackageFiles()") (path . "go/ast/index#MergePackageFiles") (type . "go")) ((name . "ast.NewCommentMap()") (path . "go/ast/index#NewCommentMap") (type . "go")) ((name . "ast.NewIdent()") (path . "go/ast/index#NewIdent") (type . "go")) ((name . "ast.NewObj()") (path . "go/ast/index#NewObj") (type . "go")) ((name . "ast.NewPackage()") (path . "go/ast/index#NewPackage") (type . "go")) ((name . "ast.NewScope()") (path . "go/ast/index#NewScope") (type . "go")) ((name . "ast.Node") (path . "go/ast/index#Node") (type . "go")) ((name . "ast.NotNilFilter()") (path . "go/ast/index#NotNilFilter") (type . "go")) ((name . "ast.Object") (path . "go/ast/index#Object") (type . "go")) ((name . "ast.Object.Pos()") (path . "go/ast/index#Object.Pos") (type . "go")) ((name . "ast.ObjKind") (path . "go/ast/index#ObjKind") (type . "go")) ((name . "ast.ObjKind.String()") (path . "go/ast/index#ObjKind.String") (type . "go")) ((name . "ast.Package") (path . "go/ast/index#Package") (type . "go")) ((name . "ast.Package.End()") (path . "go/ast/index#Package.End") (type . "go")) ((name . "ast.Package.Pos()") (path . "go/ast/index#Package.Pos") (type . "go")) ((name . "ast.PackageExports()") (path . "go/ast/index#PackageExports") (type . "go")) ((name . "ast.ParenExpr") (path . "go/ast/index#ParenExpr") (type . "go")) ((name . "ast.ParenExpr.End()") (path . "go/ast/index#ParenExpr.End") (type . "go")) ((name . "ast.ParenExpr.Pos()") (path . "go/ast/index#ParenExpr.Pos") (type . "go")) ((name . "ast.Print()") (path . "go/ast/index#Print") (type . "go")) ((name . "ast.RangeStmt") (path . "go/ast/index#RangeStmt") (type . "go")) ((name . "ast.RangeStmt.End()") (path . "go/ast/index#RangeStmt.End") (type . "go")) ((name . "ast.RangeStmt.Pos()") (path . "go/ast/index#RangeStmt.Pos") (type . "go")) ((name . "ast.ReturnStmt") (path . "go/ast/index#ReturnStmt") (type . "go")) ((name . "ast.ReturnStmt.End()") (path . "go/ast/index#ReturnStmt.End") (type . "go")) ((name . "ast.ReturnStmt.Pos()") (path . "go/ast/index#ReturnStmt.Pos") (type . "go")) ((name . "ast.Scope") (path . "go/ast/index#Scope") (type . "go")) ((name . "ast.Scope.Insert()") (path . "go/ast/index#Scope.Insert") (type . "go")) ((name . "ast.Scope.Lookup()") (path . "go/ast/index#Scope.Lookup") (type . "go")) ((name . "ast.Scope.String()") (path . "go/ast/index#Scope.String") (type . "go")) ((name . "ast.SelectorExpr") (path . "go/ast/index#SelectorExpr") (type . "go")) ((name . "ast.SelectorExpr.End()") (path . "go/ast/index#SelectorExpr.End") (type . "go")) ((name . "ast.SelectorExpr.Pos()") (path . "go/ast/index#SelectorExpr.Pos") (type . "go")) ((name . "ast.SelectStmt") (path . "go/ast/index#SelectStmt") (type . "go")) ((name . "ast.SelectStmt.End()") (path . "go/ast/index#SelectStmt.End") (type . "go")) ((name . "ast.SelectStmt.Pos()") (path . "go/ast/index#SelectStmt.Pos") (type . "go")) ((name . "ast.SendStmt") (path . "go/ast/index#SendStmt") (type . "go")) ((name . "ast.SendStmt.End()") (path . "go/ast/index#SendStmt.End") (type . "go")) ((name . "ast.SendStmt.Pos()") (path . "go/ast/index#SendStmt.Pos") (type . "go")) ((name . "ast.SliceExpr") (path . "go/ast/index#SliceExpr") (type . "go")) ((name . "ast.SliceExpr.End()") (path . "go/ast/index#SliceExpr.End") (type . "go")) ((name . "ast.SliceExpr.Pos()") (path . "go/ast/index#SliceExpr.Pos") (type . "go")) ((name . "ast.SortImports()") (path . "go/ast/index#SortImports") (type . "go")) ((name . "ast.Spec") (path . "go/ast/index#Spec") (type . "go")) ((name . "ast.StarExpr") (path . "go/ast/index#StarExpr") (type . "go")) ((name . "ast.StarExpr.End()") (path . "go/ast/index#StarExpr.End") (type . "go")) ((name . "ast.StarExpr.Pos()") (path . "go/ast/index#StarExpr.Pos") (type . "go")) ((name . "ast.Stmt") (path . "go/ast/index#Stmt") (type . "go")) ((name . "ast.StructType") (path . "go/ast/index#StructType") (type . "go")) ((name . "ast.StructType.End()") (path . "go/ast/index#StructType.End") (type . "go")) ((name . "ast.StructType.Pos()") (path . "go/ast/index#StructType.Pos") (type . "go")) ((name . "ast.SwitchStmt") (path . "go/ast/index#SwitchStmt") (type . "go")) ((name . "ast.SwitchStmt.End()") (path . "go/ast/index#SwitchStmt.End") (type . "go")) ((name . "ast.SwitchStmt.Pos()") (path . "go/ast/index#SwitchStmt.Pos") (type . "go")) ((name . "ast.TypeAssertExpr") (path . "go/ast/index#TypeAssertExpr") (type . "go")) ((name . "ast.TypeAssertExpr.End()") (path . "go/ast/index#TypeAssertExpr.End") (type . "go")) ((name . "ast.TypeAssertExpr.Pos()") (path . "go/ast/index#TypeAssertExpr.Pos") (type . "go")) ((name . "ast.TypeSpec") (path . "go/ast/index#TypeSpec") (type . "go")) ((name . "ast.TypeSpec.End()") (path . "go/ast/index#TypeSpec.End") (type . "go")) ((name . "ast.TypeSpec.Pos()") (path . "go/ast/index#TypeSpec.Pos") (type . "go")) ((name . "ast.TypeSwitchStmt") (path . "go/ast/index#TypeSwitchStmt") (type . "go")) ((name . "ast.TypeSwitchStmt.End()") (path . "go/ast/index#TypeSwitchStmt.End") (type . "go")) ((name . "ast.TypeSwitchStmt.Pos()") (path . "go/ast/index#TypeSwitchStmt.Pos") (type . "go")) ((name . "ast.UnaryExpr") (path . "go/ast/index#UnaryExpr") (type . "go")) ((name . "ast.UnaryExpr.End()") (path . "go/ast/index#UnaryExpr.End") (type . "go")) ((name . "ast.UnaryExpr.Pos()") (path . "go/ast/index#UnaryExpr.Pos") (type . "go")) ((name . "ast.Unparen()") (path . "go/ast/index#Unparen") (type . "go")) ((name . "ast.ValueSpec") (path . "go/ast/index#ValueSpec") (type . "go")) ((name . "ast.ValueSpec.End()") (path . "go/ast/index#ValueSpec.End") (type . "go")) ((name . "ast.ValueSpec.Pos()") (path . "go/ast/index#ValueSpec.Pos") (type . "go")) ((name . "ast.Visitor") (path . "go/ast/index#Visitor") (type . "go")) ((name . "ast.Walk()") (path . "go/ast/index#Walk") (type . "go")) ((name . "atomic.AddInt32()") (path . "sync/atomic/index#AddInt32") (type . "sync")) ((name . "atomic.AddInt64()") (path . "sync/atomic/index#AddInt64") (type . "sync")) ((name . "atomic.AddUint32()") (path . "sync/atomic/index#AddUint32") (type . "sync")) ((name . "atomic.AddUint64()") (path . "sync/atomic/index#AddUint64") (type . "sync")) ((name . "atomic.AddUintptr()") (path . "sync/atomic/index#AddUintptr") (type . "sync")) ((name . "atomic.Bool") (path . "sync/atomic/index#Bool") (type . "sync")) ((name . "atomic.Bool.CompareAndSwap()") (path . "sync/atomic/index#Bool.CompareAndSwap") (type . "sync")) ((name . "atomic.Bool.Load()") (path . "sync/atomic/index#Bool.Load") (type . "sync")) ((name . "atomic.Bool.Store()") (path . "sync/atomic/index#Bool.Store") (type . "sync")) ((name . "atomic.Bool.Swap()") (path . "sync/atomic/index#Bool.Swap") (type . "sync")) ((name . "atomic.CompareAndSwapInt32()") (path . "sync/atomic/index#CompareAndSwapInt32") (type . "sync")) ((name . "atomic.CompareAndSwapInt64()") (path . "sync/atomic/index#CompareAndSwapInt64") (type . "sync")) ((name . "atomic.CompareAndSwapPointer()") (path . "sync/atomic/index#CompareAndSwapPointer") (type . "sync")) ((name . "atomic.CompareAndSwapUint32()") (path . "sync/atomic/index#CompareAndSwapUint32") (type . "sync")) ((name . "atomic.CompareAndSwapUint64()") (path . "sync/atomic/index#CompareAndSwapUint64") (type . "sync")) ((name . "atomic.CompareAndSwapUintptr()") (path . "sync/atomic/index#CompareAndSwapUintptr") (type . "sync")) ((name . "atomic.Int32") (path . "sync/atomic/index#Int32") (type . "sync")) ((name . "atomic.Int32.Add()") (path . "sync/atomic/index#Int32.Add") (type . "sync")) ((name . "atomic.Int32.CompareAndSwap()") (path . "sync/atomic/index#Int32.CompareAndSwap") (type . "sync")) ((name . "atomic.Int32.Load()") (path . "sync/atomic/index#Int32.Load") (type . "sync")) ((name . "atomic.Int32.Store()") (path . "sync/atomic/index#Int32.Store") (type . "sync")) ((name . "atomic.Int32.Swap()") (path . "sync/atomic/index#Int32.Swap") (type . "sync")) ((name . "atomic.Int64") (path . "sync/atomic/index#Int64") (type . "sync")) ((name . "atomic.Int64.Add()") (path . "sync/atomic/index#Int64.Add") (type . "sync")) ((name . "atomic.Int64.CompareAndSwap()") (path . "sync/atomic/index#Int64.CompareAndSwap") (type . "sync")) ((name . "atomic.Int64.Load()") (path . "sync/atomic/index#Int64.Load") (type . "sync")) ((name . "atomic.Int64.Store()") (path . "sync/atomic/index#Int64.Store") (type . "sync")) ((name . "atomic.Int64.Swap()") (path . "sync/atomic/index#Int64.Swap") (type . "sync")) ((name . "atomic.LoadInt32()") (path . "sync/atomic/index#LoadInt32") (type . "sync")) ((name . "atomic.LoadInt64()") (path . "sync/atomic/index#LoadInt64") (type . "sync")) ((name . "atomic.LoadPointer()") (path . "sync/atomic/index#LoadPointer") (type . "sync")) ((name . "atomic.LoadUint32()") (path . "sync/atomic/index#LoadUint32") (type . "sync")) ((name . "atomic.LoadUint64()") (path . "sync/atomic/index#LoadUint64") (type . "sync")) ((name . "atomic.LoadUintptr()") (path . "sync/atomic/index#LoadUintptr") (type . "sync")) ((name . "atomic.Pointer") (path . "sync/atomic/index#Pointer") (type . "sync")) ((name . "atomic.Pointer.CompareAndSwap()") (path . "sync/atomic/index#Pointer.CompareAndSwap") (type . "sync")) ((name . "atomic.Pointer.Load()") (path . "sync/atomic/index#Pointer.Load") (type . "sync")) ((name . "atomic.Pointer.Store()") (path . "sync/atomic/index#Pointer.Store") (type . "sync")) ((name . "atomic.Pointer.Swap()") (path . "sync/atomic/index#Pointer.Swap") (type . "sync")) ((name . "atomic.StoreInt32()") (path . "sync/atomic/index#StoreInt32") (type . "sync")) ((name . "atomic.StoreInt64()") (path . "sync/atomic/index#StoreInt64") (type . "sync")) ((name . "atomic.StorePointer()") (path . "sync/atomic/index#StorePointer") (type . "sync")) ((name . "atomic.StoreUint32()") (path . "sync/atomic/index#StoreUint32") (type . "sync")) ((name . "atomic.StoreUint64()") (path . "sync/atomic/index#StoreUint64") (type . "sync")) ((name . "atomic.StoreUintptr()") (path . "sync/atomic/index#StoreUintptr") (type . "sync")) ((name . "atomic.SwapInt32()") (path . "sync/atomic/index#SwapInt32") (type . "sync")) ((name . "atomic.SwapInt64()") (path . "sync/atomic/index#SwapInt64") (type . "sync")) ((name . "atomic.SwapPointer()") (path . "sync/atomic/index#SwapPointer") (type . "sync")) ((name . "atomic.SwapUint32()") (path . "sync/atomic/index#SwapUint32") (type . "sync")) ((name . "atomic.SwapUint64()") (path . "sync/atomic/index#SwapUint64") (type . "sync")) ((name . "atomic.SwapUintptr()") (path . "sync/atomic/index#SwapUintptr") (type . "sync")) ((name . "atomic.Uint32") (path . "sync/atomic/index#Uint32") (type . "sync")) ((name . "atomic.Uint32.Add()") (path . "sync/atomic/index#Uint32.Add") (type . "sync")) ((name . "atomic.Uint32.CompareAndSwap()") (path . "sync/atomic/index#Uint32.CompareAndSwap") (type . "sync")) ((name . "atomic.Uint32.Load()") (path . "sync/atomic/index#Uint32.Load") (type . "sync")) ((name . "atomic.Uint32.Store()") (path . "sync/atomic/index#Uint32.Store") (type . "sync")) ((name . "atomic.Uint32.Swap()") (path . "sync/atomic/index#Uint32.Swap") (type . "sync")) ((name . "atomic.Uint64") (path . "sync/atomic/index#Uint64") (type . "sync")) ((name . "atomic.Uint64.Add()") (path . "sync/atomic/index#Uint64.Add") (type . "sync")) ((name . "atomic.Uint64.CompareAndSwap()") (path . "sync/atomic/index#Uint64.CompareAndSwap") (type . "sync")) ((name . "atomic.Uint64.Load()") (path . "sync/atomic/index#Uint64.Load") (type . "sync")) ((name . "atomic.Uint64.Store()") (path . "sync/atomic/index#Uint64.Store") (type . "sync")) ((name . "atomic.Uint64.Swap()") (path . "sync/atomic/index#Uint64.Swap") (type . "sync")) ((name . "atomic.Uintptr") (path . "sync/atomic/index#Uintptr") (type . "sync")) ((name . "atomic.Uintptr.Add()") (path . "sync/atomic/index#Uintptr.Add") (type . "sync")) ((name . "atomic.Uintptr.CompareAndSwap()") (path . "sync/atomic/index#Uintptr.CompareAndSwap") (type . "sync")) ((name . "atomic.Uintptr.Load()") (path . "sync/atomic/index#Uintptr.Load") (type . "sync")) ((name . "atomic.Uintptr.Store()") (path . "sync/atomic/index#Uintptr.Store") (type . "sync")) ((name . "atomic.Uintptr.Swap()") (path . "sync/atomic/index#Uintptr.Swap") (type . "sync")) ((name . "atomic.Value") (path . "sync/atomic/index#Value") (type . "sync")) ((name . "atomic.Value.CompareAndSwap()") (path . "sync/atomic/index#Value.CompareAndSwap") (type . "sync")) ((name . "atomic.Value.Load()") (path . "sync/atomic/index#Value.Load") (type . "sync")) ((name . "atomic.Value.Store()") (path . "sync/atomic/index#Value.Store") (type . "sync")) ((name . "atomic.Value.Swap()") (path . "sync/atomic/index#Value.Swap") (type . "sync")) ((name . "base32.CorruptInputError") (path . "encoding/base32/index#CorruptInputError") (type . "encoding")) ((name . "base32.CorruptInputError.Error()") (path . "encoding/base32/index#CorruptInputError.Error") (type . "encoding")) ((name . "base32.Encoding") (path . "encoding/base32/index#Encoding") (type . "encoding")) ((name . "base32.Encoding.AppendDecode()") (path . "encoding/base32/index#Encoding.AppendDecode") (type . "encoding")) ((name . "base32.Encoding.AppendEncode()") (path . "encoding/base32/index#Encoding.AppendEncode") (type . "encoding")) ((name . "base32.Encoding.Decode()") (path . "encoding/base32/index#Encoding.Decode") (type . "encoding")) ((name . "base32.Encoding.DecodedLen()") (path . "encoding/base32/index#Encoding.DecodedLen") (type . "encoding")) ((name . "base32.Encoding.DecodeString()") (path . "encoding/base32/index#Encoding.DecodeString") (type . "encoding")) ((name . "base32.Encoding.Encode()") (path . "encoding/base32/index#Encoding.Encode") (type . "encoding")) ((name . "base32.Encoding.EncodedLen()") (path . "encoding/base32/index#Encoding.EncodedLen") (type . "encoding")) ((name . "base32.Encoding.EncodeToString()") (path . "encoding/base32/index#Encoding.EncodeToString") (type . "encoding")) ((name . "base32.Encoding.WithPadding()") (path . "encoding/base32/index#Encoding.WithPadding") (type . "encoding")) ((name . "base32.NewDecoder()") (path . "encoding/base32/index#NewDecoder") (type . "encoding")) ((name . "base32.NewEncoder()") (path . "encoding/base32/index#NewEncoder") (type . "encoding")) ((name . "base32.NewEncoding()") (path . "encoding/base32/index#NewEncoding") (type . "encoding")) ((name . "base64.CorruptInputError") (path . "encoding/base64/index#CorruptInputError") (type . "encoding")) ((name . "base64.CorruptInputError.Error()") (path . "encoding/base64/index#CorruptInputError.Error") (type . "encoding")) ((name . "base64.Encoding") (path . "encoding/base64/index#Encoding") (type . "encoding")) ((name . "base64.Encoding.AppendDecode()") (path . "encoding/base64/index#Encoding.AppendDecode") (type . "encoding")) ((name . "base64.Encoding.AppendEncode()") (path . "encoding/base64/index#Encoding.AppendEncode") (type . "encoding")) ((name . "base64.Encoding.Decode()") (path . "encoding/base64/index#Encoding.Decode") (type . "encoding")) ((name . "base64.Encoding.DecodedLen()") (path . "encoding/base64/index#Encoding.DecodedLen") (type . "encoding")) ((name . "base64.Encoding.DecodeString()") (path . "encoding/base64/index#Encoding.DecodeString") (type . "encoding")) ((name . "base64.Encoding.Encode()") (path . "encoding/base64/index#Encoding.Encode") (type . "encoding")) ((name . "base64.Encoding.EncodedLen()") (path . "encoding/base64/index#Encoding.EncodedLen") (type . "encoding")) ((name . "base64.Encoding.EncodeToString()") (path . "encoding/base64/index#Encoding.EncodeToString") (type . "encoding")) ((name . "base64.Encoding.Strict()") (path . "encoding/base64/index#Encoding.Strict") (type . "encoding")) ((name . "base64.Encoding.WithPadding()") (path . "encoding/base64/index#Encoding.WithPadding") (type . "encoding")) ((name . "base64.NewDecoder()") (path . "encoding/base64/index#NewDecoder") (type . "encoding")) ((name . "base64.NewEncoder()") (path . "encoding/base64/index#NewEncoder") (type . "encoding")) ((name . "base64.NewEncoding()") (path . "encoding/base64/index#NewEncoding") (type . "encoding")) ((name . "big.Accuracy") (path . "math/big/index#Accuracy") (type . "math/big")) ((name . "big.Accuracy.String()") (path . "math/big/index#Accuracy.String") (type . "math/big")) ((name . "big.ErrNaN") (path . "math/big/index#ErrNaN") (type . "math/big")) ((name . "big.ErrNaN.Error()") (path . "math/big/index#ErrNaN.Error") (type . "math/big")) ((name . "big.Float") (path . "math/big/index#Float") (type . "math/big")) ((name . "big.Float.Abs()") (path . "math/big/index#Float.Abs") (type . "math/big")) ((name . "big.Float.Acc()") (path . "math/big/index#Float.Acc") (type . "math/big")) ((name . "big.Float.Add()") (path . "math/big/index#Float.Add") (type . "math/big")) ((name . "big.Float.Append()") (path . "math/big/index#Float.Append") (type . "math/big")) ((name . "big.Float.Cmp()") (path . "math/big/index#Float.Cmp") (type . "math/big")) ((name . "big.Float.Copy()") (path . "math/big/index#Float.Copy") (type . "math/big")) ((name . "big.Float.Float32()") (path . "math/big/index#Float.Float32") (type . "math/big")) ((name . "big.Float.Float64()") (path . "math/big/index#Float.Float64") (type . "math/big")) ((name . "big.Float.Format()") (path . "math/big/index#Float.Format") (type . "math/big")) ((name . "big.Float.GobDecode()") (path . "math/big/index#Float.GobDecode") (type . "math/big")) ((name . "big.Float.GobEncode()") (path . "math/big/index#Float.GobEncode") (type . "math/big")) ((name . "big.Float.Int()") (path . "math/big/index#Float.Int") (type . "math/big")) ((name . "big.Float.Int64()") (path . "math/big/index#Float.Int64") (type . "math/big")) ((name . "big.Float.IsInf()") (path . "math/big/index#Float.IsInf") (type . "math/big")) ((name . "big.Float.IsInt()") (path . "math/big/index#Float.IsInt") (type . "math/big")) ((name . "big.Float.MantExp()") (path . "math/big/index#Float.MantExp") (type . "math/big")) ((name . "big.Float.MarshalText()") (path . "math/big/index#Float.MarshalText") (type . "math/big")) ((name . "big.Float.MinPrec()") (path . "math/big/index#Float.MinPrec") (type . "math/big")) ((name . "big.Float.Mode()") (path . "math/big/index#Float.Mode") (type . "math/big")) ((name . "big.Float.Mul()") (path . "math/big/index#Float.Mul") (type . "math/big")) ((name . "big.Float.Neg()") (path . "math/big/index#Float.Neg") (type . "math/big")) ((name . "big.Float.Parse()") (path . "math/big/index#Float.Parse") (type . "math/big")) ((name . "big.Float.Prec()") (path . "math/big/index#Float.Prec") (type . "math/big")) ((name . "big.Float.Quo()") (path . "math/big/index#Float.Quo") (type . "math/big")) ((name . "big.Float.Rat()") (path . "math/big/index#Float.Rat") (type . "math/big")) ((name . "big.Float.Scan()") (path . "math/big/index#Float.Scan") (type . "math/big")) ((name . "big.Float.Set()") (path . "math/big/index#Float.Set") (type . "math/big")) ((name . "big.Float.SetFloat64()") (path . "math/big/index#Float.SetFloat64") (type . "math/big")) ((name . "big.Float.SetInf()") (path . "math/big/index#Float.SetInf") (type . "math/big")) ((name . "big.Float.SetInt()") (path . "math/big/index#Float.SetInt") (type . "math/big")) ((name . "big.Float.SetInt64()") (path . "math/big/index#Float.SetInt64") (type . "math/big")) ((name . "big.Float.SetMantExp()") (path . "math/big/index#Float.SetMantExp") (type . "math/big")) ((name . "big.Float.SetMode()") (path . "math/big/index#Float.SetMode") (type . "math/big")) ((name . "big.Float.SetPrec()") (path . "math/big/index#Float.SetPrec") (type . "math/big")) ((name . "big.Float.SetRat()") (path . "math/big/index#Float.SetRat") (type . "math/big")) ((name . "big.Float.SetString()") (path . "math/big/index#Float.SetString") (type . "math/big")) ((name . "big.Float.SetUint64()") (path . "math/big/index#Float.SetUint64") (type . "math/big")) ((name . "big.Float.Sign()") (path . "math/big/index#Float.Sign") (type . "math/big")) ((name . "big.Float.Signbit()") (path . "math/big/index#Float.Signbit") (type . "math/big")) ((name . "big.Float.Sqrt()") (path . "math/big/index#Float.Sqrt") (type . "math/big")) ((name . "big.Float.String()") (path . "math/big/index#Float.String") (type . "math/big")) ((name . "big.Float.Sub()") (path . "math/big/index#Float.Sub") (type . "math/big")) ((name . "big.Float.Text()") (path . "math/big/index#Float.Text") (type . "math/big")) ((name . "big.Float.Uint64()") (path . "math/big/index#Float.Uint64") (type . "math/big")) ((name . "big.Float.UnmarshalText()") (path . "math/big/index#Float.UnmarshalText") (type . "math/big")) ((name . "big.Int") (path . "math/big/index#Int") (type . "math/big")) ((name . "big.Int.Abs()") (path . "math/big/index#Int.Abs") (type . "math/big")) ((name . "big.Int.Add()") (path . "math/big/index#Int.Add") (type . "math/big")) ((name . "big.Int.And()") (path . "math/big/index#Int.And") (type . "math/big")) ((name . "big.Int.AndNot()") (path . "math/big/index#Int.AndNot") (type . "math/big")) ((name . "big.Int.Append()") (path . "math/big/index#Int.Append") (type . "math/big")) ((name . "big.Int.Binomial()") (path . "math/big/index#Int.Binomial") (type . "math/big")) ((name . "big.Int.Bit()") (path . "math/big/index#Int.Bit") (type . "math/big")) ((name . "big.Int.BitLen()") (path . "math/big/index#Int.BitLen") (type . "math/big")) ((name . "big.Int.Bits()") (path . "math/big/index#Int.Bits") (type . "math/big")) ((name . "big.Int.Bytes()") (path . "math/big/index#Int.Bytes") (type . "math/big")) ((name . "big.Int.Cmp()") (path . "math/big/index#Int.Cmp") (type . "math/big")) ((name . "big.Int.CmpAbs()") (path . "math/big/index#Int.CmpAbs") (type . "math/big")) ((name . "big.Int.Div()") (path . "math/big/index#Int.Div") (type . "math/big")) ((name . "big.Int.DivMod()") (path . "math/big/index#Int.DivMod") (type . "math/big")) ((name . "big.Int.Exp()") (path . "math/big/index#Int.Exp") (type . "math/big")) ((name . "big.Int.FillBytes()") (path . "math/big/index#Int.FillBytes") (type . "math/big")) ((name . "big.Int.Float64()") (path . "math/big/index#Int.Float64") (type . "math/big")) ((name . "big.Int.Format()") (path . "math/big/index#Int.Format") (type . "math/big")) ((name . "big.Int.GCD()") (path . "math/big/index#Int.GCD") (type . "math/big")) ((name . "big.Int.GobDecode()") (path . "math/big/index#Int.GobDecode") (type . "math/big")) ((name . "big.Int.GobEncode()") (path . "math/big/index#Int.GobEncode") (type . "math/big")) ((name . "big.Int.Int64()") (path . "math/big/index#Int.Int64") (type . "math/big")) ((name . "big.Int.IsInt64()") (path . "math/big/index#Int.IsInt64") (type . "math/big")) ((name . "big.Int.IsUint64()") (path . "math/big/index#Int.IsUint64") (type . "math/big")) ((name . "big.Int.Lsh()") (path . "math/big/index#Int.Lsh") (type . "math/big")) ((name . "big.Int.MarshalJSON()") (path . "math/big/index#Int.MarshalJSON") (type . "math/big")) ((name . "big.Int.MarshalText()") (path . "math/big/index#Int.MarshalText") (type . "math/big")) ((name . "big.Int.Mod()") (path . "math/big/index#Int.Mod") (type . "math/big")) ((name . "big.Int.ModInverse()") (path . "math/big/index#Int.ModInverse") (type . "math/big")) ((name . "big.Int.ModSqrt()") (path . "math/big/index#Int.ModSqrt") (type . "math/big")) ((name . "big.Int.Mul()") (path . "math/big/index#Int.Mul") (type . "math/big")) ((name . "big.Int.MulRange()") (path . "math/big/index#Int.MulRange") (type . "math/big")) ((name . "big.Int.Neg()") (path . "math/big/index#Int.Neg") (type . "math/big")) ((name . "big.Int.Not()") (path . "math/big/index#Int.Not") (type . "math/big")) ((name . "big.Int.Or()") (path . "math/big/index#Int.Or") (type . "math/big")) ((name . "big.Int.ProbablyPrime()") (path . "math/big/index#Int.ProbablyPrime") (type . "math/big")) ((name . "big.Int.Quo()") (path . "math/big/index#Int.Quo") (type . "math/big")) ((name . "big.Int.QuoRem()") (path . "math/big/index#Int.QuoRem") (type . "math/big")) ((name . "big.Int.Rand()") (path . "math/big/index#Int.Rand") (type . "math/big")) ((name . "big.Int.Rem()") (path . "math/big/index#Int.Rem") (type . "math/big")) ((name . "big.Int.Rsh()") (path . "math/big/index#Int.Rsh") (type . "math/big")) ((name . "big.Int.Scan()") (path . "math/big/index#Int.Scan") (type . "math/big")) ((name . "big.Int.Set()") (path . "math/big/index#Int.Set") (type . "math/big")) ((name . "big.Int.SetBit()") (path . "math/big/index#Int.SetBit") (type . "math/big")) ((name . "big.Int.SetBits()") (path . "math/big/index#Int.SetBits") (type . "math/big")) ((name . "big.Int.SetBytes()") (path . "math/big/index#Int.SetBytes") (type . "math/big")) ((name . "big.Int.SetInt64()") (path . "math/big/index#Int.SetInt64") (type . "math/big")) ((name . "big.Int.SetString()") (path . "math/big/index#Int.SetString") (type . "math/big")) ((name . "big.Int.SetUint64()") (path . "math/big/index#Int.SetUint64") (type . "math/big")) ((name . "big.Int.Sign()") (path . "math/big/index#Int.Sign") (type . "math/big")) ((name . "big.Int.Sqrt()") (path . "math/big/index#Int.Sqrt") (type . "math/big")) ((name . "big.Int.String()") (path . "math/big/index#Int.String") (type . "math/big")) ((name . "big.Int.Sub()") (path . "math/big/index#Int.Sub") (type . "math/big")) ((name . "big.Int.Text()") (path . "math/big/index#Int.Text") (type . "math/big")) ((name . "big.Int.TrailingZeroBits()") (path . "math/big/index#Int.TrailingZeroBits") (type . "math/big")) ((name . "big.Int.Uint64()") (path . "math/big/index#Int.Uint64") (type . "math/big")) ((name . "big.Int.UnmarshalJSON()") (path . "math/big/index#Int.UnmarshalJSON") (type . "math/big")) ((name . "big.Int.UnmarshalText()") (path . "math/big/index#Int.UnmarshalText") (type . "math/big")) ((name . "big.Int.Xor()") (path . "math/big/index#Int.Xor") (type . "math/big")) ((name . "big.Jacobi()") (path . "math/big/index#Jacobi") (type . "math/big")) ((name . "big.NewFloat()") (path . "math/big/index#NewFloat") (type . "math/big")) ((name . "big.NewInt()") (path . "math/big/index#NewInt") (type . "math/big")) ((name . "big.NewRat()") (path . "math/big/index#NewRat") (type . "math/big")) ((name . "big.ParseFloat()") (path . "math/big/index#ParseFloat") (type . "math/big")) ((name . "big.Rat") (path . "math/big/index#Rat") (type . "math/big")) ((name . "big.Rat.Abs()") (path . "math/big/index#Rat.Abs") (type . "math/big")) ((name . "big.Rat.Add()") (path . "math/big/index#Rat.Add") (type . "math/big")) ((name . "big.Rat.Cmp()") (path . "math/big/index#Rat.Cmp") (type . "math/big")) ((name . "big.Rat.Denom()") (path . "math/big/index#Rat.Denom") (type . "math/big")) ((name . "big.Rat.Float32()") (path . "math/big/index#Rat.Float32") (type . "math/big")) ((name . "big.Rat.Float64()") (path . "math/big/index#Rat.Float64") (type . "math/big")) ((name . "big.Rat.FloatPrec()") (path . "math/big/index#Rat.FloatPrec") (type . "math/big")) ((name . "big.Rat.FloatString()") (path . "math/big/index#Rat.FloatString") (type . "math/big")) ((name . "big.Rat.GobDecode()") (path . "math/big/index#Rat.GobDecode") (type . "math/big")) ((name . "big.Rat.GobEncode()") (path . "math/big/index#Rat.GobEncode") (type . "math/big")) ((name . "big.Rat.Inv()") (path . "math/big/index#Rat.Inv") (type . "math/big")) ((name . "big.Rat.IsInt()") (path . "math/big/index#Rat.IsInt") (type . "math/big")) ((name . "big.Rat.MarshalText()") (path . "math/big/index#Rat.MarshalText") (type . "math/big")) ((name . "big.Rat.Mul()") (path . "math/big/index#Rat.Mul") (type . "math/big")) ((name . "big.Rat.Neg()") (path . "math/big/index#Rat.Neg") (type . "math/big")) ((name . "big.Rat.Num()") (path . "math/big/index#Rat.Num") (type . "math/big")) ((name . "big.Rat.Quo()") (path . "math/big/index#Rat.Quo") (type . "math/big")) ((name . "big.Rat.RatString()") (path . "math/big/index#Rat.RatString") (type . "math/big")) ((name . "big.Rat.Scan()") (path . "math/big/index#Rat.Scan") (type . "math/big")) ((name . "big.Rat.Set()") (path . "math/big/index#Rat.Set") (type . "math/big")) ((name . "big.Rat.SetFloat64()") (path . "math/big/index#Rat.SetFloat64") (type . "math/big")) ((name . "big.Rat.SetFrac()") (path . "math/big/index#Rat.SetFrac") (type . "math/big")) ((name . "big.Rat.SetFrac64()") (path . "math/big/index#Rat.SetFrac64") (type . "math/big")) ((name . "big.Rat.SetInt()") (path . "math/big/index#Rat.SetInt") (type . "math/big")) ((name . "big.Rat.SetInt64()") (path . "math/big/index#Rat.SetInt64") (type . "math/big")) ((name . "big.Rat.SetString()") (path . "math/big/index#Rat.SetString") (type . "math/big")) ((name . "big.Rat.SetUint64()") (path . "math/big/index#Rat.SetUint64") (type . "math/big")) ((name . "big.Rat.Sign()") (path . "math/big/index#Rat.Sign") (type . "math/big")) ((name . "big.Rat.String()") (path . "math/big/index#Rat.String") (type . "math/big")) ((name . "big.Rat.Sub()") (path . "math/big/index#Rat.Sub") (type . "math/big")) ((name . "big.Rat.UnmarshalText()") (path . "math/big/index#Rat.UnmarshalText") (type . "math/big")) ((name . "big.RoundingMode") (path . "math/big/index#RoundingMode") (type . "math/big")) ((name . "big.RoundingMode.String()") (path . "math/big/index#RoundingMode.String") (type . "math/big")) ((name . "big.Word") (path . "math/big/index#Word") (type . "math/big")) ((name . "binary.AppendByteOrder") (path . "encoding/binary/index#AppendByteOrder") (type . "encoding")) ((name . "binary.AppendUvarint()") (path . "encoding/binary/index#AppendUvarint") (type . "encoding")) ((name . "binary.AppendVarint()") (path . "encoding/binary/index#AppendVarint") (type . "encoding")) ((name . "binary.ByteOrder") (path . "encoding/binary/index#ByteOrder") (type . "encoding")) ((name . "binary.PutUvarint()") (path . "encoding/binary/index#PutUvarint") (type . "encoding")) ((name . "binary.PutVarint()") (path . "encoding/binary/index#PutVarint") (type . "encoding")) ((name . "binary.Read()") (path . "encoding/binary/index#Read") (type . "encoding")) ((name . "binary.ReadUvarint()") (path . "encoding/binary/index#ReadUvarint") (type . "encoding")) ((name . "binary.ReadVarint()") (path . "encoding/binary/index#ReadVarint") (type . "encoding")) ((name . "binary.Size()") (path . "encoding/binary/index#Size") (type . "encoding")) ((name . "binary.Uvarint()") (path . "encoding/binary/index#Uvarint") (type . "encoding")) ((name . "binary.Varint()") (path . "encoding/binary/index#Varint") (type . "encoding")) ((name . "binary.Write()") (path . "encoding/binary/index#Write") (type . "encoding")) ((name . "bits.Add()") (path . "math/bits/index#Add") (type . "math/bits")) ((name . "bits.Add32()") (path . "math/bits/index#Add32") (type . "math/bits")) ((name . "bits.Add64()") (path . "math/bits/index#Add64") (type . "math/bits")) ((name . "bits.Div()") (path . "math/bits/index#Div") (type . "math/bits")) ((name . "bits.Div32()") (path . "math/bits/index#Div32") (type . "math/bits")) ((name . "bits.Div64()") (path . "math/bits/index#Div64") (type . "math/bits")) ((name . "bits.LeadingZeros()") (path . "math/bits/index#LeadingZeros") (type . "math/bits")) ((name . "bits.LeadingZeros16()") (path . "math/bits/index#LeadingZeros16") (type . "math/bits")) ((name . "bits.LeadingZeros32()") (path . "math/bits/index#LeadingZeros32") (type . "math/bits")) ((name . "bits.LeadingZeros64()") (path . "math/bits/index#LeadingZeros64") (type . "math/bits")) ((name . "bits.LeadingZeros8()") (path . "math/bits/index#LeadingZeros8") (type . "math/bits")) ((name . "bits.Len()") (path . "math/bits/index#Len") (type . "math/bits")) ((name . "bits.Len16()") (path . "math/bits/index#Len16") (type . "math/bits")) ((name . "bits.Len32()") (path . "math/bits/index#Len32") (type . "math/bits")) ((name . "bits.Len64()") (path . "math/bits/index#Len64") (type . "math/bits")) ((name . "bits.Len8()") (path . "math/bits/index#Len8") (type . "math/bits")) ((name . "bits.Mul()") (path . "math/bits/index#Mul") (type . "math/bits")) ((name . "bits.Mul32()") (path . "math/bits/index#Mul32") (type . "math/bits")) ((name . "bits.Mul64()") (path . "math/bits/index#Mul64") (type . "math/bits")) ((name . "bits.OnesCount()") (path . "math/bits/index#OnesCount") (type . "math/bits")) ((name . "bits.OnesCount16()") (path . "math/bits/index#OnesCount16") (type . "math/bits")) ((name . "bits.OnesCount32()") (path . "math/bits/index#OnesCount32") (type . "math/bits")) ((name . "bits.OnesCount64()") (path . "math/bits/index#OnesCount64") (type . "math/bits")) ((name . "bits.OnesCount8()") (path . "math/bits/index#OnesCount8") (type . "math/bits")) ((name . "bits.Rem()") (path . "math/bits/index#Rem") (type . "math/bits")) ((name . "bits.Rem32()") (path . "math/bits/index#Rem32") (type . "math/bits")) ((name . "bits.Rem64()") (path . "math/bits/index#Rem64") (type . "math/bits")) ((name . "bits.Reverse()") (path . "math/bits/index#Reverse") (type . "math/bits")) ((name . "bits.Reverse16()") (path . "math/bits/index#Reverse16") (type . "math/bits")) ((name . "bits.Reverse32()") (path . "math/bits/index#Reverse32") (type . "math/bits")) ((name . "bits.Reverse64()") (path . "math/bits/index#Reverse64") (type . "math/bits")) ((name . "bits.Reverse8()") (path . "math/bits/index#Reverse8") (type . "math/bits")) ((name . "bits.ReverseBytes()") (path . "math/bits/index#ReverseBytes") (type . "math/bits")) ((name . "bits.ReverseBytes16()") (path . "math/bits/index#ReverseBytes16") (type . "math/bits")) ((name . "bits.ReverseBytes32()") (path . "math/bits/index#ReverseBytes32") (type . "math/bits")) ((name . "bits.ReverseBytes64()") (path . "math/bits/index#ReverseBytes64") (type . "math/bits")) ((name . "bits.RotateLeft()") (path . "math/bits/index#RotateLeft") (type . "math/bits")) ((name . "bits.RotateLeft16()") (path . "math/bits/index#RotateLeft16") (type . "math/bits")) ((name . "bits.RotateLeft32()") (path . "math/bits/index#RotateLeft32") (type . "math/bits")) ((name . "bits.RotateLeft64()") (path . "math/bits/index#RotateLeft64") (type . "math/bits")) ((name . "bits.RotateLeft8()") (path . "math/bits/index#RotateLeft8") (type . "math/bits")) ((name . "bits.Sub()") (path . "math/bits/index#Sub") (type . "math/bits")) ((name . "bits.Sub32()") (path . "math/bits/index#Sub32") (type . "math/bits")) ((name . "bits.Sub64()") (path . "math/bits/index#Sub64") (type . "math/bits")) ((name . "bits.TrailingZeros()") (path . "math/bits/index#TrailingZeros") (type . "math/bits")) ((name . "bits.TrailingZeros16()") (path . "math/bits/index#TrailingZeros16") (type . "math/bits")) ((name . "bits.TrailingZeros32()") (path . "math/bits/index#TrailingZeros32") (type . "math/bits")) ((name . "bits.TrailingZeros64()") (path . "math/bits/index#TrailingZeros64") (type . "math/bits")) ((name . "bits.TrailingZeros8()") (path . "math/bits/index#TrailingZeros8") (type . "math/bits")) ((name . "bufio") (path . "bufio/index") (type . "bufio")) ((name . "bufio constants") (path . "bufio/index#pkg-constants") (type . "bufio")) ((name . "bufio variables") (path . "bufio/index#pkg-variables") (type . "bufio")) ((name . "bufio.NewReader()") (path . "bufio/index#NewReader") (type . "bufio")) ((name . "bufio.NewReaderSize()") (path . "bufio/index#NewReaderSize") (type . "bufio")) ((name . "bufio.NewReadWriter()") (path . "bufio/index#NewReadWriter") (type . "bufio")) ((name . "bufio.NewScanner()") (path . "bufio/index#NewScanner") (type . "bufio")) ((name . "bufio.NewWriter()") (path . "bufio/index#NewWriter") (type . "bufio")) ((name . "bufio.NewWriterSize()") (path . "bufio/index#NewWriterSize") (type . "bufio")) ((name . "bufio.Reader") (path . "bufio/index#Reader") (type . "bufio")) ((name . "bufio.Reader.Buffered()") (path . "bufio/index#Reader.Buffered") (type . "bufio")) ((name . "bufio.Reader.Discard()") (path . "bufio/index#Reader.Discard") (type . "bufio")) ((name . "bufio.Reader.Peek()") (path . "bufio/index#Reader.Peek") (type . "bufio")) ((name . "bufio.Reader.Read()") (path . "bufio/index#Reader.Read") (type . "bufio")) ((name . "bufio.Reader.ReadByte()") (path . "bufio/index#Reader.ReadByte") (type . "bufio")) ((name . "bufio.Reader.ReadBytes()") (path . "bufio/index#Reader.ReadBytes") (type . "bufio")) ((name . "bufio.Reader.ReadLine()") (path . "bufio/index#Reader.ReadLine") (type . "bufio")) ((name . "bufio.Reader.ReadRune()") (path . "bufio/index#Reader.ReadRune") (type . "bufio")) ((name . "bufio.Reader.ReadSlice()") (path . "bufio/index#Reader.ReadSlice") (type . "bufio")) ((name . "bufio.Reader.ReadString()") (path . "bufio/index#Reader.ReadString") (type . "bufio")) ((name . "bufio.Reader.Reset()") (path . "bufio/index#Reader.Reset") (type . "bufio")) ((name . "bufio.Reader.Size()") (path . "bufio/index#Reader.Size") (type . "bufio")) ((name . "bufio.Reader.UnreadByte()") (path . "bufio/index#Reader.UnreadByte") (type . "bufio")) ((name . "bufio.Reader.UnreadRune()") (path . "bufio/index#Reader.UnreadRune") (type . "bufio")) ((name . "bufio.Reader.WriteTo()") (path . "bufio/index#Reader.WriteTo") (type . "bufio")) ((name . "bufio.ReadWriter") (path . "bufio/index#ReadWriter") (type . "bufio")) ((name . "bufio.ScanBytes()") (path . "bufio/index#ScanBytes") (type . "bufio")) ((name . "bufio.ScanLines()") (path . "bufio/index#ScanLines") (type . "bufio")) ((name . "bufio.Scanner") (path . "bufio/index#Scanner") (type . "bufio")) ((name . "bufio.Scanner.Buffer()") (path . "bufio/index#Scanner.Buffer") (type . "bufio")) ((name . "bufio.Scanner.Bytes()") (path . "bufio/index#Scanner.Bytes") (type . "bufio")) ((name . "bufio.Scanner.Err()") (path . "bufio/index#Scanner.Err") (type . "bufio")) ((name . "bufio.Scanner.Scan()") (path . "bufio/index#Scanner.Scan") (type . "bufio")) ((name . "bufio.Scanner.Split()") (path . "bufio/index#Scanner.Split") (type . "bufio")) ((name . "bufio.Scanner.Text()") (path . "bufio/index#Scanner.Text") (type . "bufio")) ((name . "bufio.ScanRunes()") (path . "bufio/index#ScanRunes") (type . "bufio")) ((name . "bufio.ScanWords()") (path . "bufio/index#ScanWords") (type . "bufio")) ((name . "bufio.SplitFunc") (path . "bufio/index#SplitFunc") (type . "bufio")) ((name . "bufio.Writer") (path . "bufio/index#Writer") (type . "bufio")) ((name . "bufio.Writer.Available()") (path . "bufio/index#Writer.Available") (type . "bufio")) ((name . "bufio.Writer.AvailableBuffer()") (path . "bufio/index#Writer.AvailableBuffer") (type . "bufio")) ((name . "bufio.Writer.Buffered()") (path . "bufio/index#Writer.Buffered") (type . "bufio")) ((name . "bufio.Writer.Flush()") (path . "bufio/index#Writer.Flush") (type . "bufio")) ((name . "bufio.Writer.ReadFrom()") (path . "bufio/index#Writer.ReadFrom") (type . "bufio")) ((name . "bufio.Writer.Reset()") (path . "bufio/index#Writer.Reset") (type . "bufio")) ((name . "bufio.Writer.Size()") (path . "bufio/index#Writer.Size") (type . "bufio")) ((name . "bufio.Writer.Write()") (path . "bufio/index#Writer.Write") (type . "bufio")) ((name . "bufio.Writer.WriteByte()") (path . "bufio/index#Writer.WriteByte") (type . "bufio")) ((name . "bufio.Writer.WriteRune()") (path . "bufio/index#Writer.WriteRune") (type . "bufio")) ((name . "bufio.Writer.WriteString()") (path . "bufio/index#Writer.WriteString") (type . "bufio")) ((name . "build.ArchChar()") (path . "go/build/index#ArchChar") (type . "go")) ((name . "build.Context") (path . "go/build/index#Context") (type . "go")) ((name . "build.Context.Import()") (path . "go/build/index#Context.Import") (type . "go")) ((name . "build.Context.ImportDir()") (path . "go/build/index#Context.ImportDir") (type . "go")) ((name . "build.Context.MatchFile()") (path . "go/build/index#Context.MatchFile") (type . "go")) ((name . "build.Context.SrcDirs()") (path . "go/build/index#Context.SrcDirs") (type . "go")) ((name . "build.Directive") (path . "go/build/index#Directive") (type . "go")) ((name . "build.Import()") (path . "go/build/index#Import") (type . "go")) ((name . "build.ImportDir()") (path . "go/build/index#ImportDir") (type . "go")) ((name . "build.ImportMode") (path . "go/build/index#ImportMode") (type . "go")) ((name . "build.IsLocalImport()") (path . "go/build/index#IsLocalImport") (type . "go")) ((name . "build.MultiplePackageError") (path . "go/build/index#MultiplePackageError") (type . "go")) ((name . "build.MultiplePackageError.Error()") (path . "go/build/index#MultiplePackageError.Error") (type . "go")) ((name . "build.NoGoError") (path . "go/build/index#NoGoError") (type . "go")) ((name . "build.NoGoError.Error()") (path . "go/build/index#NoGoError.Error") (type . "go")) ((name . "build.Package") (path . "go/build/index#Package") (type . "go")) ((name . "build.Package.IsCommand()") (path . "go/build/index#Package.IsCommand") (type . "go")) ((name . "buildinfo.BuildInfo") (path . "debug/buildinfo/index#BuildInfo") (type . "debug")) ((name . "buildinfo.Read()") (path . "debug/buildinfo/index#Read") (type . "debug")) ((name . "buildinfo.ReadFile()") (path . "debug/buildinfo/index#ReadFile") (type . "debug")) ((name . "builtin") (path . "builtin/index") (type . "builtin")) ((name . "builtin constants") (path . "builtin/index#pkg-constants") (type . "builtin")) ((name . "builtin variables") (path . "builtin/index#pkg-variables") (type . "builtin")) ((name . "builtin.any") (path . "builtin/index#any") (type . "builtin")) ((name . "builtin.append()") (path . "builtin/index#append") (type . "builtin")) ((name . "builtin.bool") (path . "builtin/index#bool") (type . "builtin")) ((name . "builtin.byte") (path . "builtin/index#byte") (type . "builtin")) ((name . "builtin.cap()") (path . "builtin/index#cap") (type . "builtin")) ((name . "builtin.clear()") (path . "builtin/index#clear") (type . "builtin")) ((name . "builtin.close()") (path . "builtin/index#close") (type . "builtin")) ((name . "builtin.comparable") (path . "builtin/index#comparable") (type . "builtin")) ((name . "builtin.complex()") (path . "builtin/index#complex") (type . "builtin")) ((name . "builtin.complex128") (path . "builtin/index#complex128") (type . "builtin")) ((name . "builtin.complex64") (path . "builtin/index#complex64") (type . "builtin")) ((name . "builtin.ComplexType") (path . "builtin/index#ComplexType") (type . "builtin")) ((name . "builtin.copy()") (path . "builtin/index#copy") (type . "builtin")) ((name . "builtin.delete()") (path . "builtin/index#delete") (type . "builtin")) ((name . "builtin.error") (path . "builtin/index#error") (type . "builtin")) ((name . "builtin.float32") (path . "builtin/index#float32") (type . "builtin")) ((name . "builtin.float64") (path . "builtin/index#float64") (type . "builtin")) ((name . "builtin.FloatType") (path . "builtin/index#FloatType") (type . "builtin")) ((name . "builtin.imag()") (path . "builtin/index#imag") (type . "builtin")) ((name . "builtin.int") (path . "builtin/index#int") (type . "builtin")) ((name . "builtin.int16") (path . "builtin/index#int16") (type . "builtin")) ((name . "builtin.int32") (path . "builtin/index#int32") (type . "builtin")) ((name . "builtin.int64") (path . "builtin/index#int64") (type . "builtin")) ((name . "builtin.int8") (path . "builtin/index#int8") (type . "builtin")) ((name . "builtin.IntegerType") (path . "builtin/index#IntegerType") (type . "builtin")) ((name . "builtin.len()") (path . "builtin/index#len") (type . "builtin")) ((name . "builtin.make()") (path . "builtin/index#make") (type . "builtin")) ((name . "builtin.max()") (path . "builtin/index#max") (type . "builtin")) ((name . "builtin.min()") (path . "builtin/index#min") (type . "builtin")) ((name . "builtin.new()") (path . "builtin/index#new") (type . "builtin")) ((name . "builtin.panic()") (path . "builtin/index#panic") (type . "builtin")) ((name . "builtin.print()") (path . "builtin/index#print") (type . "builtin")) ((name . "builtin.println()") (path . "builtin/index#println") (type . "builtin")) ((name . "builtin.real()") (path . "builtin/index#real") (type . "builtin")) ((name . "builtin.recover()") (path . "builtin/index#recover") (type . "builtin")) ((name . "builtin.rune") (path . "builtin/index#rune") (type . "builtin")) ((name . "builtin.string") (path . "builtin/index#string") (type . "builtin")) ((name . "builtin.Type") (path . "builtin/index#Type") (type . "builtin")) ((name . "builtin.Type1") (path . "builtin/index#Type1") (type . "builtin")) ((name . "builtin.uint") (path . "builtin/index#uint") (type . "builtin")) ((name . "builtin.uint16") (path . "builtin/index#uint16") (type . "builtin")) ((name . "builtin.uint32") (path . "builtin/index#uint32") (type . "builtin")) ((name . "builtin.uint64") (path . "builtin/index#uint64") (type . "builtin")) ((name . "builtin.uint8") (path . "builtin/index#uint8") (type . "builtin")) ((name . "builtin.uintptr") (path . "builtin/index#uintptr") (type . "builtin")) ((name . "bytes") (path . "bytes/index") (type . "bytes")) ((name . "bytes constants") (path . "bytes/index#pkg-constants") (type . "bytes")) ((name . "bytes variables") (path . "bytes/index#pkg-variables") (type . "bytes")) ((name . "bytes.Buffer") (path . "bytes/index#Buffer") (type . "bytes")) ((name . "bytes.Buffer.Available()") (path . "bytes/index#Buffer.Available") (type . "bytes")) ((name . "bytes.Buffer.AvailableBuffer()") (path . "bytes/index#Buffer.AvailableBuffer") (type . "bytes")) ((name . "bytes.Buffer.Bytes()") (path . "bytes/index#Buffer.Bytes") (type . "bytes")) ((name . "bytes.Buffer.Cap()") (path . "bytes/index#Buffer.Cap") (type . "bytes")) ((name . "bytes.Buffer.Grow()") (path . "bytes/index#Buffer.Grow") (type . "bytes")) ((name . "bytes.Buffer.Len()") (path . "bytes/index#Buffer.Len") (type . "bytes")) ((name . "bytes.Buffer.Next()") (path . "bytes/index#Buffer.Next") (type . "bytes")) ((name . "bytes.Buffer.Read()") (path . "bytes/index#Buffer.Read") (type . "bytes")) ((name . "bytes.Buffer.ReadByte()") (path . "bytes/index#Buffer.ReadByte") (type . "bytes")) ((name . "bytes.Buffer.ReadBytes()") (path . "bytes/index#Buffer.ReadBytes") (type . "bytes")) ((name . "bytes.Buffer.ReadFrom()") (path . "bytes/index#Buffer.ReadFrom") (type . "bytes")) ((name . "bytes.Buffer.ReadRune()") (path . "bytes/index#Buffer.ReadRune") (type . "bytes")) ((name . "bytes.Buffer.ReadString()") (path . "bytes/index#Buffer.ReadString") (type . "bytes")) ((name . "bytes.Buffer.Reset()") (path . "bytes/index#Buffer.Reset") (type . "bytes")) ((name . "bytes.Buffer.String()") (path . "bytes/index#Buffer.String") (type . "bytes")) ((name . "bytes.Buffer.Truncate()") (path . "bytes/index#Buffer.Truncate") (type . "bytes")) ((name . "bytes.Buffer.UnreadByte()") (path . "bytes/index#Buffer.UnreadByte") (type . "bytes")) ((name . "bytes.Buffer.UnreadRune()") (path . "bytes/index#Buffer.UnreadRune") (type . "bytes")) ((name . "bytes.Buffer.Write()") (path . "bytes/index#Buffer.Write") (type . "bytes")) ((name . "bytes.Buffer.WriteByte()") (path . "bytes/index#Buffer.WriteByte") (type . "bytes")) ((name . "bytes.Buffer.WriteRune()") (path . "bytes/index#Buffer.WriteRune") (type . "bytes")) ((name . "bytes.Buffer.WriteString()") (path . "bytes/index#Buffer.WriteString") (type . "bytes")) ((name . "bytes.Buffer.WriteTo()") (path . "bytes/index#Buffer.WriteTo") (type . "bytes")) ((name . "bytes.Clone()") (path . "bytes/index#Clone") (type . "bytes")) ((name . "bytes.Compare()") (path . "bytes/index#Compare") (type . "bytes")) ((name . "bytes.Contains()") (path . "bytes/index#Contains") (type . "bytes")) ((name . "bytes.ContainsAny()") (path . "bytes/index#ContainsAny") (type . "bytes")) ((name . "bytes.ContainsFunc()") (path . "bytes/index#ContainsFunc") (type . "bytes")) ((name . "bytes.ContainsRune()") (path . "bytes/index#ContainsRune") (type . "bytes")) ((name . "bytes.Count()") (path . "bytes/index#Count") (type . "bytes")) ((name . "bytes.Cut()") (path . "bytes/index#Cut") (type . "bytes")) ((name . "bytes.CutPrefix()") (path . "bytes/index#CutPrefix") (type . "bytes")) ((name . "bytes.CutSuffix()") (path . "bytes/index#CutSuffix") (type . "bytes")) ((name . "bytes.Equal()") (path . "bytes/index#Equal") (type . "bytes")) ((name . "bytes.EqualFold()") (path . "bytes/index#EqualFold") (type . "bytes")) ((name . "bytes.Fields()") (path . "bytes/index#Fields") (type . "bytes")) ((name . "bytes.FieldsFunc()") (path . "bytes/index#FieldsFunc") (type . "bytes")) ((name . "bytes.HasPrefix()") (path . "bytes/index#HasPrefix") (type . "bytes")) ((name . "bytes.HasSuffix()") (path . "bytes/index#HasSuffix") (type . "bytes")) ((name . "bytes.Index()") (path . "bytes/index#Index") (type . "bytes")) ((name . "bytes.IndexAny()") (path . "bytes/index#IndexAny") (type . "bytes")) ((name . "bytes.IndexByte()") (path . "bytes/index#IndexByte") (type . "bytes")) ((name . "bytes.IndexFunc()") (path . "bytes/index#IndexFunc") (type . "bytes")) ((name . "bytes.IndexRune()") (path . "bytes/index#IndexRune") (type . "bytes")) ((name . "bytes.Join()") (path . "bytes/index#Join") (type . "bytes")) ((name . "bytes.LastIndex()") (path . "bytes/index#LastIndex") (type . "bytes")) ((name . "bytes.LastIndexAny()") (path . "bytes/index#LastIndexAny") (type . "bytes")) ((name . "bytes.LastIndexByte()") (path . "bytes/index#LastIndexByte") (type . "bytes")) ((name . "bytes.LastIndexFunc()") (path . "bytes/index#LastIndexFunc") (type . "bytes")) ((name . "bytes.Map()") (path . "bytes/index#Map") (type . "bytes")) ((name . "bytes.NewBuffer()") (path . "bytes/index#NewBuffer") (type . "bytes")) ((name . "bytes.NewBufferString()") (path . "bytes/index#NewBufferString") (type . "bytes")) ((name . "bytes.NewReader()") (path . "bytes/index#NewReader") (type . "bytes")) ((name . "bytes.Reader") (path . "bytes/index#Reader") (type . "bytes")) ((name . "bytes.Reader.Len()") (path . "bytes/index#Reader.Len") (type . "bytes")) ((name . "bytes.Reader.Read()") (path . "bytes/index#Reader.Read") (type . "bytes")) ((name . "bytes.Reader.ReadAt()") (path . "bytes/index#Reader.ReadAt") (type . "bytes")) ((name . "bytes.Reader.ReadByte()") (path . "bytes/index#Reader.ReadByte") (type . "bytes")) ((name . "bytes.Reader.ReadRune()") (path . "bytes/index#Reader.ReadRune") (type . "bytes")) ((name . "bytes.Reader.Reset()") (path . "bytes/index#Reader.Reset") (type . "bytes")) ((name . "bytes.Reader.Seek()") (path . "bytes/index#Reader.Seek") (type . "bytes")) ((name . "bytes.Reader.Size()") (path . "bytes/index#Reader.Size") (type . "bytes")) ((name . "bytes.Reader.UnreadByte()") (path . "bytes/index#Reader.UnreadByte") (type . "bytes")) ((name . "bytes.Reader.UnreadRune()") (path . "bytes/index#Reader.UnreadRune") (type . "bytes")) ((name . "bytes.Reader.WriteTo()") (path . "bytes/index#Reader.WriteTo") (type . "bytes")) ((name . "bytes.Repeat()") (path . "bytes/index#Repeat") (type . "bytes")) ((name . "bytes.Replace()") (path . "bytes/index#Replace") (type . "bytes")) ((name . "bytes.ReplaceAll()") (path . "bytes/index#ReplaceAll") (type . "bytes")) ((name . "bytes.Runes()") (path . "bytes/index#Runes") (type . "bytes")) ((name . "bytes.Split()") (path . "bytes/index#Split") (type . "bytes")) ((name . "bytes.SplitAfter()") (path . "bytes/index#SplitAfter") (type . "bytes")) ((name . "bytes.SplitAfterN()") (path . "bytes/index#SplitAfterN") (type . "bytes")) ((name . "bytes.SplitN()") (path . "bytes/index#SplitN") (type . "bytes")) ((name . "bytes.Title()") (path . "bytes/index#Title") (type . "bytes")) ((name . "bytes.ToLower()") (path . "bytes/index#ToLower") (type . "bytes")) ((name . "bytes.ToLowerSpecial()") (path . "bytes/index#ToLowerSpecial") (type . "bytes")) ((name . "bytes.ToTitle()") (path . "bytes/index#ToTitle") (type . "bytes")) ((name . "bytes.ToTitleSpecial()") (path . "bytes/index#ToTitleSpecial") (type . "bytes")) ((name . "bytes.ToUpper()") (path . "bytes/index#ToUpper") (type . "bytes")) ((name . "bytes.ToUpperSpecial()") (path . "bytes/index#ToUpperSpecial") (type . "bytes")) ((name . "bytes.ToValidUTF8()") (path . "bytes/index#ToValidUTF8") (type . "bytes")) ((name . "bytes.Trim()") (path . "bytes/index#Trim") (type . "bytes")) ((name . "bytes.TrimFunc()") (path . "bytes/index#TrimFunc") (type . "bytes")) ((name . "bytes.TrimLeft()") (path . "bytes/index#TrimLeft") (type . "bytes")) ((name . "bytes.TrimLeftFunc()") (path . "bytes/index#TrimLeftFunc") (type . "bytes")) ((name . "bytes.TrimPrefix()") (path . "bytes/index#TrimPrefix") (type . "bytes")) ((name . "bytes.TrimRight()") (path . "bytes/index#TrimRight") (type . "bytes")) ((name . "bytes.TrimRightFunc()") (path . "bytes/index#TrimRightFunc") (type . "bytes")) ((name . "bytes.TrimSpace()") (path . "bytes/index#TrimSpace") (type . "bytes")) ((name . "bytes.TrimSuffix()") (path . "bytes/index#TrimSuffix") (type . "bytes")) ((name . "bzip2.NewReader()") (path . "compress/bzip2/index#NewReader") (type . "compress")) ((name . "bzip2.StructuralError") (path . "compress/bzip2/index#StructuralError") (type . "compress")) ((name . "bzip2.StructuralError.Error()") (path . "compress/bzip2/index#StructuralError.Error") (type . "compress")) ((name . "cgi.Handler") (path . "net/http/cgi/index#Handler") (type . "net/http")) ((name . "cgi.Handler.ServeHTTP()") (path . "net/http/cgi/index#Handler.ServeHTTP") (type . "net/http")) ((name . "cgi.Request()") (path . "net/http/cgi/index#Request") (type . "net/http")) ((name . "cgi.RequestFromMap()") (path . "net/http/cgi/index#RequestFromMap") (type . "net/http")) ((name . "cgi.Serve()") (path . "net/http/cgi/index#Serve") (type . "net/http")) ((name . "cgo.Handle") (path . "runtime/cgo/index#Handle") (type . "runtime")) ((name . "cgo.Handle.Delete()") (path . "runtime/cgo/index#Handle.Delete") (type . "runtime")) ((name . "cgo.Handle.Value()") (path . "runtime/cgo/index#Handle.Value") (type . "runtime")) ((name . "cgo.Incomplete") (path . "runtime/cgo/index#Incomplete") (type . "runtime")) ((name . "cgo.NewHandle()") (path . "runtime/cgo/index#NewHandle") (type . "runtime")) ((name . "cipher.AEAD") (path . "crypto/cipher/index#AEAD") (type . "crypto")) ((name . "cipher.Block") (path . "crypto/cipher/index#Block") (type . "crypto")) ((name . "cipher.BlockMode") (path . "crypto/cipher/index#BlockMode") (type . "crypto")) ((name . "cipher.NewCBCDecrypter()") (path . "crypto/cipher/index#NewCBCDecrypter") (type . "crypto")) ((name . "cipher.NewCBCEncrypter()") (path . "crypto/cipher/index#NewCBCEncrypter") (type . "crypto")) ((name . "cipher.NewCFBDecrypter()") (path . "crypto/cipher/index#NewCFBDecrypter") (type . "crypto")) ((name . "cipher.NewCFBEncrypter()") (path . "crypto/cipher/index#NewCFBEncrypter") (type . "crypto")) ((name . "cipher.NewCTR()") (path . "crypto/cipher/index#NewCTR") (type . "crypto")) ((name . "cipher.NewGCM()") (path . "crypto/cipher/index#NewGCM") (type . "crypto")) ((name . "cipher.NewGCMWithNonceSize()") (path . "crypto/cipher/index#NewGCMWithNonceSize") (type . "crypto")) ((name . "cipher.NewGCMWithTagSize()") (path . "crypto/cipher/index#NewGCMWithTagSize") (type . "crypto")) ((name . "cipher.NewOFB()") (path . "crypto/cipher/index#NewOFB") (type . "crypto")) ((name . "cipher.Stream") (path . "crypto/cipher/index#Stream") (type . "crypto")) ((name . "cipher.StreamReader") (path . "crypto/cipher/index#StreamReader") (type . "crypto")) ((name . "cipher.StreamReader.Read()") (path . "crypto/cipher/index#StreamReader.Read") (type . "crypto")) ((name . "cipher.StreamWriter") (path . "crypto/cipher/index#StreamWriter") (type . "crypto")) ((name . "cipher.StreamWriter.Close()") (path . "crypto/cipher/index#StreamWriter.Close") (type . "crypto")) ((name . "cipher.StreamWriter.Write()") (path . "crypto/cipher/index#StreamWriter.Write") (type . "crypto")) ((name . "cmp") (path . "cmp/index") (type . "cmp")) ((name . "cmp.Compare()") (path . "cmp/index#Compare") (type . "cmp")) ((name . "cmp.Less()") (path . "cmp/index#Less") (type . "cmp")) ((name . "cmp.Or()") (path . "cmp/index#Or") (type . "cmp")) ((name . "cmp.Ordered") (path . "cmp/index#Ordered") (type . "cmp")) ((name . "cmplx.Abs()") (path . "math/cmplx/index#Abs") (type . "math/cmplx")) ((name . "cmplx.Acos()") (path . "math/cmplx/index#Acos") (type . "math/cmplx")) ((name . "cmplx.Acosh()") (path . "math/cmplx/index#Acosh") (type . "math/cmplx")) ((name . "cmplx.Asin()") (path . "math/cmplx/index#Asin") (type . "math/cmplx")) ((name . "cmplx.Asinh()") (path . "math/cmplx/index#Asinh") (type . "math/cmplx")) ((name . "cmplx.Atan()") (path . "math/cmplx/index#Atan") (type . "math/cmplx")) ((name . "cmplx.Atanh()") (path . "math/cmplx/index#Atanh") (type . "math/cmplx")) ((name . "cmplx.Conj()") (path . "math/cmplx/index#Conj") (type . "math/cmplx")) ((name . "cmplx.Cos()") (path . "math/cmplx/index#Cos") (type . "math/cmplx")) ((name . "cmplx.Cosh()") (path . "math/cmplx/index#Cosh") (type . "math/cmplx")) ((name . "cmplx.Cot()") (path . "math/cmplx/index#Cot") (type . "math/cmplx")) ((name . "cmplx.Exp()") (path . "math/cmplx/index#Exp") (type . "math/cmplx")) ((name . "cmplx.Inf()") (path . "math/cmplx/index#Inf") (type . "math/cmplx")) ((name . "cmplx.IsInf()") (path . "math/cmplx/index#IsInf") (type . "math/cmplx")) ((name . "cmplx.IsNaN()") (path . "math/cmplx/index#IsNaN") (type . "math/cmplx")) ((name . "cmplx.Log()") (path . "math/cmplx/index#Log") (type . "math/cmplx")) ((name . "cmplx.Log10()") (path . "math/cmplx/index#Log10") (type . "math/cmplx")) ((name . "cmplx.NaN()") (path . "math/cmplx/index#NaN") (type . "math/cmplx")) ((name . "cmplx.Phase()") (path . "math/cmplx/index#Phase") (type . "math/cmplx")) ((name . "cmplx.Polar()") (path . "math/cmplx/index#Polar") (type . "math/cmplx")) ((name . "cmplx.Pow()") (path . "math/cmplx/index#Pow") (type . "math/cmplx")) ((name . "cmplx.Rect()") (path . "math/cmplx/index#Rect") (type . "math/cmplx")) ((name . "cmplx.Sin()") (path . "math/cmplx/index#Sin") (type . "math/cmplx")) ((name . "cmplx.Sinh()") (path . "math/cmplx/index#Sinh") (type . "math/cmplx")) ((name . "cmplx.Sqrt()") (path . "math/cmplx/index#Sqrt") (type . "math/cmplx")) ((name . "cmplx.Tan()") (path . "math/cmplx/index#Tan") (type . "math/cmplx")) ((name . "cmplx.Tanh()") (path . "math/cmplx/index#Tanh") (type . "math/cmplx")) ((name . "color.Alpha") (path . "image/color/index#Alpha") (type . "image")) ((name . "color.Alpha.RGBA()") (path . "image/color/index#Alpha.RGBA") (type . "image")) ((name . "color.Alpha16") (path . "image/color/index#Alpha16") (type . "image")) ((name . "color.Alpha16.RGBA()") (path . "image/color/index#Alpha16.RGBA") (type . "image")) ((name . "color.CMYK") (path . "image/color/index#CMYK") (type . "image")) ((name . "color.CMYK.RGBA()") (path . "image/color/index#CMYK.RGBA") (type . "image")) ((name . "color.CMYKToRGB()") (path . "image/color/index#CMYKToRGB") (type . "image")) ((name . "color.Color") (path . "image/color/index#Color") (type . "image")) ((name . "color.Gray") (path . "image/color/index#Gray") (type . "image")) ((name . "color.Gray.RGBA()") (path . "image/color/index#Gray.RGBA") (type . "image")) ((name . "color.Gray16") (path . "image/color/index#Gray16") (type . "image")) ((name . "color.Gray16.RGBA()") (path . "image/color/index#Gray16.RGBA") (type . "image")) ((name . "color.Model") (path . "image/color/index#Model") (type . "image")) ((name . "color.ModelFunc()") (path . "image/color/index#ModelFunc") (type . "image")) ((name . "color.NRGBA") (path . "image/color/index#NRGBA") (type . "image")) ((name . "color.NRGBA.RGBA()") (path . "image/color/index#NRGBA.RGBA") (type . "image")) ((name . "color.NRGBA64") (path . "image/color/index#NRGBA64") (type . "image")) ((name . "color.NRGBA64.RGBA()") (path . "image/color/index#NRGBA64.RGBA") (type . "image")) ((name . "color.NYCbCrA") (path . "image/color/index#NYCbCrA") (type . "image")) ((name . "color.NYCbCrA.RGBA()") (path . "image/color/index#NYCbCrA.RGBA") (type . "image")) ((name . "color.Palette") (path . "image/color/index#Palette") (type . "image")) ((name . "color.Palette.Convert()") (path . "image/color/index#Palette.Convert") (type . "image")) ((name . "color.Palette.Index()") (path . "image/color/index#Palette.Index") (type . "image")) ((name . "color.RGBA") (path . "image/color/index#RGBA") (type . "image")) ((name . "color.RGBA.RGBA()") (path . "image/color/index#RGBA.RGBA") (type . "image")) ((name . "color.RGBA64") (path . "image/color/index#RGBA64") (type . "image")) ((name . "color.RGBA64.RGBA()") (path . "image/color/index#RGBA64.RGBA") (type . "image")) ((name . "color.RGBToCMYK()") (path . "image/color/index#RGBToCMYK") (type . "image")) ((name . "color.RGBToYCbCr()") (path . "image/color/index#RGBToYCbCr") (type . "image")) ((name . "color.YCbCr") (path . "image/color/index#YCbCr") (type . "image")) ((name . "color.YCbCr.RGBA()") (path . "image/color/index#YCbCr.RGBA") (type . "image")) ((name . "color.YCbCrToRGB()") (path . "image/color/index#YCbCrToRGB") (type . "image")) ((name . "Command arena") (path . "arena/index") (type . "arena")) ((name . "Command asan") (path . "runtime/asan/index") (type . "runtime")) ((name . "Command boring") (path . "crypto/boring/index") (type . "crypto")) ((name . "Command fipsonly") (path . "crypto/tls/fipsonly/index") (type . "crypto")) ((name . "Command iter") (path . "iter/index") (type . "iter")) ((name . "comment.Block") (path . "go/doc/comment/index#Block") (type . "go")) ((name . "comment.Code") (path . "go/doc/comment/index#Code") (type . "go")) ((name . "comment.DefaultLookupPackage()") (path . "go/doc/comment/index#DefaultLookupPackage") (type . "go")) ((name . "comment.Doc") (path . "go/doc/comment/index#Doc") (type . "go")) ((name . "comment.DocLink") (path . "go/doc/comment/index#DocLink") (type . "go")) ((name . "comment.DocLink.DefaultURL()") (path . "go/doc/comment/index#DocLink.DefaultURL") (type . "go")) ((name . "comment.Heading") (path . "go/doc/comment/index#Heading") (type . "go")) ((name . "comment.Heading.DefaultID()") (path . "go/doc/comment/index#Heading.DefaultID") (type . "go")) ((name . "comment.Italic") (path . "go/doc/comment/index#Italic") (type . "go")) ((name . "comment.Link") (path . "go/doc/comment/index#Link") (type . "go")) ((name . "comment.LinkDef") (path . "go/doc/comment/index#LinkDef") (type . "go")) ((name . "comment.List") (path . "go/doc/comment/index#List") (type . "go")) ((name . "comment.List.BlankBefore()") (path . "go/doc/comment/index#List.BlankBefore") (type . "go")) ((name . "comment.List.BlankBetween()") (path . "go/doc/comment/index#List.BlankBetween") (type . "go")) ((name . "comment.ListItem") (path . "go/doc/comment/index#ListItem") (type . "go")) ((name . "comment.Paragraph") (path . "go/doc/comment/index#Paragraph") (type . "go")) ((name . "comment.Parser") (path . "go/doc/comment/index#Parser") (type . "go")) ((name . "comment.Parser.Parse()") (path . "go/doc/comment/index#Parser.Parse") (type . "go")) ((name . "comment.Plain") (path . "go/doc/comment/index#Plain") (type . "go")) ((name . "comment.Printer") (path . "go/doc/comment/index#Printer") (type . "go")) ((name . "comment.Printer.Comment()") (path . "go/doc/comment/index#Printer.Comment") (type . "go")) ((name . "comment.Printer.HTML()") (path . "go/doc/comment/index#Printer.HTML") (type . "go")) ((name . "comment.Printer.Markdown()") (path . "go/doc/comment/index#Printer.Markdown") (type . "go")) ((name . "comment.Printer.Text()") (path . "go/doc/comment/index#Printer.Text") (type . "go")) ((name . "comment.Text") (path . "go/doc/comment/index#Text") (type . "go")) ((name . "compress/bzip2") (path . "compress/bzip2/index") (type . "compress")) ((name . "compress/flate") (path . "compress/flate/index") (type . "compress")) ((name . "compress/flate constants") (path . "compress/flate/index#pkg-constants") (type . "compress")) ((name . "compress/gzip") (path . "compress/gzip/index") (type . "compress")) ((name . "compress/gzip constants") (path . "compress/gzip/index#pkg-constants") (type . "compress")) ((name . "compress/gzip variables") (path . "compress/gzip/index#pkg-variables") (type . "compress")) ((name . "compress/lzw") (path . "compress/lzw/index") (type . "compress")) ((name . "compress/zlib") (path . "compress/zlib/index") (type . "compress")) ((name . "compress/zlib constants") (path . "compress/zlib/index#pkg-constants") (type . "compress")) ((name . "compress/zlib variables") (path . "compress/zlib/index#pkg-variables") (type . "compress")) ((name . "constant.BinaryOp()") (path . "go/constant/index#BinaryOp") (type . "go")) ((name . "constant.BitLen()") (path . "go/constant/index#BitLen") (type . "go")) ((name . "constant.BoolVal()") (path . "go/constant/index#BoolVal") (type . "go")) ((name . "constant.Bytes()") (path . "go/constant/index#Bytes") (type . "go")) ((name . "constant.Compare()") (path . "go/constant/index#Compare") (type . "go")) ((name . "constant.Denom()") (path . "go/constant/index#Denom") (type . "go")) ((name . "constant.Float32Val()") (path . "go/constant/index#Float32Val") (type . "go")) ((name . "constant.Float64Val()") (path . "go/constant/index#Float64Val") (type . "go")) ((name . "constant.Imag()") (path . "go/constant/index#Imag") (type . "go")) ((name . "constant.Int64Val()") (path . "go/constant/index#Int64Val") (type . "go")) ((name . "constant.Kind") (path . "go/constant/index#Kind") (type . "go")) ((name . "constant.Kind.String()") (path . "go/constant/index#Kind.String") (type . "go")) ((name . "constant.Make()") (path . "go/constant/index#Make") (type . "go")) ((name . "constant.MakeBool()") (path . "go/constant/index#MakeBool") (type . "go")) ((name . "constant.MakeFloat64()") (path . "go/constant/index#MakeFloat64") (type . "go")) ((name . "constant.MakeFromBytes()") (path . "go/constant/index#MakeFromBytes") (type . "go")) ((name . "constant.MakeFromLiteral()") (path . "go/constant/index#MakeFromLiteral") (type . "go")) ((name . "constant.MakeImag()") (path . "go/constant/index#MakeImag") (type . "go")) ((name . "constant.MakeInt64()") (path . "go/constant/index#MakeInt64") (type . "go")) ((name . "constant.MakeString()") (path . "go/constant/index#MakeString") (type . "go")) ((name . "constant.MakeUint64()") (path . "go/constant/index#MakeUint64") (type . "go")) ((name . "constant.MakeUnknown()") (path . "go/constant/index#MakeUnknown") (type . "go")) ((name . "constant.Num()") (path . "go/constant/index#Num") (type . "go")) ((name . "constant.Real()") (path . "go/constant/index#Real") (type . "go")) ((name . "constant.Shift()") (path . "go/constant/index#Shift") (type . "go")) ((name . "constant.Sign()") (path . "go/constant/index#Sign") (type . "go")) ((name . "constant.StringVal()") (path . "go/constant/index#StringVal") (type . "go")) ((name . "constant.ToComplex()") (path . "go/constant/index#ToComplex") (type . "go")) ((name . "constant.ToFloat()") (path . "go/constant/index#ToFloat") (type . "go")) ((name . "constant.ToInt()") (path . "go/constant/index#ToInt") (type . "go")) ((name . "constant.Uint64Val()") (path . "go/constant/index#Uint64Val") (type . "go")) ((name . "constant.UnaryOp()") (path . "go/constant/index#UnaryOp") (type . "go")) ((name . "constant.Val()") (path . "go/constant/index#Val") (type . "go")) ((name . "constant.Value") (path . "go/constant/index#Value") (type . "go")) ((name . "constraint.AndExpr") (path . "go/build/constraint/index#AndExpr") (type . "go")) ((name . "constraint.AndExpr.Eval()") (path . "go/build/constraint/index#AndExpr.Eval") (type . "go")) ((name . "constraint.AndExpr.String()") (path . "go/build/constraint/index#AndExpr.String") (type . "go")) ((name . "constraint.Expr") (path . "go/build/constraint/index#Expr") (type . "go")) ((name . "constraint.GoVersion()") (path . "go/build/constraint/index#GoVersion") (type . "go")) ((name . "constraint.IsGoBuild()") (path . "go/build/constraint/index#IsGoBuild") (type . "go")) ((name . "constraint.IsPlusBuild()") (path . "go/build/constraint/index#IsPlusBuild") (type . "go")) ((name . "constraint.NotExpr") (path . "go/build/constraint/index#NotExpr") (type . "go")) ((name . "constraint.NotExpr.Eval()") (path . "go/build/constraint/index#NotExpr.Eval") (type . "go")) ((name . "constraint.NotExpr.String()") (path . "go/build/constraint/index#NotExpr.String") (type . "go")) ((name . "constraint.OrExpr") (path . "go/build/constraint/index#OrExpr") (type . "go")) ((name . "constraint.OrExpr.Eval()") (path . "go/build/constraint/index#OrExpr.Eval") (type . "go")) ((name . "constraint.OrExpr.String()") (path . "go/build/constraint/index#OrExpr.String") (type . "go")) ((name . "constraint.Parse()") (path . "go/build/constraint/index#Parse") (type . "go")) ((name . "constraint.PlusBuildLines()") (path . "go/build/constraint/index#PlusBuildLines") (type . "go")) ((name . "constraint.SyntaxError") (path . "go/build/constraint/index#SyntaxError") (type . "go")) ((name . "constraint.SyntaxError.Error()") (path . "go/build/constraint/index#SyntaxError.Error") (type . "go")) ((name . "constraint.TagExpr") (path . "go/build/constraint/index#TagExpr") (type . "go")) ((name . "constraint.TagExpr.Eval()") (path . "go/build/constraint/index#TagExpr.Eval") (type . "go")) ((name . "constraint.TagExpr.String()") (path . "go/build/constraint/index#TagExpr.String") (type . "go")) ((name . "container/heap") (path . "container/heap/index") (type . "container")) ((name . "container/list") (path . "container/list/index") (type . "container")) ((name . "container/ring") (path . "container/ring/index") (type . "container")) ((name . "context") (path . "context/index") (type . "context")) ((name . "context variables") (path . "context/index#pkg-variables") (type . "context")) ((name . "context.AfterFunc()") (path . "context/index#AfterFunc") (type . "context")) ((name . "context.Background()") (path . "context/index#Background") (type . "context")) ((name . "context.CancelCauseFunc") (path . "context/index#CancelCauseFunc") (type . "context")) ((name . "context.CancelFunc") (path . "context/index#CancelFunc") (type . "context")) ((name . "context.Cause()") (path . "context/index#Cause") (type . "context")) ((name . "context.Context") (path . "context/index#Context") (type . "context")) ((name . "context.TODO()") (path . "context/index#TODO") (type . "context")) ((name . "context.WithCancel()") (path . "context/index#WithCancel") (type . "context")) ((name . "context.WithCancelCause()") (path . "context/index#WithCancelCause") (type . "context")) ((name . "context.WithDeadline()") (path . "context/index#WithDeadline") (type . "context")) ((name . "context.WithDeadlineCause()") (path . "context/index#WithDeadlineCause") (type . "context")) ((name . "context.WithoutCancel()") (path . "context/index#WithoutCancel") (type . "context")) ((name . "context.WithTimeout()") (path . "context/index#WithTimeout") (type . "context")) ((name . "context.WithTimeoutCause()") (path . "context/index#WithTimeoutCause") (type . "context")) ((name . "context.WithValue()") (path . "context/index#WithValue") (type . "context")) ((name . "cookiejar.Jar") (path . "net/http/cookiejar/index#Jar") (type . "net/http")) ((name . "cookiejar.Jar.Cookies()") (path . "net/http/cookiejar/index#Jar.Cookies") (type . "net/http")) ((name . "cookiejar.Jar.SetCookies()") (path . "net/http/cookiejar/index#Jar.SetCookies") (type . "net/http")) ((name . "cookiejar.New()") (path . "net/http/cookiejar/index#New") (type . "net/http")) ((name . "cookiejar.Options") (path . "net/http/cookiejar/index#Options") (type . "net/http")) ((name . "cookiejar.PublicSuffixList") (path . "net/http/cookiejar/index#PublicSuffixList") (type . "net/http")) ((name . "coverage.ClearCounters()") (path . "runtime/coverage/index#ClearCounters") (type . "runtime")) ((name . "coverage.WriteCounters()") (path . "runtime/coverage/index#WriteCounters") (type . "runtime")) ((name . "coverage.WriteCountersDir()") (path . "runtime/coverage/index#WriteCountersDir") (type . "runtime")) ((name . "coverage.WriteMeta()") (path . "runtime/coverage/index#WriteMeta") (type . "runtime")) ((name . "coverage.WriteMetaDir()") (path . "runtime/coverage/index#WriteMetaDir") (type . "runtime")) ((name . "crc32.Checksum()") (path . "hash/crc32/index#Checksum") (type . "hash")) ((name . "crc32.ChecksumIEEE()") (path . "hash/crc32/index#ChecksumIEEE") (type . "hash")) ((name . "crc32.MakeTable()") (path . "hash/crc32/index#MakeTable") (type . "hash")) ((name . "crc32.New()") (path . "hash/crc32/index#New") (type . "hash")) ((name . "crc32.NewIEEE()") (path . "hash/crc32/index#NewIEEE") (type . "hash")) ((name . "crc32.Table") (path . "hash/crc32/index#Table") (type . "hash")) ((name . "crc32.Update()") (path . "hash/crc32/index#Update") (type . "hash")) ((name . "crc64.Checksum()") (path . "hash/crc64/index#Checksum") (type . "hash")) ((name . "crc64.MakeTable()") (path . "hash/crc64/index#MakeTable") (type . "hash")) ((name . "crc64.New()") (path . "hash/crc64/index#New") (type . "hash")) ((name . "crc64.Table") (path . "hash/crc64/index#Table") (type . "hash")) ((name . "crc64.Update()") (path . "hash/crc64/index#Update") (type . "hash")) ((name . "crypto") (path . "crypto/index") (type . "crypto")) ((name . "crypto.Decrypter") (path . "crypto/index#Decrypter") (type . "crypto")) ((name . "crypto.DecrypterOpts") (path . "crypto/index#DecrypterOpts") (type . "crypto")) ((name . "crypto.Hash") (path . "crypto/index#Hash") (type . "crypto")) ((name . "crypto.Hash.Available()") (path . "crypto/index#Hash.Available") (type . "crypto")) ((name . "crypto.Hash.HashFunc()") (path . "crypto/index#Hash.HashFunc") (type . "crypto")) ((name . "crypto.Hash.New()") (path . "crypto/index#Hash.New") (type . "crypto")) ((name . "crypto.Hash.Size()") (path . "crypto/index#Hash.Size") (type . "crypto")) ((name . "crypto.Hash.String()") (path . "crypto/index#Hash.String") (type . "crypto")) ((name . "crypto.PrivateKey") (path . "crypto/index#PrivateKey") (type . "crypto")) ((name . "crypto.PublicKey") (path . "crypto/index#PublicKey") (type . "crypto")) ((name . "crypto.RegisterHash()") (path . "crypto/index#RegisterHash") (type . "crypto")) ((name . "crypto.Signer") (path . "crypto/index#Signer") (type . "crypto")) ((name . "crypto.SignerOpts") (path . "crypto/index#SignerOpts") (type . "crypto")) ((name . "crypto/aes") (path . "crypto/aes/index") (type . "crypto")) ((name . "crypto/aes constants") (path . "crypto/aes/index#pkg-constants") (type . "crypto")) ((name . "crypto/cipher") (path . "crypto/cipher/index") (type . "crypto")) ((name . "crypto/des") (path . "crypto/des/index") (type . "crypto")) ((name . "crypto/des constants") (path . "crypto/des/index#pkg-constants") (type . "crypto")) ((name . "crypto/dsa") (path . "crypto/dsa/index") (type . "crypto")) ((name . "crypto/dsa variables") (path . "crypto/dsa/index#pkg-variables") (type . "crypto")) ((name . "crypto/ecdh") (path . "crypto/ecdh/index") (type . "crypto")) ((name . "crypto/ecdsa") (path . "crypto/ecdsa/index") (type . "crypto")) ((name . "crypto/ed25519") (path . "crypto/ed25519/index") (type . "crypto")) ((name . "crypto/ed25519 constants") (path . "crypto/ed25519/index#pkg-constants") (type . "crypto")) ((name . "crypto/elliptic") (path . "crypto/elliptic/index") (type . "crypto")) ((name . "crypto/hmac") (path . "crypto/hmac/index") (type . "crypto")) ((name . "crypto/md5") (path . "crypto/md5/index") (type . "crypto")) ((name . "crypto/md5 constants") (path . "crypto/md5/index#pkg-constants") (type . "crypto")) ((name . "crypto/rand") (path . "crypto/rand/index") (type . "crypto")) ((name . "crypto/rand variables") (path . "crypto/rand/index#pkg-variables") (type . "crypto")) ((name . "crypto/rc4") (path . "crypto/rc4/index") (type . "crypto")) ((name . "crypto/rsa") (path . "crypto/rsa/index") (type . "crypto")) ((name . "crypto/rsa constants") (path . "crypto/rsa/index#pkg-constants") (type . "crypto")) ((name . "crypto/rsa variables") (path . "crypto/rsa/index#pkg-variables") (type . "crypto")) ((name . "crypto/sha1") (path . "crypto/sha1/index") (type . "crypto")) ((name . "crypto/sha1 constants") (path . "crypto/sha1/index#pkg-constants") (type . "crypto")) ((name . "crypto/sha256") (path . "crypto/sha256/index") (type . "crypto")) ((name . "crypto/sha256 constants") (path . "crypto/sha256/index#pkg-constants") (type . "crypto")) ((name . "crypto/sha512") (path . "crypto/sha512/index") (type . "crypto")) ((name . "crypto/sha512 constants") (path . "crypto/sha512/index#pkg-constants") (type . "crypto")) ((name . "crypto/subtle") (path . "crypto/subtle/index") (type . "crypto")) ((name . "crypto/tls") (path . "crypto/tls/index") (type . "crypto")) ((name . "crypto/tls constants") (path . "crypto/tls/index#pkg-constants") (type . "crypto")) ((name . "crypto/x509") (path . "crypto/x509/index") (type . "crypto")) ((name . "crypto/x509 variables") (path . "crypto/x509/index#pkg-variables") (type . "crypto")) ((name . "crypto/x509/pkix") (path . "crypto/x509/pkix/index") (type . "crypto")) ((name . "csv.NewReader()") (path . "encoding/csv/index#NewReader") (type . "encoding")) ((name . "csv.NewWriter()") (path . "encoding/csv/index#NewWriter") (type . "encoding")) ((name . "csv.ParseError") (path . "encoding/csv/index#ParseError") (type . "encoding")) ((name . "csv.ParseError.Error()") (path . "encoding/csv/index#ParseError.Error") (type . "encoding")) ((name . "csv.ParseError.Unwrap()") (path . "encoding/csv/index#ParseError.Unwrap") (type . "encoding")) ((name . "csv.Reader") (path . "encoding/csv/index#Reader") (type . "encoding")) ((name . "csv.Reader.FieldPos()") (path . "encoding/csv/index#Reader.FieldPos") (type . "encoding")) ((name . "csv.Reader.InputOffset()") (path . "encoding/csv/index#Reader.InputOffset") (type . "encoding")) ((name . "csv.Reader.Read()") (path . "encoding/csv/index#Reader.Read") (type . "encoding")) ((name . "csv.Reader.ReadAll()") (path . "encoding/csv/index#Reader.ReadAll") (type . "encoding")) ((name . "csv.Writer") (path . "encoding/csv/index#Writer") (type . "encoding")) ((name . "csv.Writer.Error()") (path . "encoding/csv/index#Writer.Error") (type . "encoding")) ((name . "csv.Writer.Flush()") (path . "encoding/csv/index#Writer.Flush") (type . "encoding")) ((name . "csv.Writer.Write()") (path . "encoding/csv/index#Writer.Write") (type . "encoding")) ((name . "csv.Writer.WriteAll()") (path . "encoding/csv/index#Writer.WriteAll") (type . "encoding")) ((name . "database/sql") (path . "database/sql/index") (type . "database")) ((name . "database/sql variables") (path . "database/sql/index#pkg-variables") (type . "database")) ((name . "database/sql/driver") (path . "database/sql/driver/index") (type . "database")) ((name . "database/sql/driver variables") (path . "database/sql/driver/index#pkg-variables") (type . "database")) ((name . "debug.BuildInfo") (path . "runtime/debug/index#BuildInfo") (type . "runtime")) ((name . "debug.BuildInfo.String()") (path . "runtime/debug/index#BuildInfo.String") (type . "runtime")) ((name . "debug.BuildSetting") (path . "runtime/debug/index#BuildSetting") (type . "runtime")) ((name . "debug.FreeOSMemory()") (path . "runtime/debug/index#FreeOSMemory") (type . "runtime")) ((name . "debug.GCStats") (path . "runtime/debug/index#GCStats") (type . "runtime")) ((name . "debug.Module") (path . "runtime/debug/index#Module") (type . "runtime")) ((name . "debug.ParseBuildInfo()") (path . "runtime/debug/index#ParseBuildInfo") (type . "runtime")) ((name . "debug.PrintStack()") (path . "runtime/debug/index#PrintStack") (type . "runtime")) ((name . "debug.ReadBuildInfo()") (path . "runtime/debug/index#ReadBuildInfo") (type . "runtime")) ((name . "debug.ReadGCStats()") (path . "runtime/debug/index#ReadGCStats") (type . "runtime")) ((name . "debug.SetGCPercent()") (path . "runtime/debug/index#SetGCPercent") (type . "runtime")) ((name . "debug.SetMaxStack()") (path . "runtime/debug/index#SetMaxStack") (type . "runtime")) ((name . "debug.SetMaxThreads()") (path . "runtime/debug/index#SetMaxThreads") (type . "runtime")) ((name . "debug.SetMemoryLimit()") (path . "runtime/debug/index#SetMemoryLimit") (type . "runtime")) ((name . "debug.SetPanicOnFault()") (path . "runtime/debug/index#SetPanicOnFault") (type . "runtime")) ((name . "debug.SetTraceback()") (path . "runtime/debug/index#SetTraceback") (type . "runtime")) ((name . "debug.Stack()") (path . "runtime/debug/index#Stack") (type . "runtime")) ((name . "debug.WriteHeapDump()") (path . "runtime/debug/index#WriteHeapDump") (type . "runtime")) ((name . "debug/buildinfo") (path . "debug/buildinfo/index") (type . "debug")) ((name . "debug/dwarf") (path . "debug/dwarf/index") (type . "debug")) ((name . "debug/dwarf variables") (path . "debug/dwarf/index#pkg-variables") (type . "debug")) ((name . "debug/elf") (path . "debug/elf/index") (type . "debug")) ((name . "debug/elf constants") (path . "debug/elf/index#pkg-constants") (type . "debug")) ((name . "debug/elf variables") (path . "debug/elf/index#pkg-variables") (type . "debug")) ((name . "debug/gosym") (path . "debug/gosym/index") (type . "debug")) ((name . "debug/macho") (path . "debug/macho/index") (type . "debug")) ((name . "debug/macho constants") (path . "debug/macho/index#pkg-constants") (type . "debug")) ((name . "debug/macho variables") (path . "debug/macho/index#pkg-variables") (type . "debug")) ((name . "debug/pe") (path . "debug/pe/index") (type . "debug")) ((name . "debug/pe constants") (path . "debug/pe/index#pkg-constants") (type . "debug")) ((name . "debug/plan9obj") (path . "debug/plan9obj/index") (type . "debug")) ((name . "debug/plan9obj constants") (path . "debug/plan9obj/index#pkg-constants") (type . "debug")) ((name . "debug/plan9obj variables") (path . "debug/plan9obj/index#pkg-variables") (type . "debug")) ((name . "des.KeySizeError") (path . "crypto/des/index#KeySizeError") (type . "crypto")) ((name . "des.KeySizeError.Error()") (path . "crypto/des/index#KeySizeError.Error") (type . "crypto")) ((name . "des.NewCipher()") (path . "crypto/des/index#NewCipher") (type . "crypto")) ((name . "des.NewTripleDESCipher()") (path . "crypto/des/index#NewTripleDESCipher") (type . "crypto")) ((name . "doc.Example") (path . "go/doc/index#Example") (type . "go")) ((name . "doc.Examples()") (path . "go/doc/index#Examples") (type . "go")) ((name . "doc.Filter") (path . "go/doc/index#Filter") (type . "go")) ((name . "doc.Func") (path . "go/doc/index#Func") (type . "go")) ((name . "doc.IsPredeclared()") (path . "go/doc/index#IsPredeclared") (type . "go")) ((name . "doc.Mode") (path . "go/doc/index#Mode") (type . "go")) ((name . "doc.New()") (path . "go/doc/index#New") (type . "go")) ((name . "doc.NewFromFiles()") (path . "go/doc/index#NewFromFiles") (type . "go")) ((name . "doc.Note") (path . "go/doc/index#Note") (type . "go")) ((name . "doc.Package") (path . "go/doc/index#Package") (type . "go")) ((name . "doc.Package.Filter()") (path . "go/doc/index#Package.Filter") (type . "go")) ((name . "doc.Package.HTML()") (path . "go/doc/index#Package.HTML") (type . "go")) ((name . "doc.Package.Markdown()") (path . "go/doc/index#Package.Markdown") (type . "go")) ((name . "doc.Package.Parser()") (path . "go/doc/index#Package.Parser") (type . "go")) ((name . "doc.Package.Printer()") (path . "go/doc/index#Package.Printer") (type . "go")) ((name . "doc.Package.Synopsis()") (path . "go/doc/index#Package.Synopsis") (type . "go")) ((name . "doc.Package.Text()") (path . "go/doc/index#Package.Text") (type . "go")) ((name . "doc.Synopsis()") (path . "go/doc/index#Synopsis") (type . "go")) ((name . "doc.ToHTML()") (path . "go/doc/index#ToHTML") (type . "go")) ((name . "doc.ToText()") (path . "go/doc/index#ToText") (type . "go")) ((name . "doc.Type") (path . "go/doc/index#Type") (type . "go")) ((name . "doc.Value") (path . "go/doc/index#Value") (type . "go")) ((name . "draw.Draw()") (path . "image/draw/index#Draw") (type . "image")) ((name . "draw.Drawer") (path . "image/draw/index#Drawer") (type . "image")) ((name . "draw.DrawMask()") (path . "image/draw/index#DrawMask") (type . "image")) ((name . "draw.Image") (path . "image/draw/index#Image") (type . "image")) ((name . "draw.Op") (path . "image/draw/index#Op") (type . "image")) ((name . "draw.Op.Draw()") (path . "image/draw/index#Op.Draw") (type . "image")) ((name . "draw.Quantizer") (path . "image/draw/index#Quantizer") (type . "image")) ((name . "draw.RGBA64Image") (path . "image/draw/index#RGBA64Image") (type . "image")) ((name . "driver.ColumnConverter") (path . "database/sql/driver/index#ColumnConverter") (type . "database")) ((name . "driver.Conn") (path . "database/sql/driver/index#Conn") (type . "database")) ((name . "driver.ConnBeginTx") (path . "database/sql/driver/index#ConnBeginTx") (type . "database")) ((name . "driver.Connector") (path . "database/sql/driver/index#Connector") (type . "database")) ((name . "driver.ConnPrepareContext") (path . "database/sql/driver/index#ConnPrepareContext") (type . "database")) ((name . "driver.Driver") (path . "database/sql/driver/index#Driver") (type . "database")) ((name . "driver.DriverContext") (path . "database/sql/driver/index#DriverContext") (type . "database")) ((name . "driver.Execer") (path . "database/sql/driver/index#Execer") (type . "database")) ((name . "driver.ExecerContext") (path . "database/sql/driver/index#ExecerContext") (type . "database")) ((name . "driver.IsolationLevel") (path . "database/sql/driver/index#IsolationLevel") (type . "database")) ((name . "driver.IsScanValue()") (path . "database/sql/driver/index#IsScanValue") (type . "database")) ((name . "driver.IsValue()") (path . "database/sql/driver/index#IsValue") (type . "database")) ((name . "driver.NamedValue") (path . "database/sql/driver/index#NamedValue") (type . "database")) ((name . "driver.NamedValueChecker") (path . "database/sql/driver/index#NamedValueChecker") (type . "database")) ((name . "driver.NotNull") (path . "database/sql/driver/index#NotNull") (type . "database")) ((name . "driver.NotNull.ConvertValue()") (path . "database/sql/driver/index#NotNull.ConvertValue") (type . "database")) ((name . "driver.Null") (path . "database/sql/driver/index#Null") (type . "database")) ((name . "driver.Null.ConvertValue()") (path . "database/sql/driver/index#Null.ConvertValue") (type . "database")) ((name . "driver.Pinger") (path . "database/sql/driver/index#Pinger") (type . "database")) ((name . "driver.Queryer") (path . "database/sql/driver/index#Queryer") (type . "database")) ((name . "driver.QueryerContext") (path . "database/sql/driver/index#QueryerContext") (type . "database")) ((name . "driver.Result") (path . "database/sql/driver/index#Result") (type . "database")) ((name . "driver.Rows") (path . "database/sql/driver/index#Rows") (type . "database")) ((name . "driver.RowsAffected") (path . "database/sql/driver/index#RowsAffected") (type . "database")) ((name . "driver.RowsAffected.LastInsertId()") (path . "database/sql/driver/index#RowsAffected.LastInsertId") (type . "database")) ((name . "driver.RowsAffected.RowsAffected()") (path . "database/sql/driver/index#RowsAffected.RowsAffected") (type . "database")) ((name . "driver.RowsColumnTypeDatabaseTypeName") (path . "database/sql/driver/index#RowsColumnTypeDatabaseTypeName") (type . "database")) ((name . "driver.RowsColumnTypeLength") (path . "database/sql/driver/index#RowsColumnTypeLength") (type . "database")) ((name . "driver.RowsColumnTypeNullable") (path . "database/sql/driver/index#RowsColumnTypeNullable") (type . "database")) ((name . "driver.RowsColumnTypePrecisionScale") (path . "database/sql/driver/index#RowsColumnTypePrecisionScale") (type . "database")) ((name . "driver.RowsColumnTypeScanType") (path . "database/sql/driver/index#RowsColumnTypeScanType") (type . "database")) ((name . "driver.RowsNextResultSet") (path . "database/sql/driver/index#RowsNextResultSet") (type . "database")) ((name . "driver.SessionResetter") (path . "database/sql/driver/index#SessionResetter") (type . "database")) ((name . "driver.Stmt") (path . "database/sql/driver/index#Stmt") (type . "database")) ((name . "driver.StmtExecContext") (path . "database/sql/driver/index#StmtExecContext") (type . "database")) ((name . "driver.StmtQueryContext") (path . "database/sql/driver/index#StmtQueryContext") (type . "database")) ((name . "driver.Tx") (path . "database/sql/driver/index#Tx") (type . "database")) ((name . "driver.TxOptions") (path . "database/sql/driver/index#TxOptions") (type . "database")) ((name . "driver.Validator") (path . "database/sql/driver/index#Validator") (type . "database")) ((name . "driver.Value") (path . "database/sql/driver/index#Value") (type . "database")) ((name . "driver.ValueConverter") (path . "database/sql/driver/index#ValueConverter") (type . "database")) ((name . "driver.Valuer") (path . "database/sql/driver/index#Valuer") (type . "database")) ((name . "dsa.GenerateKey()") (path . "crypto/dsa/index#GenerateKey") (type . "crypto")) ((name . "dsa.GenerateParameters()") (path . "crypto/dsa/index#GenerateParameters") (type . "crypto")) ((name . "dsa.Parameters") (path . "crypto/dsa/index#Parameters") (type . "crypto")) ((name . "dsa.ParameterSizes") (path . "crypto/dsa/index#ParameterSizes") (type . "crypto")) ((name . "dsa.PrivateKey") (path . "crypto/dsa/index#PrivateKey") (type . "crypto")) ((name . "dsa.PublicKey") (path . "crypto/dsa/index#PublicKey") (type . "crypto")) ((name . "dsa.Sign()") (path . "crypto/dsa/index#Sign") (type . "crypto")) ((name . "dsa.Verify()") (path . "crypto/dsa/index#Verify") (type . "crypto")) ((name . "dwarf.AddrType") (path . "debug/dwarf/index#AddrType") (type . "debug")) ((name . "dwarf.ArrayType") (path . "debug/dwarf/index#ArrayType") (type . "debug")) ((name . "dwarf.ArrayType.Size()") (path . "debug/dwarf/index#ArrayType.Size") (type . "debug")) ((name . "dwarf.ArrayType.String()") (path . "debug/dwarf/index#ArrayType.String") (type . "debug")) ((name . "dwarf.Attr") (path . "debug/dwarf/index#Attr") (type . "debug")) ((name . "dwarf.Attr.GoString()") (path . "debug/dwarf/index#Attr.GoString") (type . "debug")) ((name . "dwarf.Attr.String()") (path . "debug/dwarf/index#Attr.String") (type . "debug")) ((name . "dwarf.BasicType") (path . "debug/dwarf/index#BasicType") (type . "debug")) ((name . "dwarf.BasicType.Basic()") (path . "debug/dwarf/index#BasicType.Basic") (type . "debug")) ((name . "dwarf.BasicType.String()") (path . "debug/dwarf/index#BasicType.String") (type . "debug")) ((name . "dwarf.BoolType") (path . "debug/dwarf/index#BoolType") (type . "debug")) ((name . "dwarf.CharType") (path . "debug/dwarf/index#CharType") (type . "debug")) ((name . "dwarf.Class") (path . "debug/dwarf/index#Class") (type . "debug")) ((name . "dwarf.Class.GoString()") (path . "debug/dwarf/index#Class.GoString") (type . "debug")) ((name . "dwarf.Class.String()") (path . "debug/dwarf/index#Class.String") (type . "debug")) ((name . "dwarf.CommonType") (path . "debug/dwarf/index#CommonType") (type . "debug")) ((name . "dwarf.CommonType.Common()") (path . "debug/dwarf/index#CommonType.Common") (type . "debug")) ((name . "dwarf.CommonType.Size()") (path . "debug/dwarf/index#CommonType.Size") (type . "debug")) ((name . "dwarf.ComplexType") (path . "debug/dwarf/index#ComplexType") (type . "debug")) ((name . "dwarf.Data") (path . "debug/dwarf/index#Data") (type . "debug")) ((name . "dwarf.Data.AddSection()") (path . "debug/dwarf/index#Data.AddSection") (type . "debug")) ((name . "dwarf.Data.AddTypes()") (path . "debug/dwarf/index#Data.AddTypes") (type . "debug")) ((name . "dwarf.Data.LineReader()") (path . "debug/dwarf/index#Data.LineReader") (type . "debug")) ((name . "dwarf.Data.Ranges()") (path . "debug/dwarf/index#Data.Ranges") (type . "debug")) ((name . "dwarf.Data.Reader()") (path . "debug/dwarf/index#Data.Reader") (type . "debug")) ((name . "dwarf.Data.Type()") (path . "debug/dwarf/index#Data.Type") (type . "debug")) ((name . "dwarf.DecodeError") (path . "debug/dwarf/index#DecodeError") (type . "debug")) ((name . "dwarf.DecodeError.Error()") (path . "debug/dwarf/index#DecodeError.Error") (type . "debug")) ((name . "dwarf.DotDotDotType") (path . "debug/dwarf/index#DotDotDotType") (type . "debug")) ((name . "dwarf.DotDotDotType.String()") (path . "debug/dwarf/index#DotDotDotType.String") (type . "debug")) ((name . "dwarf.Entry") (path . "debug/dwarf/index#Entry") (type . "debug")) ((name . "dwarf.Entry.AttrField()") (path . "debug/dwarf/index#Entry.AttrField") (type . "debug")) ((name . "dwarf.Entry.Val()") (path . "debug/dwarf/index#Entry.Val") (type . "debug")) ((name . "dwarf.EnumType") (path . "debug/dwarf/index#EnumType") (type . "debug")) ((name . "dwarf.EnumType.String()") (path . "debug/dwarf/index#EnumType.String") (type . "debug")) ((name . "dwarf.EnumValue") (path . "debug/dwarf/index#EnumValue") (type . "debug")) ((name . "dwarf.Field") (path . "debug/dwarf/index#Field") (type . "debug")) ((name . "dwarf.FloatType") (path . "debug/dwarf/index#FloatType") (type . "debug")) ((name . "dwarf.FuncType") (path . "debug/dwarf/index#FuncType") (type . "debug")) ((name . "dwarf.FuncType.String()") (path . "debug/dwarf/index#FuncType.String") (type . "debug")) ((name . "dwarf.IntType") (path . "debug/dwarf/index#IntType") (type . "debug")) ((name . "dwarf.LineEntry") (path . "debug/dwarf/index#LineEntry") (type . "debug")) ((name . "dwarf.LineFile") (path . "debug/dwarf/index#LineFile") (type . "debug")) ((name . "dwarf.LineReader") (path . "debug/dwarf/index#LineReader") (type . "debug")) ((name . "dwarf.LineReader.Files()") (path . "debug/dwarf/index#LineReader.Files") (type . "debug")) ((name . "dwarf.LineReader.Next()") (path . "debug/dwarf/index#LineReader.Next") (type . "debug")) ((name . "dwarf.LineReader.Reset()") (path . "debug/dwarf/index#LineReader.Reset") (type . "debug")) ((name . "dwarf.LineReader.Seek()") (path . "debug/dwarf/index#LineReader.Seek") (type . "debug")) ((name . "dwarf.LineReader.SeekPC()") (path . "debug/dwarf/index#LineReader.SeekPC") (type . "debug")) ((name . "dwarf.LineReader.Tell()") (path . "debug/dwarf/index#LineReader.Tell") (type . "debug")) ((name . "dwarf.LineReaderPos") (path . "debug/dwarf/index#LineReaderPos") (type . "debug")) ((name . "dwarf.New()") (path . "debug/dwarf/index#New") (type . "debug")) ((name . "dwarf.Offset") (path . "debug/dwarf/index#Offset") (type . "debug")) ((name . "dwarf.PtrType") (path . "debug/dwarf/index#PtrType") (type . "debug")) ((name . "dwarf.PtrType.String()") (path . "debug/dwarf/index#PtrType.String") (type . "debug")) ((name . "dwarf.QualType") (path . "debug/dwarf/index#QualType") (type . "debug")) ((name . "dwarf.QualType.Size()") (path . "debug/dwarf/index#QualType.Size") (type . "debug")) ((name . "dwarf.QualType.String()") (path . "debug/dwarf/index#QualType.String") (type . "debug")) ((name . "dwarf.Reader") (path . "debug/dwarf/index#Reader") (type . "debug")) ((name . "dwarf.Reader.AddressSize()") (path . "debug/dwarf/index#Reader.AddressSize") (type . "debug")) ((name . "dwarf.Reader.ByteOrder()") (path . "debug/dwarf/index#Reader.ByteOrder") (type . "debug")) ((name . "dwarf.Reader.Next()") (path . "debug/dwarf/index#Reader.Next") (type . "debug")) ((name . "dwarf.Reader.Seek()") (path . "debug/dwarf/index#Reader.Seek") (type . "debug")) ((name . "dwarf.Reader.SeekPC()") (path . "debug/dwarf/index#Reader.SeekPC") (type . "debug")) ((name . "dwarf.Reader.SkipChildren()") (path . "debug/dwarf/index#Reader.SkipChildren") (type . "debug")) ((name . "dwarf.StructField") (path . "debug/dwarf/index#StructField") (type . "debug")) ((name . "dwarf.StructType") (path . "debug/dwarf/index#StructType") (type . "debug")) ((name . "dwarf.StructType.Defn()") (path . "debug/dwarf/index#StructType.Defn") (type . "debug")) ((name . "dwarf.StructType.String()") (path . "debug/dwarf/index#StructType.String") (type . "debug")) ((name . "dwarf.Tag") (path . "debug/dwarf/index#Tag") (type . "debug")) ((name . "dwarf.Tag.GoString()") (path . "debug/dwarf/index#Tag.GoString") (type . "debug")) ((name . "dwarf.Tag.String()") (path . "debug/dwarf/index#Tag.String") (type . "debug")) ((name . "dwarf.Type") (path . "debug/dwarf/index#Type") (type . "debug")) ((name . "dwarf.TypedefType") (path . "debug/dwarf/index#TypedefType") (type . "debug")) ((name . "dwarf.TypedefType.Size()") (path . "debug/dwarf/index#TypedefType.Size") (type . "debug")) ((name . "dwarf.TypedefType.String()") (path . "debug/dwarf/index#TypedefType.String") (type . "debug")) ((name . "dwarf.UcharType") (path . "debug/dwarf/index#UcharType") (type . "debug")) ((name . "dwarf.UintType") (path . "debug/dwarf/index#UintType") (type . "debug")) ((name . "dwarf.UnspecifiedType") (path . "debug/dwarf/index#UnspecifiedType") (type . "debug")) ((name . "dwarf.UnsupportedType") (path . "debug/dwarf/index#UnsupportedType") (type . "debug")) ((name . "dwarf.UnsupportedType.String()") (path . "debug/dwarf/index#UnsupportedType.String") (type . "debug")) ((name . "dwarf.VoidType") (path . "debug/dwarf/index#VoidType") (type . "debug")) ((name . "dwarf.VoidType.String()") (path . "debug/dwarf/index#VoidType.String") (type . "debug")) ((name . "ecdh.Curve") (path . "crypto/ecdh/index#Curve") (type . "crypto")) ((name . "ecdh.P256()") (path . "crypto/ecdh/index#P256") (type . "crypto")) ((name . "ecdh.P384()") (path . "crypto/ecdh/index#P384") (type . "crypto")) ((name . "ecdh.P521()") (path . "crypto/ecdh/index#P521") (type . "crypto")) ((name . "ecdh.PrivateKey") (path . "crypto/ecdh/index#PrivateKey") (type . "crypto")) ((name . "ecdh.PrivateKey.Bytes()") (path . "crypto/ecdh/index#PrivateKey.Bytes") (type . "crypto")) ((name . "ecdh.PrivateKey.Curve()") (path . "crypto/ecdh/index#PrivateKey.Curve") (type . "crypto")) ((name . "ecdh.PrivateKey.ECDH()") (path . "crypto/ecdh/index#PrivateKey.ECDH") (type . "crypto")) ((name . "ecdh.PrivateKey.Equal()") (path . "crypto/ecdh/index#PrivateKey.Equal") (type . "crypto")) ((name . "ecdh.PrivateKey.Public()") (path . "crypto/ecdh/index#PrivateKey.Public") (type . "crypto")) ((name . "ecdh.PrivateKey.PublicKey()") (path . "crypto/ecdh/index#PrivateKey.PublicKey") (type . "crypto")) ((name . "ecdh.PublicKey") (path . "crypto/ecdh/index#PublicKey") (type . "crypto")) ((name . "ecdh.PublicKey.Bytes()") (path . "crypto/ecdh/index#PublicKey.Bytes") (type . "crypto")) ((name . "ecdh.PublicKey.Curve()") (path . "crypto/ecdh/index#PublicKey.Curve") (type . "crypto")) ((name . "ecdh.PublicKey.Equal()") (path . "crypto/ecdh/index#PublicKey.Equal") (type . "crypto")) ((name . "ecdh.X25519()") (path . "crypto/ecdh/index#X25519") (type . "crypto")) ((name . "ecdsa.GenerateKey()") (path . "crypto/ecdsa/index#GenerateKey") (type . "crypto")) ((name . "ecdsa.PrivateKey") (path . "crypto/ecdsa/index#PrivateKey") (type . "crypto")) ((name . "ecdsa.PrivateKey.ECDH()") (path . "crypto/ecdsa/index#PrivateKey.ECDH") (type . "crypto")) ((name . "ecdsa.PrivateKey.Equal()") (path . "crypto/ecdsa/index#PrivateKey.Equal") (type . "crypto")) ((name . "ecdsa.PrivateKey.Public()") (path . "crypto/ecdsa/index#PrivateKey.Public") (type . "crypto")) ((name . "ecdsa.PrivateKey.Sign()") (path . "crypto/ecdsa/index#PrivateKey.Sign") (type . "crypto")) ((name . "ecdsa.PublicKey") (path . "crypto/ecdsa/index#PublicKey") (type . "crypto")) ((name . "ecdsa.PublicKey.ECDH()") (path . "crypto/ecdsa/index#PublicKey.ECDH") (type . "crypto")) ((name . "ecdsa.PublicKey.Equal()") (path . "crypto/ecdsa/index#PublicKey.Equal") (type . "crypto")) ((name . "ecdsa.Sign()") (path . "crypto/ecdsa/index#Sign") (type . "crypto")) ((name . "ecdsa.SignASN1()") (path . "crypto/ecdsa/index#SignASN1") (type . "crypto")) ((name . "ecdsa.Verify()") (path . "crypto/ecdsa/index#Verify") (type . "crypto")) ((name . "ecdsa.VerifyASN1()") (path . "crypto/ecdsa/index#VerifyASN1") (type . "crypto")) ((name . "ed25519.GenerateKey()") (path . "crypto/ed25519/index#GenerateKey") (type . "crypto")) ((name . "ed25519.NewKeyFromSeed()") (path . "crypto/ed25519/index#NewKeyFromSeed") (type . "crypto")) ((name . "ed25519.Options") (path . "crypto/ed25519/index#Options") (type . "crypto")) ((name . "ed25519.Options.HashFunc()") (path . "crypto/ed25519/index#Options.HashFunc") (type . "crypto")) ((name . "ed25519.PrivateKey") (path . "crypto/ed25519/index#PrivateKey") (type . "crypto")) ((name . "ed25519.PrivateKey.Equal()") (path . "crypto/ed25519/index#PrivateKey.Equal") (type . "crypto")) ((name . "ed25519.PrivateKey.Public()") (path . "crypto/ed25519/index#PrivateKey.Public") (type . "crypto")) ((name . "ed25519.PrivateKey.Seed()") (path . "crypto/ed25519/index#PrivateKey.Seed") (type . "crypto")) ((name . "ed25519.PrivateKey.Sign()") (path . "crypto/ed25519/index#PrivateKey.Sign") (type . "crypto")) ((name . "ed25519.PublicKey") (path . "crypto/ed25519/index#PublicKey") (type . "crypto")) ((name . "ed25519.PublicKey.Equal()") (path . "crypto/ed25519/index#PublicKey.Equal") (type . "crypto")) ((name . "ed25519.Sign()") (path . "crypto/ed25519/index#Sign") (type . "crypto")) ((name . "ed25519.Verify()") (path . "crypto/ed25519/index#Verify") (type . "crypto")) ((name . "ed25519.VerifyWithOptions()") (path . "crypto/ed25519/index#VerifyWithOptions") (type . "crypto")) ((name . "elf.Chdr32") (path . "debug/elf/index#Chdr32") (type . "debug")) ((name . "elf.Chdr64") (path . "debug/elf/index#Chdr64") (type . "debug")) ((name . "elf.Class") (path . "debug/elf/index#Class") (type . "debug")) ((name . "elf.Class.GoString()") (path . "debug/elf/index#Class.GoString") (type . "debug")) ((name . "elf.Class.String()") (path . "debug/elf/index#Class.String") (type . "debug")) ((name . "elf.CompressionType") (path . "debug/elf/index#CompressionType") (type . "debug")) ((name . "elf.CompressionType.GoString()") (path . "debug/elf/index#CompressionType.GoString") (type . "debug")) ((name . "elf.CompressionType.String()") (path . "debug/elf/index#CompressionType.String") (type . "debug")) ((name . "elf.Data") (path . "debug/elf/index#Data") (type . "debug")) ((name . "elf.Data.GoString()") (path . "debug/elf/index#Data.GoString") (type . "debug")) ((name . "elf.Data.String()") (path . "debug/elf/index#Data.String") (type . "debug")) ((name . "elf.Dyn32") (path . "debug/elf/index#Dyn32") (type . "debug")) ((name . "elf.Dyn64") (path . "debug/elf/index#Dyn64") (type . "debug")) ((name . "elf.DynFlag") (path . "debug/elf/index#DynFlag") (type . "debug")) ((name . "elf.DynFlag.GoString()") (path . "debug/elf/index#DynFlag.GoString") (type . "debug")) ((name . "elf.DynFlag.String()") (path . "debug/elf/index#DynFlag.String") (type . "debug")) ((name . "elf.DynFlag1") (path . "debug/elf/index#DynFlag1") (type . "debug")) ((name . "elf.DynFlag1.GoString()") (path . "debug/elf/index#DynFlag1.GoString") (type . "debug")) ((name . "elf.DynFlag1.String()") (path . "debug/elf/index#DynFlag1.String") (type . "debug")) ((name . "elf.DynTag") (path . "debug/elf/index#DynTag") (type . "debug")) ((name . "elf.DynTag.GoString()") (path . "debug/elf/index#DynTag.GoString") (type . "debug")) ((name . "elf.DynTag.String()") (path . "debug/elf/index#DynTag.String") (type . "debug")) ((name . "elf.File") (path . "debug/elf/index#File") (type . "debug")) ((name . "elf.File.Close()") (path . "debug/elf/index#File.Close") (type . "debug")) ((name . "elf.File.DWARF()") (path . "debug/elf/index#File.DWARF") (type . "debug")) ((name . "elf.File.DynamicSymbols()") (path . "debug/elf/index#File.DynamicSymbols") (type . "debug")) ((name . "elf.File.DynString()") (path . "debug/elf/index#File.DynString") (type . "debug")) ((name . "elf.File.DynValue()") (path . "debug/elf/index#File.DynValue") (type . "debug")) ((name . "elf.File.ImportedLibraries()") (path . "debug/elf/index#File.ImportedLibraries") (type . "debug")) ((name . "elf.File.ImportedSymbols()") (path . "debug/elf/index#File.ImportedSymbols") (type . "debug")) ((name . "elf.File.Section()") (path . "debug/elf/index#File.Section") (type . "debug")) ((name . "elf.File.SectionByType()") (path . "debug/elf/index#File.SectionByType") (type . "debug")) ((name . "elf.File.Symbols()") (path . "debug/elf/index#File.Symbols") (type . "debug")) ((name . "elf.FileHeader") (path . "debug/elf/index#FileHeader") (type . "debug")) ((name . "elf.FormatError") (path . "debug/elf/index#FormatError") (type . "debug")) ((name . "elf.FormatError.Error()") (path . "debug/elf/index#FormatError.Error") (type . "debug")) ((name . "elf.Header32") (path . "debug/elf/index#Header32") (type . "debug")) ((name . "elf.Header64") (path . "debug/elf/index#Header64") (type . "debug")) ((name . "elf.ImportedSymbol") (path . "debug/elf/index#ImportedSymbol") (type . "debug")) ((name . "elf.Machine") (path . "debug/elf/index#Machine") (type . "debug")) ((name . "elf.Machine.GoString()") (path . "debug/elf/index#Machine.GoString") (type . "debug")) ((name . "elf.Machine.String()") (path . "debug/elf/index#Machine.String") (type . "debug")) ((name . "elf.NewFile()") (path . "debug/elf/index#NewFile") (type . "debug")) ((name . "elf.NType") (path . "debug/elf/index#NType") (type . "debug")) ((name . "elf.NType.GoString()") (path . "debug/elf/index#NType.GoString") (type . "debug")) ((name . "elf.NType.String()") (path . "debug/elf/index#NType.String") (type . "debug")) ((name . "elf.Open()") (path . "debug/elf/index#Open") (type . "debug")) ((name . "elf.OSABI") (path . "debug/elf/index#OSABI") (type . "debug")) ((name . "elf.OSABI.GoString()") (path . "debug/elf/index#OSABI.GoString") (type . "debug")) ((name . "elf.OSABI.String()") (path . "debug/elf/index#OSABI.String") (type . "debug")) ((name . "elf.Prog") (path . "debug/elf/index#Prog") (type . "debug")) ((name . "elf.Prog.Open()") (path . "debug/elf/index#Prog.Open") (type . "debug")) ((name . "elf.Prog32") (path . "debug/elf/index#Prog32") (type . "debug")) ((name . "elf.Prog64") (path . "debug/elf/index#Prog64") (type . "debug")) ((name . "elf.ProgFlag") (path . "debug/elf/index#ProgFlag") (type . "debug")) ((name . "elf.ProgFlag.GoString()") (path . "debug/elf/index#ProgFlag.GoString") (type . "debug")) ((name . "elf.ProgFlag.String()") (path . "debug/elf/index#ProgFlag.String") (type . "debug")) ((name . "elf.ProgHeader") (path . "debug/elf/index#ProgHeader") (type . "debug")) ((name . "elf.ProgType") (path . "debug/elf/index#ProgType") (type . "debug")) ((name . "elf.ProgType.GoString()") (path . "debug/elf/index#ProgType.GoString") (type . "debug")) ((name . "elf.ProgType.String()") (path . "debug/elf/index#ProgType.String") (type . "debug")) ((name . "elf.R_386") (path . "debug/elf/index#R_386") (type . "debug")) ((name . "elf.R_386.GoString()") (path . "debug/elf/index#R_386.GoString") (type . "debug")) ((name . "elf.R_386.String()") (path . "debug/elf/index#R_386.String") (type . "debug")) ((name . "elf.R_390") (path . "debug/elf/index#R_390") (type . "debug")) ((name . "elf.R_390.GoString()") (path . "debug/elf/index#R_390.GoString") (type . "debug")) ((name . "elf.R_390.String()") (path . "debug/elf/index#R_390.String") (type . "debug")) ((name . "elf.R_AARCH64") (path . "debug/elf/index#R_AARCH64") (type . "debug")) ((name . "elf.R_AARCH64.GoString()") (path . "debug/elf/index#R_AARCH64.GoString") (type . "debug")) ((name . "elf.R_AARCH64.String()") (path . "debug/elf/index#R_AARCH64.String") (type . "debug")) ((name . "elf.R_ALPHA") (path . "debug/elf/index#R_ALPHA") (type . "debug")) ((name . "elf.R_ALPHA.GoString()") (path . "debug/elf/index#R_ALPHA.GoString") (type . "debug")) ((name . "elf.R_ALPHA.String()") (path . "debug/elf/index#R_ALPHA.String") (type . "debug")) ((name . "elf.R_ARM") (path . "debug/elf/index#R_ARM") (type . "debug")) ((name . "elf.R_ARM.GoString()") (path . "debug/elf/index#R_ARM.GoString") (type . "debug")) ((name . "elf.R_ARM.String()") (path . "debug/elf/index#R_ARM.String") (type . "debug")) ((name . "elf.R_INFO()") (path . "debug/elf/index#R_INFO") (type . "debug")) ((name . "elf.R_INFO32()") (path . "debug/elf/index#R_INFO32") (type . "debug")) ((name . "elf.R_LARCH") (path . "debug/elf/index#R_LARCH") (type . "debug")) ((name . "elf.R_LARCH.GoString()") (path . "debug/elf/index#R_LARCH.GoString") (type . "debug")) ((name . "elf.R_LARCH.String()") (path . "debug/elf/index#R_LARCH.String") (type . "debug")) ((name . "elf.R_MIPS") (path . "debug/elf/index#R_MIPS") (type . "debug")) ((name . "elf.R_MIPS.GoString()") (path . "debug/elf/index#R_MIPS.GoString") (type . "debug")) ((name . "elf.R_MIPS.String()") (path . "debug/elf/index#R_MIPS.String") (type . "debug")) ((name . "elf.R_PPC") (path . "debug/elf/index#R_PPC") (type . "debug")) ((name . "elf.R_PPC.GoString()") (path . "debug/elf/index#R_PPC.GoString") (type . "debug")) ((name . "elf.R_PPC.String()") (path . "debug/elf/index#R_PPC.String") (type . "debug")) ((name . "elf.R_PPC64") (path . "debug/elf/index#R_PPC64") (type . "debug")) ((name . "elf.R_PPC64.GoString()") (path . "debug/elf/index#R_PPC64.GoString") (type . "debug")) ((name . "elf.R_PPC64.String()") (path . "debug/elf/index#R_PPC64.String") (type . "debug")) ((name . "elf.R_RISCV") (path . "debug/elf/index#R_RISCV") (type . "debug")) ((name . "elf.R_RISCV.GoString()") (path . "debug/elf/index#R_RISCV.GoString") (type . "debug")) ((name . "elf.R_RISCV.String()") (path . "debug/elf/index#R_RISCV.String") (type . "debug")) ((name . "elf.R_SPARC") (path . "debug/elf/index#R_SPARC") (type . "debug")) ((name . "elf.R_SPARC.GoString()") (path . "debug/elf/index#R_SPARC.GoString") (type . "debug")) ((name . "elf.R_SPARC.String()") (path . "debug/elf/index#R_SPARC.String") (type . "debug")) ((name . "elf.R_SYM32()") (path . "debug/elf/index#R_SYM32") (type . "debug")) ((name . "elf.R_SYM64()") (path . "debug/elf/index#R_SYM64") (type . "debug")) ((name . "elf.R_TYPE32()") (path . "debug/elf/index#R_TYPE32") (type . "debug")) ((name . "elf.R_TYPE64()") (path . "debug/elf/index#R_TYPE64") (type . "debug")) ((name . "elf.R_X86_64") (path . "debug/elf/index#R_X86_64") (type . "debug")) ((name . "elf.R_X86_64.GoString()") (path . "debug/elf/index#R_X86_64.GoString") (type . "debug")) ((name . "elf.R_X86_64.String()") (path . "debug/elf/index#R_X86_64.String") (type . "debug")) ((name . "elf.Rel32") (path . "debug/elf/index#Rel32") (type . "debug")) ((name . "elf.Rel64") (path . "debug/elf/index#Rel64") (type . "debug")) ((name . "elf.Rela32") (path . "debug/elf/index#Rela32") (type . "debug")) ((name . "elf.Rela64") (path . "debug/elf/index#Rela64") (type . "debug")) ((name . "elf.Section") (path . "debug/elf/index#Section") (type . "debug")) ((name . "elf.Section.Data()") (path . "debug/elf/index#Section.Data") (type . "debug")) ((name . "elf.Section.Open()") (path . "debug/elf/index#Section.Open") (type . "debug")) ((name . "elf.Section32") (path . "debug/elf/index#Section32") (type . "debug")) ((name . "elf.Section64") (path . "debug/elf/index#Section64") (type . "debug")) ((name . "elf.SectionFlag") (path . "debug/elf/index#SectionFlag") (type . "debug")) ((name . "elf.SectionFlag.GoString()") (path . "debug/elf/index#SectionFlag.GoString") (type . "debug")) ((name . "elf.SectionFlag.String()") (path . "debug/elf/index#SectionFlag.String") (type . "debug")) ((name . "elf.SectionHeader") (path . "debug/elf/index#SectionHeader") (type . "debug")) ((name . "elf.SectionIndex") (path . "debug/elf/index#SectionIndex") (type . "debug")) ((name . "elf.SectionIndex.GoString()") (path . "debug/elf/index#SectionIndex.GoString") (type . "debug")) ((name . "elf.SectionIndex.String()") (path . "debug/elf/index#SectionIndex.String") (type . "debug")) ((name . "elf.SectionType") (path . "debug/elf/index#SectionType") (type . "debug")) ((name . "elf.SectionType.GoString()") (path . "debug/elf/index#SectionType.GoString") (type . "debug")) ((name . "elf.SectionType.String()") (path . "debug/elf/index#SectionType.String") (type . "debug")) ((name . "elf.ST_BIND()") (path . "debug/elf/index#ST_BIND") (type . "debug")) ((name . "elf.ST_INFO()") (path . "debug/elf/index#ST_INFO") (type . "debug")) ((name . "elf.ST_TYPE()") (path . "debug/elf/index#ST_TYPE") (type . "debug")) ((name . "elf.ST_VISIBILITY()") (path . "debug/elf/index#ST_VISIBILITY") (type . "debug")) ((name . "elf.Sym32") (path . "debug/elf/index#Sym32") (type . "debug")) ((name . "elf.Sym64") (path . "debug/elf/index#Sym64") (type . "debug")) ((name . "elf.SymBind") (path . "debug/elf/index#SymBind") (type . "debug")) ((name . "elf.SymBind.GoString()") (path . "debug/elf/index#SymBind.GoString") (type . "debug")) ((name . "elf.SymBind.String()") (path . "debug/elf/index#SymBind.String") (type . "debug")) ((name . "elf.Symbol") (path . "debug/elf/index#Symbol") (type . "debug")) ((name . "elf.SymType") (path . "debug/elf/index#SymType") (type . "debug")) ((name . "elf.SymType.GoString()") (path . "debug/elf/index#SymType.GoString") (type . "debug")) ((name . "elf.SymType.String()") (path . "debug/elf/index#SymType.String") (type . "debug")) ((name . "elf.SymVis") (path . "debug/elf/index#SymVis") (type . "debug")) ((name . "elf.SymVis.GoString()") (path . "debug/elf/index#SymVis.GoString") (type . "debug")) ((name . "elf.SymVis.String()") (path . "debug/elf/index#SymVis.String") (type . "debug")) ((name . "elf.Type") (path . "debug/elf/index#Type") (type . "debug")) ((name . "elf.Type.GoString()") (path . "debug/elf/index#Type.GoString") (type . "debug")) ((name . "elf.Type.String()") (path . "debug/elf/index#Type.String") (type . "debug")) ((name . "elf.Version") (path . "debug/elf/index#Version") (type . "debug")) ((name . "elf.Version.GoString()") (path . "debug/elf/index#Version.GoString") (type . "debug")) ((name . "elf.Version.String()") (path . "debug/elf/index#Version.String") (type . "debug")) ((name . "elliptic.Curve") (path . "crypto/elliptic/index#Curve") (type . "crypto")) ((name . "elliptic.CurveParams") (path . "crypto/elliptic/index#CurveParams") (type . "crypto")) ((name . "elliptic.CurveParams.Add()") (path . "crypto/elliptic/index#CurveParams.Add") (type . "crypto")) ((name . "elliptic.CurveParams.Double()") (path . "crypto/elliptic/index#CurveParams.Double") (type . "crypto")) ((name . "elliptic.CurveParams.IsOnCurve()") (path . "crypto/elliptic/index#CurveParams.IsOnCurve") (type . "crypto")) ((name . "elliptic.CurveParams.Params()") (path . "crypto/elliptic/index#CurveParams.Params") (type . "crypto")) ((name . "elliptic.CurveParams.ScalarBaseMult()") (path . "crypto/elliptic/index#CurveParams.ScalarBaseMult") (type . "crypto")) ((name . "elliptic.CurveParams.ScalarMult()") (path . "crypto/elliptic/index#CurveParams.ScalarMult") (type . "crypto")) ((name . "elliptic.GenerateKey()") (path . "crypto/elliptic/index#GenerateKey") (type . "crypto")) ((name . "elliptic.Marshal()") (path . "crypto/elliptic/index#Marshal") (type . "crypto")) ((name . "elliptic.MarshalCompressed()") (path . "crypto/elliptic/index#MarshalCompressed") (type . "crypto")) ((name . "elliptic.P224()") (path . "crypto/elliptic/index#P224") (type . "crypto")) ((name . "elliptic.P256()") (path . "crypto/elliptic/index#P256") (type . "crypto")) ((name . "elliptic.P384()") (path . "crypto/elliptic/index#P384") (type . "crypto")) ((name . "elliptic.P521()") (path . "crypto/elliptic/index#P521") (type . "crypto")) ((name . "elliptic.Unmarshal()") (path . "crypto/elliptic/index#Unmarshal") (type . "crypto")) ((name . "elliptic.UnmarshalCompressed()") (path . "crypto/elliptic/index#UnmarshalCompressed") (type . "crypto")) ((name . "embed") (path . "embed/index") (type . "embed")) ((name . "embed.FS") (path . "embed/index#FS") (type . "embed")) ((name . "embed.FS.Open()") (path . "embed/index#FS.Open") (type . "embed")) ((name . "embed.FS.ReadDir()") (path . "embed/index#FS.ReadDir") (type . "embed")) ((name . "embed.FS.ReadFile()") (path . "embed/index#FS.ReadFile") (type . "embed")) ((name . "encoding") (path . "encoding/index") (type . "encoding")) ((name . "encoding.BinaryMarshaler") (path . "encoding/index#BinaryMarshaler") (type . "encoding")) ((name . "encoding.BinaryUnmarshaler") (path . "encoding/index#BinaryUnmarshaler") (type . "encoding")) ((name . "encoding.TextMarshaler") (path . "encoding/index#TextMarshaler") (type . "encoding")) ((name . "encoding.TextUnmarshaler") (path . "encoding/index#TextUnmarshaler") (type . "encoding")) ((name . "encoding/ascii85") (path . "encoding/ascii85/index") (type . "encoding")) ((name . "encoding/asn1") (path . "encoding/asn1/index") (type . "encoding")) ((name . "encoding/asn1 constants") (path . "encoding/asn1/index#pkg-constants") (type . "encoding")) ((name . "encoding/asn1 variables") (path . "encoding/asn1/index#pkg-variables") (type . "encoding")) ((name . "encoding/base32") (path . "encoding/base32/index") (type . "encoding")) ((name . "encoding/base32 constants") (path . "encoding/base32/index#pkg-constants") (type . "encoding")) ((name . "encoding/base32 variables") (path . "encoding/base32/index#pkg-variables") (type . "encoding")) ((name . "encoding/base64") (path . "encoding/base64/index") (type . "encoding")) ((name . "encoding/base64 constants") (path . "encoding/base64/index#pkg-constants") (type . "encoding")) ((name . "encoding/base64 variables") (path . "encoding/base64/index#pkg-variables") (type . "encoding")) ((name . "encoding/binary") (path . "encoding/binary/index") (type . "encoding")) ((name . "encoding/binary constants") (path . "encoding/binary/index#pkg-constants") (type . "encoding")) ((name . "encoding/binary variables") (path . "encoding/binary/index#pkg-variables") (type . "encoding")) ((name . "encoding/csv") (path . "encoding/csv/index") (type . "encoding")) ((name . "encoding/csv variables") (path . "encoding/csv/index#pkg-variables") (type . "encoding")) ((name . "encoding/gob") (path . "encoding/gob/index") (type . "encoding")) ((name . "encoding/hex") (path . "encoding/hex/index") (type . "encoding")) ((name . "encoding/hex variables") (path . "encoding/hex/index#pkg-variables") (type . "encoding")) ((name . "encoding/json") (path . "encoding/json/index") (type . "encoding")) ((name . "encoding/pem") (path . "encoding/pem/index") (type . "encoding")) ((name . "encoding/xml") (path . "encoding/xml/index") (type . "encoding")) ((name . "encoding/xml constants") (path . "encoding/xml/index#pkg-constants") (type . "encoding")) ((name . "encoding/xml variables") (path . "encoding/xml/index#pkg-variables") (type . "encoding")) ((name . "errors") (path . "errors/index") (type . "errors")) ((name . "errors variables") (path . "errors/index#pkg-variables") (type . "errors")) ((name . "errors.As()") (path . "errors/index#As") (type . "errors")) ((name . "errors.Is()") (path . "errors/index#Is") (type . "errors")) ((name . "errors.Join()") (path . "errors/index#Join") (type . "errors")) ((name . "errors.New()") (path . "errors/index#New") (type . "errors")) ((name . "errors.Unwrap()") (path . "errors/index#Unwrap") (type . "errors")) ((name . "exec.Cmd") (path . "os/exec/index#Cmd") (type . "os")) ((name . "exec.Cmd.CombinedOutput()") (path . "os/exec/index#Cmd.CombinedOutput") (type . "os")) ((name . "exec.Cmd.Environ()") (path . "os/exec/index#Cmd.Environ") (type . "os")) ((name . "exec.Cmd.Output()") (path . "os/exec/index#Cmd.Output") (type . "os")) ((name . "exec.Cmd.Run()") (path . "os/exec/index#Cmd.Run") (type . "os")) ((name . "exec.Cmd.Start()") (path . "os/exec/index#Cmd.Start") (type . "os")) ((name . "exec.Cmd.StderrPipe()") (path . "os/exec/index#Cmd.StderrPipe") (type . "os")) ((name . "exec.Cmd.StdinPipe()") (path . "os/exec/index#Cmd.StdinPipe") (type . "os")) ((name . "exec.Cmd.StdoutPipe()") (path . "os/exec/index#Cmd.StdoutPipe") (type . "os")) ((name . "exec.Cmd.String()") (path . "os/exec/index#Cmd.String") (type . "os")) ((name . "exec.Cmd.Wait()") (path . "os/exec/index#Cmd.Wait") (type . "os")) ((name . "exec.Command()") (path . "os/exec/index#Command") (type . "os")) ((name . "exec.CommandContext()") (path . "os/exec/index#CommandContext") (type . "os")) ((name . "exec.Error") (path . "os/exec/index#Error") (type . "os")) ((name . "exec.Error.Error()") (path . "os/exec/index#Error.Error") (type . "os")) ((name . "exec.Error.Unwrap()") (path . "os/exec/index#Error.Unwrap") (type . "os")) ((name . "exec.ExitError") (path . "os/exec/index#ExitError") (type . "os")) ((name . "exec.ExitError.Error()") (path . "os/exec/index#ExitError.Error") (type . "os")) ((name . "exec.LookPath()") (path . "os/exec/index#LookPath") (type . "os")) ((name . "expvar") (path . "expvar/index") (type . "expvar")) ((name . "expvar.Do()") (path . "expvar/index#Do") (type . "expvar")) ((name . "expvar.Float") (path . "expvar/index#Float") (type . "expvar")) ((name . "expvar.Float.Add()") (path . "expvar/index#Float.Add") (type . "expvar")) ((name . "expvar.Float.Set()") (path . "expvar/index#Float.Set") (type . "expvar")) ((name . "expvar.Float.String()") (path . "expvar/index#Float.String") (type . "expvar")) ((name . "expvar.Float.Value()") (path . "expvar/index#Float.Value") (type . "expvar")) ((name . "expvar.Func") (path . "expvar/index#Func") (type . "expvar")) ((name . "expvar.Func.String()") (path . "expvar/index#Func.String") (type . "expvar")) ((name . "expvar.Func.Value()") (path . "expvar/index#Func.Value") (type . "expvar")) ((name . "expvar.Get()") (path . "expvar/index#Get") (type . "expvar")) ((name . "expvar.Handler()") (path . "expvar/index#Handler") (type . "expvar")) ((name . "expvar.Int") (path . "expvar/index#Int") (type . "expvar")) ((name . "expvar.Int.Add()") (path . "expvar/index#Int.Add") (type . "expvar")) ((name . "expvar.Int.Set()") (path . "expvar/index#Int.Set") (type . "expvar")) ((name . "expvar.Int.String()") (path . "expvar/index#Int.String") (type . "expvar")) ((name . "expvar.Int.Value()") (path . "expvar/index#Int.Value") (type . "expvar")) ((name . "expvar.KeyValue") (path . "expvar/index#KeyValue") (type . "expvar")) ((name . "expvar.Map") (path . "expvar/index#Map") (type . "expvar")) ((name . "expvar.Map.Add()") (path . "expvar/index#Map.Add") (type . "expvar")) ((name . "expvar.Map.AddFloat()") (path . "expvar/index#Map.AddFloat") (type . "expvar")) ((name . "expvar.Map.Delete()") (path . "expvar/index#Map.Delete") (type . "expvar")) ((name . "expvar.Map.Do()") (path . "expvar/index#Map.Do") (type . "expvar")) ((name . "expvar.Map.Get()") (path . "expvar/index#Map.Get") (type . "expvar")) ((name . "expvar.Map.Init()") (path . "expvar/index#Map.Init") (type . "expvar")) ((name . "expvar.Map.Set()") (path . "expvar/index#Map.Set") (type . "expvar")) ((name . "expvar.Map.String()") (path . "expvar/index#Map.String") (type . "expvar")) ((name . "expvar.NewFloat()") (path . "expvar/index#NewFloat") (type . "expvar")) ((name . "expvar.NewInt()") (path . "expvar/index#NewInt") (type . "expvar")) ((name . "expvar.NewMap()") (path . "expvar/index#NewMap") (type . "expvar")) ((name . "expvar.NewString()") (path . "expvar/index#NewString") (type . "expvar")) ((name . "expvar.Publish()") (path . "expvar/index#Publish") (type . "expvar")) ((name . "expvar.String") (path . "expvar/index#String") (type . "expvar")) ((name . "expvar.String.Set()") (path . "expvar/index#String.Set") (type . "expvar")) ((name . "expvar.String.String()") (path . "expvar/index#String.String") (type . "expvar")) ((name . "expvar.String.Value()") (path . "expvar/index#String.Value") (type . "expvar")) ((name . "expvar.Var") (path . "expvar/index#Var") (type . "expvar")) ((name . "fcgi.ProcessEnv()") (path . "net/http/fcgi/index#ProcessEnv") (type . "net/http")) ((name . "fcgi.Serve()") (path . "net/http/fcgi/index#Serve") (type . "net/http")) ((name . "filepath.Abs()") (path . "path/filepath/index#Abs") (type . "path")) ((name . "filepath.Base()") (path . "path/filepath/index#Base") (type . "path")) ((name . "filepath.Clean()") (path . "path/filepath/index#Clean") (type . "path")) ((name . "filepath.Dir()") (path . "path/filepath/index#Dir") (type . "path")) ((name . "filepath.EvalSymlinks()") (path . "path/filepath/index#EvalSymlinks") (type . "path")) ((name . "filepath.Ext()") (path . "path/filepath/index#Ext") (type . "path")) ((name . "filepath.FromSlash()") (path . "path/filepath/index#FromSlash") (type . "path")) ((name . "filepath.Glob()") (path . "path/filepath/index#Glob") (type . "path")) ((name . "filepath.HasPrefix()") (path . "path/filepath/index#HasPrefix") (type . "path")) ((name . "filepath.IsAbs()") (path . "path/filepath/index#IsAbs") (type . "path")) ((name . "filepath.IsLocal()") (path . "path/filepath/index#IsLocal") (type . "path")) ((name . "filepath.Join()") (path . "path/filepath/index#Join") (type . "path")) ((name . "filepath.Match()") (path . "path/filepath/index#Match") (type . "path")) ((name . "filepath.Rel()") (path . "path/filepath/index#Rel") (type . "path")) ((name . "filepath.Split()") (path . "path/filepath/index#Split") (type . "path")) ((name . "filepath.SplitList()") (path . "path/filepath/index#SplitList") (type . "path")) ((name . "filepath.ToSlash()") (path . "path/filepath/index#ToSlash") (type . "path")) ((name . "filepath.VolumeName()") (path . "path/filepath/index#VolumeName") (type . "path")) ((name . "filepath.Walk()") (path . "path/filepath/index#Walk") (type . "path")) ((name . "filepath.WalkDir()") (path . "path/filepath/index#WalkDir") (type . "path")) ((name . "filepath.WalkFunc") (path . "path/filepath/index#WalkFunc") (type . "path")) ((name . "flag") (path . "flag/index") (type . "flag")) ((name . "flag variables") (path . "flag/index#pkg-variables") (type . "flag")) ((name . "flag.Arg()") (path . "flag/index#Arg") (type . "flag")) ((name . "flag.Args()") (path . "flag/index#Args") (type . "flag")) ((name . "flag.Bool()") (path . "flag/index#Bool") (type . "flag")) ((name . "flag.BoolFunc()") (path . "flag/index#BoolFunc") (type . "flag")) ((name . "flag.BoolVar()") (path . "flag/index#BoolVar") (type . "flag")) ((name . "flag.Duration()") (path . "flag/index#Duration") (type . "flag")) ((name . "flag.DurationVar()") (path . "flag/index#DurationVar") (type . "flag")) ((name . "flag.ErrorHandling") (path . "flag/index#ErrorHandling") (type . "flag")) ((name . "flag.Flag") (path . "flag/index#Flag") (type . "flag")) ((name . "flag.FlagSet") (path . "flag/index#FlagSet") (type . "flag")) ((name . "flag.FlagSet.Arg()") (path . "flag/index#FlagSet.Arg") (type . "flag")) ((name . "flag.FlagSet.Args()") (path . "flag/index#FlagSet.Args") (type . "flag")) ((name . "flag.FlagSet.Bool()") (path . "flag/index#FlagSet.Bool") (type . "flag")) ((name . "flag.FlagSet.BoolFunc()") (path . "flag/index#FlagSet.BoolFunc") (type . "flag")) ((name . "flag.FlagSet.BoolVar()") (path . "flag/index#FlagSet.BoolVar") (type . "flag")) ((name . "flag.FlagSet.Duration()") (path . "flag/index#FlagSet.Duration") (type . "flag")) ((name . "flag.FlagSet.DurationVar()") (path . "flag/index#FlagSet.DurationVar") (type . "flag")) ((name . "flag.FlagSet.ErrorHandling()") (path . "flag/index#FlagSet.ErrorHandling") (type . "flag")) ((name . "flag.FlagSet.Float64()") (path . "flag/index#FlagSet.Float64") (type . "flag")) ((name . "flag.FlagSet.Float64Var()") (path . "flag/index#FlagSet.Float64Var") (type . "flag")) ((name . "flag.FlagSet.Func()") (path . "flag/index#FlagSet.Func") (type . "flag")) ((name . "flag.FlagSet.Init()") (path . "flag/index#FlagSet.Init") (type . "flag")) ((name . "flag.FlagSet.Int()") (path . "flag/index#FlagSet.Int") (type . "flag")) ((name . "flag.FlagSet.Int64()") (path . "flag/index#FlagSet.Int64") (type . "flag")) ((name . "flag.FlagSet.Int64Var()") (path . "flag/index#FlagSet.Int64Var") (type . "flag")) ((name . "flag.FlagSet.IntVar()") (path . "flag/index#FlagSet.IntVar") (type . "flag")) ((name . "flag.FlagSet.Lookup()") (path . "flag/index#FlagSet.Lookup") (type . "flag")) ((name . "flag.FlagSet.Name()") (path . "flag/index#FlagSet.Name") (type . "flag")) ((name . "flag.FlagSet.NArg()") (path . "flag/index#FlagSet.NArg") (type . "flag")) ((name . "flag.FlagSet.NFlag()") (path . "flag/index#FlagSet.NFlag") (type . "flag")) ((name . "flag.FlagSet.Output()") (path . "flag/index#FlagSet.Output") (type . "flag")) ((name . "flag.FlagSet.Parse()") (path . "flag/index#FlagSet.Parse") (type . "flag")) ((name . "flag.FlagSet.Parsed()") (path . "flag/index#FlagSet.Parsed") (type . "flag")) ((name . "flag.FlagSet.PrintDefaults()") (path . "flag/index#FlagSet.PrintDefaults") (type . "flag")) ((name . "flag.FlagSet.Set()") (path . "flag/index#FlagSet.Set") (type . "flag")) ((name . "flag.FlagSet.SetOutput()") (path . "flag/index#FlagSet.SetOutput") (type . "flag")) ((name . "flag.FlagSet.String()") (path . "flag/index#FlagSet.String") (type . "flag")) ((name . "flag.FlagSet.StringVar()") (path . "flag/index#FlagSet.StringVar") (type . "flag")) ((name . "flag.FlagSet.TextVar()") (path . "flag/index#FlagSet.TextVar") (type . "flag")) ((name . "flag.FlagSet.Uint()") (path . "flag/index#FlagSet.Uint") (type . "flag")) ((name . "flag.FlagSet.Uint64()") (path . "flag/index#FlagSet.Uint64") (type . "flag")) ((name . "flag.FlagSet.Uint64Var()") (path . "flag/index#FlagSet.Uint64Var") (type . "flag")) ((name . "flag.FlagSet.UintVar()") (path . "flag/index#FlagSet.UintVar") (type . "flag")) ((name . "flag.FlagSet.Var()") (path . "flag/index#FlagSet.Var") (type . "flag")) ((name . "flag.FlagSet.Visit()") (path . "flag/index#FlagSet.Visit") (type . "flag")) ((name . "flag.FlagSet.VisitAll()") (path . "flag/index#FlagSet.VisitAll") (type . "flag")) ((name . "flag.Float64()") (path . "flag/index#Float64") (type . "flag")) ((name . "flag.Float64Var()") (path . "flag/index#Float64Var") (type . "flag")) ((name . "flag.Func()") (path . "flag/index#Func") (type . "flag")) ((name . "flag.Getter") (path . "flag/index#Getter") (type . "flag")) ((name . "flag.Int()") (path . "flag/index#Int") (type . "flag")) ((name . "flag.Int64()") (path . "flag/index#Int64") (type . "flag")) ((name . "flag.Int64Var()") (path . "flag/index#Int64Var") (type . "flag")) ((name . "flag.IntVar()") (path . "flag/index#IntVar") (type . "flag")) ((name . "flag.Lookup()") (path . "flag/index#Lookup") (type . "flag")) ((name . "flag.NArg()") (path . "flag/index#NArg") (type . "flag")) ((name . "flag.NewFlagSet()") (path . "flag/index#NewFlagSet") (type . "flag")) ((name . "flag.NFlag()") (path . "flag/index#NFlag") (type . "flag")) ((name . "flag.Parse()") (path . "flag/index#Parse") (type . "flag")) ((name . "flag.Parsed()") (path . "flag/index#Parsed") (type . "flag")) ((name . "flag.PrintDefaults()") (path . "flag/index#PrintDefaults") (type . "flag")) ((name . "flag.Set()") (path . "flag/index#Set") (type . "flag")) ((name . "flag.String()") (path . "flag/index#String") (type . "flag")) ((name . "flag.StringVar()") (path . "flag/index#StringVar") (type . "flag")) ((name . "flag.TextVar()") (path . "flag/index#TextVar") (type . "flag")) ((name . "flag.Uint()") (path . "flag/index#Uint") (type . "flag")) ((name . "flag.Uint64()") (path . "flag/index#Uint64") (type . "flag")) ((name . "flag.Uint64Var()") (path . "flag/index#Uint64Var") (type . "flag")) ((name . "flag.UintVar()") (path . "flag/index#UintVar") (type . "flag")) ((name . "flag.UnquoteUsage()") (path . "flag/index#UnquoteUsage") (type . "flag")) ((name . "flag.Value") (path . "flag/index#Value") (type . "flag")) ((name . "flag.Var()") (path . "flag/index#Var") (type . "flag")) ((name . "flag.Visit()") (path . "flag/index#Visit") (type . "flag")) ((name . "flag.VisitAll()") (path . "flag/index#VisitAll") (type . "flag")) ((name . "flate.CorruptInputError") (path . "compress/flate/index#CorruptInputError") (type . "compress")) ((name . "flate.CorruptInputError.Error()") (path . "compress/flate/index#CorruptInputError.Error") (type . "compress")) ((name . "flate.InternalError") (path . "compress/flate/index#InternalError") (type . "compress")) ((name . "flate.InternalError.Error()") (path . "compress/flate/index#InternalError.Error") (type . "compress")) ((name . "flate.NewReader()") (path . "compress/flate/index#NewReader") (type . "compress")) ((name . "flate.NewReaderDict()") (path . "compress/flate/index#NewReaderDict") (type . "compress")) ((name . "flate.NewWriter()") (path . "compress/flate/index#NewWriter") (type . "compress")) ((name . "flate.NewWriterDict()") (path . "compress/flate/index#NewWriterDict") (type . "compress")) ((name . "flate.Reader") (path . "compress/flate/index#Reader") (type . "compress")) ((name . "flate.ReadError") (path . "compress/flate/index#ReadError") (type . "compress")) ((name . "flate.ReadError.Error()") (path . "compress/flate/index#ReadError.Error") (type . "compress")) ((name . "flate.Resetter") (path . "compress/flate/index#Resetter") (type . "compress")) ((name . "flate.WriteError") (path . "compress/flate/index#WriteError") (type . "compress")) ((name . "flate.WriteError.Error()") (path . "compress/flate/index#WriteError.Error") (type . "compress")) ((name . "flate.Writer") (path . "compress/flate/index#Writer") (type . "compress")) ((name . "flate.Writer.Close()") (path . "compress/flate/index#Writer.Close") (type . "compress")) ((name . "flate.Writer.Flush()") (path . "compress/flate/index#Writer.Flush") (type . "compress")) ((name . "flate.Writer.Reset()") (path . "compress/flate/index#Writer.Reset") (type . "compress")) ((name . "flate.Writer.Write()") (path . "compress/flate/index#Writer.Write") (type . "compress")) ((name . "fmt") (path . "fmt/index") (type . "fmt")) ((name . "fmt.Append()") (path . "fmt/index#Append") (type . "fmt")) ((name . "fmt.Appendf()") (path . "fmt/index#Appendf") (type . "fmt")) ((name . "fmt.Appendln()") (path . "fmt/index#Appendln") (type . "fmt")) ((name . "fmt.Errorf()") (path . "fmt/index#Errorf") (type . "fmt")) ((name . "fmt.FormatString()") (path . "fmt/index#FormatString") (type . "fmt")) ((name . "fmt.Formatter") (path . "fmt/index#Formatter") (type . "fmt")) ((name . "fmt.Fprint()") (path . "fmt/index#Fprint") (type . "fmt")) ((name . "fmt.Fprintf()") (path . "fmt/index#Fprintf") (type . "fmt")) ((name . "fmt.Fprintln()") (path . "fmt/index#Fprintln") (type . "fmt")) ((name . "fmt.Fscan()") (path . "fmt/index#Fscan") (type . "fmt")) ((name . "fmt.Fscanf()") (path . "fmt/index#Fscanf") (type . "fmt")) ((name . "fmt.Fscanln()") (path . "fmt/index#Fscanln") (type . "fmt")) ((name . "fmt.GoStringer") (path . "fmt/index#GoStringer") (type . "fmt")) ((name . "fmt.Print()") (path . "fmt/index#Print") (type . "fmt")) ((name . "fmt.Printf()") (path . "fmt/index#Printf") (type . "fmt")) ((name . "fmt.Println()") (path . "fmt/index#Println") (type . "fmt")) ((name . "fmt.Scan()") (path . "fmt/index#Scan") (type . "fmt")) ((name . "fmt.Scanf()") (path . "fmt/index#Scanf") (type . "fmt")) ((name . "fmt.Scanln()") (path . "fmt/index#Scanln") (type . "fmt")) ((name . "fmt.Scanner") (path . "fmt/index#Scanner") (type . "fmt")) ((name . "fmt.ScanState") (path . "fmt/index#ScanState") (type . "fmt")) ((name . "fmt.Sprint()") (path . "fmt/index#Sprint") (type . "fmt")) ((name . "fmt.Sprintf()") (path . "fmt/index#Sprintf") (type . "fmt")) ((name . "fmt.Sprintln()") (path . "fmt/index#Sprintln") (type . "fmt")) ((name . "fmt.Sscan()") (path . "fmt/index#Sscan") (type . "fmt")) ((name . "fmt.Sscanf()") (path . "fmt/index#Sscanf") (type . "fmt")) ((name . "fmt.Sscanln()") (path . "fmt/index#Sscanln") (type . "fmt")) ((name . "fmt.State") (path . "fmt/index#State") (type . "fmt")) ((name . "fmt.Stringer") (path . "fmt/index#Stringer") (type . "fmt")) ((name . "fnv.New128()") (path . "hash/fnv/index#New128") (type . "hash")) ((name . "fnv.New128a()") (path . "hash/fnv/index#New128a") (type . "hash")) ((name . "fnv.New32()") (path . "hash/fnv/index#New32") (type . "hash")) ((name . "fnv.New32a()") (path . "hash/fnv/index#New32a") (type . "hash")) ((name . "fnv.New64()") (path . "hash/fnv/index#New64") (type . "hash")) ((name . "fnv.New64a()") (path . "hash/fnv/index#New64a") (type . "hash")) ((name . "format.Node()") (path . "go/format/index#Node") (type . "go")) ((name . "format.Source()") (path . "go/format/index#Source") (type . "go")) ((name . "fs.DirEntry") (path . "io/fs/index#DirEntry") (type . "io")) ((name . "fs.File") (path . "io/fs/index#File") (type . "io")) ((name . "fs.FileInfo") (path . "io/fs/index#FileInfo") (type . "io")) ((name . "fs.FileInfoToDirEntry()") (path . "io/fs/index#FileInfoToDirEntry") (type . "io")) ((name . "fs.FileMode") (path . "io/fs/index#FileMode") (type . "io")) ((name . "fs.FileMode.IsDir()") (path . "io/fs/index#FileMode.IsDir") (type . "io")) ((name . "fs.FileMode.IsRegular()") (path . "io/fs/index#FileMode.IsRegular") (type . "io")) ((name . "fs.FileMode.Perm()") (path . "io/fs/index#FileMode.Perm") (type . "io")) ((name . "fs.FileMode.String()") (path . "io/fs/index#FileMode.String") (type . "io")) ((name . "fs.FileMode.Type()") (path . "io/fs/index#FileMode.Type") (type . "io")) ((name . "fs.FormatDirEntry()") (path . "io/fs/index#FormatDirEntry") (type . "io")) ((name . "fs.FormatFileInfo()") (path . "io/fs/index#FormatFileInfo") (type . "io")) ((name . "fs.FS") (path . "io/fs/index#FS") (type . "io")) ((name . "fs.Glob()") (path . "io/fs/index#Glob") (type . "io")) ((name . "fs.GlobFS") (path . "io/fs/index#GlobFS") (type . "io")) ((name . "fs.PathError") (path . "io/fs/index#PathError") (type . "io")) ((name . "fs.PathError.Error()") (path . "io/fs/index#PathError.Error") (type . "io")) ((name . "fs.PathError.Timeout()") (path . "io/fs/index#PathError.Timeout") (type . "io")) ((name . "fs.PathError.Unwrap()") (path . "io/fs/index#PathError.Unwrap") (type . "io")) ((name . "fs.ReadDir()") (path . "io/fs/index#ReadDir") (type . "io")) ((name . "fs.ReadDirFile") (path . "io/fs/index#ReadDirFile") (type . "io")) ((name . "fs.ReadDirFS") (path . "io/fs/index#ReadDirFS") (type . "io")) ((name . "fs.ReadFile()") (path . "io/fs/index#ReadFile") (type . "io")) ((name . "fs.ReadFileFS") (path . "io/fs/index#ReadFileFS") (type . "io")) ((name . "fs.Stat()") (path . "io/fs/index#Stat") (type . "io")) ((name . "fs.StatFS") (path . "io/fs/index#StatFS") (type . "io")) ((name . "fs.Sub()") (path . "io/fs/index#Sub") (type . "io")) ((name . "fs.SubFS") (path . "io/fs/index#SubFS") (type . "io")) ((name . "fs.ValidPath()") (path . "io/fs/index#ValidPath") (type . "io")) ((name . "fs.WalkDir()") (path . "io/fs/index#WalkDir") (type . "io")) ((name . "fs.WalkDirFunc") (path . "io/fs/index#WalkDirFunc") (type . "io")) ((name . "fstest.MapFile") (path . "testing/fstest/index#MapFile") (type . "testing")) ((name . "fstest.MapFS") (path . "testing/fstest/index#MapFS") (type . "testing")) ((name . "fstest.MapFS.Glob()") (path . "testing/fstest/index#MapFS.Glob") (type . "testing")) ((name . "fstest.MapFS.Open()") (path . "testing/fstest/index#MapFS.Open") (type . "testing")) ((name . "fstest.MapFS.ReadDir()") (path . "testing/fstest/index#MapFS.ReadDir") (type . "testing")) ((name . "fstest.MapFS.ReadFile()") (path . "testing/fstest/index#MapFS.ReadFile") (type . "testing")) ((name . "fstest.MapFS.Stat()") (path . "testing/fstest/index#MapFS.Stat") (type . "testing")) ((name . "fstest.MapFS.Sub()") (path . "testing/fstest/index#MapFS.Sub") (type . "testing")) ((name . "fstest.TestFS()") (path . "testing/fstest/index#TestFS") (type . "testing")) ((name . "gif.Decode()") (path . "image/gif/index#Decode") (type . "image")) ((name . "gif.DecodeAll()") (path . "image/gif/index#DecodeAll") (type . "image")) ((name . "gif.DecodeConfig()") (path . "image/gif/index#DecodeConfig") (type . "image")) ((name . "gif.Encode()") (path . "image/gif/index#Encode") (type . "image")) ((name . "gif.EncodeAll()") (path . "image/gif/index#EncodeAll") (type . "image")) ((name . "gif.GIF") (path . "image/gif/index#GIF") (type . "image")) ((name . "gif.Options") (path . "image/gif/index#Options") (type . "image")) ((name . "go/ast") (path . "go/ast/index") (type . "go")) ((name . "go/build") (path . "go/build/index") (type . "go")) ((name . "go/build variables") (path . "go/build/index#pkg-variables") (type . "go")) ((name . "go/build/constraint") (path . "go/build/constraint/index") (type . "go")) ((name . "go/constant") (path . "go/constant/index") (type . "go")) ((name . "go/doc") (path . "go/doc/index") (type . "go")) ((name . "go/doc variables") (path . "go/doc/index#pkg-variables") (type . "go")) ((name . "go/doc/comment") (path . "go/doc/comment/index") (type . "go")) ((name . "go/format") (path . "go/format/index") (type . "go")) ((name . "go/importer") (path . "go/importer/index") (type . "go")) ((name . "go/parser") (path . "go/parser/index") (type . "go")) ((name . "go/printer") (path . "go/printer/index") (type . "go")) ((name . "go/scanner") (path . "go/scanner/index") (type . "go")) ((name . "go/token") (path . "go/token/index") (type . "go")) ((name . "go/token constants") (path . "go/token/index#pkg-constants") (type . "go")) ((name . "go/types") (path . "go/types/index") (type . "go")) ((name . "go/types variables") (path . "go/types/index#pkg-variables") (type . "go")) ((name . "go/version") (path . "go/version/index") (type . "go")) ((name . "goarch.ArchFamilyType") (path . "internal/goarch/index#ArchFamilyType") (type . "internal")) ((name . "gob.CommonType") (path . "encoding/gob/index#CommonType") (type . "encoding")) ((name . "gob.Decoder") (path . "encoding/gob/index#Decoder") (type . "encoding")) ((name . "gob.Decoder.Decode()") (path . "encoding/gob/index#Decoder.Decode") (type . "encoding")) ((name . "gob.Decoder.DecodeValue()") (path . "encoding/gob/index#Decoder.DecodeValue") (type . "encoding")) ((name . "gob.Encoder") (path . "encoding/gob/index#Encoder") (type . "encoding")) ((name . "gob.Encoder.Encode()") (path . "encoding/gob/index#Encoder.Encode") (type . "encoding")) ((name . "gob.Encoder.EncodeValue()") (path . "encoding/gob/index#Encoder.EncodeValue") (type . "encoding")) ((name . "gob.GobDecoder") (path . "encoding/gob/index#GobDecoder") (type . "encoding")) ((name . "gob.GobEncoder") (path . "encoding/gob/index#GobEncoder") (type . "encoding")) ((name . "gob.NewDecoder()") (path . "encoding/gob/index#NewDecoder") (type . "encoding")) ((name . "gob.NewEncoder()") (path . "encoding/gob/index#NewEncoder") (type . "encoding")) ((name . "gob.Register()") (path . "encoding/gob/index#Register") (type . "encoding")) ((name . "gob.RegisterName()") (path . "encoding/gob/index#RegisterName") (type . "encoding")) ((name . "gosym.DecodingError") (path . "debug/gosym/index#DecodingError") (type . "debug")) ((name . "gosym.DecodingError.Error()") (path . "debug/gosym/index#DecodingError.Error") (type . "debug")) ((name . "gosym.Func") (path . "debug/gosym/index#Func") (type . "debug")) ((name . "gosym.LineTable") (path . "debug/gosym/index#LineTable") (type . "debug")) ((name . "gosym.LineTable.LineToPC()") (path . "debug/gosym/index#LineTable.LineToPC") (type . "debug")) ((name . "gosym.LineTable.PCToLine()") (path . "debug/gosym/index#LineTable.PCToLine") (type . "debug")) ((name . "gosym.NewLineTable()") (path . "debug/gosym/index#NewLineTable") (type . "debug")) ((name . "gosym.NewTable()") (path . "debug/gosym/index#NewTable") (type . "debug")) ((name . "gosym.Obj") (path . "debug/gosym/index#Obj") (type . "debug")) ((name . "gosym.Sym") (path . "debug/gosym/index#Sym") (type . "debug")) ((name . "gosym.Sym.BaseName()") (path . "debug/gosym/index#Sym.BaseName") (type . "debug")) ((name . "gosym.Sym.PackageName()") (path . "debug/gosym/index#Sym.PackageName") (type . "debug")) ((name . "gosym.Sym.ReceiverName()") (path . "debug/gosym/index#Sym.ReceiverName") (type . "debug")) ((name . "gosym.Sym.Static()") (path . "debug/gosym/index#Sym.Static") (type . "debug")) ((name . "gosym.Table") (path . "debug/gosym/index#Table") (type . "debug")) ((name . "gosym.Table.LineToPC()") (path . "debug/gosym/index#Table.LineToPC") (type . "debug")) ((name . "gosym.Table.LookupFunc()") (path . "debug/gosym/index#Table.LookupFunc") (type . "debug")) ((name . "gosym.Table.LookupSym()") (path . "debug/gosym/index#Table.LookupSym") (type . "debug")) ((name . "gosym.Table.PCToFunc()") (path . "debug/gosym/index#Table.PCToFunc") (type . "debug")) ((name . "gosym.Table.PCToLine()") (path . "debug/gosym/index#Table.PCToLine") (type . "debug")) ((name . "gosym.Table.SymByAddr()") (path . "debug/gosym/index#Table.SymByAddr") (type . "debug")) ((name . "gosym.UnknownFileError") (path . "debug/gosym/index#UnknownFileError") (type . "debug")) ((name . "gosym.UnknownFileError.Error()") (path . "debug/gosym/index#UnknownFileError.Error") (type . "debug")) ((name . "gosym.UnknownLineError") (path . "debug/gosym/index#UnknownLineError") (type . "debug")) ((name . "gosym.UnknownLineError.Error()") (path . "debug/gosym/index#UnknownLineError.Error") (type . "debug")) ((name . "gzip.Header") (path . "compress/gzip/index#Header") (type . "compress")) ((name . "gzip.NewReader()") (path . "compress/gzip/index#NewReader") (type . "compress")) ((name . "gzip.NewWriter()") (path . "compress/gzip/index#NewWriter") (type . "compress")) ((name . "gzip.NewWriterLevel()") (path . "compress/gzip/index#NewWriterLevel") (type . "compress")) ((name . "gzip.Reader") (path . "compress/gzip/index#Reader") (type . "compress")) ((name . "gzip.Reader.Close()") (path . "compress/gzip/index#Reader.Close") (type . "compress")) ((name . "gzip.Reader.Multistream()") (path . "compress/gzip/index#Reader.Multistream") (type . "compress")) ((name . "gzip.Reader.Read()") (path . "compress/gzip/index#Reader.Read") (type . "compress")) ((name . "gzip.Reader.Reset()") (path . "compress/gzip/index#Reader.Reset") (type . "compress")) ((name . "gzip.Writer") (path . "compress/gzip/index#Writer") (type . "compress")) ((name . "gzip.Writer.Close()") (path . "compress/gzip/index#Writer.Close") (type . "compress")) ((name . "gzip.Writer.Flush()") (path . "compress/gzip/index#Writer.Flush") (type . "compress")) ((name . "gzip.Writer.Reset()") (path . "compress/gzip/index#Writer.Reset") (type . "compress")) ((name . "gzip.Writer.Write()") (path . "compress/gzip/index#Writer.Write") (type . "compress")) ((name . "hash") (path . "hash/index") (type . "hash")) ((name . "hash.Hash") (path . "hash/index#Hash") (type . "hash")) ((name . "hash.Hash32") (path . "hash/index#Hash32") (type . "hash")) ((name . "hash.Hash64") (path . "hash/index#Hash64") (type . "hash")) ((name . "hash/adler32") (path . "hash/adler32/index") (type . "hash")) ((name . "hash/adler32 constants") (path . "hash/adler32/index#pkg-constants") (type . "hash")) ((name . "hash/crc32") (path . "hash/crc32/index") (type . "hash")) ((name . "hash/crc32 constants") (path . "hash/crc32/index#pkg-constants") (type . "hash")) ((name . "hash/crc32 variables") (path . "hash/crc32/index#pkg-variables") (type . "hash")) ((name . "hash/crc64") (path . "hash/crc64/index") (type . "hash")) ((name . "hash/crc64 constants") (path . "hash/crc64/index#pkg-constants") (type . "hash")) ((name . "hash/fnv") (path . "hash/fnv/index") (type . "hash")) ((name . "hash/maphash") (path . "hash/maphash/index") (type . "hash")) ((name . "heap.Fix()") (path . "container/heap/index#Fix") (type . "container")) ((name . "heap.Init()") (path . "container/heap/index#Init") (type . "container")) ((name . "heap.Interface") (path . "container/heap/index#Interface") (type . "container")) ((name . "heap.Pop()") (path . "container/heap/index#Pop") (type . "container")) ((name . "heap.Push()") (path . "container/heap/index#Push") (type . "container")) ((name . "heap.Remove()") (path . "container/heap/index#Remove") (type . "container")) ((name . "hex.AppendDecode()") (path . "encoding/hex/index#AppendDecode") (type . "encoding")) ((name . "hex.AppendEncode()") (path . "encoding/hex/index#AppendEncode") (type . "encoding")) ((name . "hex.Decode()") (path . "encoding/hex/index#Decode") (type . "encoding")) ((name . "hex.DecodedLen()") (path . "encoding/hex/index#DecodedLen") (type . "encoding")) ((name . "hex.DecodeString()") (path . "encoding/hex/index#DecodeString") (type . "encoding")) ((name . "hex.Dump()") (path . "encoding/hex/index#Dump") (type . "encoding")) ((name . "hex.Dumper()") (path . "encoding/hex/index#Dumper") (type . "encoding")) ((name . "hex.Encode()") (path . "encoding/hex/index#Encode") (type . "encoding")) ((name . "hex.EncodedLen()") (path . "encoding/hex/index#EncodedLen") (type . "encoding")) ((name . "hex.EncodeToString()") (path . "encoding/hex/index#EncodeToString") (type . "encoding")) ((name . "hex.InvalidByteError") (path . "encoding/hex/index#InvalidByteError") (type . "encoding")) ((name . "hex.InvalidByteError.Error()") (path . "encoding/hex/index#InvalidByteError.Error") (type . "encoding")) ((name . "hex.NewDecoder()") (path . "encoding/hex/index#NewDecoder") (type . "encoding")) ((name . "hex.NewEncoder()") (path . "encoding/hex/index#NewEncoder") (type . "encoding")) ((name . "hmac.Equal()") (path . "crypto/hmac/index#Equal") (type . "crypto")) ((name . "hmac.New()") (path . "crypto/hmac/index#New") (type . "crypto")) ((name . "html") (path . "html/index") (type . "html")) ((name . "html.EscapeString()") (path . "html/index#EscapeString") (type . "html")) ((name . "html.UnescapeString()") (path . "html/index#UnescapeString") (type . "html")) ((name . "html/template") (path . "html/template/index") (type . "html")) ((name . "http.AllowQuerySemicolons()") (path . "net/http/index#AllowQuerySemicolons") (type . "net/http")) ((name . "http.CanonicalHeaderKey()") (path . "net/http/index#CanonicalHeaderKey") (type . "net/http")) ((name . "http.Client") (path . "net/http/index#Client") (type . "net/http")) ((name . "http.Client.CloseIdleConnections()") (path . "net/http/index#Client.CloseIdleConnections") (type . "net/http")) ((name . "http.Client.Do()") (path . "net/http/index#Client.Do") (type . "net/http")) ((name . "http.Client.Get()") (path . "net/http/index#Client.Get") (type . "net/http")) ((name . "http.Client.Head()") (path . "net/http/index#Client.Head") (type . "net/http")) ((name . "http.Client.Post()") (path . "net/http/index#Client.Post") (type . "net/http")) ((name . "http.Client.PostForm()") (path . "net/http/index#Client.PostForm") (type . "net/http")) ((name . "http.CloseNotifier") (path . "net/http/index#CloseNotifier") (type . "net/http")) ((name . "http.ConnState") (path . "net/http/index#ConnState") (type . "net/http")) ((name . "http.ConnState.String()") (path . "net/http/index#ConnState.String") (type . "net/http")) ((name . "http.Cookie") (path . "net/http/index#Cookie") (type . "net/http")) ((name . "http.Cookie.String()") (path . "net/http/index#Cookie.String") (type . "net/http")) ((name . "http.Cookie.Valid()") (path . "net/http/index#Cookie.Valid") (type . "net/http")) ((name . "http.CookieJar") (path . "net/http/index#CookieJar") (type . "net/http")) ((name . "http.DetectContentType()") (path . "net/http/index#DetectContentType") (type . "net/http")) ((name . "http.Dir") (path . "net/http/index#Dir") (type . "net/http")) ((name . "http.Dir.Open()") (path . "net/http/index#Dir.Open") (type . "net/http")) ((name . "http.Error()") (path . "net/http/index#Error") (type . "net/http")) ((name . "http.File") (path . "net/http/index#File") (type . "net/http")) ((name . "http.FileServer()") (path . "net/http/index#FileServer") (type . "net/http")) ((name . "http.FileServerFS()") (path . "net/http/index#FileServerFS") (type . "net/http")) ((name . "http.FileSystem") (path . "net/http/index#FileSystem") (type . "net/http")) ((name . "http.Flusher") (path . "net/http/index#Flusher") (type . "net/http")) ((name . "http.FS()") (path . "net/http/index#FS") (type . "net/http")) ((name . "http.Get()") (path . "net/http/index#Get") (type . "net/http")) ((name . "http.Handle()") (path . "net/http/index#Handle") (type . "net/http")) ((name . "http.HandleFunc()") (path . "net/http/index#HandleFunc") (type . "net/http")) ((name . "http.Handler") (path . "net/http/index#Handler") (type . "net/http")) ((name . "http.HandlerFunc") (path . "net/http/index#HandlerFunc") (type . "net/http")) ((name . "http.HandlerFunc.ServeHTTP()") (path . "net/http/index#HandlerFunc.ServeHTTP") (type . "net/http")) ((name . "http.Head()") (path . "net/http/index#Head") (type . "net/http")) ((name . "http.Header") (path . "net/http/index#Header") (type . "net/http")) ((name . "http.Header.Add()") (path . "net/http/index#Header.Add") (type . "net/http")) ((name . "http.Header.Clone()") (path . "net/http/index#Header.Clone") (type . "net/http")) ((name . "http.Header.Del()") (path . "net/http/index#Header.Del") (type . "net/http")) ((name . "http.Header.Get()") (path . "net/http/index#Header.Get") (type . "net/http")) ((name . "http.Header.Set()") (path . "net/http/index#Header.Set") (type . "net/http")) ((name . "http.Header.Values()") (path . "net/http/index#Header.Values") (type . "net/http")) ((name . "http.Header.Write()") (path . "net/http/index#Header.Write") (type . "net/http")) ((name . "http.Header.WriteSubset()") (path . "net/http/index#Header.WriteSubset") (type . "net/http")) ((name . "http.Hijacker") (path . "net/http/index#Hijacker") (type . "net/http")) ((name . "http.ListenAndServe()") (path . "net/http/index#ListenAndServe") (type . "net/http")) ((name . "http.ListenAndServeTLS()") (path . "net/http/index#ListenAndServeTLS") (type . "net/http")) ((name . "http.MaxBytesError") (path . "net/http/index#MaxBytesError") (type . "net/http")) ((name . "http.MaxBytesError.Error()") (path . "net/http/index#MaxBytesError.Error") (type . "net/http")) ((name . "http.MaxBytesHandler()") (path . "net/http/index#MaxBytesHandler") (type . "net/http")) ((name . "http.MaxBytesReader()") (path . "net/http/index#MaxBytesReader") (type . "net/http")) ((name . "http.NewFileTransport()") (path . "net/http/index#NewFileTransport") (type . "net/http")) ((name . "http.NewFileTransportFS()") (path . "net/http/index#NewFileTransportFS") (type . "net/http")) ((name . "http.NewRequest()") (path . "net/http/index#NewRequest") (type . "net/http")) ((name . "http.NewRequestWithContext()") (path . "net/http/index#NewRequestWithContext") (type . "net/http")) ((name . "http.NewResponseController()") (path . "net/http/index#NewResponseController") (type . "net/http")) ((name . "http.NewServeMux()") (path . "net/http/index#NewServeMux") (type . "net/http")) ((name . "http.NotFound()") (path . "net/http/index#NotFound") (type . "net/http")) ((name . "http.NotFoundHandler()") (path . "net/http/index#NotFoundHandler") (type . "net/http")) ((name . "http.ParseHTTPVersion()") (path . "net/http/index#ParseHTTPVersion") (type . "net/http")) ((name . "http.ParseTime()") (path . "net/http/index#ParseTime") (type . "net/http")) ((name . "http.Post()") (path . "net/http/index#Post") (type . "net/http")) ((name . "http.PostForm()") (path . "net/http/index#PostForm") (type . "net/http")) ((name . "http.ProtocolError") (path . "net/http/index#ProtocolError") (type . "net/http")) ((name . "http.ProtocolError.Error()") (path . "net/http/index#ProtocolError.Error") (type . "net/http")) ((name . "http.ProtocolError.Is()") (path . "net/http/index#ProtocolError.Is") (type . "net/http")) ((name . "http.ProxyFromEnvironment()") (path . "net/http/index#ProxyFromEnvironment") (type . "net/http")) ((name . "http.ProxyURL()") (path . "net/http/index#ProxyURL") (type . "net/http")) ((name . "http.Pusher") (path . "net/http/index#Pusher") (type . "net/http")) ((name . "http.PushOptions") (path . "net/http/index#PushOptions") (type . "net/http")) ((name . "http.ReadRequest()") (path . "net/http/index#ReadRequest") (type . "net/http")) ((name . "http.ReadResponse()") (path . "net/http/index#ReadResponse") (type . "net/http")) ((name . "http.Redirect()") (path . "net/http/index#Redirect") (type . "net/http")) ((name . "http.RedirectHandler()") (path . "net/http/index#RedirectHandler") (type . "net/http")) ((name . "http.Request") (path . "net/http/index#Request") (type . "net/http")) ((name . "http.Request.AddCookie()") (path . "net/http/index#Request.AddCookie") (type . "net/http")) ((name . "http.Request.BasicAuth()") (path . "net/http/index#Request.BasicAuth") (type . "net/http")) ((name . "http.Request.Clone()") (path . "net/http/index#Request.Clone") (type . "net/http")) ((name . "http.Request.Context()") (path . "net/http/index#Request.Context") (type . "net/http")) ((name . "http.Request.Cookie()") (path . "net/http/index#Request.Cookie") (type . "net/http")) ((name . "http.Request.Cookies()") (path . "net/http/index#Request.Cookies") (type . "net/http")) ((name . "http.Request.FormFile()") (path . "net/http/index#Request.FormFile") (type . "net/http")) ((name . "http.Request.FormValue()") (path . "net/http/index#Request.FormValue") (type . "net/http")) ((name . "http.Request.MultipartReader()") (path . "net/http/index#Request.MultipartReader") (type . "net/http")) ((name . "http.Request.ParseForm()") (path . "net/http/index#Request.ParseForm") (type . "net/http")) ((name . "http.Request.ParseMultipartForm()") (path . "net/http/index#Request.ParseMultipartForm") (type . "net/http")) ((name . "http.Request.PathValue()") (path . "net/http/index#Request.PathValue") (type . "net/http")) ((name . "http.Request.PostFormValue()") (path . "net/http/index#Request.PostFormValue") (type . "net/http")) ((name . "http.Request.ProtoAtLeast()") (path . "net/http/index#Request.ProtoAtLeast") (type . "net/http")) ((name . "http.Request.Referer()") (path . "net/http/index#Request.Referer") (type . "net/http")) ((name . "http.Request.SetBasicAuth()") (path . "net/http/index#Request.SetBasicAuth") (type . "net/http")) ((name . "http.Request.SetPathValue()") (path . "net/http/index#Request.SetPathValue") (type . "net/http")) ((name . "http.Request.UserAgent()") (path . "net/http/index#Request.UserAgent") (type . "net/http")) ((name . "http.Request.WithContext()") (path . "net/http/index#Request.WithContext") (type . "net/http")) ((name . "http.Request.Write()") (path . "net/http/index#Request.Write") (type . "net/http")) ((name . "http.Request.WriteProxy()") (path . "net/http/index#Request.WriteProxy") (type . "net/http")) ((name . "http.Response") (path . "net/http/index#Response") (type . "net/http")) ((name . "http.Response.Cookies()") (path . "net/http/index#Response.Cookies") (type . "net/http")) ((name . "http.Response.Location()") (path . "net/http/index#Response.Location") (type . "net/http")) ((name . "http.Response.ProtoAtLeast()") (path . "net/http/index#Response.ProtoAtLeast") (type . "net/http")) ((name . "http.Response.Write()") (path . "net/http/index#Response.Write") (type . "net/http")) ((name . "http.ResponseController") (path . "net/http/index#ResponseController") (type . "net/http")) ((name . "http.ResponseController.EnableFullDuplex()") (path . "net/http/index#ResponseController.EnableFullDuplex") (type . "net/http")) ((name . "http.ResponseController.Flush()") (path . "net/http/index#ResponseController.Flush") (type . "net/http")) ((name . "http.ResponseController.Hijack()") (path . "net/http/index#ResponseController.Hijack") (type . "net/http")) ((name . "http.ResponseController.SetReadDeadline()") (path . "net/http/index#ResponseController.SetReadDeadline") (type . "net/http")) ((name . "http.ResponseController.SetWriteDeadline()") (path . "net/http/index#ResponseController.SetWriteDeadline") (type . "net/http")) ((name . "http.ResponseWriter") (path . "net/http/index#ResponseWriter") (type . "net/http")) ((name . "http.RoundTripper") (path . "net/http/index#RoundTripper") (type . "net/http")) ((name . "http.SameSite") (path . "net/http/index#SameSite") (type . "net/http")) ((name . "http.Serve()") (path . "net/http/index#Serve") (type . "net/http")) ((name . "http.ServeContent()") (path . "net/http/index#ServeContent") (type . "net/http")) ((name . "http.ServeFile()") (path . "net/http/index#ServeFile") (type . "net/http")) ((name . "http.ServeFileFS()") (path . "net/http/index#ServeFileFS") (type . "net/http")) ((name . "http.ServeMux") (path . "net/http/index#ServeMux") (type . "net/http")) ((name . "http.ServeMux.Handle()") (path . "net/http/index#ServeMux.Handle") (type . "net/http")) ((name . "http.ServeMux.HandleFunc()") (path . "net/http/index#ServeMux.HandleFunc") (type . "net/http")) ((name . "http.ServeMux.Handler()") (path . "net/http/index#ServeMux.Handler") (type . "net/http")) ((name . "http.ServeMux.ServeHTTP()") (path . "net/http/index#ServeMux.ServeHTTP") (type . "net/http")) ((name . "http.Server") (path . "net/http/index#Server") (type . "net/http")) ((name . "http.Server.Close()") (path . "net/http/index#Server.Close") (type . "net/http")) ((name . "http.Server.ListenAndServe()") (path . "net/http/index#Server.ListenAndServe") (type . "net/http")) ((name . "http.Server.ListenAndServeTLS()") (path . "net/http/index#Server.ListenAndServeTLS") (type . "net/http")) ((name . "http.Server.RegisterOnShutdown()") (path . "net/http/index#Server.RegisterOnShutdown") (type . "net/http")) ((name . "http.Server.Serve()") (path . "net/http/index#Server.Serve") (type . "net/http")) ((name . "http.Server.ServeTLS()") (path . "net/http/index#Server.ServeTLS") (type . "net/http")) ((name . "http.Server.SetKeepAlivesEnabled()") (path . "net/http/index#Server.SetKeepAlivesEnabled") (type . "net/http")) ((name . "http.Server.Shutdown()") (path . "net/http/index#Server.Shutdown") (type . "net/http")) ((name . "http.ServeTLS()") (path . "net/http/index#ServeTLS") (type . "net/http")) ((name . "http.SetCookie()") (path . "net/http/index#SetCookie") (type . "net/http")) ((name . "http.StatusText()") (path . "net/http/index#StatusText") (type . "net/http")) ((name . "http.StripPrefix()") (path . "net/http/index#StripPrefix") (type . "net/http")) ((name . "http.TimeoutHandler()") (path . "net/http/index#TimeoutHandler") (type . "net/http")) ((name . "http.Transport") (path . "net/http/index#Transport") (type . "net/http")) ((name . "http.Transport.CancelRequest()") (path . "net/http/index#Transport.CancelRequest") (type . "net/http")) ((name . "http.Transport.Clone()") (path . "net/http/index#Transport.Clone") (type . "net/http")) ((name . "http.Transport.CloseIdleConnections()") (path . "net/http/index#Transport.CloseIdleConnections") (type . "net/http")) ((name . "http.Transport.RegisterProtocol()") (path . "net/http/index#Transport.RegisterProtocol") (type . "net/http")) ((name . "http.Transport.RoundTrip()") (path . "net/http/index#Transport.RoundTrip") (type . "net/http")) ((name . "httptest.NewRecorder()") (path . "net/http/httptest/index#NewRecorder") (type . "net/http")) ((name . "httptest.NewRequest()") (path . "net/http/httptest/index#NewRequest") (type . "net/http")) ((name . "httptest.NewServer()") (path . "net/http/httptest/index#NewServer") (type . "net/http")) ((name . "httptest.NewTLSServer()") (path . "net/http/httptest/index#NewTLSServer") (type . "net/http")) ((name . "httptest.NewUnstartedServer()") (path . "net/http/httptest/index#NewUnstartedServer") (type . "net/http")) ((name . "httptest.ResponseRecorder") (path . "net/http/httptest/index#ResponseRecorder") (type . "net/http")) ((name . "httptest.ResponseRecorder.Flush()") (path . "net/http/httptest/index#ResponseRecorder.Flush") (type . "net/http")) ((name . "httptest.ResponseRecorder.Header()") (path . "net/http/httptest/index#ResponseRecorder.Header") (type . "net/http")) ((name . "httptest.ResponseRecorder.Result()") (path . "net/http/httptest/index#ResponseRecorder.Result") (type . "net/http")) ((name . "httptest.ResponseRecorder.Write()") (path . "net/http/httptest/index#ResponseRecorder.Write") (type . "net/http")) ((name . "httptest.ResponseRecorder.WriteHeader()") (path . "net/http/httptest/index#ResponseRecorder.WriteHeader") (type . "net/http")) ((name . "httptest.ResponseRecorder.WriteString()") (path . "net/http/httptest/index#ResponseRecorder.WriteString") (type . "net/http")) ((name . "httptest.Server") (path . "net/http/httptest/index#Server") (type . "net/http")) ((name . "httptest.Server.Certificate()") (path . "net/http/httptest/index#Server.Certificate") (type . "net/http")) ((name . "httptest.Server.Client()") (path . "net/http/httptest/index#Server.Client") (type . "net/http")) ((name . "httptest.Server.Close()") (path . "net/http/httptest/index#Server.Close") (type . "net/http")) ((name . "httptest.Server.CloseClientConnections()") (path . "net/http/httptest/index#Server.CloseClientConnections") (type . "net/http")) ((name . "httptest.Server.Start()") (path . "net/http/httptest/index#Server.Start") (type . "net/http")) ((name . "httptest.Server.StartTLS()") (path . "net/http/httptest/index#Server.StartTLS") (type . "net/http")) ((name . "httptrace.ClientTrace") (path . "net/http/httptrace/index#ClientTrace") (type . "net/http")) ((name . "httptrace.ContextClientTrace()") (path . "net/http/httptrace/index#ContextClientTrace") (type . "net/http")) ((name . "httptrace.DNSDoneInfo") (path . "net/http/httptrace/index#DNSDoneInfo") (type . "net/http")) ((name . "httptrace.DNSStartInfo") (path . "net/http/httptrace/index#DNSStartInfo") (type . "net/http")) ((name . "httptrace.GotConnInfo") (path . "net/http/httptrace/index#GotConnInfo") (type . "net/http")) ((name . "httptrace.WithClientTrace()") (path . "net/http/httptrace/index#WithClientTrace") (type . "net/http")) ((name . "httptrace.WroteRequestInfo") (path . "net/http/httptrace/index#WroteRequestInfo") (type . "net/http")) ((name . "httputil.BufferPool") (path . "net/http/httputil/index#BufferPool") (type . "net/http")) ((name . "httputil.ClientConn") (path . "net/http/httputil/index#ClientConn") (type . "net/http")) ((name . "httputil.ClientConn.Close()") (path . "net/http/httputil/index#ClientConn.Close") (type . "net/http")) ((name . "httputil.ClientConn.Do()") (path . "net/http/httputil/index#ClientConn.Do") (type . "net/http")) ((name . "httputil.ClientConn.Hijack()") (path . "net/http/httputil/index#ClientConn.Hijack") (type . "net/http")) ((name . "httputil.ClientConn.Pending()") (path . "net/http/httputil/index#ClientConn.Pending") (type . "net/http")) ((name . "httputil.ClientConn.Read()") (path . "net/http/httputil/index#ClientConn.Read") (type . "net/http")) ((name . "httputil.ClientConn.Write()") (path . "net/http/httputil/index#ClientConn.Write") (type . "net/http")) ((name . "httputil.DumpRequest()") (path . "net/http/httputil/index#DumpRequest") (type . "net/http")) ((name . "httputil.DumpRequestOut()") (path . "net/http/httputil/index#DumpRequestOut") (type . "net/http")) ((name . "httputil.DumpResponse()") (path . "net/http/httputil/index#DumpResponse") (type . "net/http")) ((name . "httputil.NewChunkedReader()") (path . "net/http/httputil/index#NewChunkedReader") (type . "net/http")) ((name . "httputil.NewChunkedWriter()") (path . "net/http/httputil/index#NewChunkedWriter") (type . "net/http")) ((name . "httputil.NewClientConn()") (path . "net/http/httputil/index#NewClientConn") (type . "net/http")) ((name . "httputil.NewProxyClientConn()") (path . "net/http/httputil/index#NewProxyClientConn") (type . "net/http")) ((name . "httputil.NewServerConn()") (path . "net/http/httputil/index#NewServerConn") (type . "net/http")) ((name . "httputil.NewSingleHostReverseProxy()") (path . "net/http/httputil/index#NewSingleHostReverseProxy") (type . "net/http")) ((name . "httputil.ProxyRequest") (path . "net/http/httputil/index#ProxyRequest") (type . "net/http")) ((name . "httputil.ProxyRequest.SetURL()") (path . "net/http/httputil/index#ProxyRequest.SetURL") (type . "net/http")) ((name . "httputil.ProxyRequest.SetXForwarded()") (path . "net/http/httputil/index#ProxyRequest.SetXForwarded") (type . "net/http")) ((name . "httputil.ReverseProxy") (path . "net/http/httputil/index#ReverseProxy") (type . "net/http")) ((name . "httputil.ReverseProxy.ServeHTTP()") (path . "net/http/httputil/index#ReverseProxy.ServeHTTP") (type . "net/http")) ((name . "httputil.ServerConn") (path . "net/http/httputil/index#ServerConn") (type . "net/http")) ((name . "httputil.ServerConn.Close()") (path . "net/http/httputil/index#ServerConn.Close") (type . "net/http")) ((name . "httputil.ServerConn.Hijack()") (path . "net/http/httputil/index#ServerConn.Hijack") (type . "net/http")) ((name . "httputil.ServerConn.Pending()") (path . "net/http/httputil/index#ServerConn.Pending") (type . "net/http")) ((name . "httputil.ServerConn.Read()") (path . "net/http/httputil/index#ServerConn.Read") (type . "net/http")) ((name . "httputil.ServerConn.Write()") (path . "net/http/httputil/index#ServerConn.Write") (type . "net/http")) ((name . "image") (path . "image/index") (type . "image")) ((name . "image variables") (path . "image/index#pkg-variables") (type . "image")) ((name . "image.Alpha") (path . "image/index#Alpha") (type . "image")) ((name . "image.Alpha.AlphaAt()") (path . "image/index#Alpha.AlphaAt") (type . "image")) ((name . "image.Alpha.At()") (path . "image/index#Alpha.At") (type . "image")) ((name . "image.Alpha.Bounds()") (path . "image/index#Alpha.Bounds") (type . "image")) ((name . "image.Alpha.ColorModel()") (path . "image/index#Alpha.ColorModel") (type . "image")) ((name . "image.Alpha.Opaque()") (path . "image/index#Alpha.Opaque") (type . "image")) ((name . "image.Alpha.PixOffset()") (path . "image/index#Alpha.PixOffset") (type . "image")) ((name . "image.Alpha.RGBA64At()") (path . "image/index#Alpha.RGBA64At") (type . "image")) ((name . "image.Alpha.Set()") (path . "image/index#Alpha.Set") (type . "image")) ((name . "image.Alpha.SetAlpha()") (path . "image/index#Alpha.SetAlpha") (type . "image")) ((name . "image.Alpha.SetRGBA64()") (path . "image/index#Alpha.SetRGBA64") (type . "image")) ((name . "image.Alpha.SubImage()") (path . "image/index#Alpha.SubImage") (type . "image")) ((name . "image.Alpha16") (path . "image/index#Alpha16") (type . "image")) ((name . "image.Alpha16.Alpha16At()") (path . "image/index#Alpha16.Alpha16At") (type . "image")) ((name . "image.Alpha16.At()") (path . "image/index#Alpha16.At") (type . "image")) ((name . "image.Alpha16.Bounds()") (path . "image/index#Alpha16.Bounds") (type . "image")) ((name . "image.Alpha16.ColorModel()") (path . "image/index#Alpha16.ColorModel") (type . "image")) ((name . "image.Alpha16.Opaque()") (path . "image/index#Alpha16.Opaque") (type . "image")) ((name . "image.Alpha16.PixOffset()") (path . "image/index#Alpha16.PixOffset") (type . "image")) ((name . "image.Alpha16.RGBA64At()") (path . "image/index#Alpha16.RGBA64At") (type . "image")) ((name . "image.Alpha16.Set()") (path . "image/index#Alpha16.Set") (type . "image")) ((name . "image.Alpha16.SetAlpha16()") (path . "image/index#Alpha16.SetAlpha16") (type . "image")) ((name . "image.Alpha16.SetRGBA64()") (path . "image/index#Alpha16.SetRGBA64") (type . "image")) ((name . "image.Alpha16.SubImage()") (path . "image/index#Alpha16.SubImage") (type . "image")) ((name . "image.CMYK") (path . "image/index#CMYK") (type . "image")) ((name . "image.CMYK.At()") (path . "image/index#CMYK.At") (type . "image")) ((name . "image.CMYK.Bounds()") (path . "image/index#CMYK.Bounds") (type . "image")) ((name . "image.CMYK.CMYKAt()") (path . "image/index#CMYK.CMYKAt") (type . "image")) ((name . "image.CMYK.ColorModel()") (path . "image/index#CMYK.ColorModel") (type . "image")) ((name . "image.CMYK.Opaque()") (path . "image/index#CMYK.Opaque") (type . "image")) ((name . "image.CMYK.PixOffset()") (path . "image/index#CMYK.PixOffset") (type . "image")) ((name . "image.CMYK.RGBA64At()") (path . "image/index#CMYK.RGBA64At") (type . "image")) ((name . "image.CMYK.Set()") (path . "image/index#CMYK.Set") (type . "image")) ((name . "image.CMYK.SetCMYK()") (path . "image/index#CMYK.SetCMYK") (type . "image")) ((name . "image.CMYK.SetRGBA64()") (path . "image/index#CMYK.SetRGBA64") (type . "image")) ((name . "image.CMYK.SubImage()") (path . "image/index#CMYK.SubImage") (type . "image")) ((name . "image.Config") (path . "image/index#Config") (type . "image")) ((name . "image.Decode()") (path . "image/index#Decode") (type . "image")) ((name . "image.DecodeConfig()") (path . "image/index#DecodeConfig") (type . "image")) ((name . "image.Gray") (path . "image/index#Gray") (type . "image")) ((name . "image.Gray.At()") (path . "image/index#Gray.At") (type . "image")) ((name . "image.Gray.Bounds()") (path . "image/index#Gray.Bounds") (type . "image")) ((name . "image.Gray.ColorModel()") (path . "image/index#Gray.ColorModel") (type . "image")) ((name . "image.Gray.GrayAt()") (path . "image/index#Gray.GrayAt") (type . "image")) ((name . "image.Gray.Opaque()") (path . "image/index#Gray.Opaque") (type . "image")) ((name . "image.Gray.PixOffset()") (path . "image/index#Gray.PixOffset") (type . "image")) ((name . "image.Gray.RGBA64At()") (path . "image/index#Gray.RGBA64At") (type . "image")) ((name . "image.Gray.Set()") (path . "image/index#Gray.Set") (type . "image")) ((name . "image.Gray.SetGray()") (path . "image/index#Gray.SetGray") (type . "image")) ((name . "image.Gray.SetRGBA64()") (path . "image/index#Gray.SetRGBA64") (type . "image")) ((name . "image.Gray.SubImage()") (path . "image/index#Gray.SubImage") (type . "image")) ((name . "image.Gray16") (path . "image/index#Gray16") (type . "image")) ((name . "image.Gray16.At()") (path . "image/index#Gray16.At") (type . "image")) ((name . "image.Gray16.Bounds()") (path . "image/index#Gray16.Bounds") (type . "image")) ((name . "image.Gray16.ColorModel()") (path . "image/index#Gray16.ColorModel") (type . "image")) ((name . "image.Gray16.Gray16At()") (path . "image/index#Gray16.Gray16At") (type . "image")) ((name . "image.Gray16.Opaque()") (path . "image/index#Gray16.Opaque") (type . "image")) ((name . "image.Gray16.PixOffset()") (path . "image/index#Gray16.PixOffset") (type . "image")) ((name . "image.Gray16.RGBA64At()") (path . "image/index#Gray16.RGBA64At") (type . "image")) ((name . "image.Gray16.Set()") (path . "image/index#Gray16.Set") (type . "image")) ((name . "image.Gray16.SetGray16()") (path . "image/index#Gray16.SetGray16") (type . "image")) ((name . "image.Gray16.SetRGBA64()") (path . "image/index#Gray16.SetRGBA64") (type . "image")) ((name . "image.Gray16.SubImage()") (path . "image/index#Gray16.SubImage") (type . "image")) ((name . "image.Image") (path . "image/index#Image") (type . "image")) ((name . "image.NewAlpha()") (path . "image/index#NewAlpha") (type . "image")) ((name . "image.NewAlpha16()") (path . "image/index#NewAlpha16") (type . "image")) ((name . "image.NewCMYK()") (path . "image/index#NewCMYK") (type . "image")) ((name . "image.NewGray()") (path . "image/index#NewGray") (type . "image")) ((name . "image.NewGray16()") (path . "image/index#NewGray16") (type . "image")) ((name . "image.NewNRGBA()") (path . "image/index#NewNRGBA") (type . "image")) ((name . "image.NewNRGBA64()") (path . "image/index#NewNRGBA64") (type . "image")) ((name . "image.NewNYCbCrA()") (path . "image/index#NewNYCbCrA") (type . "image")) ((name . "image.NewPaletted()") (path . "image/index#NewPaletted") (type . "image")) ((name . "image.NewRGBA()") (path . "image/index#NewRGBA") (type . "image")) ((name . "image.NewRGBA64()") (path . "image/index#NewRGBA64") (type . "image")) ((name . "image.NewUniform()") (path . "image/index#NewUniform") (type . "image")) ((name . "image.NewYCbCr()") (path . "image/index#NewYCbCr") (type . "image")) ((name . "image.NRGBA") (path . "image/index#NRGBA") (type . "image")) ((name . "image.NRGBA.At()") (path . "image/index#NRGBA.At") (type . "image")) ((name . "image.NRGBA.Bounds()") (path . "image/index#NRGBA.Bounds") (type . "image")) ((name . "image.NRGBA.ColorModel()") (path . "image/index#NRGBA.ColorModel") (type . "image")) ((name . "image.NRGBA.NRGBAAt()") (path . "image/index#NRGBA.NRGBAAt") (type . "image")) ((name . "image.NRGBA.Opaque()") (path . "image/index#NRGBA.Opaque") (type . "image")) ((name . "image.NRGBA.PixOffset()") (path . "image/index#NRGBA.PixOffset") (type . "image")) ((name . "image.NRGBA.RGBA64At()") (path . "image/index#NRGBA.RGBA64At") (type . "image")) ((name . "image.NRGBA.Set()") (path . "image/index#NRGBA.Set") (type . "image")) ((name . "image.NRGBA.SetNRGBA()") (path . "image/index#NRGBA.SetNRGBA") (type . "image")) ((name . "image.NRGBA.SetRGBA64()") (path . "image/index#NRGBA.SetRGBA64") (type . "image")) ((name . "image.NRGBA.SubImage()") (path . "image/index#NRGBA.SubImage") (type . "image")) ((name . "image.NRGBA64") (path . "image/index#NRGBA64") (type . "image")) ((name . "image.NRGBA64.At()") (path . "image/index#NRGBA64.At") (type . "image")) ((name . "image.NRGBA64.Bounds()") (path . "image/index#NRGBA64.Bounds") (type . "image")) ((name . "image.NRGBA64.ColorModel()") (path . "image/index#NRGBA64.ColorModel") (type . "image")) ((name . "image.NRGBA64.NRGBA64At()") (path . "image/index#NRGBA64.NRGBA64At") (type . "image")) ((name . "image.NRGBA64.Opaque()") (path . "image/index#NRGBA64.Opaque") (type . "image")) ((name . "image.NRGBA64.PixOffset()") (path . "image/index#NRGBA64.PixOffset") (type . "image")) ((name . "image.NRGBA64.RGBA64At()") (path . "image/index#NRGBA64.RGBA64At") (type . "image")) ((name . "image.NRGBA64.Set()") (path . "image/index#NRGBA64.Set") (type . "image")) ((name . "image.NRGBA64.SetNRGBA64()") (path . "image/index#NRGBA64.SetNRGBA64") (type . "image")) ((name . "image.NRGBA64.SetRGBA64()") (path . "image/index#NRGBA64.SetRGBA64") (type . "image")) ((name . "image.NRGBA64.SubImage()") (path . "image/index#NRGBA64.SubImage") (type . "image")) ((name . "image.NYCbCrA") (path . "image/index#NYCbCrA") (type . "image")) ((name . "image.NYCbCrA.AOffset()") (path . "image/index#NYCbCrA.AOffset") (type . "image")) ((name . "image.NYCbCrA.At()") (path . "image/index#NYCbCrA.At") (type . "image")) ((name . "image.NYCbCrA.ColorModel()") (path . "image/index#NYCbCrA.ColorModel") (type . "image")) ((name . "image.NYCbCrA.NYCbCrAAt()") (path . "image/index#NYCbCrA.NYCbCrAAt") (type . "image")) ((name . "image.NYCbCrA.Opaque()") (path . "image/index#NYCbCrA.Opaque") (type . "image")) ((name . "image.NYCbCrA.RGBA64At()") (path . "image/index#NYCbCrA.RGBA64At") (type . "image")) ((name . "image.NYCbCrA.SubImage()") (path . "image/index#NYCbCrA.SubImage") (type . "image")) ((name . "image.Paletted") (path . "image/index#Paletted") (type . "image")) ((name . "image.Paletted.At()") (path . "image/index#Paletted.At") (type . "image")) ((name . "image.Paletted.Bounds()") (path . "image/index#Paletted.Bounds") (type . "image")) ((name . "image.Paletted.ColorIndexAt()") (path . "image/index#Paletted.ColorIndexAt") (type . "image")) ((name . "image.Paletted.ColorModel()") (path . "image/index#Paletted.ColorModel") (type . "image")) ((name . "image.Paletted.Opaque()") (path . "image/index#Paletted.Opaque") (type . "image")) ((name . "image.Paletted.PixOffset()") (path . "image/index#Paletted.PixOffset") (type . "image")) ((name . "image.Paletted.RGBA64At()") (path . "image/index#Paletted.RGBA64At") (type . "image")) ((name . "image.Paletted.Set()") (path . "image/index#Paletted.Set") (type . "image")) ((name . "image.Paletted.SetColorIndex()") (path . "image/index#Paletted.SetColorIndex") (type . "image")) ((name . "image.Paletted.SetRGBA64()") (path . "image/index#Paletted.SetRGBA64") (type . "image")) ((name . "image.Paletted.SubImage()") (path . "image/index#Paletted.SubImage") (type . "image")) ((name . "image.PalettedImage") (path . "image/index#PalettedImage") (type . "image")) ((name . "image.Point") (path . "image/index#Point") (type . "image")) ((name . "image.Point.Add()") (path . "image/index#Point.Add") (type . "image")) ((name . "image.Point.Div()") (path . "image/index#Point.Div") (type . "image")) ((name . "image.Point.Eq()") (path . "image/index#Point.Eq") (type . "image")) ((name . "image.Point.In()") (path . "image/index#Point.In") (type . "image")) ((name . "image.Point.Mod()") (path . "image/index#Point.Mod") (type . "image")) ((name . "image.Point.Mul()") (path . "image/index#Point.Mul") (type . "image")) ((name . "image.Point.String()") (path . "image/index#Point.String") (type . "image")) ((name . "image.Point.Sub()") (path . "image/index#Point.Sub") (type . "image")) ((name . "image.Pt()") (path . "image/index#Pt") (type . "image")) ((name . "image.Rect()") (path . "image/index#Rect") (type . "image")) ((name . "image.Rectangle") (path . "image/index#Rectangle") (type . "image")) ((name . "image.Rectangle.Add()") (path . "image/index#Rectangle.Add") (type . "image")) ((name . "image.Rectangle.At()") (path . "image/index#Rectangle.At") (type . "image")) ((name . "image.Rectangle.Bounds()") (path . "image/index#Rectangle.Bounds") (type . "image")) ((name . "image.Rectangle.Canon()") (path . "image/index#Rectangle.Canon") (type . "image")) ((name . "image.Rectangle.ColorModel()") (path . "image/index#Rectangle.ColorModel") (type . "image")) ((name . "image.Rectangle.Dx()") (path . "image/index#Rectangle.Dx") (type . "image")) ((name . "image.Rectangle.Dy()") (path . "image/index#Rectangle.Dy") (type . "image")) ((name . "image.Rectangle.Empty()") (path . "image/index#Rectangle.Empty") (type . "image")) ((name . "image.Rectangle.Eq()") (path . "image/index#Rectangle.Eq") (type . "image")) ((name . "image.Rectangle.In()") (path . "image/index#Rectangle.In") (type . "image")) ((name . "image.Rectangle.Inset()") (path . "image/index#Rectangle.Inset") (type . "image")) ((name . "image.Rectangle.Intersect()") (path . "image/index#Rectangle.Intersect") (type . "image")) ((name . "image.Rectangle.Overlaps()") (path . "image/index#Rectangle.Overlaps") (type . "image")) ((name . "image.Rectangle.RGBA64At()") (path . "image/index#Rectangle.RGBA64At") (type . "image")) ((name . "image.Rectangle.Size()") (path . "image/index#Rectangle.Size") (type . "image")) ((name . "image.Rectangle.String()") (path . "image/index#Rectangle.String") (type . "image")) ((name . "image.Rectangle.Sub()") (path . "image/index#Rectangle.Sub") (type . "image")) ((name . "image.Rectangle.Union()") (path . "image/index#Rectangle.Union") (type . "image")) ((name . "image.RegisterFormat()") (path . "image/index#RegisterFormat") (type . "image")) ((name . "image.RGBA") (path . "image/index#RGBA") (type . "image")) ((name . "image.RGBA.At()") (path . "image/index#RGBA.At") (type . "image")) ((name . "image.RGBA.Bounds()") (path . "image/index#RGBA.Bounds") (type . "image")) ((name . "image.RGBA.ColorModel()") (path . "image/index#RGBA.ColorModel") (type . "image")) ((name . "image.RGBA.Opaque()") (path . "image/index#RGBA.Opaque") (type . "image")) ((name . "image.RGBA.PixOffset()") (path . "image/index#RGBA.PixOffset") (type . "image")) ((name . "image.RGBA.RGBA64At()") (path . "image/index#RGBA.RGBA64At") (type . "image")) ((name . "image.RGBA.RGBAAt()") (path . "image/index#RGBA.RGBAAt") (type . "image")) ((name . "image.RGBA.Set()") (path . "image/index#RGBA.Set") (type . "image")) ((name . "image.RGBA.SetRGBA()") (path . "image/index#RGBA.SetRGBA") (type . "image")) ((name . "image.RGBA.SetRGBA64()") (path . "image/index#RGBA.SetRGBA64") (type . "image")) ((name . "image.RGBA.SubImage()") (path . "image/index#RGBA.SubImage") (type . "image")) ((name . "image.RGBA64") (path . "image/index#RGBA64") (type . "image")) ((name . "image.RGBA64.At()") (path . "image/index#RGBA64.At") (type . "image")) ((name . "image.RGBA64.Bounds()") (path . "image/index#RGBA64.Bounds") (type . "image")) ((name . "image.RGBA64.ColorModel()") (path . "image/index#RGBA64.ColorModel") (type . "image")) ((name . "image.RGBA64.Opaque()") (path . "image/index#RGBA64.Opaque") (type . "image")) ((name . "image.RGBA64.PixOffset()") (path . "image/index#RGBA64.PixOffset") (type . "image")) ((name . "image.RGBA64.RGBA64At()") (path . "image/index#RGBA64.RGBA64At") (type . "image")) ((name . "image.RGBA64.Set()") (path . "image/index#RGBA64.Set") (type . "image")) ((name . "image.RGBA64.SetRGBA64()") (path . "image/index#RGBA64.SetRGBA64") (type . "image")) ((name . "image.RGBA64.SubImage()") (path . "image/index#RGBA64.SubImage") (type . "image")) ((name . "image.RGBA64Image") (path . "image/index#RGBA64Image") (type . "image")) ((name . "image.Uniform") (path . "image/index#Uniform") (type . "image")) ((name . "image.Uniform.At()") (path . "image/index#Uniform.At") (type . "image")) ((name . "image.Uniform.Bounds()") (path . "image/index#Uniform.Bounds") (type . "image")) ((name . "image.Uniform.ColorModel()") (path . "image/index#Uniform.ColorModel") (type . "image")) ((name . "image.Uniform.Convert()") (path . "image/index#Uniform.Convert") (type . "image")) ((name . "image.Uniform.Opaque()") (path . "image/index#Uniform.Opaque") (type . "image")) ((name . "image.Uniform.RGBA()") (path . "image/index#Uniform.RGBA") (type . "image")) ((name . "image.Uniform.RGBA64At()") (path . "image/index#Uniform.RGBA64At") (type . "image")) ((name . "image.YCbCr") (path . "image/index#YCbCr") (type . "image")) ((name . "image.YCbCr.At()") (path . "image/index#YCbCr.At") (type . "image")) ((name . "image.YCbCr.Bounds()") (path . "image/index#YCbCr.Bounds") (type . "image")) ((name . "image.YCbCr.COffset()") (path . "image/index#YCbCr.COffset") (type . "image")) ((name . "image.YCbCr.ColorModel()") (path . "image/index#YCbCr.ColorModel") (type . "image")) ((name . "image.YCbCr.Opaque()") (path . "image/index#YCbCr.Opaque") (type . "image")) ((name . "image.YCbCr.RGBA64At()") (path . "image/index#YCbCr.RGBA64At") (type . "image")) ((name . "image.YCbCr.SubImage()") (path . "image/index#YCbCr.SubImage") (type . "image")) ((name . "image.YCbCr.YCbCrAt()") (path . "image/index#YCbCr.YCbCrAt") (type . "image")) ((name . "image.YCbCr.YOffset()") (path . "image/index#YCbCr.YOffset") (type . "image")) ((name . "image.YCbCrSubsampleRatio") (path . "image/index#YCbCrSubsampleRatio") (type . "image")) ((name . "image.YCbCrSubsampleRatio.String()") (path . "image/index#YCbCrSubsampleRatio.String") (type . "image")) ((name . "image/color") (path . "image/color/index") (type . "image")) ((name . "image/color variables") (path . "image/color/index#pkg-variables") (type . "image")) ((name . "image/color/palette") (path . "image/color/palette/index") (type . "image")) ((name . "image/color/palette variables") (path . "image/color/palette/index#pkg-variables") (type . "image")) ((name . "image/draw") (path . "image/draw/index") (type . "image")) ((name . "image/gif") (path . "image/gif/index") (type . "image")) ((name . "image/gif constants") (path . "image/gif/index#pkg-constants") (type . "image")) ((name . "image/jpeg") (path . "image/jpeg/index") (type . "image")) ((name . "image/jpeg constants") (path . "image/jpeg/index#pkg-constants") (type . "image")) ((name . "image/png") (path . "image/png/index") (type . "image")) ((name . "importer.Default()") (path . "go/importer/index#Default") (type . "go")) ((name . "importer.For()") (path . "go/importer/index#For") (type . "go")) ((name . "importer.ForCompiler()") (path . "go/importer/index#ForCompiler") (type . "go")) ((name . "importer.Lookup") (path . "go/importer/index#Lookup") (type . "go")) ((name . "index/suffixarray") (path . "index/suffixarray/index") (type . "index")) ((name . "internal.FlushAfterChunkWriter") (path . "net/http/internal/index#FlushAfterChunkWriter") (type . "net/http")) ((name . "internal.NewChunkedReader()") (path . "net/http/internal/index#NewChunkedReader") (type . "net/http")) ((name . "internal.NewChunkedWriter()") (path . "net/http/internal/index#NewChunkedWriter") (type . "net/http")) ((name . "internal/goarch") (path . "internal/goarch/index") (type . "internal")) ((name . "internal/goarch constants") (path . "internal/goarch/index#pkg-constants") (type . "internal")) ((name . "internal/goos") (path . "internal/goos/index") (type . "internal")) ((name . "internal/goos constants") (path . "internal/goos/index#pkg-constants") (type . "internal")) ((name . "io") (path . "io/index") (type . "io")) ((name . "io constants") (path . "io/index#pkg-constants") (type . "io")) ((name . "io variables") (path . "io/index#pkg-variables") (type . "io")) ((name . "io.ByteReader") (path . "io/index#ByteReader") (type . "io")) ((name . "io.ByteScanner") (path . "io/index#ByteScanner") (type . "io")) ((name . "io.ByteWriter") (path . "io/index#ByteWriter") (type . "io")) ((name . "io.Closer") (path . "io/index#Closer") (type . "io")) ((name . "io.Copy()") (path . "io/index#Copy") (type . "io")) ((name . "io.CopyBuffer()") (path . "io/index#CopyBuffer") (type . "io")) ((name . "io.CopyN()") (path . "io/index#CopyN") (type . "io")) ((name . "io.LimitedReader") (path . "io/index#LimitedReader") (type . "io")) ((name . "io.LimitedReader.Read()") (path . "io/index#LimitedReader.Read") (type . "io")) ((name . "io.LimitReader()") (path . "io/index#LimitReader") (type . "io")) ((name . "io.MultiReader()") (path . "io/index#MultiReader") (type . "io")) ((name . "io.MultiWriter()") (path . "io/index#MultiWriter") (type . "io")) ((name . "io.NewOffsetWriter()") (path . "io/index#NewOffsetWriter") (type . "io")) ((name . "io.NewSectionReader()") (path . "io/index#NewSectionReader") (type . "io")) ((name . "io.NopCloser()") (path . "io/index#NopCloser") (type . "io")) ((name . "io.OffsetWriter") (path . "io/index#OffsetWriter") (type . "io")) ((name . "io.OffsetWriter.Seek()") (path . "io/index#OffsetWriter.Seek") (type . "io")) ((name . "io.OffsetWriter.Write()") (path . "io/index#OffsetWriter.Write") (type . "io")) ((name . "io.OffsetWriter.WriteAt()") (path . "io/index#OffsetWriter.WriteAt") (type . "io")) ((name . "io.Pipe()") (path . "io/index#Pipe") (type . "io")) ((name . "io.PipeReader") (path . "io/index#PipeReader") (type . "io")) ((name . "io.PipeReader.Close()") (path . "io/index#PipeReader.Close") (type . "io")) ((name . "io.PipeReader.CloseWithError()") (path . "io/index#PipeReader.CloseWithError") (type . "io")) ((name . "io.PipeReader.Read()") (path . "io/index#PipeReader.Read") (type . "io")) ((name . "io.PipeWriter") (path . "io/index#PipeWriter") (type . "io")) ((name . "io.PipeWriter.Close()") (path . "io/index#PipeWriter.Close") (type . "io")) ((name . "io.PipeWriter.CloseWithError()") (path . "io/index#PipeWriter.CloseWithError") (type . "io")) ((name . "io.PipeWriter.Write()") (path . "io/index#PipeWriter.Write") (type . "io")) ((name . "io.ReadAll()") (path . "io/index#ReadAll") (type . "io")) ((name . "io.ReadAtLeast()") (path . "io/index#ReadAtLeast") (type . "io")) ((name . "io.ReadCloser") (path . "io/index#ReadCloser") (type . "io")) ((name . "io.Reader") (path . "io/index#Reader") (type . "io")) ((name . "io.ReaderAt") (path . "io/index#ReaderAt") (type . "io")) ((name . "io.ReaderFrom") (path . "io/index#ReaderFrom") (type . "io")) ((name . "io.ReadFull()") (path . "io/index#ReadFull") (type . "io")) ((name . "io.ReadSeekCloser") (path . "io/index#ReadSeekCloser") (type . "io")) ((name . "io.ReadSeeker") (path . "io/index#ReadSeeker") (type . "io")) ((name . "io.ReadWriteCloser") (path . "io/index#ReadWriteCloser") (type . "io")) ((name . "io.ReadWriter") (path . "io/index#ReadWriter") (type . "io")) ((name . "io.ReadWriteSeeker") (path . "io/index#ReadWriteSeeker") (type . "io")) ((name . "io.RuneReader") (path . "io/index#RuneReader") (type . "io")) ((name . "io.RuneScanner") (path . "io/index#RuneScanner") (type . "io")) ((name . "io.SectionReader") (path . "io/index#SectionReader") (type . "io")) ((name . "io.SectionReader.Outer()") (path . "io/index#SectionReader.Outer") (type . "io")) ((name . "io.SectionReader.Read()") (path . "io/index#SectionReader.Read") (type . "io")) ((name . "io.SectionReader.ReadAt()") (path . "io/index#SectionReader.ReadAt") (type . "io")) ((name . "io.SectionReader.Seek()") (path . "io/index#SectionReader.Seek") (type . "io")) ((name . "io.SectionReader.Size()") (path . "io/index#SectionReader.Size") (type . "io")) ((name . "io.Seeker") (path . "io/index#Seeker") (type . "io")) ((name . "io.StringWriter") (path . "io/index#StringWriter") (type . "io")) ((name . "io.TeeReader()") (path . "io/index#TeeReader") (type . "io")) ((name . "io.WriteCloser") (path . "io/index#WriteCloser") (type . "io")) ((name . "io.Writer") (path . "io/index#Writer") (type . "io")) ((name . "io.WriterAt") (path . "io/index#WriterAt") (type . "io")) ((name . "io.WriterTo") (path . "io/index#WriterTo") (type . "io")) ((name . "io.WriteSeeker") (path . "io/index#WriteSeeker") (type . "io")) ((name . "io.WriteString()") (path . "io/index#WriteString") (type . "io")) ((name . "io/fs") (path . "io/fs/index") (type . "io")) ((name . "io/fs variables") (path . "io/fs/index#pkg-variables") (type . "io")) ((name . "io/ioutil") (path . "io/ioutil/index") (type . "io")) ((name . "io/ioutil variables") (path . "io/ioutil/index#pkg-variables") (type . "io")) ((name . "iotest.DataErrReader()") (path . "testing/iotest/index#DataErrReader") (type . "testing")) ((name . "iotest.ErrReader()") (path . "testing/iotest/index#ErrReader") (type . "testing")) ((name . "iotest.HalfReader()") (path . "testing/iotest/index#HalfReader") (type . "testing")) ((name . "iotest.NewReadLogger()") (path . "testing/iotest/index#NewReadLogger") (type . "testing")) ((name . "iotest.NewWriteLogger()") (path . "testing/iotest/index#NewWriteLogger") (type . "testing")) ((name . "iotest.OneByteReader()") (path . "testing/iotest/index#OneByteReader") (type . "testing")) ((name . "iotest.TestReader()") (path . "testing/iotest/index#TestReader") (type . "testing")) ((name . "iotest.TimeoutReader()") (path . "testing/iotest/index#TimeoutReader") (type . "testing")) ((name . "iotest.TruncateWriter()") (path . "testing/iotest/index#TruncateWriter") (type . "testing")) ((name . "ioutil.NopCloser()") (path . "io/ioutil/index#NopCloser") (type . "io")) ((name . "ioutil.ReadAll()") (path . "io/ioutil/index#ReadAll") (type . "io")) ((name . "ioutil.ReadDir()") (path . "io/ioutil/index#ReadDir") (type . "io")) ((name . "ioutil.ReadFile()") (path . "io/ioutil/index#ReadFile") (type . "io")) ((name . "ioutil.TempDir()") (path . "io/ioutil/index#TempDir") (type . "io")) ((name . "ioutil.TempFile()") (path . "io/ioutil/index#TempFile") (type . "io")) ((name . "ioutil.WriteFile()") (path . "io/ioutil/index#WriteFile") (type . "io")) ((name . "jpeg.Decode()") (path . "image/jpeg/index#Decode") (type . "image")) ((name . "jpeg.DecodeConfig()") (path . "image/jpeg/index#DecodeConfig") (type . "image")) ((name . "jpeg.Encode()") (path . "image/jpeg/index#Encode") (type . "image")) ((name . "jpeg.FormatError") (path . "image/jpeg/index#FormatError") (type . "image")) ((name . "jpeg.FormatError.Error()") (path . "image/jpeg/index#FormatError.Error") (type . "image")) ((name . "jpeg.Options") (path . "image/jpeg/index#Options") (type . "image")) ((name . "jpeg.Reader") (path . "image/jpeg/index#Reader") (type . "image")) ((name . "jpeg.UnsupportedError") (path . "image/jpeg/index#UnsupportedError") (type . "image")) ((name . "jpeg.UnsupportedError.Error()") (path . "image/jpeg/index#UnsupportedError.Error") (type . "image")) ((name . "js.CopyBytesToGo()") (path . "syscall/js/index#CopyBytesToGo") (type . "syscall")) ((name . "js.CopyBytesToJS()") (path . "syscall/js/index#CopyBytesToJS") (type . "syscall")) ((name . "js.Error") (path . "syscall/js/index#Error") (type . "syscall")) ((name . "js.Error.Error()") (path . "syscall/js/index#Error.Error") (type . "syscall")) ((name . "js.Func") (path . "syscall/js/index#Func") (type . "syscall")) ((name . "js.Func.Release()") (path . "syscall/js/index#Func.Release") (type . "syscall")) ((name . "js.FuncOf()") (path . "syscall/js/index#FuncOf") (type . "syscall")) ((name . "js.Global()") (path . "syscall/js/index#Global") (type . "syscall")) ((name . "js.Null()") (path . "syscall/js/index#Null") (type . "syscall")) ((name . "js.Type") (path . "syscall/js/index#Type") (type . "syscall")) ((name . "js.Type.String()") (path . "syscall/js/index#Type.String") (type . "syscall")) ((name . "js.Undefined()") (path . "syscall/js/index#Undefined") (type . "syscall")) ((name . "js.Value") (path . "syscall/js/index#Value") (type . "syscall")) ((name . "js.Value.Bool()") (path . "syscall/js/index#Value.Bool") (type . "syscall")) ((name . "js.Value.Call()") (path . "syscall/js/index#Value.Call") (type . "syscall")) ((name . "js.Value.Delete()") (path . "syscall/js/index#Value.Delete") (type . "syscall")) ((name . "js.Value.Equal()") (path . "syscall/js/index#Value.Equal") (type . "syscall")) ((name . "js.Value.Float()") (path . "syscall/js/index#Value.Float") (type . "syscall")) ((name . "js.Value.Get()") (path . "syscall/js/index#Value.Get") (type . "syscall")) ((name . "js.Value.Index()") (path . "syscall/js/index#Value.Index") (type . "syscall")) ((name . "js.Value.InstanceOf()") (path . "syscall/js/index#Value.InstanceOf") (type . "syscall")) ((name . "js.Value.Int()") (path . "syscall/js/index#Value.Int") (type . "syscall")) ((name . "js.Value.Invoke()") (path . "syscall/js/index#Value.Invoke") (type . "syscall")) ((name . "js.Value.IsNaN()") (path . "syscall/js/index#Value.IsNaN") (type . "syscall")) ((name . "js.Value.IsNull()") (path . "syscall/js/index#Value.IsNull") (type . "syscall")) ((name . "js.Value.IsUndefined()") (path . "syscall/js/index#Value.IsUndefined") (type . "syscall")) ((name . "js.Value.Length()") (path . "syscall/js/index#Value.Length") (type . "syscall")) ((name . "js.Value.New()") (path . "syscall/js/index#Value.New") (type . "syscall")) ((name . "js.Value.Set()") (path . "syscall/js/index#Value.Set") (type . "syscall")) ((name . "js.Value.SetIndex()") (path . "syscall/js/index#Value.SetIndex") (type . "syscall")) ((name . "js.Value.String()") (path . "syscall/js/index#Value.String") (type . "syscall")) ((name . "js.Value.Truthy()") (path . "syscall/js/index#Value.Truthy") (type . "syscall")) ((name . "js.Value.Type()") (path . "syscall/js/index#Value.Type") (type . "syscall")) ((name . "js.ValueError") (path . "syscall/js/index#ValueError") (type . "syscall")) ((name . "js.ValueError.Error()") (path . "syscall/js/index#ValueError.Error") (type . "syscall")) ((name . "js.ValueOf()") (path . "syscall/js/index#ValueOf") (type . "syscall")) ((name . "json.Compact()") (path . "encoding/json/index#Compact") (type . "encoding")) ((name . "json.Decoder") (path . "encoding/json/index#Decoder") (type . "encoding")) ((name . "json.Decoder.Buffered()") (path . "encoding/json/index#Decoder.Buffered") (type . "encoding")) ((name . "json.Decoder.Decode()") (path . "encoding/json/index#Decoder.Decode") (type . "encoding")) ((name . "json.Decoder.DisallowUnknownFields()") (path . "encoding/json/index#Decoder.DisallowUnknownFields") (type . "encoding")) ((name . "json.Decoder.InputOffset()") (path . "encoding/json/index#Decoder.InputOffset") (type . "encoding")) ((name . "json.Decoder.More()") (path . "encoding/json/index#Decoder.More") (type . "encoding")) ((name . "json.Decoder.Token()") (path . "encoding/json/index#Decoder.Token") (type . "encoding")) ((name . "json.Decoder.UseNumber()") (path . "encoding/json/index#Decoder.UseNumber") (type . "encoding")) ((name . "json.Delim") (path . "encoding/json/index#Delim") (type . "encoding")) ((name . "json.Delim.String()") (path . "encoding/json/index#Delim.String") (type . "encoding")) ((name . "json.Encoder") (path . "encoding/json/index#Encoder") (type . "encoding")) ((name . "json.Encoder.Encode()") (path . "encoding/json/index#Encoder.Encode") (type . "encoding")) ((name . "json.Encoder.SetEscapeHTML()") (path . "encoding/json/index#Encoder.SetEscapeHTML") (type . "encoding")) ((name . "json.Encoder.SetIndent()") (path . "encoding/json/index#Encoder.SetIndent") (type . "encoding")) ((name . "json.HTMLEscape()") (path . "encoding/json/index#HTMLEscape") (type . "encoding")) ((name . "json.Indent()") (path . "encoding/json/index#Indent") (type . "encoding")) ((name . "json.InvalidUnmarshalError") (path . "encoding/json/index#InvalidUnmarshalError") (type . "encoding")) ((name . "json.InvalidUnmarshalError.Error()") (path . "encoding/json/index#InvalidUnmarshalError.Error") (type . "encoding")) ((name . "json.InvalidUTF8Error") (path . "encoding/json/index#InvalidUTF8Error") (type . "encoding")) ((name . "json.InvalidUTF8Error.Error()") (path . "encoding/json/index#InvalidUTF8Error.Error") (type . "encoding")) ((name . "json.Marshal()") (path . "encoding/json/index#Marshal") (type . "encoding")) ((name . "json.Marshaler") (path . "encoding/json/index#Marshaler") (type . "encoding")) ((name . "json.MarshalerError") (path . "encoding/json/index#MarshalerError") (type . "encoding")) ((name . "json.MarshalerError.Error()") (path . "encoding/json/index#MarshalerError.Error") (type . "encoding")) ((name . "json.MarshalerError.Unwrap()") (path . "encoding/json/index#MarshalerError.Unwrap") (type . "encoding")) ((name . "json.MarshalIndent()") (path . "encoding/json/index#MarshalIndent") (type . "encoding")) ((name . "json.NewDecoder()") (path . "encoding/json/index#NewDecoder") (type . "encoding")) ((name . "json.NewEncoder()") (path . "encoding/json/index#NewEncoder") (type . "encoding")) ((name . "json.Number") (path . "encoding/json/index#Number") (type . "encoding")) ((name . "json.Number.Float64()") (path . "encoding/json/index#Number.Float64") (type . "encoding")) ((name . "json.Number.Int64()") (path . "encoding/json/index#Number.Int64") (type . "encoding")) ((name . "json.Number.String()") (path . "encoding/json/index#Number.String") (type . "encoding")) ((name . "json.RawMessage") (path . "encoding/json/index#RawMessage") (type . "encoding")) ((name . "json.RawMessage.MarshalJSON()") (path . "encoding/json/index#RawMessage.MarshalJSON") (type . "encoding")) ((name . "json.RawMessage.UnmarshalJSON()") (path . "encoding/json/index#RawMessage.UnmarshalJSON") (type . "encoding")) ((name . "json.SyntaxError") (path . "encoding/json/index#SyntaxError") (type . "encoding")) ((name . "json.SyntaxError.Error()") (path . "encoding/json/index#SyntaxError.Error") (type . "encoding")) ((name . "json.Token") (path . "encoding/json/index#Token") (type . "encoding")) ((name . "json.Unmarshal()") (path . "encoding/json/index#Unmarshal") (type . "encoding")) ((name . "json.Unmarshaler") (path . "encoding/json/index#Unmarshaler") (type . "encoding")) ((name . "json.UnmarshalFieldError") (path . "encoding/json/index#UnmarshalFieldError") (type . "encoding")) ((name . "json.UnmarshalFieldError.Error()") (path . "encoding/json/index#UnmarshalFieldError.Error") (type . "encoding")) ((name . "json.UnmarshalTypeError") (path . "encoding/json/index#UnmarshalTypeError") (type . "encoding")) ((name . "json.UnmarshalTypeError.Error()") (path . "encoding/json/index#UnmarshalTypeError.Error") (type . "encoding")) ((name . "json.UnsupportedTypeError") (path . "encoding/json/index#UnsupportedTypeError") (type . "encoding")) ((name . "json.UnsupportedTypeError.Error()") (path . "encoding/json/index#UnsupportedTypeError.Error") (type . "encoding")) ((name . "json.UnsupportedValueError") (path . "encoding/json/index#UnsupportedValueError") (type . "encoding")) ((name . "json.UnsupportedValueError.Error()") (path . "encoding/json/index#UnsupportedValueError.Error") (type . "encoding")) ((name . "json.Valid()") (path . "encoding/json/index#Valid") (type . "encoding")) ((name . "jsonrpc.Dial()") (path . "net/rpc/jsonrpc/index#Dial") (type . "net/rpc")) ((name . "jsonrpc.NewClient()") (path . "net/rpc/jsonrpc/index#NewClient") (type . "net/rpc")) ((name . "jsonrpc.NewClientCodec()") (path . "net/rpc/jsonrpc/index#NewClientCodec") (type . "net/rpc")) ((name . "jsonrpc.NewServerCodec()") (path . "net/rpc/jsonrpc/index#NewServerCodec") (type . "net/rpc")) ((name . "jsonrpc.ServeConn()") (path . "net/rpc/jsonrpc/index#ServeConn") (type . "net/rpc")) ((name . "list.Element") (path . "container/list/index#Element") (type . "container")) ((name . "list.Element.Next()") (path . "container/list/index#Element.Next") (type . "container")) ((name . "list.Element.Prev()") (path . "container/list/index#Element.Prev") (type . "container")) ((name . "list.List") (path . "container/list/index#List") (type . "container")) ((name . "list.List.Back()") (path . "container/list/index#List.Back") (type . "container")) ((name . "list.List.Front()") (path . "container/list/index#List.Front") (type . "container")) ((name . "list.List.Init()") (path . "container/list/index#List.Init") (type . "container")) ((name . "list.List.InsertAfter()") (path . "container/list/index#List.InsertAfter") (type . "container")) ((name . "list.List.InsertBefore()") (path . "container/list/index#List.InsertBefore") (type . "container")) ((name . "list.List.Len()") (path . "container/list/index#List.Len") (type . "container")) ((name . "list.List.MoveAfter()") (path . "container/list/index#List.MoveAfter") (type . "container")) ((name . "list.List.MoveBefore()") (path . "container/list/index#List.MoveBefore") (type . "container")) ((name . "list.List.MoveToBack()") (path . "container/list/index#List.MoveToBack") (type . "container")) ((name . "list.List.MoveToFront()") (path . "container/list/index#List.MoveToFront") (type . "container")) ((name . "list.List.PushBack()") (path . "container/list/index#List.PushBack") (type . "container")) ((name . "list.List.PushBackList()") (path . "container/list/index#List.PushBackList") (type . "container")) ((name . "list.List.PushFront()") (path . "container/list/index#List.PushFront") (type . "container")) ((name . "list.List.PushFrontList()") (path . "container/list/index#List.PushFrontList") (type . "container")) ((name . "list.List.Remove()") (path . "container/list/index#List.Remove") (type . "container")) ((name . "list.New()") (path . "container/list/index#New") (type . "container")) ((name . "log") (path . "log/index") (type . "log")) ((name . "log constants") (path . "log/index#pkg-constants") (type . "log")) ((name . "log.Default()") (path . "log/index#Default") (type . "log")) ((name . "log.Fatal()") (path . "log/index#Fatal") (type . "log")) ((name . "log.Fatalf()") (path . "log/index#Fatalf") (type . "log")) ((name . "log.Fatalln()") (path . "log/index#Fatalln") (type . "log")) ((name . "log.Flags()") (path . "log/index#Flags") (type . "log")) ((name . "log.Logger") (path . "log/index#Logger") (type . "log")) ((name . "log.Logger.Fatal()") (path . "log/index#Logger.Fatal") (type . "log")) ((name . "log.Logger.Fatalf()") (path . "log/index#Logger.Fatalf") (type . "log")) ((name . "log.Logger.Fatalln()") (path . "log/index#Logger.Fatalln") (type . "log")) ((name . "log.Logger.Flags()") (path . "log/index#Logger.Flags") (type . "log")) ((name . "log.Logger.Output()") (path . "log/index#Logger.Output") (type . "log")) ((name . "log.Logger.Panic()") (path . "log/index#Logger.Panic") (type . "log")) ((name . "log.Logger.Panicf()") (path . "log/index#Logger.Panicf") (type . "log")) ((name . "log.Logger.Panicln()") (path . "log/index#Logger.Panicln") (type . "log")) ((name . "log.Logger.Prefix()") (path . "log/index#Logger.Prefix") (type . "log")) ((name . "log.Logger.Print()") (path . "log/index#Logger.Print") (type . "log")) ((name . "log.Logger.Printf()") (path . "log/index#Logger.Printf") (type . "log")) ((name . "log.Logger.Println()") (path . "log/index#Logger.Println") (type . "log")) ((name . "log.Logger.SetFlags()") (path . "log/index#Logger.SetFlags") (type . "log")) ((name . "log.Logger.SetOutput()") (path . "log/index#Logger.SetOutput") (type . "log")) ((name . "log.Logger.SetPrefix()") (path . "log/index#Logger.SetPrefix") (type . "log")) ((name . "log.Logger.Writer()") (path . "log/index#Logger.Writer") (type . "log")) ((name . "log.New()") (path . "log/index#New") (type . "log")) ((name . "log.Output()") (path . "log/index#Output") (type . "log")) ((name . "log.Panic()") (path . "log/index#Panic") (type . "log")) ((name . "log.Panicf()") (path . "log/index#Panicf") (type . "log")) ((name . "log.Panicln()") (path . "log/index#Panicln") (type . "log")) ((name . "log.Prefix()") (path . "log/index#Prefix") (type . "log")) ((name . "log.Print()") (path . "log/index#Print") (type . "log")) ((name . "log.Printf()") (path . "log/index#Printf") (type . "log")) ((name . "log.Println()") (path . "log/index#Println") (type . "log")) ((name . "log.SetFlags()") (path . "log/index#SetFlags") (type . "log")) ((name . "log.SetOutput()") (path . "log/index#SetOutput") (type . "log")) ((name . "log.SetPrefix()") (path . "log/index#SetPrefix") (type . "log")) ((name . "log.Writer()") (path . "log/index#Writer") (type . "log")) ((name . "log/slog") (path . "log/slog/index") (type . "log")) ((name . "log/slog constants") (path . "log/slog/index#pkg-constants") (type . "log")) ((name . "log/syslog") (path . "log/syslog/index") (type . "log")) ((name . "lzw.NewReader()") (path . "compress/lzw/index#NewReader") (type . "compress")) ((name . "lzw.NewWriter()") (path . "compress/lzw/index#NewWriter") (type . "compress")) ((name . "lzw.Order") (path . "compress/lzw/index#Order") (type . "compress")) ((name . "lzw.Reader") (path . "compress/lzw/index#Reader") (type . "compress")) ((name . "lzw.Reader.Close()") (path . "compress/lzw/index#Reader.Close") (type . "compress")) ((name . "lzw.Reader.Read()") (path . "compress/lzw/index#Reader.Read") (type . "compress")) ((name . "lzw.Reader.Reset()") (path . "compress/lzw/index#Reader.Reset") (type . "compress")) ((name . "lzw.Writer") (path . "compress/lzw/index#Writer") (type . "compress")) ((name . "lzw.Writer.Close()") (path . "compress/lzw/index#Writer.Close") (type . "compress")) ((name . "lzw.Writer.Reset()") (path . "compress/lzw/index#Writer.Reset") (type . "compress")) ((name . "lzw.Writer.Write()") (path . "compress/lzw/index#Writer.Write") (type . "compress")) ((name . "macho.Cpu") (path . "debug/macho/index#Cpu") (type . "debug")) ((name . "macho.Cpu.GoString()") (path . "debug/macho/index#Cpu.GoString") (type . "debug")) ((name . "macho.Cpu.String()") (path . "debug/macho/index#Cpu.String") (type . "debug")) ((name . "macho.Dylib") (path . "debug/macho/index#Dylib") (type . "debug")) ((name . "macho.DylibCmd") (path . "debug/macho/index#DylibCmd") (type . "debug")) ((name . "macho.Dysymtab") (path . "debug/macho/index#Dysymtab") (type . "debug")) ((name . "macho.DysymtabCmd") (path . "debug/macho/index#DysymtabCmd") (type . "debug")) ((name . "macho.FatArch") (path . "debug/macho/index#FatArch") (type . "debug")) ((name . "macho.FatArchHeader") (path . "debug/macho/index#FatArchHeader") (type . "debug")) ((name . "macho.FatFile") (path . "debug/macho/index#FatFile") (type . "debug")) ((name . "macho.FatFile.Close()") (path . "debug/macho/index#FatFile.Close") (type . "debug")) ((name . "macho.File") (path . "debug/macho/index#File") (type . "debug")) ((name . "macho.File.Close()") (path . "debug/macho/index#File.Close") (type . "debug")) ((name . "macho.File.DWARF()") (path . "debug/macho/index#File.DWARF") (type . "debug")) ((name . "macho.File.ImportedLibraries()") (path . "debug/macho/index#File.ImportedLibraries") (type . "debug")) ((name . "macho.File.ImportedSymbols()") (path . "debug/macho/index#File.ImportedSymbols") (type . "debug")) ((name . "macho.File.Section()") (path . "debug/macho/index#File.Section") (type . "debug")) ((name . "macho.File.Segment()") (path . "debug/macho/index#File.Segment") (type . "debug")) ((name . "macho.FileHeader") (path . "debug/macho/index#FileHeader") (type . "debug")) ((name . "macho.FormatError") (path . "debug/macho/index#FormatError") (type . "debug")) ((name . "macho.FormatError.Error()") (path . "debug/macho/index#FormatError.Error") (type . "debug")) ((name . "macho.Load") (path . "debug/macho/index#Load") (type . "debug")) ((name . "macho.LoadBytes") (path . "debug/macho/index#LoadBytes") (type . "debug")) ((name . "macho.LoadBytes.Raw()") (path . "debug/macho/index#LoadBytes.Raw") (type . "debug")) ((name . "macho.LoadCmd") (path . "debug/macho/index#LoadCmd") (type . "debug")) ((name . "macho.LoadCmd.GoString()") (path . "debug/macho/index#LoadCmd.GoString") (type . "debug")) ((name . "macho.LoadCmd.String()") (path . "debug/macho/index#LoadCmd.String") (type . "debug")) ((name . "macho.NewFatFile()") (path . "debug/macho/index#NewFatFile") (type . "debug")) ((name . "macho.NewFile()") (path . "debug/macho/index#NewFile") (type . "debug")) ((name . "macho.Nlist32") (path . "debug/macho/index#Nlist32") (type . "debug")) ((name . "macho.Nlist64") (path . "debug/macho/index#Nlist64") (type . "debug")) ((name . "macho.Open()") (path . "debug/macho/index#Open") (type . "debug")) ((name . "macho.OpenFat()") (path . "debug/macho/index#OpenFat") (type . "debug")) ((name . "macho.Regs386") (path . "debug/macho/index#Regs386") (type . "debug")) ((name . "macho.RegsAMD64") (path . "debug/macho/index#RegsAMD64") (type . "debug")) ((name . "macho.Reloc") (path . "debug/macho/index#Reloc") (type . "debug")) ((name . "macho.RelocTypeARM") (path . "debug/macho/index#RelocTypeARM") (type . "debug")) ((name . "macho.RelocTypeARM.GoString()") (path . "debug/macho/index#RelocTypeARM.GoString") (type . "debug")) ((name . "macho.RelocTypeARM.String()") (path . "debug/macho/index#RelocTypeARM.String") (type . "debug")) ((name . "macho.RelocTypeARM64") (path . "debug/macho/index#RelocTypeARM64") (type . "debug")) ((name . "macho.RelocTypeARM64.GoString()") (path . "debug/macho/index#RelocTypeARM64.GoString") (type . "debug")) ((name . "macho.RelocTypeARM64.String()") (path . "debug/macho/index#RelocTypeARM64.String") (type . "debug")) ((name . "macho.RelocTypeGeneric") (path . "debug/macho/index#RelocTypeGeneric") (type . "debug")) ((name . "macho.RelocTypeGeneric.GoString()") (path . "debug/macho/index#RelocTypeGeneric.GoString") (type . "debug")) ((name . "macho.RelocTypeGeneric.String()") (path . "debug/macho/index#RelocTypeGeneric.String") (type . "debug")) ((name . "macho.RelocTypeX86_64") (path . "debug/macho/index#RelocTypeX86_64") (type . "debug")) ((name . "macho.RelocTypeX86_64.GoString()") (path . "debug/macho/index#RelocTypeX86_64.GoString") (type . "debug")) ((name . "macho.RelocTypeX86_64.String()") (path . "debug/macho/index#RelocTypeX86_64.String") (type . "debug")) ((name . "macho.Rpath") (path . "debug/macho/index#Rpath") (type . "debug")) ((name . "macho.RpathCmd") (path . "debug/macho/index#RpathCmd") (type . "debug")) ((name . "macho.Section") (path . "debug/macho/index#Section") (type . "debug")) ((name . "macho.Section.Data()") (path . "debug/macho/index#Section.Data") (type . "debug")) ((name . "macho.Section.Open()") (path . "debug/macho/index#Section.Open") (type . "debug")) ((name . "macho.Section32") (path . "debug/macho/index#Section32") (type . "debug")) ((name . "macho.Section64") (path . "debug/macho/index#Section64") (type . "debug")) ((name . "macho.SectionHeader") (path . "debug/macho/index#SectionHeader") (type . "debug")) ((name . "macho.Segment") (path . "debug/macho/index#Segment") (type . "debug")) ((name . "macho.Segment.Data()") (path . "debug/macho/index#Segment.Data") (type . "debug")) ((name . "macho.Segment.Open()") (path . "debug/macho/index#Segment.Open") (type . "debug")) ((name . "macho.Segment32") (path . "debug/macho/index#Segment32") (type . "debug")) ((name . "macho.Segment64") (path . "debug/macho/index#Segment64") (type . "debug")) ((name . "macho.SegmentHeader") (path . "debug/macho/index#SegmentHeader") (type . "debug")) ((name . "macho.Symbol") (path . "debug/macho/index#Symbol") (type . "debug")) ((name . "macho.Symtab") (path . "debug/macho/index#Symtab") (type . "debug")) ((name . "macho.SymtabCmd") (path . "debug/macho/index#SymtabCmd") (type . "debug")) ((name . "macho.Thread") (path . "debug/macho/index#Thread") (type . "debug")) ((name . "macho.Type") (path . "debug/macho/index#Type") (type . "debug")) ((name . "macho.Type.GoString()") (path . "debug/macho/index#Type.GoString") (type . "debug")) ((name . "macho.Type.String()") (path . "debug/macho/index#Type.String") (type . "debug")) ((name . "mail.Address") (path . "net/mail/index#Address") (type . "net/mail")) ((name . "mail.Address.String()") (path . "net/mail/index#Address.String") (type . "net/mail")) ((name . "mail.AddressParser") (path . "net/mail/index#AddressParser") (type . "net/mail")) ((name . "mail.AddressParser.Parse()") (path . "net/mail/index#AddressParser.Parse") (type . "net/mail")) ((name . "mail.AddressParser.ParseList()") (path . "net/mail/index#AddressParser.ParseList") (type . "net/mail")) ((name . "mail.Header") (path . "net/mail/index#Header") (type . "net/mail")) ((name . "mail.Header.AddressList()") (path . "net/mail/index#Header.AddressList") (type . "net/mail")) ((name . "mail.Header.Date()") (path . "net/mail/index#Header.Date") (type . "net/mail")) ((name . "mail.Header.Get()") (path . "net/mail/index#Header.Get") (type . "net/mail")) ((name . "mail.Message") (path . "net/mail/index#Message") (type . "net/mail")) ((name . "mail.ParseAddress()") (path . "net/mail/index#ParseAddress") (type . "net/mail")) ((name . "mail.ParseAddressList()") (path . "net/mail/index#ParseAddressList") (type . "net/mail")) ((name . "mail.ParseDate()") (path . "net/mail/index#ParseDate") (type . "net/mail")) ((name . "mail.ReadMessage()") (path . "net/mail/index#ReadMessage") (type . "net/mail")) ((name . "maphash.Bytes()") (path . "hash/maphash/index#Bytes") (type . "hash")) ((name . "maphash.Hash") (path . "hash/maphash/index#Hash") (type . "hash")) ((name . "maphash.Hash.BlockSize()") (path . "hash/maphash/index#Hash.BlockSize") (type . "hash")) ((name . "maphash.Hash.Reset()") (path . "hash/maphash/index#Hash.Reset") (type . "hash")) ((name . "maphash.Hash.Seed()") (path . "hash/maphash/index#Hash.Seed") (type . "hash")) ((name . "maphash.Hash.SetSeed()") (path . "hash/maphash/index#Hash.SetSeed") (type . "hash")) ((name . "maphash.Hash.Size()") (path . "hash/maphash/index#Hash.Size") (type . "hash")) ((name . "maphash.Hash.Sum()") (path . "hash/maphash/index#Hash.Sum") (type . "hash")) ((name . "maphash.Hash.Sum64()") (path . "hash/maphash/index#Hash.Sum64") (type . "hash")) ((name . "maphash.Hash.Write()") (path . "hash/maphash/index#Hash.Write") (type . "hash")) ((name . "maphash.Hash.WriteByte()") (path . "hash/maphash/index#Hash.WriteByte") (type . "hash")) ((name . "maphash.Hash.WriteString()") (path . "hash/maphash/index#Hash.WriteString") (type . "hash")) ((name . "maphash.MakeSeed()") (path . "hash/maphash/index#MakeSeed") (type . "hash")) ((name . "maphash.Seed") (path . "hash/maphash/index#Seed") (type . "hash")) ((name . "maphash.String()") (path . "hash/maphash/index#String") (type . "hash")) ((name . "maps") (path . "maps/index") (type . "maps")) ((name . "maps.Clone()") (path . "maps/index#Clone") (type . "maps")) ((name . "maps.Copy()") (path . "maps/index#Copy") (type . "maps")) ((name . "maps.DeleteFunc()") (path . "maps/index#DeleteFunc") (type . "maps")) ((name . "maps.Equal()") (path . "maps/index#Equal") (type . "maps")) ((name . "maps.EqualFunc()") (path . "maps/index#EqualFunc") (type . "maps")) ((name . "math") (path . "math/index") (type . "math")) ((name . "math constants") (path . "math/index#pkg-constants") (type . "math")) ((name . "math.Abs()") (path . "math/index#Abs") (type . "math")) ((name . "math.Acos()") (path . "math/index#Acos") (type . "math")) ((name . "math.Acosh()") (path . "math/index#Acosh") (type . "math")) ((name . "math.Asin()") (path . "math/index#Asin") (type . "math")) ((name . "math.Asinh()") (path . "math/index#Asinh") (type . "math")) ((name . "math.Atan()") (path . "math/index#Atan") (type . "math")) ((name . "math.Atan2()") (path . "math/index#Atan2") (type . "math")) ((name . "math.Atanh()") (path . "math/index#Atanh") (type . "math")) ((name . "math.Cbrt()") (path . "math/index#Cbrt") (type . "math")) ((name . "math.Ceil()") (path . "math/index#Ceil") (type . "math")) ((name . "math.Copysign()") (path . "math/index#Copysign") (type . "math")) ((name . "math.Cos()") (path . "math/index#Cos") (type . "math")) ((name . "math.Cosh()") (path . "math/index#Cosh") (type . "math")) ((name . "math.Dim()") (path . "math/index#Dim") (type . "math")) ((name . "math.Erf()") (path . "math/index#Erf") (type . "math")) ((name . "math.Erfc()") (path . "math/index#Erfc") (type . "math")) ((name . "math.Erfcinv()") (path . "math/index#Erfcinv") (type . "math")) ((name . "math.Erfinv()") (path . "math/index#Erfinv") (type . "math")) ((name . "math.Exp()") (path . "math/index#Exp") (type . "math")) ((name . "math.Exp2()") (path . "math/index#Exp2") (type . "math")) ((name . "math.Expm1()") (path . "math/index#Expm1") (type . "math")) ((name . "math.Float32bits()") (path . "math/index#Float32bits") (type . "math")) ((name . "math.Float32frombits()") (path . "math/index#Float32frombits") (type . "math")) ((name . "math.Float64bits()") (path . "math/index#Float64bits") (type . "math")) ((name . "math.Float64frombits()") (path . "math/index#Float64frombits") (type . "math")) ((name . "math.Floor()") (path . "math/index#Floor") (type . "math")) ((name . "math.FMA()") (path . "math/index#FMA") (type . "math")) ((name . "math.Frexp()") (path . "math/index#Frexp") (type . "math")) ((name . "math.Gamma()") (path . "math/index#Gamma") (type . "math")) ((name . "math.Hypot()") (path . "math/index#Hypot") (type . "math")) ((name . "math.Ilogb()") (path . "math/index#Ilogb") (type . "math")) ((name . "math.Inf()") (path . "math/index#Inf") (type . "math")) ((name . "math.IsInf()") (path . "math/index#IsInf") (type . "math")) ((name . "math.IsNaN()") (path . "math/index#IsNaN") (type . "math")) ((name . "math.J0()") (path . "math/index#J0") (type . "math")) ((name . "math.J1()") (path . "math/index#J1") (type . "math")) ((name . "math.Jn()") (path . "math/index#Jn") (type . "math")) ((name . "math.Ldexp()") (path . "math/index#Ldexp") (type . "math")) ((name . "math.Lgamma()") (path . "math/index#Lgamma") (type . "math")) ((name . "math.Log()") (path . "math/index#Log") (type . "math")) ((name . "math.Log10()") (path . "math/index#Log10") (type . "math")) ((name . "math.Log1p()") (path . "math/index#Log1p") (type . "math")) ((name . "math.Log2()") (path . "math/index#Log2") (type . "math")) ((name . "math.Logb()") (path . "math/index#Logb") (type . "math")) ((name . "math.Max()") (path . "math/index#Max") (type . "math")) ((name . "math.Min()") (path . "math/index#Min") (type . "math")) ((name . "math.Mod()") (path . "math/index#Mod") (type . "math")) ((name . "math.Modf()") (path . "math/index#Modf") (type . "math")) ((name . "math.NaN()") (path . "math/index#NaN") (type . "math")) ((name . "math.Nextafter()") (path . "math/index#Nextafter") (type . "math")) ((name . "math.Nextafter32()") (path . "math/index#Nextafter32") (type . "math")) ((name . "math.Pow()") (path . "math/index#Pow") (type . "math")) ((name . "math.Pow10()") (path . "math/index#Pow10") (type . "math")) ((name . "math.Remainder()") (path . "math/index#Remainder") (type . "math")) ((name . "math.Round()") (path . "math/index#Round") (type . "math")) ((name . "math.RoundToEven()") (path . "math/index#RoundToEven") (type . "math")) ((name . "math.Signbit()") (path . "math/index#Signbit") (type . "math")) ((name . "math.Sin()") (path . "math/index#Sin") (type . "math")) ((name . "math.Sincos()") (path . "math/index#Sincos") (type . "math")) ((name . "math.Sinh()") (path . "math/index#Sinh") (type . "math")) ((name . "math.Sqrt()") (path . "math/index#Sqrt") (type . "math")) ((name . "math.Tan()") (path . "math/index#Tan") (type . "math")) ((name . "math.Tanh()") (path . "math/index#Tanh") (type . "math")) ((name . "math.Trunc()") (path . "math/index#Trunc") (type . "math")) ((name . "math.Y0()") (path . "math/index#Y0") (type . "math")) ((name . "math.Y1()") (path . "math/index#Y1") (type . "math")) ((name . "math.Yn()") (path . "math/index#Yn") (type . "math")) ((name . "math/big") (path . "math/big/index") (type . "math/big")) ((name . "math/big constants") (path . "math/big/index#pkg-constants") (type . "math/big")) ((name . "math/bits") (path . "math/bits/index") (type . "math/bits")) ((name . "math/bits constants") (path . "math/bits/index#pkg-constants") (type . "math/bits")) ((name . "math/cmplx") (path . "math/cmplx/index") (type . "math/cmplx")) ((name . "math/rand") (path . "math/rand/index") (type . "math/rand")) ((name . "math/rand/v2") (path . "math/rand/v2/index") (type . "math/rand")) ((name . "md5.New()") (path . "crypto/md5/index#New") (type . "crypto")) ((name . "md5.Sum()") (path . "crypto/md5/index#Sum") (type . "crypto")) ((name . "metrics.All()") (path . "runtime/metrics/index#All") (type . "runtime")) ((name . "metrics.Description") (path . "runtime/metrics/index#Description") (type . "runtime")) ((name . "metrics.Float64Histogram") (path . "runtime/metrics/index#Float64Histogram") (type . "runtime")) ((name . "metrics.Read()") (path . "runtime/metrics/index#Read") (type . "runtime")) ((name . "metrics.Sample") (path . "runtime/metrics/index#Sample") (type . "runtime")) ((name . "metrics.Value") (path . "runtime/metrics/index#Value") (type . "runtime")) ((name . "metrics.Value.Float64()") (path . "runtime/metrics/index#Value.Float64") (type . "runtime")) ((name . "metrics.Value.Float64Histogram()") (path . "runtime/metrics/index#Value.Float64Histogram") (type . "runtime")) ((name . "metrics.Value.Kind()") (path . "runtime/metrics/index#Value.Kind") (type . "runtime")) ((name . "metrics.Value.Uint64()") (path . "runtime/metrics/index#Value.Uint64") (type . "runtime")) ((name . "metrics.ValueKind") (path . "runtime/metrics/index#ValueKind") (type . "runtime")) ((name . "mime") (path . "mime/index") (type . "mime")) ((name . "mime constants") (path . "mime/index#pkg-constants") (type . "mime")) ((name . "mime variables") (path . "mime/index#pkg-variables") (type . "mime")) ((name . "mime.AddExtensionType()") (path . "mime/index#AddExtensionType") (type . "mime")) ((name . "mime.ExtensionsByType()") (path . "mime/index#ExtensionsByType") (type . "mime")) ((name . "mime.FormatMediaType()") (path . "mime/index#FormatMediaType") (type . "mime")) ((name . "mime.string") (path . "mime/index#ParseMediaType") (type . "mime")) ((name . "mime.TypeByExtension()") (path . "mime/index#TypeByExtension") (type . "mime")) ((name . "mime.WordDecoder") (path . "mime/index#WordDecoder") (type . "mime")) ((name . "mime.WordDecoder.Decode()") (path . "mime/index#WordDecoder.Decode") (type . "mime")) ((name . "mime.WordDecoder.DecodeHeader()") (path . "mime/index#WordDecoder.DecodeHeader") (type . "mime")) ((name . "mime.WordEncoder") (path . "mime/index#WordEncoder") (type . "mime")) ((name . "mime.WordEncoder.Encode()") (path . "mime/index#WordEncoder.Encode") (type . "mime")) ((name . "mime/multipart") (path . "mime/multipart/index") (type . "mime")) ((name . "mime/multipart variables") (path . "mime/multipart/index#pkg-variables") (type . "mime")) ((name . "mime/quotedprintable") (path . "mime/quotedprintable/index") (type . "mime")) ((name . "multipart.File") (path . "mime/multipart/index#File") (type . "mime")) ((name . "multipart.FileHeader") (path . "mime/multipart/index#FileHeader") (type . "mime")) ((name . "multipart.FileHeader.Open()") (path . "mime/multipart/index#FileHeader.Open") (type . "mime")) ((name . "multipart.Form") (path . "mime/multipart/index#Form") (type . "mime")) ((name . "multipart.Form.RemoveAll()") (path . "mime/multipart/index#Form.RemoveAll") (type . "mime")) ((name . "multipart.NewReader()") (path . "mime/multipart/index#NewReader") (type . "mime")) ((name . "multipart.NewWriter()") (path . "mime/multipart/index#NewWriter") (type . "mime")) ((name . "multipart.Part") (path . "mime/multipart/index#Part") (type . "mime")) ((name . "multipart.Part.Close()") (path . "mime/multipart/index#Part.Close") (type . "mime")) ((name . "multipart.Part.FileName()") (path . "mime/multipart/index#Part.FileName") (type . "mime")) ((name . "multipart.Part.FormName()") (path . "mime/multipart/index#Part.FormName") (type . "mime")) ((name . "multipart.Part.Read()") (path . "mime/multipart/index#Part.Read") (type . "mime")) ((name . "multipart.Reader") (path . "mime/multipart/index#Reader") (type . "mime")) ((name . "multipart.Reader.NextPart()") (path . "mime/multipart/index#Reader.NextPart") (type . "mime")) ((name . "multipart.Reader.NextRawPart()") (path . "mime/multipart/index#Reader.NextRawPart") (type . "mime")) ((name . "multipart.Reader.ReadForm()") (path . "mime/multipart/index#Reader.ReadForm") (type . "mime")) ((name . "multipart.Writer") (path . "mime/multipart/index#Writer") (type . "mime")) ((name . "multipart.Writer.Boundary()") (path . "mime/multipart/index#Writer.Boundary") (type . "mime")) ((name . "multipart.Writer.Close()") (path . "mime/multipart/index#Writer.Close") (type . "mime")) ((name . "multipart.Writer.CreateFormField()") (path . "mime/multipart/index#Writer.CreateFormField") (type . "mime")) ((name . "multipart.Writer.CreateFormFile()") (path . "mime/multipart/index#Writer.CreateFormFile") (type . "mime")) ((name . "multipart.Writer.CreatePart()") (path . "mime/multipart/index#Writer.CreatePart") (type . "mime")) ((name . "multipart.Writer.FormDataContentType()") (path . "mime/multipart/index#Writer.FormDataContentType") (type . "mime")) ((name . "multipart.Writer.SetBoundary()") (path . "mime/multipart/index#Writer.SetBoundary") (type . "mime")) ((name . "multipart.Writer.WriteField()") (path . "mime/multipart/index#Writer.WriteField") (type . "mime")) ((name . "net") (path . "net/index") (type . "net")) ((name . "net constants") (path . "net/index#pkg-constants") (type . "net")) ((name . "net variables") (path . "net/index#pkg-variables") (type . "net")) ((name . "net.Addr") (path . "net/index#Addr") (type . "net")) ((name . "net.AddrError") (path . "net/index#AddrError") (type . "net")) ((name . "net.AddrError.Error()") (path . "net/index#AddrError.Error") (type . "net")) ((name . "net.AddrError.Temporary()") (path . "net/index#AddrError.Temporary") (type . "net")) ((name . "net.AddrError.Timeout()") (path . "net/index#AddrError.Timeout") (type . "net")) ((name . "net.Buffers") (path . "net/index#Buffers") (type . "net")) ((name . "net.Buffers.Read()") (path . "net/index#Buffers.Read") (type . "net")) ((name . "net.Buffers.WriteTo()") (path . "net/index#Buffers.WriteTo") (type . "net")) ((name . "net.CIDRMask()") (path . "net/index#CIDRMask") (type . "net")) ((name . "net.Conn") (path . "net/index#Conn") (type . "net")) ((name . "net.Dial()") (path . "net/index#Dial") (type . "net")) ((name . "net.Dialer") (path . "net/index#Dialer") (type . "net")) ((name . "net.Dialer.Dial()") (path . "net/index#Dialer.Dial") (type . "net")) ((name . "net.Dialer.DialContext()") (path . "net/index#Dialer.DialContext") (type . "net")) ((name . "net.Dialer.MultipathTCP()") (path . "net/index#Dialer.MultipathTCP") (type . "net")) ((name . "net.Dialer.SetMultipathTCP()") (path . "net/index#Dialer.SetMultipathTCP") (type . "net")) ((name . "net.DialIP()") (path . "net/index#DialIP") (type . "net")) ((name . "net.DialTCP()") (path . "net/index#DialTCP") (type . "net")) ((name . "net.DialTimeout()") (path . "net/index#DialTimeout") (type . "net")) ((name . "net.DialUDP()") (path . "net/index#DialUDP") (type . "net")) ((name . "net.DialUnix()") (path . "net/index#DialUnix") (type . "net")) ((name . "net.DNSConfigError") (path . "net/index#DNSConfigError") (type . "net")) ((name . "net.DNSConfigError.Error()") (path . "net/index#DNSConfigError.Error") (type . "net")) ((name . "net.DNSConfigError.Temporary()") (path . "net/index#DNSConfigError.Temporary") (type . "net")) ((name . "net.DNSConfigError.Timeout()") (path . "net/index#DNSConfigError.Timeout") (type . "net")) ((name . "net.DNSConfigError.Unwrap()") (path . "net/index#DNSConfigError.Unwrap") (type . "net")) ((name . "net.DNSError") (path . "net/index#DNSError") (type . "net")) ((name . "net.DNSError.Error()") (path . "net/index#DNSError.Error") (type . "net")) ((name . "net.DNSError.Temporary()") (path . "net/index#DNSError.Temporary") (type . "net")) ((name . "net.DNSError.Timeout()") (path . "net/index#DNSError.Timeout") (type . "net")) ((name . "net.Error") (path . "net/index#Error") (type . "net")) ((name . "net.FileConn()") (path . "net/index#FileConn") (type . "net")) ((name . "net.FileListener()") (path . "net/index#FileListener") (type . "net")) ((name . "net.FilePacketConn()") (path . "net/index#FilePacketConn") (type . "net")) ((name . "net.Flags") (path . "net/index#Flags") (type . "net")) ((name . "net.Flags.String()") (path . "net/index#Flags.String") (type . "net")) ((name . "net.HardwareAddr") (path . "net/index#HardwareAddr") (type . "net")) ((name . "net.HardwareAddr.String()") (path . "net/index#HardwareAddr.String") (type . "net")) ((name . "net.Interface") (path . "net/index#Interface") (type . "net")) ((name . "net.Interface.Addrs()") (path . "net/index#Interface.Addrs") (type . "net")) ((name . "net.Interface.MulticastAddrs()") (path . "net/index#Interface.MulticastAddrs") (type . "net")) ((name . "net.InterfaceAddrs()") (path . "net/index#InterfaceAddrs") (type . "net")) ((name . "net.InterfaceByIndex()") (path . "net/index#InterfaceByIndex") (type . "net")) ((name . "net.InterfaceByName()") (path . "net/index#InterfaceByName") (type . "net")) ((name . "net.Interfaces()") (path . "net/index#Interfaces") (type . "net")) ((name . "net.InvalidAddrError") (path . "net/index#InvalidAddrError") (type . "net")) ((name . "net.InvalidAddrError.Error()") (path . "net/index#InvalidAddrError.Error") (type . "net")) ((name . "net.InvalidAddrError.Temporary()") (path . "net/index#InvalidAddrError.Temporary") (type . "net")) ((name . "net.InvalidAddrError.Timeout()") (path . "net/index#InvalidAddrError.Timeout") (type . "net")) ((name . "net.IP") (path . "net/index#IP") (type . "net")) ((name . "net.IP.DefaultMask()") (path . "net/index#IP.DefaultMask") (type . "net")) ((name . "net.IP.Equal()") (path . "net/index#IP.Equal") (type . "net")) ((name . "net.IP.IsGlobalUnicast()") (path . "net/index#IP.IsGlobalUnicast") (type . "net")) ((name . "net.IP.IsInterfaceLocalMulticast()") (path . "net/index#IP.IsInterfaceLocalMulticast") (type . "net")) ((name . "net.IP.IsLinkLocalMulticast()") (path . "net/index#IP.IsLinkLocalMulticast") (type . "net")) ((name . "net.IP.IsLinkLocalUnicast()") (path . "net/index#IP.IsLinkLocalUnicast") (type . "net")) ((name . "net.IP.IsLoopback()") (path . "net/index#IP.IsLoopback") (type . "net")) ((name . "net.IP.IsMulticast()") (path . "net/index#IP.IsMulticast") (type . "net")) ((name . "net.IP.IsPrivate()") (path . "net/index#IP.IsPrivate") (type . "net")) ((name . "net.IP.IsUnspecified()") (path . "net/index#IP.IsUnspecified") (type . "net")) ((name . "net.IP.MarshalText()") (path . "net/index#IP.MarshalText") (type . "net")) ((name . "net.IP.Mask()") (path . "net/index#IP.Mask") (type . "net")) ((name . "net.IP.String()") (path . "net/index#IP.String") (type . "net")) ((name . "net.IP.To16()") (path . "net/index#IP.To16") (type . "net")) ((name . "net.IP.To4()") (path . "net/index#IP.To4") (type . "net")) ((name . "net.IP.UnmarshalText()") (path . "net/index#IP.UnmarshalText") (type . "net")) ((name . "net.IPAddr") (path . "net/index#IPAddr") (type . "net")) ((name . "net.IPAddr.Network()") (path . "net/index#IPAddr.Network") (type . "net")) ((name . "net.IPAddr.String()") (path . "net/index#IPAddr.String") (type . "net")) ((name . "net.IPConn") (path . "net/index#IPConn") (type . "net")) ((name . "net.IPConn.Close()") (path . "net/index#IPConn.Close") (type . "net")) ((name . "net.IPConn.File()") (path . "net/index#IPConn.File") (type . "net")) ((name . "net.IPConn.LocalAddr()") (path . "net/index#IPConn.LocalAddr") (type . "net")) ((name . "net.IPConn.Read()") (path . "net/index#IPConn.Read") (type . "net")) ((name . "net.IPConn.ReadFrom()") (path . "net/index#IPConn.ReadFrom") (type . "net")) ((name . "net.IPConn.ReadFromIP()") (path . "net/index#IPConn.ReadFromIP") (type . "net")) ((name . "net.IPConn.ReadMsgIP()") (path . "net/index#IPConn.ReadMsgIP") (type . "net")) ((name . "net.IPConn.RemoteAddr()") (path . "net/index#IPConn.RemoteAddr") (type . "net")) ((name . "net.IPConn.SetDeadline()") (path . "net/index#IPConn.SetDeadline") (type . "net")) ((name . "net.IPConn.SetReadBuffer()") (path . "net/index#IPConn.SetReadBuffer") (type . "net")) ((name . "net.IPConn.SetReadDeadline()") (path . "net/index#IPConn.SetReadDeadline") (type . "net")) ((name . "net.IPConn.SetWriteBuffer()") (path . "net/index#IPConn.SetWriteBuffer") (type . "net")) ((name . "net.IPConn.SetWriteDeadline()") (path . "net/index#IPConn.SetWriteDeadline") (type . "net")) ((name . "net.IPConn.SyscallConn()") (path . "net/index#IPConn.SyscallConn") (type . "net")) ((name . "net.IPConn.Write()") (path . "net/index#IPConn.Write") (type . "net")) ((name . "net.IPConn.WriteMsgIP()") (path . "net/index#IPConn.WriteMsgIP") (type . "net")) ((name . "net.IPConn.WriteTo()") (path . "net/index#IPConn.WriteTo") (type . "net")) ((name . "net.IPConn.WriteToIP()") (path . "net/index#IPConn.WriteToIP") (type . "net")) ((name . "net.IPMask") (path . "net/index#IPMask") (type . "net")) ((name . "net.IPMask.Size()") (path . "net/index#IPMask.Size") (type . "net")) ((name . "net.IPMask.String()") (path . "net/index#IPMask.String") (type . "net")) ((name . "net.IPNet") (path . "net/index#IPNet") (type . "net")) ((name . "net.IPNet.Contains()") (path . "net/index#IPNet.Contains") (type . "net")) ((name . "net.IPNet.Network()") (path . "net/index#IPNet.Network") (type . "net")) ((name . "net.IPNet.String()") (path . "net/index#IPNet.String") (type . "net")) ((name . "net.IPv4()") (path . "net/index#IPv4") (type . "net")) ((name . "net.IPv4Mask()") (path . "net/index#IPv4Mask") (type . "net")) ((name . "net.JoinHostPort()") (path . "net/index#JoinHostPort") (type . "net")) ((name . "net.Listen()") (path . "net/index#Listen") (type . "net")) ((name . "net.ListenConfig") (path . "net/index#ListenConfig") (type . "net")) ((name . "net.ListenConfig.Listen()") (path . "net/index#ListenConfig.Listen") (type . "net")) ((name . "net.ListenConfig.ListenPacket()") (path . "net/index#ListenConfig.ListenPacket") (type . "net")) ((name . "net.ListenConfig.MultipathTCP()") (path . "net/index#ListenConfig.MultipathTCP") (type . "net")) ((name . "net.ListenConfig.SetMultipathTCP()") (path . "net/index#ListenConfig.SetMultipathTCP") (type . "net")) ((name . "net.Listener") (path . "net/index#Listener") (type . "net")) ((name . "net.ListenIP()") (path . "net/index#ListenIP") (type . "net")) ((name . "net.ListenMulticastUDP()") (path . "net/index#ListenMulticastUDP") (type . "net")) ((name . "net.ListenPacket()") (path . "net/index#ListenPacket") (type . "net")) ((name . "net.ListenTCP()") (path . "net/index#ListenTCP") (type . "net")) ((name . "net.ListenUDP()") (path . "net/index#ListenUDP") (type . "net")) ((name . "net.ListenUnix()") (path . "net/index#ListenUnix") (type . "net")) ((name . "net.ListenUnixgram()") (path . "net/index#ListenUnixgram") (type . "net")) ((name . "net.LookupAddr()") (path . "net/index#LookupAddr") (type . "net")) ((name . "net.LookupCNAME()") (path . "net/index#LookupCNAME") (type . "net")) ((name . "net.LookupHost()") (path . "net/index#LookupHost") (type . "net")) ((name . "net.LookupIP()") (path . "net/index#LookupIP") (type . "net")) ((name . "net.LookupMX()") (path . "net/index#LookupMX") (type . "net")) ((name . "net.LookupNS()") (path . "net/index#LookupNS") (type . "net")) ((name . "net.LookupPort()") (path . "net/index#LookupPort") (type . "net")) ((name . "net.LookupSRV()") (path . "net/index#LookupSRV") (type . "net")) ((name . "net.LookupTXT()") (path . "net/index#LookupTXT") (type . "net")) ((name . "net.MX") (path . "net/index#MX") (type . "net")) ((name . "net.NS") (path . "net/index#NS") (type . "net")) ((name . "net.OpError") (path . "net/index#OpError") (type . "net")) ((name . "net.OpError.Error()") (path . "net/index#OpError.Error") (type . "net")) ((name . "net.OpError.Temporary()") (path . "net/index#OpError.Temporary") (type . "net")) ((name . "net.OpError.Timeout()") (path . "net/index#OpError.Timeout") (type . "net")) ((name . "net.OpError.Unwrap()") (path . "net/index#OpError.Unwrap") (type . "net")) ((name . "net.PacketConn") (path . "net/index#PacketConn") (type . "net")) ((name . "net.ParseCIDR()") (path . "net/index#ParseCIDR") (type . "net")) ((name . "net.ParseError") (path . "net/index#ParseError") (type . "net")) ((name . "net.ParseError.Error()") (path . "net/index#ParseError.Error") (type . "net")) ((name . "net.ParseError.Temporary()") (path . "net/index#ParseError.Temporary") (type . "net")) ((name . "net.ParseError.Timeout()") (path . "net/index#ParseError.Timeout") (type . "net")) ((name . "net.ParseIP()") (path . "net/index#ParseIP") (type . "net")) ((name . "net.ParseMAC()") (path . "net/index#ParseMAC") (type . "net")) ((name . "net.Pipe()") (path . "net/index#Pipe") (type . "net")) ((name . "net.ResolveIPAddr()") (path . "net/index#ResolveIPAddr") (type . "net")) ((name . "net.Resolver") (path . "net/index#Resolver") (type . "net")) ((name . "net.Resolver.LookupAddr()") (path . "net/index#Resolver.LookupAddr") (type . "net")) ((name . "net.Resolver.LookupCNAME()") (path . "net/index#Resolver.LookupCNAME") (type . "net")) ((name . "net.Resolver.LookupHost()") (path . "net/index#Resolver.LookupHost") (type . "net")) ((name . "net.Resolver.LookupIP()") (path . "net/index#Resolver.LookupIP") (type . "net")) ((name . "net.Resolver.LookupIPAddr()") (path . "net/index#Resolver.LookupIPAddr") (type . "net")) ((name . "net.Resolver.LookupMX()") (path . "net/index#Resolver.LookupMX") (type . "net")) ((name . "net.Resolver.LookupNetIP()") (path . "net/index#Resolver.LookupNetIP") (type . "net")) ((name . "net.Resolver.LookupNS()") (path . "net/index#Resolver.LookupNS") (type . "net")) ((name . "net.Resolver.LookupPort()") (path . "net/index#Resolver.LookupPort") (type . "net")) ((name . "net.Resolver.LookupSRV()") (path . "net/index#Resolver.LookupSRV") (type . "net")) ((name . "net.Resolver.LookupTXT()") (path . "net/index#Resolver.LookupTXT") (type . "net")) ((name . "net.ResolveTCPAddr()") (path . "net/index#ResolveTCPAddr") (type . "net")) ((name . "net.ResolveUDPAddr()") (path . "net/index#ResolveUDPAddr") (type . "net")) ((name . "net.ResolveUnixAddr()") (path . "net/index#ResolveUnixAddr") (type . "net")) ((name . "net.SplitHostPort()") (path . "net/index#SplitHostPort") (type . "net")) ((name . "net.SRV") (path . "net/index#SRV") (type . "net")) ((name . "net.TCPAddr") (path . "net/index#TCPAddr") (type . "net")) ((name . "net.TCPAddr.AddrPort()") (path . "net/index#TCPAddr.AddrPort") (type . "net")) ((name . "net.TCPAddr.Network()") (path . "net/index#TCPAddr.Network") (type . "net")) ((name . "net.TCPAddr.String()") (path . "net/index#TCPAddr.String") (type . "net")) ((name . "net.TCPAddrFromAddrPort()") (path . "net/index#TCPAddrFromAddrPort") (type . "net")) ((name . "net.TCPConn") (path . "net/index#TCPConn") (type . "net")) ((name . "net.TCPConn.Close()") (path . "net/index#TCPConn.Close") (type . "net")) ((name . "net.TCPConn.CloseRead()") (path . "net/index#TCPConn.CloseRead") (type . "net")) ((name . "net.TCPConn.CloseWrite()") (path . "net/index#TCPConn.CloseWrite") (type . "net")) ((name . "net.TCPConn.File()") (path . "net/index#TCPConn.File") (type . "net")) ((name . "net.TCPConn.LocalAddr()") (path . "net/index#TCPConn.LocalAddr") (type . "net")) ((name . "net.TCPConn.MultipathTCP()") (path . "net/index#TCPConn.MultipathTCP") (type . "net")) ((name . "net.TCPConn.Read()") (path . "net/index#TCPConn.Read") (type . "net")) ((name . "net.TCPConn.ReadFrom()") (path . "net/index#TCPConn.ReadFrom") (type . "net")) ((name . "net.TCPConn.RemoteAddr()") (path . "net/index#TCPConn.RemoteAddr") (type . "net")) ((name . "net.TCPConn.SetDeadline()") (path . "net/index#TCPConn.SetDeadline") (type . "net")) ((name . "net.TCPConn.SetKeepAlive()") (path . "net/index#TCPConn.SetKeepAlive") (type . "net")) ((name . "net.TCPConn.SetKeepAlivePeriod()") (path . "net/index#TCPConn.SetKeepAlivePeriod") (type . "net")) ((name . "net.TCPConn.SetLinger()") (path . "net/index#TCPConn.SetLinger") (type . "net")) ((name . "net.TCPConn.SetNoDelay()") (path . "net/index#TCPConn.SetNoDelay") (type . "net")) ((name . "net.TCPConn.SetReadBuffer()") (path . "net/index#TCPConn.SetReadBuffer") (type . "net")) ((name . "net.TCPConn.SetReadDeadline()") (path . "net/index#TCPConn.SetReadDeadline") (type . "net")) ((name . "net.TCPConn.SetWriteBuffer()") (path . "net/index#TCPConn.SetWriteBuffer") (type . "net")) ((name . "net.TCPConn.SetWriteDeadline()") (path . "net/index#TCPConn.SetWriteDeadline") (type . "net")) ((name . "net.TCPConn.SyscallConn()") (path . "net/index#TCPConn.SyscallConn") (type . "net")) ((name . "net.TCPConn.Write()") (path . "net/index#TCPConn.Write") (type . "net")) ((name . "net.TCPConn.WriteTo()") (path . "net/index#TCPConn.WriteTo") (type . "net")) ((name . "net.TCPListener") (path . "net/index#TCPListener") (type . "net")) ((name . "net.TCPListener.Accept()") (path . "net/index#TCPListener.Accept") (type . "net")) ((name . "net.TCPListener.AcceptTCP()") (path . "net/index#TCPListener.AcceptTCP") (type . "net")) ((name . "net.TCPListener.Addr()") (path . "net/index#TCPListener.Addr") (type . "net")) ((name . "net.TCPListener.Close()") (path . "net/index#TCPListener.Close") (type . "net")) ((name . "net.TCPListener.File()") (path . "net/index#TCPListener.File") (type . "net")) ((name . "net.TCPListener.SetDeadline()") (path . "net/index#TCPListener.SetDeadline") (type . "net")) ((name . "net.TCPListener.SyscallConn()") (path . "net/index#TCPListener.SyscallConn") (type . "net")) ((name . "net.UDPAddr") (path . "net/index#UDPAddr") (type . "net")) ((name . "net.UDPAddr.AddrPort()") (path . "net/index#UDPAddr.AddrPort") (type . "net")) ((name . "net.UDPAddr.Network()") (path . "net/index#UDPAddr.Network") (type . "net")) ((name . "net.UDPAddr.String()") (path . "net/index#UDPAddr.String") (type . "net")) ((name . "net.UDPAddrFromAddrPort()") (path . "net/index#UDPAddrFromAddrPort") (type . "net")) ((name . "net.UDPConn") (path . "net/index#UDPConn") (type . "net")) ((name . "net.UDPConn.Close()") (path . "net/index#UDPConn.Close") (type . "net")) ((name . "net.UDPConn.File()") (path . "net/index#UDPConn.File") (type . "net")) ((name . "net.UDPConn.LocalAddr()") (path . "net/index#UDPConn.LocalAddr") (type . "net")) ((name . "net.UDPConn.Read()") (path . "net/index#UDPConn.Read") (type . "net")) ((name . "net.UDPConn.ReadFrom()") (path . "net/index#UDPConn.ReadFrom") (type . "net")) ((name . "net.UDPConn.ReadFromUDP()") (path . "net/index#UDPConn.ReadFromUDP") (type . "net")) ((name . "net.UDPConn.ReadFromUDPAddrPort()") (path . "net/index#UDPConn.ReadFromUDPAddrPort") (type . "net")) ((name . "net.UDPConn.ReadMsgUDP()") (path . "net/index#UDPConn.ReadMsgUDP") (type . "net")) ((name . "net.UDPConn.ReadMsgUDPAddrPort()") (path . "net/index#UDPConn.ReadMsgUDPAddrPort") (type . "net")) ((name . "net.UDPConn.RemoteAddr()") (path . "net/index#UDPConn.RemoteAddr") (type . "net")) ((name . "net.UDPConn.SetDeadline()") (path . "net/index#UDPConn.SetDeadline") (type . "net")) ((name . "net.UDPConn.SetReadBuffer()") (path . "net/index#UDPConn.SetReadBuffer") (type . "net")) ((name . "net.UDPConn.SetReadDeadline()") (path . "net/index#UDPConn.SetReadDeadline") (type . "net")) ((name . "net.UDPConn.SetWriteBuffer()") (path . "net/index#UDPConn.SetWriteBuffer") (type . "net")) ((name . "net.UDPConn.SetWriteDeadline()") (path . "net/index#UDPConn.SetWriteDeadline") (type . "net")) ((name . "net.UDPConn.SyscallConn()") (path . "net/index#UDPConn.SyscallConn") (type . "net")) ((name . "net.UDPConn.Write()") (path . "net/index#UDPConn.Write") (type . "net")) ((name . "net.UDPConn.WriteMsgUDP()") (path . "net/index#UDPConn.WriteMsgUDP") (type . "net")) ((name . "net.UDPConn.WriteMsgUDPAddrPort()") (path . "net/index#UDPConn.WriteMsgUDPAddrPort") (type . "net")) ((name . "net.UDPConn.WriteTo()") (path . "net/index#UDPConn.WriteTo") (type . "net")) ((name . "net.UDPConn.WriteToUDP()") (path . "net/index#UDPConn.WriteToUDP") (type . "net")) ((name . "net.UDPConn.WriteToUDPAddrPort()") (path . "net/index#UDPConn.WriteToUDPAddrPort") (type . "net")) ((name . "net.UnixAddr") (path . "net/index#UnixAddr") (type . "net")) ((name . "net.UnixAddr.Network()") (path . "net/index#UnixAddr.Network") (type . "net")) ((name . "net.UnixAddr.String()") (path . "net/index#UnixAddr.String") (type . "net")) ((name . "net.UnixConn") (path . "net/index#UnixConn") (type . "net")) ((name . "net.UnixConn.Close()") (path . "net/index#UnixConn.Close") (type . "net")) ((name . "net.UnixConn.CloseRead()") (path . "net/index#UnixConn.CloseRead") (type . "net")) ((name . "net.UnixConn.CloseWrite()") (path . "net/index#UnixConn.CloseWrite") (type . "net")) ((name . "net.UnixConn.File()") (path . "net/index#UnixConn.File") (type . "net")) ((name . "net.UnixConn.LocalAddr()") (path . "net/index#UnixConn.LocalAddr") (type . "net")) ((name . "net.UnixConn.Read()") (path . "net/index#UnixConn.Read") (type . "net")) ((name . "net.UnixConn.ReadFrom()") (path . "net/index#UnixConn.ReadFrom") (type . "net")) ((name . "net.UnixConn.ReadFromUnix()") (path . "net/index#UnixConn.ReadFromUnix") (type . "net")) ((name . "net.UnixConn.ReadMsgUnix()") (path . "net/index#UnixConn.ReadMsgUnix") (type . "net")) ((name . "net.UnixConn.RemoteAddr()") (path . "net/index#UnixConn.RemoteAddr") (type . "net")) ((name . "net.UnixConn.SetDeadline()") (path . "net/index#UnixConn.SetDeadline") (type . "net")) ((name . "net.UnixConn.SetReadBuffer()") (path . "net/index#UnixConn.SetReadBuffer") (type . "net")) ((name . "net.UnixConn.SetReadDeadline()") (path . "net/index#UnixConn.SetReadDeadline") (type . "net")) ((name . "net.UnixConn.SetWriteBuffer()") (path . "net/index#UnixConn.SetWriteBuffer") (type . "net")) ((name . "net.UnixConn.SetWriteDeadline()") (path . "net/index#UnixConn.SetWriteDeadline") (type . "net")) ((name . "net.UnixConn.SyscallConn()") (path . "net/index#UnixConn.SyscallConn") (type . "net")) ((name . "net.UnixConn.Write()") (path . "net/index#UnixConn.Write") (type . "net")) ((name . "net.UnixConn.WriteMsgUnix()") (path . "net/index#UnixConn.WriteMsgUnix") (type . "net")) ((name . "net.UnixConn.WriteTo()") (path . "net/index#UnixConn.WriteTo") (type . "net")) ((name . "net.UnixConn.WriteToUnix()") (path . "net/index#UnixConn.WriteToUnix") (type . "net")) ((name . "net.UnixListener") (path . "net/index#UnixListener") (type . "net")) ((name . "net.UnixListener.Accept()") (path . "net/index#UnixListener.Accept") (type . "net")) ((name . "net.UnixListener.AcceptUnix()") (path . "net/index#UnixListener.AcceptUnix") (type . "net")) ((name . "net.UnixListener.Addr()") (path . "net/index#UnixListener.Addr") (type . "net")) ((name . "net.UnixListener.Close()") (path . "net/index#UnixListener.Close") (type . "net")) ((name . "net.UnixListener.File()") (path . "net/index#UnixListener.File") (type . "net")) ((name . "net.UnixListener.SetDeadline()") (path . "net/index#UnixListener.SetDeadline") (type . "net")) ((name . "net.UnixListener.SetUnlinkOnClose()") (path . "net/index#UnixListener.SetUnlinkOnClose") (type . "net")) ((name . "net.UnixListener.SyscallConn()") (path . "net/index#UnixListener.SyscallConn") (type . "net")) ((name . "net.UnknownNetworkError") (path . "net/index#UnknownNetworkError") (type . "net")) ((name . "net.UnknownNetworkError.Error()") (path . "net/index#UnknownNetworkError.Error") (type . "net")) ((name . "net.UnknownNetworkError.Temporary()") (path . "net/index#UnknownNetworkError.Temporary") (type . "net")) ((name . "net.UnknownNetworkError.Timeout()") (path . "net/index#UnknownNetworkError.Timeout") (type . "net")) ((name . "net/http") (path . "net/http/index") (type . "net/http")) ((name . "net/http constants") (path . "net/http/index#pkg-constants") (type . "net/http")) ((name . "net/http variables") (path . "net/http/index#pkg-variables") (type . "net/http")) ((name . "net/http/cgi") (path . "net/http/cgi/index") (type . "net/http")) ((name . "net/http/cookiejar") (path . "net/http/cookiejar/index") (type . "net/http")) ((name . "net/http/fcgi") (path . "net/http/fcgi/index") (type . "net/http")) ((name . "net/http/fcgi variables") (path . "net/http/fcgi/index#pkg-variables") (type . "net/http")) ((name . "net/http/httptest") (path . "net/http/httptest/index") (type . "net/http")) ((name . "net/http/httptest constants") (path . "net/http/httptest/index#pkg-constants") (type . "net/http")) ((name . "net/http/httptrace") (path . "net/http/httptrace/index") (type . "net/http")) ((name . "net/http/httputil") (path . "net/http/httputil/index") (type . "net/http")) ((name . "net/http/httputil variables") (path . "net/http/httputil/index#pkg-variables") (type . "net/http")) ((name . "net/http/internal") (path . "net/http/internal/index") (type . "net/http")) ((name . "net/http/internal variables") (path . "net/http/internal/index#pkg-variables") (type . "net/http")) ((name . "net/http/pprof") (path . "net/http/pprof/index") (type . "net/http")) ((name . "net/mail") (path . "net/mail/index") (type . "net/mail")) ((name . "net/mail variables") (path . "net/mail/index#pkg-variables") (type . "net/mail")) ((name . "net/netip") (path . "net/netip/index") (type . "net/netip")) ((name . "net/rpc") (path . "net/rpc/index") (type . "net/rpc")) ((name . "net/rpc constants") (path . "net/rpc/index#pkg-constants") (type . "net/rpc")) ((name . "net/rpc variables") (path . "net/rpc/index#pkg-variables") (type . "net/rpc")) ((name . "net/rpc/jsonrpc") (path . "net/rpc/jsonrpc/index") (type . "net/rpc")) ((name . "net/smtp") (path . "net/smtp/index") (type . "net/smtp")) ((name . "net/textproto") (path . "net/textproto/index") (type . "net/textproto")) ((name . "net/url") (path . "net/url/index") (type . "net/url")) ((name . "netip.Addr") (path . "net/netip/index#Addr") (type . "net/netip")) ((name . "netip.Addr.AppendTo()") (path . "net/netip/index#Addr.AppendTo") (type . "net/netip")) ((name . "netip.Addr.As16()") (path . "net/netip/index#Addr.As16") (type . "net/netip")) ((name . "netip.Addr.As4()") (path . "net/netip/index#Addr.As4") (type . "net/netip")) ((name . "netip.Addr.AsSlice()") (path . "net/netip/index#Addr.AsSlice") (type . "net/netip")) ((name . "netip.Addr.BitLen()") (path . "net/netip/index#Addr.BitLen") (type . "net/netip")) ((name . "netip.Addr.Compare()") (path . "net/netip/index#Addr.Compare") (type . "net/netip")) ((name . "netip.Addr.Is4()") (path . "net/netip/index#Addr.Is4") (type . "net/netip")) ((name . "netip.Addr.Is4In6()") (path . "net/netip/index#Addr.Is4In6") (type . "net/netip")) ((name . "netip.Addr.Is6()") (path . "net/netip/index#Addr.Is6") (type . "net/netip")) ((name . "netip.Addr.IsGlobalUnicast()") (path . "net/netip/index#Addr.IsGlobalUnicast") (type . "net/netip")) ((name . "netip.Addr.IsInterfaceLocalMulticast()") (path . "net/netip/index#Addr.IsInterfaceLocalMulticast") (type . "net/netip")) ((name . "netip.Addr.IsLinkLocalMulticast()") (path . "net/netip/index#Addr.IsLinkLocalMulticast") (type . "net/netip")) ((name . "netip.Addr.IsLinkLocalUnicast()") (path . "net/netip/index#Addr.IsLinkLocalUnicast") (type . "net/netip")) ((name . "netip.Addr.IsLoopback()") (path . "net/netip/index#Addr.IsLoopback") (type . "net/netip")) ((name . "netip.Addr.IsMulticast()") (path . "net/netip/index#Addr.IsMulticast") (type . "net/netip")) ((name . "netip.Addr.IsPrivate()") (path . "net/netip/index#Addr.IsPrivate") (type . "net/netip")) ((name . "netip.Addr.IsUnspecified()") (path . "net/netip/index#Addr.IsUnspecified") (type . "net/netip")) ((name . "netip.Addr.IsValid()") (path . "net/netip/index#Addr.IsValid") (type . "net/netip")) ((name . "netip.Addr.Less()") (path . "net/netip/index#Addr.Less") (type . "net/netip")) ((name . "netip.Addr.MarshalBinary()") (path . "net/netip/index#Addr.MarshalBinary") (type . "net/netip")) ((name . "netip.Addr.MarshalText()") (path . "net/netip/index#Addr.MarshalText") (type . "net/netip")) ((name . "netip.Addr.Next()") (path . "net/netip/index#Addr.Next") (type . "net/netip")) ((name . "netip.Addr.Prefix()") (path . "net/netip/index#Addr.Prefix") (type . "net/netip")) ((name . "netip.Addr.Prev()") (path . "net/netip/index#Addr.Prev") (type . "net/netip")) ((name . "netip.Addr.String()") (path . "net/netip/index#Addr.String") (type . "net/netip")) ((name . "netip.Addr.StringExpanded()") (path . "net/netip/index#Addr.StringExpanded") (type . "net/netip")) ((name . "netip.Addr.Unmap()") (path . "net/netip/index#Addr.Unmap") (type . "net/netip")) ((name . "netip.Addr.UnmarshalBinary()") (path . "net/netip/index#Addr.UnmarshalBinary") (type . "net/netip")) ((name . "netip.Addr.UnmarshalText()") (path . "net/netip/index#Addr.UnmarshalText") (type . "net/netip")) ((name . "netip.Addr.WithZone()") (path . "net/netip/index#Addr.WithZone") (type . "net/netip")) ((name . "netip.Addr.Zone()") (path . "net/netip/index#Addr.Zone") (type . "net/netip")) ((name . "netip.AddrFrom16()") (path . "net/netip/index#AddrFrom16") (type . "net/netip")) ((name . "netip.AddrFrom4()") (path . "net/netip/index#AddrFrom4") (type . "net/netip")) ((name . "netip.AddrFromSlice()") (path . "net/netip/index#AddrFromSlice") (type . "net/netip")) ((name . "netip.AddrPort") (path . "net/netip/index#AddrPort") (type . "net/netip")) ((name . "netip.AddrPort.Addr()") (path . "net/netip/index#AddrPort.Addr") (type . "net/netip")) ((name . "netip.AddrPort.AppendTo()") (path . "net/netip/index#AddrPort.AppendTo") (type . "net/netip")) ((name . "netip.AddrPort.Compare()") (path . "net/netip/index#AddrPort.Compare") (type . "net/netip")) ((name . "netip.AddrPort.IsValid()") (path . "net/netip/index#AddrPort.IsValid") (type . "net/netip")) ((name . "netip.AddrPort.MarshalBinary()") (path . "net/netip/index#AddrPort.MarshalBinary") (type . "net/netip")) ((name . "netip.AddrPort.MarshalText()") (path . "net/netip/index#AddrPort.MarshalText") (type . "net/netip")) ((name . "netip.AddrPort.Port()") (path . "net/netip/index#AddrPort.Port") (type . "net/netip")) ((name . "netip.AddrPort.String()") (path . "net/netip/index#AddrPort.String") (type . "net/netip")) ((name . "netip.AddrPort.UnmarshalBinary()") (path . "net/netip/index#AddrPort.UnmarshalBinary") (type . "net/netip")) ((name . "netip.AddrPort.UnmarshalText()") (path . "net/netip/index#AddrPort.UnmarshalText") (type . "net/netip")) ((name . "netip.AddrPortFrom()") (path . "net/netip/index#AddrPortFrom") (type . "net/netip")) ((name . "netip.IPv4Unspecified()") (path . "net/netip/index#IPv4Unspecified") (type . "net/netip")) ((name . "netip.IPv6LinkLocalAllNodes()") (path . "net/netip/index#IPv6LinkLocalAllNodes") (type . "net/netip")) ((name . "netip.IPv6LinkLocalAllRouters()") (path . "net/netip/index#IPv6LinkLocalAllRouters") (type . "net/netip")) ((name . "netip.IPv6Loopback()") (path . "net/netip/index#IPv6Loopback") (type . "net/netip")) ((name . "netip.IPv6Unspecified()") (path . "net/netip/index#IPv6Unspecified") (type . "net/netip")) ((name . "netip.MustParseAddr()") (path . "net/netip/index#MustParseAddr") (type . "net/netip")) ((name . "netip.MustParseAddrPort()") (path . "net/netip/index#MustParseAddrPort") (type . "net/netip")) ((name . "netip.MustParsePrefix()") (path . "net/netip/index#MustParsePrefix") (type . "net/netip")) ((name . "netip.ParseAddr()") (path . "net/netip/index#ParseAddr") (type . "net/netip")) ((name . "netip.ParseAddrPort()") (path . "net/netip/index#ParseAddrPort") (type . "net/netip")) ((name . "netip.ParsePrefix()") (path . "net/netip/index#ParsePrefix") (type . "net/netip")) ((name . "netip.Prefix") (path . "net/netip/index#Prefix") (type . "net/netip")) ((name . "netip.Prefix.Addr()") (path . "net/netip/index#Prefix.Addr") (type . "net/netip")) ((name . "netip.Prefix.AppendTo()") (path . "net/netip/index#Prefix.AppendTo") (type . "net/netip")) ((name . "netip.Prefix.Bits()") (path . "net/netip/index#Prefix.Bits") (type . "net/netip")) ((name . "netip.Prefix.Contains()") (path . "net/netip/index#Prefix.Contains") (type . "net/netip")) ((name . "netip.Prefix.IsSingleIP()") (path . "net/netip/index#Prefix.IsSingleIP") (type . "net/netip")) ((name . "netip.Prefix.IsValid()") (path . "net/netip/index#Prefix.IsValid") (type . "net/netip")) ((name . "netip.Prefix.MarshalBinary()") (path . "net/netip/index#Prefix.MarshalBinary") (type . "net/netip")) ((name . "netip.Prefix.MarshalText()") (path . "net/netip/index#Prefix.MarshalText") (type . "net/netip")) ((name . "netip.Prefix.Masked()") (path . "net/netip/index#Prefix.Masked") (type . "net/netip")) ((name . "netip.Prefix.Overlaps()") (path . "net/netip/index#Prefix.Overlaps") (type . "net/netip")) ((name . "netip.Prefix.String()") (path . "net/netip/index#Prefix.String") (type . "net/netip")) ((name . "netip.Prefix.UnmarshalBinary()") (path . "net/netip/index#Prefix.UnmarshalBinary") (type . "net/netip")) ((name . "netip.Prefix.UnmarshalText()") (path . "net/netip/index#Prefix.UnmarshalText") (type . "net/netip")) ((name . "netip.PrefixFrom()") (path . "net/netip/index#PrefixFrom") (type . "net/netip")) ((name . "os") (path . "os/index") (type . "os")) ((name . "os constants") (path . "os/index#pkg-constants") (type . "os")) ((name . "os variables") (path . "os/index#pkg-variables") (type . "os")) ((name . "os.Chdir()") (path . "os/index#Chdir") (type . "os")) ((name . "os.Chmod()") (path . "os/index#Chmod") (type . "os")) ((name . "os.Chown()") (path . "os/index#Chown") (type . "os")) ((name . "os.Chtimes()") (path . "os/index#Chtimes") (type . "os")) ((name . "os.Clearenv()") (path . "os/index#Clearenv") (type . "os")) ((name . "os.Create()") (path . "os/index#Create") (type . "os")) ((name . "os.CreateTemp()") (path . "os/index#CreateTemp") (type . "os")) ((name . "os.DirEntry") (path . "os/index#DirEntry") (type . "os")) ((name . "os.DirFS()") (path . "os/index#DirFS") (type . "os")) ((name . "os.Environ()") (path . "os/index#Environ") (type . "os")) ((name . "os.Executable()") (path . "os/index#Executable") (type . "os")) ((name . "os.Exit()") (path . "os/index#Exit") (type . "os")) ((name . "os.Expand()") (path . "os/index#Expand") (type . "os")) ((name . "os.ExpandEnv()") (path . "os/index#ExpandEnv") (type . "os")) ((name . "os.File") (path . "os/index#File") (type . "os")) ((name . "os.File.Chdir()") (path . "os/index#File.Chdir") (type . "os")) ((name . "os.File.Chmod()") (path . "os/index#File.Chmod") (type . "os")) ((name . "os.File.Chown()") (path . "os/index#File.Chown") (type . "os")) ((name . "os.File.Close()") (path . "os/index#File.Close") (type . "os")) ((name . "os.File.Fd()") (path . "os/index#File.Fd") (type . "os")) ((name . "os.File.Name()") (path . "os/index#File.Name") (type . "os")) ((name . "os.File.Read()") (path . "os/index#File.Read") (type . "os")) ((name . "os.File.ReadAt()") (path . "os/index#File.ReadAt") (type . "os")) ((name . "os.File.ReadDir()") (path . "os/index#File.ReadDir") (type . "os")) ((name . "os.File.Readdir()") (path . "os/index#File.Readdir") (type . "os")) ((name . "os.File.Readdirnames()") (path . "os/index#File.Readdirnames") (type . "os")) ((name . "os.File.ReadFrom()") (path . "os/index#File.ReadFrom") (type . "os")) ((name . "os.File.Seek()") (path . "os/index#File.Seek") (type . "os")) ((name . "os.File.SetDeadline()") (path . "os/index#File.SetDeadline") (type . "os")) ((name . "os.File.SetReadDeadline()") (path . "os/index#File.SetReadDeadline") (type . "os")) ((name . "os.File.SetWriteDeadline()") (path . "os/index#File.SetWriteDeadline") (type . "os")) ((name . "os.File.Stat()") (path . "os/index#File.Stat") (type . "os")) ((name . "os.File.Sync()") (path . "os/index#File.Sync") (type . "os")) ((name . "os.File.SyscallConn()") (path . "os/index#File.SyscallConn") (type . "os")) ((name . "os.File.Truncate()") (path . "os/index#File.Truncate") (type . "os")) ((name . "os.File.Write()") (path . "os/index#File.Write") (type . "os")) ((name . "os.File.WriteAt()") (path . "os/index#File.WriteAt") (type . "os")) ((name . "os.File.WriteString()") (path . "os/index#File.WriteString") (type . "os")) ((name . "os.File.WriteTo()") (path . "os/index#File.WriteTo") (type . "os")) ((name . "os.FileInfo") (path . "os/index#FileInfo") (type . "os")) ((name . "os.FileMode") (path . "os/index#FileMode") (type . "os")) ((name . "os.FindProcess()") (path . "os/index#FindProcess") (type . "os")) ((name . "os.Getegid()") (path . "os/index#Getegid") (type . "os")) ((name . "os.Getenv()") (path . "os/index#Getenv") (type . "os")) ((name . "os.Geteuid()") (path . "os/index#Geteuid") (type . "os")) ((name . "os.Getgid()") (path . "os/index#Getgid") (type . "os")) ((name . "os.Getgroups()") (path . "os/index#Getgroups") (type . "os")) ((name . "os.Getpagesize()") (path . "os/index#Getpagesize") (type . "os")) ((name . "os.Getpid()") (path . "os/index#Getpid") (type . "os")) ((name . "os.Getppid()") (path . "os/index#Getppid") (type . "os")) ((name . "os.Getuid()") (path . "os/index#Getuid") (type . "os")) ((name . "os.Getwd()") (path . "os/index#Getwd") (type . "os")) ((name . "os.Hostname()") (path . "os/index#Hostname") (type . "os")) ((name . "os.IsExist()") (path . "os/index#IsExist") (type . "os")) ((name . "os.IsNotExist()") (path . "os/index#IsNotExist") (type . "os")) ((name . "os.IsPathSeparator()") (path . "os/index#IsPathSeparator") (type . "os")) ((name . "os.IsPermission()") (path . "os/index#IsPermission") (type . "os")) ((name . "os.IsTimeout()") (path . "os/index#IsTimeout") (type . "os")) ((name . "os.Lchown()") (path . "os/index#Lchown") (type . "os")) ((name . "os.Link()") (path . "os/index#Link") (type . "os")) ((name . "os.LinkError") (path . "os/index#LinkError") (type . "os")) ((name . "os.LinkError.Error()") (path . "os/index#LinkError.Error") (type . "os")) ((name . "os.LinkError.Unwrap()") (path . "os/index#LinkError.Unwrap") (type . "os")) ((name . "os.LookupEnv()") (path . "os/index#LookupEnv") (type . "os")) ((name . "os.Lstat()") (path . "os/index#Lstat") (type . "os")) ((name . "os.Mkdir()") (path . "os/index#Mkdir") (type . "os")) ((name . "os.MkdirAll()") (path . "os/index#MkdirAll") (type . "os")) ((name . "os.MkdirTemp()") (path . "os/index#MkdirTemp") (type . "os")) ((name . "os.NewFile()") (path . "os/index#NewFile") (type . "os")) ((name . "os.NewSyscallError()") (path . "os/index#NewSyscallError") (type . "os")) ((name . "os.Open()") (path . "os/index#Open") (type . "os")) ((name . "os.OpenFile()") (path . "os/index#OpenFile") (type . "os")) ((name . "os.PathError") (path . "os/index#PathError") (type . "os")) ((name . "os.Pipe()") (path . "os/index#Pipe") (type . "os")) ((name . "os.ProcAttr") (path . "os/index#ProcAttr") (type . "os")) ((name . "os.Process") (path . "os/index#Process") (type . "os")) ((name . "os.Process.Kill()") (path . "os/index#Process.Kill") (type . "os")) ((name . "os.Process.Release()") (path . "os/index#Process.Release") (type . "os")) ((name . "os.Process.Signal()") (path . "os/index#Process.Signal") (type . "os")) ((name . "os.Process.Wait()") (path . "os/index#Process.Wait") (type . "os")) ((name . "os.ProcessState") (path . "os/index#ProcessState") (type . "os")) ((name . "os.ProcessState.ExitCode()") (path . "os/index#ProcessState.ExitCode") (type . "os")) ((name . "os.ProcessState.Exited()") (path . "os/index#ProcessState.Exited") (type . "os")) ((name . "os.ProcessState.Pid()") (path . "os/index#ProcessState.Pid") (type . "os")) ((name . "os.ProcessState.String()") (path . "os/index#ProcessState.String") (type . "os")) ((name . "os.ProcessState.Success()") (path . "os/index#ProcessState.Success") (type . "os")) ((name . "os.ProcessState.Sys()") (path . "os/index#ProcessState.Sys") (type . "os")) ((name . "os.ProcessState.SystemTime()") (path . "os/index#ProcessState.SystemTime") (type . "os")) ((name . "os.ProcessState.SysUsage()") (path . "os/index#ProcessState.SysUsage") (type . "os")) ((name . "os.ProcessState.UserTime()") (path . "os/index#ProcessState.UserTime") (type . "os")) ((name . "os.ReadDir()") (path . "os/index#ReadDir") (type . "os")) ((name . "os.ReadFile()") (path . "os/index#ReadFile") (type . "os")) ((name . "os.Readlink()") (path . "os/index#Readlink") (type . "os")) ((name . "os.Remove()") (path . "os/index#Remove") (type . "os")) ((name . "os.RemoveAll()") (path . "os/index#RemoveAll") (type . "os")) ((name . "os.Rename()") (path . "os/index#Rename") (type . "os")) ((name . "os.SameFile()") (path . "os/index#SameFile") (type . "os")) ((name . "os.Setenv()") (path . "os/index#Setenv") (type . "os")) ((name . "os.Signal") (path . "os/index#Signal") (type . "os")) ((name . "os.StartProcess()") (path . "os/index#StartProcess") (type . "os")) ((name . "os.Stat()") (path . "os/index#Stat") (type . "os")) ((name . "os.Symlink()") (path . "os/index#Symlink") (type . "os")) ((name . "os.SyscallError") (path . "os/index#SyscallError") (type . "os")) ((name . "os.SyscallError.Error()") (path . "os/index#SyscallError.Error") (type . "os")) ((name . "os.SyscallError.Timeout()") (path . "os/index#SyscallError.Timeout") (type . "os")) ((name . "os.SyscallError.Unwrap()") (path . "os/index#SyscallError.Unwrap") (type . "os")) ((name . "os.TempDir()") (path . "os/index#TempDir") (type . "os")) ((name . "os.Truncate()") (path . "os/index#Truncate") (type . "os")) ((name . "os.Unsetenv()") (path . "os/index#Unsetenv") (type . "os")) ((name . "os.UserCacheDir()") (path . "os/index#UserCacheDir") (type . "os")) ((name . "os.UserConfigDir()") (path . "os/index#UserConfigDir") (type . "os")) ((name . "os.UserHomeDir()") (path . "os/index#UserHomeDir") (type . "os")) ((name . "os.WriteFile()") (path . "os/index#WriteFile") (type . "os")) ((name . "os/exec") (path . "os/exec/index") (type . "os")) ((name . "os/exec variables") (path . "os/exec/index#pkg-variables") (type . "os")) ((name . "os/signal") (path . "os/signal/index") (type . "os")) ((name . "os/user") (path . "os/user/index") (type . "os")) ((name . "parse.ActionNode") (path . "text/template/parse/index#ActionNode") (type . "text")) ((name . "parse.ActionNode.Copy()") (path . "text/template/parse/index#ActionNode.Copy") (type . "text")) ((name . "parse.ActionNode.String()") (path . "text/template/parse/index#ActionNode.String") (type . "text")) ((name . "parse.BoolNode") (path . "text/template/parse/index#BoolNode") (type . "text")) ((name . "parse.BoolNode.Copy()") (path . "text/template/parse/index#BoolNode.Copy") (type . "text")) ((name . "parse.BoolNode.String()") (path . "text/template/parse/index#BoolNode.String") (type . "text")) ((name . "parse.BranchNode") (path . "text/template/parse/index#BranchNode") (type . "text")) ((name . "parse.BranchNode.Copy()") (path . "text/template/parse/index#BranchNode.Copy") (type . "text")) ((name . "parse.BranchNode.String()") (path . "text/template/parse/index#BranchNode.String") (type . "text")) ((name . "parse.BreakNode") (path . "text/template/parse/index#BreakNode") (type . "text")) ((name . "parse.BreakNode.Copy()") (path . "text/template/parse/index#BreakNode.Copy") (type . "text")) ((name . "parse.BreakNode.String()") (path . "text/template/parse/index#BreakNode.String") (type . "text")) ((name . "parse.ChainNode") (path . "text/template/parse/index#ChainNode") (type . "text")) ((name . "parse.ChainNode.Add()") (path . "text/template/parse/index#ChainNode.Add") (type . "text")) ((name . "parse.ChainNode.Copy()") (path . "text/template/parse/index#ChainNode.Copy") (type . "text")) ((name . "parse.ChainNode.String()") (path . "text/template/parse/index#ChainNode.String") (type . "text")) ((name . "parse.CommandNode") (path . "text/template/parse/index#CommandNode") (type . "text")) ((name . "parse.CommandNode.Copy()") (path . "text/template/parse/index#CommandNode.Copy") (type . "text")) ((name . "parse.CommandNode.String()") (path . "text/template/parse/index#CommandNode.String") (type . "text")) ((name . "parse.CommentNode") (path . "text/template/parse/index#CommentNode") (type . "text")) ((name . "parse.CommentNode.Copy()") (path . "text/template/parse/index#CommentNode.Copy") (type . "text")) ((name . "parse.CommentNode.String()") (path . "text/template/parse/index#CommentNode.String") (type . "text")) ((name . "parse.ContinueNode") (path . "text/template/parse/index#ContinueNode") (type . "text")) ((name . "parse.ContinueNode.Copy()") (path . "text/template/parse/index#ContinueNode.Copy") (type . "text")) ((name . "parse.ContinueNode.String()") (path . "text/template/parse/index#ContinueNode.String") (type . "text")) ((name . "parse.DotNode") (path . "text/template/parse/index#DotNode") (type . "text")) ((name . "parse.DotNode.Copy()") (path . "text/template/parse/index#DotNode.Copy") (type . "text")) ((name . "parse.DotNode.String()") (path . "text/template/parse/index#DotNode.String") (type . "text")) ((name . "parse.DotNode.Type()") (path . "text/template/parse/index#DotNode.Type") (type . "text")) ((name . "parse.FieldNode") (path . "text/template/parse/index#FieldNode") (type . "text")) ((name . "parse.FieldNode.Copy()") (path . "text/template/parse/index#FieldNode.Copy") (type . "text")) ((name . "parse.FieldNode.String()") (path . "text/template/parse/index#FieldNode.String") (type . "text")) ((name . "parse.IdentifierNode") (path . "text/template/parse/index#IdentifierNode") (type . "text")) ((name . "parse.IdentifierNode.Copy()") (path . "text/template/parse/index#IdentifierNode.Copy") (type . "text")) ((name . "parse.IdentifierNode.SetPos()") (path . "text/template/parse/index#IdentifierNode.SetPos") (type . "text")) ((name . "parse.IdentifierNode.SetTree()") (path . "text/template/parse/index#IdentifierNode.SetTree") (type . "text")) ((name . "parse.IdentifierNode.String()") (path . "text/template/parse/index#IdentifierNode.String") (type . "text")) ((name . "parse.IfNode") (path . "text/template/parse/index#IfNode") (type . "text")) ((name . "parse.IfNode.Copy()") (path . "text/template/parse/index#IfNode.Copy") (type . "text")) ((name . "parse.IsEmptyTree()") (path . "text/template/parse/index#IsEmptyTree") (type . "text")) ((name . "parse.ListNode") (path . "text/template/parse/index#ListNode") (type . "text")) ((name . "parse.ListNode.Copy()") (path . "text/template/parse/index#ListNode.Copy") (type . "text")) ((name . "parse.ListNode.CopyList()") (path . "text/template/parse/index#ListNode.CopyList") (type . "text")) ((name . "parse.ListNode.String()") (path . "text/template/parse/index#ListNode.String") (type . "text")) ((name . "parse.Mode") (path . "text/template/parse/index#Mode") (type . "text")) ((name . "parse.New()") (path . "text/template/parse/index#New") (type . "text")) ((name . "parse.NewIdentifier()") (path . "text/template/parse/index#NewIdentifier") (type . "text")) ((name . "parse.NilNode") (path . "text/template/parse/index#NilNode") (type . "text")) ((name . "parse.NilNode.Copy()") (path . "text/template/parse/index#NilNode.Copy") (type . "text")) ((name . "parse.NilNode.String()") (path . "text/template/parse/index#NilNode.String") (type . "text")) ((name . "parse.NilNode.Type()") (path . "text/template/parse/index#NilNode.Type") (type . "text")) ((name . "parse.Node") (path . "text/template/parse/index#Node") (type . "text")) ((name . "parse.NodeType") (path . "text/template/parse/index#NodeType") (type . "text")) ((name . "parse.NodeType.Type()") (path . "text/template/parse/index#NodeType.Type") (type . "text")) ((name . "parse.NumberNode") (path . "text/template/parse/index#NumberNode") (type . "text")) ((name . "parse.NumberNode.Copy()") (path . "text/template/parse/index#NumberNode.Copy") (type . "text")) ((name . "parse.NumberNode.String()") (path . "text/template/parse/index#NumberNode.String") (type . "text")) ((name . "parse.Parse()") (path . "text/template/parse/index#Parse") (type . "text")) ((name . "parse.PipeNode") (path . "text/template/parse/index#PipeNode") (type . "text")) ((name . "parse.PipeNode.Copy()") (path . "text/template/parse/index#PipeNode.Copy") (type . "text")) ((name . "parse.PipeNode.CopyPipe()") (path . "text/template/parse/index#PipeNode.CopyPipe") (type . "text")) ((name . "parse.PipeNode.String()") (path . "text/template/parse/index#PipeNode.String") (type . "text")) ((name . "parse.Pos") (path . "text/template/parse/index#Pos") (type . "text")) ((name . "parse.Pos.Position()") (path . "text/template/parse/index#Pos.Position") (type . "text")) ((name . "parse.RangeNode") (path . "text/template/parse/index#RangeNode") (type . "text")) ((name . "parse.RangeNode.Copy()") (path . "text/template/parse/index#RangeNode.Copy") (type . "text")) ((name . "parse.StringNode") (path . "text/template/parse/index#StringNode") (type . "text")) ((name . "parse.StringNode.Copy()") (path . "text/template/parse/index#StringNode.Copy") (type . "text")) ((name . "parse.StringNode.String()") (path . "text/template/parse/index#StringNode.String") (type . "text")) ((name . "parse.TemplateNode") (path . "text/template/parse/index#TemplateNode") (type . "text")) ((name . "parse.TemplateNode.Copy()") (path . "text/template/parse/index#TemplateNode.Copy") (type . "text")) ((name . "parse.TemplateNode.String()") (path . "text/template/parse/index#TemplateNode.String") (type . "text")) ((name . "parse.TextNode") (path . "text/template/parse/index#TextNode") (type . "text")) ((name . "parse.TextNode.Copy()") (path . "text/template/parse/index#TextNode.Copy") (type . "text")) ((name . "parse.TextNode.String()") (path . "text/template/parse/index#TextNode.String") (type . "text")) ((name . "parse.Tree") (path . "text/template/parse/index#Tree") (type . "text")) ((name . "parse.Tree.Copy()") (path . "text/template/parse/index#Tree.Copy") (type . "text")) ((name . "parse.Tree.ErrorContext()") (path . "text/template/parse/index#Tree.ErrorContext") (type . "text")) ((name . "parse.Tree.Parse()") (path . "text/template/parse/index#Tree.Parse") (type . "text")) ((name . "parse.VariableNode") (path . "text/template/parse/index#VariableNode") (type . "text")) ((name . "parse.VariableNode.Copy()") (path . "text/template/parse/index#VariableNode.Copy") (type . "text")) ((name . "parse.VariableNode.String()") (path . "text/template/parse/index#VariableNode.String") (type . "text")) ((name . "parse.WithNode") (path . "text/template/parse/index#WithNode") (type . "text")) ((name . "parse.WithNode.Copy()") (path . "text/template/parse/index#WithNode.Copy") (type . "text")) ((name . "parser.Mode") (path . "go/parser/index#Mode") (type . "go")) ((name . "parser.ParseDir()") (path . "go/parser/index#ParseDir") (type . "go")) ((name . "parser.ParseExpr()") (path . "go/parser/index#ParseExpr") (type . "go")) ((name . "parser.ParseExprFrom()") (path . "go/parser/index#ParseExprFrom") (type . "go")) ((name . "parser.ParseFile()") (path . "go/parser/index#ParseFile") (type . "go")) ((name . "path") (path . "path/index") (type . "path")) ((name . "path variables") (path . "path/index#pkg-variables") (type . "path")) ((name . "path.Base()") (path . "path/index#Base") (type . "path")) ((name . "path.Clean()") (path . "path/index#Clean") (type . "path")) ((name . "path.Dir()") (path . "path/index#Dir") (type . "path")) ((name . "path.Ext()") (path . "path/index#Ext") (type . "path")) ((name . "path.IsAbs()") (path . "path/index#IsAbs") (type . "path")) ((name . "path.Join()") (path . "path/index#Join") (type . "path")) ((name . "path.Match()") (path . "path/index#Match") (type . "path")) ((name . "path.Split()") (path . "path/index#Split") (type . "path")) ((name . "path/filepath") (path . "path/filepath/index") (type . "path")) ((name . "path/filepath constants") (path . "path/filepath/index#pkg-constants") (type . "path")) ((name . "path/filepath variables") (path . "path/filepath/index#pkg-variables") (type . "path")) ((name . "pe.COFFSymbol") (path . "debug/pe/index#COFFSymbol") (type . "debug")) ((name . "pe.COFFSymbol.FullName()") (path . "debug/pe/index#COFFSymbol.FullName") (type . "debug")) ((name . "pe.COFFSymbolAuxFormat5") (path . "debug/pe/index#COFFSymbolAuxFormat5") (type . "debug")) ((name . "pe.DataDirectory") (path . "debug/pe/index#DataDirectory") (type . "debug")) ((name . "pe.File") (path . "debug/pe/index#File") (type . "debug")) ((name . "pe.File.Close()") (path . "debug/pe/index#File.Close") (type . "debug")) ((name . "pe.File.COFFSymbolReadSectionDefAux()") (path . "debug/pe/index#File.COFFSymbolReadSectionDefAux") (type . "debug")) ((name . "pe.File.DWARF()") (path . "debug/pe/index#File.DWARF") (type . "debug")) ((name . "pe.File.ImportedLibraries()") (path . "debug/pe/index#File.ImportedLibraries") (type . "debug")) ((name . "pe.File.ImportedSymbols()") (path . "debug/pe/index#File.ImportedSymbols") (type . "debug")) ((name . "pe.File.Section()") (path . "debug/pe/index#File.Section") (type . "debug")) ((name . "pe.FileHeader") (path . "debug/pe/index#FileHeader") (type . "debug")) ((name . "pe.FormatError") (path . "debug/pe/index#FormatError") (type . "debug")) ((name . "pe.FormatError.Error()") (path . "debug/pe/index#FormatError.Error") (type . "debug")) ((name . "pe.ImportDirectory") (path . "debug/pe/index#ImportDirectory") (type . "debug")) ((name . "pe.NewFile()") (path . "debug/pe/index#NewFile") (type . "debug")) ((name . "pe.Open()") (path . "debug/pe/index#Open") (type . "debug")) ((name . "pe.OptionalHeader32") (path . "debug/pe/index#OptionalHeader32") (type . "debug")) ((name . "pe.OptionalHeader64") (path . "debug/pe/index#OptionalHeader64") (type . "debug")) ((name . "pe.Reloc") (path . "debug/pe/index#Reloc") (type . "debug")) ((name . "pe.Section") (path . "debug/pe/index#Section") (type . "debug")) ((name . "pe.Section.Data()") (path . "debug/pe/index#Section.Data") (type . "debug")) ((name . "pe.Section.Open()") (path . "debug/pe/index#Section.Open") (type . "debug")) ((name . "pe.SectionHeader") (path . "debug/pe/index#SectionHeader") (type . "debug")) ((name . "pe.SectionHeader32") (path . "debug/pe/index#SectionHeader32") (type . "debug")) ((name . "pe.StringTable") (path . "debug/pe/index#StringTable") (type . "debug")) ((name . "pe.StringTable.String()") (path . "debug/pe/index#StringTable.String") (type . "debug")) ((name . "pe.Symbol") (path . "debug/pe/index#Symbol") (type . "debug")) ((name . "pem.Block") (path . "encoding/pem/index#Block") (type . "encoding")) ((name . "pem.Decode()") (path . "encoding/pem/index#Decode") (type . "encoding")) ((name . "pem.Encode()") (path . "encoding/pem/index#Encode") (type . "encoding")) ((name . "pem.EncodeToMemory()") (path . "encoding/pem/index#EncodeToMemory") (type . "encoding")) ((name . "pkix.AlgorithmIdentifier") (path . "crypto/x509/pkix/index#AlgorithmIdentifier") (type . "crypto")) ((name . "pkix.AttributeTypeAndValue") (path . "crypto/x509/pkix/index#AttributeTypeAndValue") (type . "crypto")) ((name . "pkix.AttributeTypeAndValueSET") (path . "crypto/x509/pkix/index#AttributeTypeAndValueSET") (type . "crypto")) ((name . "pkix.CertificateList") (path . "crypto/x509/pkix/index#CertificateList") (type . "crypto")) ((name . "pkix.CertificateList.HasExpired()") (path . "crypto/x509/pkix/index#CertificateList.HasExpired") (type . "crypto")) ((name . "pkix.Extension") (path . "crypto/x509/pkix/index#Extension") (type . "crypto")) ((name . "pkix.Name") (path . "crypto/x509/pkix/index#Name") (type . "crypto")) ((name . "pkix.Name.FillFromRDNSequence()") (path . "crypto/x509/pkix/index#Name.FillFromRDNSequence") (type . "crypto")) ((name . "pkix.Name.String()") (path . "crypto/x509/pkix/index#Name.String") (type . "crypto")) ((name . "pkix.Name.ToRDNSequence()") (path . "crypto/x509/pkix/index#Name.ToRDNSequence") (type . "crypto")) ((name . "pkix.RDNSequence") (path . "crypto/x509/pkix/index#RDNSequence") (type . "crypto")) ((name . "pkix.RDNSequence.String()") (path . "crypto/x509/pkix/index#RDNSequence.String") (type . "crypto")) ((name . "pkix.RelativeDistinguishedNameSET") (path . "crypto/x509/pkix/index#RelativeDistinguishedNameSET") (type . "crypto")) ((name . "pkix.RevokedCertificate") (path . "crypto/x509/pkix/index#RevokedCertificate") (type . "crypto")) ((name . "pkix.TBSCertificateList") (path . "crypto/x509/pkix/index#TBSCertificateList") (type . "crypto")) ((name . "plan9obj.File") (path . "debug/plan9obj/index#File") (type . "debug")) ((name . "plan9obj.File.Close()") (path . "debug/plan9obj/index#File.Close") (type . "debug")) ((name . "plan9obj.File.Section()") (path . "debug/plan9obj/index#File.Section") (type . "debug")) ((name . "plan9obj.File.Symbols()") (path . "debug/plan9obj/index#File.Symbols") (type . "debug")) ((name . "plan9obj.FileHeader") (path . "debug/plan9obj/index#FileHeader") (type . "debug")) ((name . "plan9obj.NewFile()") (path . "debug/plan9obj/index#NewFile") (type . "debug")) ((name . "plan9obj.Open()") (path . "debug/plan9obj/index#Open") (type . "debug")) ((name . "plan9obj.Section") (path . "debug/plan9obj/index#Section") (type . "debug")) ((name . "plan9obj.Section.Data()") (path . "debug/plan9obj/index#Section.Data") (type . "debug")) ((name . "plan9obj.Section.Open()") (path . "debug/plan9obj/index#Section.Open") (type . "debug")) ((name . "plan9obj.SectionHeader") (path . "debug/plan9obj/index#SectionHeader") (type . "debug")) ((name . "plan9obj.Sym") (path . "debug/plan9obj/index#Sym") (type . "debug")) ((name . "plugin") (path . "plugin/index") (type . "plugin")) ((name . "plugin.Open()") (path . "plugin/index#Open") (type . "plugin")) ((name . "plugin.Plugin") (path . "plugin/index#Plugin") (type . "plugin")) ((name . "plugin.Plugin.Lookup()") (path . "plugin/index#Plugin.Lookup") (type . "plugin")) ((name . "plugin.Symbol") (path . "plugin/index#Symbol") (type . "plugin")) ((name . "png.CompressionLevel") (path . "image/png/index#CompressionLevel") (type . "image")) ((name . "png.Decode()") (path . "image/png/index#Decode") (type . "image")) ((name . "png.DecodeConfig()") (path . "image/png/index#DecodeConfig") (type . "image")) ((name . "png.Encode()") (path . "image/png/index#Encode") (type . "image")) ((name . "png.Encoder") (path . "image/png/index#Encoder") (type . "image")) ((name . "png.Encoder.Encode()") (path . "image/png/index#Encoder.Encode") (type . "image")) ((name . "png.EncoderBuffer") (path . "image/png/index#EncoderBuffer") (type . "image")) ((name . "png.EncoderBufferPool") (path . "image/png/index#EncoderBufferPool") (type . "image")) ((name . "png.FormatError") (path . "image/png/index#FormatError") (type . "image")) ((name . "png.FormatError.Error()") (path . "image/png/index#FormatError.Error") (type . "image")) ((name . "png.UnsupportedError") (path . "image/png/index#UnsupportedError") (type . "image")) ((name . "png.UnsupportedError.Error()") (path . "image/png/index#UnsupportedError.Error") (type . "image")) ((name . "pprof.Cmdline()") (path . "net/http/pprof/index#Cmdline") (type . "net/http")) ((name . "pprof.Do()") (path . "runtime/pprof/index#Do") (type . "runtime")) ((name . "pprof.ForLabels()") (path . "runtime/pprof/index#ForLabels") (type . "runtime")) ((name . "pprof.Handler()") (path . "net/http/pprof/index#Handler") (type . "net/http")) ((name . "pprof.Index()") (path . "net/http/pprof/index#Index") (type . "net/http")) ((name . "pprof.Label()") (path . "runtime/pprof/index#Label") (type . "runtime")) ((name . "pprof.Labels()") (path . "runtime/pprof/index#Labels") (type . "runtime")) ((name . "pprof.LabelSet") (path . "runtime/pprof/index#LabelSet") (type . "runtime")) ((name . "pprof.Lookup()") (path . "runtime/pprof/index#Lookup") (type . "runtime")) ((name . "pprof.NewProfile()") (path . "runtime/pprof/index#NewProfile") (type . "runtime")) ((name . "pprof.Profile") (path . "runtime/pprof/index#Profile") (type . "runtime")) ((name . "pprof.Profile()") (path . "net/http/pprof/index#Profile") (type . "net/http")) ((name . "pprof.Profile.Add()") (path . "runtime/pprof/index#Profile.Add") (type . "runtime")) ((name . "pprof.Profile.Count()") (path . "runtime/pprof/index#Profile.Count") (type . "runtime")) ((name . "pprof.Profile.Name()") (path . "runtime/pprof/index#Profile.Name") (type . "runtime")) ((name . "pprof.Profile.Remove()") (path . "runtime/pprof/index#Profile.Remove") (type . "runtime")) ((name . "pprof.Profile.WriteTo()") (path . "runtime/pprof/index#Profile.WriteTo") (type . "runtime")) ((name . "pprof.Profiles()") (path . "runtime/pprof/index#Profiles") (type . "runtime")) ((name . "pprof.SetGoroutineLabels()") (path . "runtime/pprof/index#SetGoroutineLabels") (type . "runtime")) ((name . "pprof.StartCPUProfile()") (path . "runtime/pprof/index#StartCPUProfile") (type . "runtime")) ((name . "pprof.StopCPUProfile()") (path . "runtime/pprof/index#StopCPUProfile") (type . "runtime")) ((name . "pprof.Symbol()") (path . "net/http/pprof/index#Symbol") (type . "net/http")) ((name . "pprof.Trace()") (path . "net/http/pprof/index#Trace") (type . "net/http")) ((name . "pprof.WithLabels()") (path . "runtime/pprof/index#WithLabels") (type . "runtime")) ((name . "pprof.WriteHeapProfile()") (path . "runtime/pprof/index#WriteHeapProfile") (type . "runtime")) ((name . "printer.CommentedNode") (path . "go/printer/index#CommentedNode") (type . "go")) ((name . "printer.Config") (path . "go/printer/index#Config") (type . "go")) ((name . "printer.Config.Fprint()") (path . "go/printer/index#Config.Fprint") (type . "go")) ((name . "printer.Fprint()") (path . "go/printer/index#Fprint") (type . "go")) ((name . "printer.Mode") (path . "go/printer/index#Mode") (type . "go")) ((name . "quick.Check()") (path . "testing/quick/index#Check") (type . "testing")) ((name . "quick.CheckEqual()") (path . "testing/quick/index#CheckEqual") (type . "testing")) ((name . "quick.CheckEqualError") (path . "testing/quick/index#CheckEqualError") (type . "testing")) ((name . "quick.CheckEqualError.Error()") (path . "testing/quick/index#CheckEqualError.Error") (type . "testing")) ((name . "quick.CheckError") (path . "testing/quick/index#CheckError") (type . "testing")) ((name . "quick.CheckError.Error()") (path . "testing/quick/index#CheckError.Error") (type . "testing")) ((name . "quick.Config") (path . "testing/quick/index#Config") (type . "testing")) ((name . "quick.Generator") (path . "testing/quick/index#Generator") (type . "testing")) ((name . "quick.SetupError") (path . "testing/quick/index#SetupError") (type . "testing")) ((name . "quick.SetupError.Error()") (path . "testing/quick/index#SetupError.Error") (type . "testing")) ((name . "quick.Value()") (path . "testing/quick/index#Value") (type . "testing")) ((name . "quotedprintable.NewReader()") (path . "mime/quotedprintable/index#NewReader") (type . "mime")) ((name . "quotedprintable.NewWriter()") (path . "mime/quotedprintable/index#NewWriter") (type . "mime")) ((name . "quotedprintable.Reader") (path . "mime/quotedprintable/index#Reader") (type . "mime")) ((name . "quotedprintable.Reader.Read()") (path . "mime/quotedprintable/index#Reader.Read") (type . "mime")) ((name . "quotedprintable.Writer") (path . "mime/quotedprintable/index#Writer") (type . "mime")) ((name . "quotedprintable.Writer.Close()") (path . "mime/quotedprintable/index#Writer.Close") (type . "mime")) ((name . "quotedprintable.Writer.Write()") (path . "mime/quotedprintable/index#Writer.Write") (type . "mime")) ((name . "rand.ExpFloat64()") (path . "math/rand/index#ExpFloat64") (type . "math/rand")) ((name . "rand.Float32()") (path . "math/rand/index#Float32") (type . "math/rand")) ((name . "rand.Float64()") (path . "math/rand/index#Float64") (type . "math/rand")) ((name . "rand.Int()") (path . "crypto/rand/index#Int") (type . "crypto")) ((name . "rand.Int()") (path . "math/rand/index#Int") (type . "math/rand")) ((name . "rand.Int31()") (path . "math/rand/index#Int31") (type . "math/rand")) ((name . "rand.Int31n()") (path . "math/rand/index#Int31n") (type . "math/rand")) ((name . "rand.Int63()") (path . "math/rand/index#Int63") (type . "math/rand")) ((name . "rand.Int63n()") (path . "math/rand/index#Int63n") (type . "math/rand")) ((name . "rand.Intn()") (path . "math/rand/index#Intn") (type . "math/rand")) ((name . "rand.New()") (path . "math/rand/index#New") (type . "math/rand")) ((name . "rand.NewSource()") (path . "math/rand/index#NewSource") (type . "math/rand")) ((name . "rand.NewZipf()") (path . "math/rand/index#NewZipf") (type . "math/rand")) ((name . "rand.NormFloat64()") (path . "math/rand/index#NormFloat64") (type . "math/rand")) ((name . "rand.Perm()") (path . "math/rand/index#Perm") (type . "math/rand")) ((name . "rand.Prime()") (path . "crypto/rand/index#Prime") (type . "crypto")) ((name . "rand.Rand") (path . "math/rand/index#Rand") (type . "math/rand")) ((name . "rand.Rand.ExpFloat64()") (path . "math/rand/index#Rand.ExpFloat64") (type . "math/rand")) ((name . "rand.Rand.Float32()") (path . "math/rand/index#Rand.Float32") (type . "math/rand")) ((name . "rand.Rand.Float64()") (path . "math/rand/index#Rand.Float64") (type . "math/rand")) ((name . "rand.Rand.Int()") (path . "math/rand/index#Rand.Int") (type . "math/rand")) ((name . "rand.Rand.Int31()") (path . "math/rand/index#Rand.Int31") (type . "math/rand")) ((name . "rand.Rand.Int31n()") (path . "math/rand/index#Rand.Int31n") (type . "math/rand")) ((name . "rand.Rand.Int63()") (path . "math/rand/index#Rand.Int63") (type . "math/rand")) ((name . "rand.Rand.Int63n()") (path . "math/rand/index#Rand.Int63n") (type . "math/rand")) ((name . "rand.Rand.Intn()") (path . "math/rand/index#Rand.Intn") (type . "math/rand")) ((name . "rand.Rand.NormFloat64()") (path . "math/rand/index#Rand.NormFloat64") (type . "math/rand")) ((name . "rand.Rand.Perm()") (path . "math/rand/index#Rand.Perm") (type . "math/rand")) ((name . "rand.Rand.Read()") (path . "math/rand/index#Rand.Read") (type . "math/rand")) ((name . "rand.Rand.Seed()") (path . "math/rand/index#Rand.Seed") (type . "math/rand")) ((name . "rand.Rand.Shuffle()") (path . "math/rand/index#Rand.Shuffle") (type . "math/rand")) ((name . "rand.Rand.Uint32()") (path . "math/rand/index#Rand.Uint32") (type . "math/rand")) ((name . "rand.Rand.Uint64()") (path . "math/rand/index#Rand.Uint64") (type . "math/rand")) ((name . "rand.Read()") (path . "math/rand/index#Read") (type . "math/rand")) ((name . "rand.Read()") (path . "crypto/rand/index#Read") (type . "crypto")) ((name . "rand.Seed()") (path . "math/rand/index#Seed") (type . "math/rand")) ((name . "rand.Shuffle()") (path . "math/rand/index#Shuffle") (type . "math/rand")) ((name . "rand.Source") (path . "math/rand/index#Source") (type . "math/rand")) ((name . "rand.Source64") (path . "math/rand/index#Source64") (type . "math/rand")) ((name . "rand.Uint32()") (path . "math/rand/index#Uint32") (type . "math/rand")) ((name . "rand.Uint64()") (path . "math/rand/index#Uint64") (type . "math/rand")) ((name . "rand.Zipf") (path . "math/rand/index#Zipf") (type . "math/rand")) ((name . "rand.Zipf.Uint64()") (path . "math/rand/index#Zipf.Uint64") (type . "math/rand")) ((name . "rc4.Cipher") (path . "crypto/rc4/index#Cipher") (type . "crypto")) ((name . "rc4.Cipher.Reset()") (path . "crypto/rc4/index#Cipher.Reset") (type . "crypto")) ((name . "rc4.Cipher.XORKeyStream()") (path . "crypto/rc4/index#Cipher.XORKeyStream") (type . "crypto")) ((name . "rc4.KeySizeError") (path . "crypto/rc4/index#KeySizeError") (type . "crypto")) ((name . "rc4.KeySizeError.Error()") (path . "crypto/rc4/index#KeySizeError.Error") (type . "crypto")) ((name . "rc4.NewCipher()") (path . "crypto/rc4/index#NewCipher") (type . "crypto")) ((name . "reflect") (path . "reflect/index") (type . "reflect")) ((name . "reflect constants") (path . "reflect/index#pkg-constants") (type . "reflect")) ((name . "reflect.Append()") (path . "reflect/index#Append") (type . "reflect")) ((name . "reflect.AppendSlice()") (path . "reflect/index#AppendSlice") (type . "reflect")) ((name . "reflect.ArrayOf()") (path . "reflect/index#ArrayOf") (type . "reflect")) ((name . "reflect.ChanDir") (path . "reflect/index#ChanDir") (type . "reflect")) ((name . "reflect.ChanDir.String()") (path . "reflect/index#ChanDir.String") (type . "reflect")) ((name . "reflect.ChanOf()") (path . "reflect/index#ChanOf") (type . "reflect")) ((name . "reflect.Copy()") (path . "reflect/index#Copy") (type . "reflect")) ((name . "reflect.DeepEqual()") (path . "reflect/index#DeepEqual") (type . "reflect")) ((name . "reflect.FuncOf()") (path . "reflect/index#FuncOf") (type . "reflect")) ((name . "reflect.Indirect()") (path . "reflect/index#Indirect") (type . "reflect")) ((name . "reflect.Kind") (path . "reflect/index#Kind") (type . "reflect")) ((name . "reflect.Kind.String()") (path . "reflect/index#Kind.String") (type . "reflect")) ((name . "reflect.MakeChan()") (path . "reflect/index#MakeChan") (type . "reflect")) ((name . "reflect.MakeFunc()") (path . "reflect/index#MakeFunc") (type . "reflect")) ((name . "reflect.MakeMap()") (path . "reflect/index#MakeMap") (type . "reflect")) ((name . "reflect.MakeMapWithSize()") (path . "reflect/index#MakeMapWithSize") (type . "reflect")) ((name . "reflect.MakeSlice()") (path . "reflect/index#MakeSlice") (type . "reflect")) ((name . "reflect.MapIter") (path . "reflect/index#MapIter") (type . "reflect")) ((name . "reflect.MapIter.Key()") (path . "reflect/index#MapIter.Key") (type . "reflect")) ((name . "reflect.MapIter.Next()") (path . "reflect/index#MapIter.Next") (type . "reflect")) ((name . "reflect.MapIter.Reset()") (path . "reflect/index#MapIter.Reset") (type . "reflect")) ((name . "reflect.MapIter.Value()") (path . "reflect/index#MapIter.Value") (type . "reflect")) ((name . "reflect.MapOf()") (path . "reflect/index#MapOf") (type . "reflect")) ((name . "reflect.Method") (path . "reflect/index#Method") (type . "reflect")) ((name . "reflect.Method.IsExported()") (path . "reflect/index#Method.IsExported") (type . "reflect")) ((name . "reflect.New()") (path . "reflect/index#New") (type . "reflect")) ((name . "reflect.NewAt()") (path . "reflect/index#NewAt") (type . "reflect")) ((name . "reflect.PointerTo()") (path . "reflect/index#PointerTo") (type . "reflect")) ((name . "reflect.PtrTo()") (path . "reflect/index#PtrTo") (type . "reflect")) ((name . "reflect.Select()") (path . "reflect/index#Select") (type . "reflect")) ((name . "reflect.SelectCase") (path . "reflect/index#SelectCase") (type . "reflect")) ((name . "reflect.SelectDir") (path . "reflect/index#SelectDir") (type . "reflect")) ((name . "reflect.SliceHeader") (path . "reflect/index#SliceHeader") (type . "reflect")) ((name . "reflect.SliceOf()") (path . "reflect/index#SliceOf") (type . "reflect")) ((name . "reflect.StringHeader") (path . "reflect/index#StringHeader") (type . "reflect")) ((name . "reflect.StructField") (path . "reflect/index#StructField") (type . "reflect")) ((name . "reflect.StructField.IsExported()") (path . "reflect/index#StructField.IsExported") (type . "reflect")) ((name . "reflect.StructOf()") (path . "reflect/index#StructOf") (type . "reflect")) ((name . "reflect.StructTag") (path . "reflect/index#StructTag") (type . "reflect")) ((name . "reflect.StructTag.Get()") (path . "reflect/index#StructTag.Get") (type . "reflect")) ((name . "reflect.StructTag.Lookup()") (path . "reflect/index#StructTag.Lookup") (type . "reflect")) ((name . "reflect.Swapper()") (path . "reflect/index#Swapper") (type . "reflect")) ((name . "reflect.Type") (path . "reflect/index#Type") (type . "reflect")) ((name . "reflect.TypeFor()") (path . "reflect/index#TypeFor") (type . "reflect")) ((name . "reflect.TypeOf()") (path . "reflect/index#TypeOf") (type . "reflect")) ((name . "reflect.Value") (path . "reflect/index#Value") (type . "reflect")) ((name . "reflect.Value.Addr()") (path . "reflect/index#Value.Addr") (type . "reflect")) ((name . "reflect.Value.Bool()") (path . "reflect/index#Value.Bool") (type . "reflect")) ((name . "reflect.Value.Bytes()") (path . "reflect/index#Value.Bytes") (type . "reflect")) ((name . "reflect.Value.Call()") (path . "reflect/index#Value.Call") (type . "reflect")) ((name . "reflect.Value.CallSlice()") (path . "reflect/index#Value.CallSlice") (type . "reflect")) ((name . "reflect.Value.CanAddr()") (path . "reflect/index#Value.CanAddr") (type . "reflect")) ((name . "reflect.Value.CanComplex()") (path . "reflect/index#Value.CanComplex") (type . "reflect")) ((name . "reflect.Value.CanConvert()") (path . "reflect/index#Value.CanConvert") (type . "reflect")) ((name . "reflect.Value.CanFloat()") (path . "reflect/index#Value.CanFloat") (type . "reflect")) ((name . "reflect.Value.CanInt()") (path . "reflect/index#Value.CanInt") (type . "reflect")) ((name . "reflect.Value.CanInterface()") (path . "reflect/index#Value.CanInterface") (type . "reflect")) ((name . "reflect.Value.CanSet()") (path . "reflect/index#Value.CanSet") (type . "reflect")) ((name . "reflect.Value.CanUint()") (path . "reflect/index#Value.CanUint") (type . "reflect")) ((name . "reflect.Value.Cap()") (path . "reflect/index#Value.Cap") (type . "reflect")) ((name . "reflect.Value.Clear()") (path . "reflect/index#Value.Clear") (type . "reflect")) ((name . "reflect.Value.Close()") (path . "reflect/index#Value.Close") (type . "reflect")) ((name . "reflect.Value.Comparable()") (path . "reflect/index#Value.Comparable") (type . "reflect")) ((name . "reflect.Value.Complex()") (path . "reflect/index#Value.Complex") (type . "reflect")) ((name . "reflect.Value.Convert()") (path . "reflect/index#Value.Convert") (type . "reflect")) ((name . "reflect.Value.Elem()") (path . "reflect/index#Value.Elem") (type . "reflect")) ((name . "reflect.Value.Equal()") (path . "reflect/index#Value.Equal") (type . "reflect")) ((name . "reflect.Value.Field()") (path . "reflect/index#Value.Field") (type . "reflect")) ((name . "reflect.Value.FieldByIndex()") (path . "reflect/index#Value.FieldByIndex") (type . "reflect")) ((name . "reflect.Value.FieldByIndexErr()") (path . "reflect/index#Value.FieldByIndexErr") (type . "reflect")) ((name . "reflect.Value.FieldByName()") (path . "reflect/index#Value.FieldByName") (type . "reflect")) ((name . "reflect.Value.FieldByNameFunc()") (path . "reflect/index#Value.FieldByNameFunc") (type . "reflect")) ((name . "reflect.Value.Float()") (path . "reflect/index#Value.Float") (type . "reflect")) ((name . "reflect.Value.Grow()") (path . "reflect/index#Value.Grow") (type . "reflect")) ((name . "reflect.Value.Index()") (path . "reflect/index#Value.Index") (type . "reflect")) ((name . "reflect.Value.Int()") (path . "reflect/index#Value.Int") (type . "reflect")) ((name . "reflect.Value.Interface()") (path . "reflect/index#Value.Interface") (type . "reflect")) ((name . "reflect.Value.InterfaceData()") (path . "reflect/index#Value.InterfaceData") (type . "reflect")) ((name . "reflect.Value.IsNil()") (path . "reflect/index#Value.IsNil") (type . "reflect")) ((name . "reflect.Value.IsValid()") (path . "reflect/index#Value.IsValid") (type . "reflect")) ((name . "reflect.Value.IsZero()") (path . "reflect/index#Value.IsZero") (type . "reflect")) ((name . "reflect.Value.Kind()") (path . "reflect/index#Value.Kind") (type . "reflect")) ((name . "reflect.Value.Len()") (path . "reflect/index#Value.Len") (type . "reflect")) ((name . "reflect.Value.MapIndex()") (path . "reflect/index#Value.MapIndex") (type . "reflect")) ((name . "reflect.Value.MapKeys()") (path . "reflect/index#Value.MapKeys") (type . "reflect")) ((name . "reflect.Value.MapRange()") (path . "reflect/index#Value.MapRange") (type . "reflect")) ((name . "reflect.Value.Method()") (path . "reflect/index#Value.Method") (type . "reflect")) ((name . "reflect.Value.MethodByName()") (path . "reflect/index#Value.MethodByName") (type . "reflect")) ((name . "reflect.Value.NumField()") (path . "reflect/index#Value.NumField") (type . "reflect")) ((name . "reflect.Value.NumMethod()") (path . "reflect/index#Value.NumMethod") (type . "reflect")) ((name . "reflect.Value.OverflowComplex()") (path . "reflect/index#Value.OverflowComplex") (type . "reflect")) ((name . "reflect.Value.OverflowFloat()") (path . "reflect/index#Value.OverflowFloat") (type . "reflect")) ((name . "reflect.Value.OverflowInt()") (path . "reflect/index#Value.OverflowInt") (type . "reflect")) ((name . "reflect.Value.OverflowUint()") (path . "reflect/index#Value.OverflowUint") (type . "reflect")) ((name . "reflect.Value.Pointer()") (path . "reflect/index#Value.Pointer") (type . "reflect")) ((name . "reflect.Value.Recv()") (path . "reflect/index#Value.Recv") (type . "reflect")) ((name . "reflect.Value.Send()") (path . "reflect/index#Value.Send") (type . "reflect")) ((name . "reflect.Value.Set()") (path . "reflect/index#Value.Set") (type . "reflect")) ((name . "reflect.Value.SetBool()") (path . "reflect/index#Value.SetBool") (type . "reflect")) ((name . "reflect.Value.SetBytes()") (path . "reflect/index#Value.SetBytes") (type . "reflect")) ((name . "reflect.Value.SetCap()") (path . "reflect/index#Value.SetCap") (type . "reflect")) ((name . "reflect.Value.SetComplex()") (path . "reflect/index#Value.SetComplex") (type . "reflect")) ((name . "reflect.Value.SetFloat()") (path . "reflect/index#Value.SetFloat") (type . "reflect")) ((name . "reflect.Value.SetInt()") (path . "reflect/index#Value.SetInt") (type . "reflect")) ((name . "reflect.Value.SetIterKey()") (path . "reflect/index#Value.SetIterKey") (type . "reflect")) ((name . "reflect.Value.SetIterValue()") (path . "reflect/index#Value.SetIterValue") (type . "reflect")) ((name . "reflect.Value.SetLen()") (path . "reflect/index#Value.SetLen") (type . "reflect")) ((name . "reflect.Value.SetMapIndex()") (path . "reflect/index#Value.SetMapIndex") (type . "reflect")) ((name . "reflect.Value.SetPointer()") (path . "reflect/index#Value.SetPointer") (type . "reflect")) ((name . "reflect.Value.SetString()") (path . "reflect/index#Value.SetString") (type . "reflect")) ((name . "reflect.Value.SetUint()") (path . "reflect/index#Value.SetUint") (type . "reflect")) ((name . "reflect.Value.SetZero()") (path . "reflect/index#Value.SetZero") (type . "reflect")) ((name . "reflect.Value.Slice()") (path . "reflect/index#Value.Slice") (type . "reflect")) ((name . "reflect.Value.Slice3()") (path . "reflect/index#Value.Slice3") (type . "reflect")) ((name . "reflect.Value.String()") (path . "reflect/index#Value.String") (type . "reflect")) ((name . "reflect.Value.TryRecv()") (path . "reflect/index#Value.TryRecv") (type . "reflect")) ((name . "reflect.Value.TrySend()") (path . "reflect/index#Value.TrySend") (type . "reflect")) ((name . "reflect.Value.Type()") (path . "reflect/index#Value.Type") (type . "reflect")) ((name . "reflect.Value.Uint()") (path . "reflect/index#Value.Uint") (type . "reflect")) ((name . "reflect.Value.UnsafeAddr()") (path . "reflect/index#Value.UnsafeAddr") (type . "reflect")) ((name . "reflect.Value.UnsafePointer()") (path . "reflect/index#Value.UnsafePointer") (type . "reflect")) ((name . "reflect.ValueError") (path . "reflect/index#ValueError") (type . "reflect")) ((name . "reflect.ValueError.Error()") (path . "reflect/index#ValueError.Error") (type . "reflect")) ((name . "reflect.ValueOf()") (path . "reflect/index#ValueOf") (type . "reflect")) ((name . "reflect.VisibleFields()") (path . "reflect/index#VisibleFields") (type . "reflect")) ((name . "reflect.Zero()") (path . "reflect/index#Zero") (type . "reflect")) ((name . "regexp") (path . "regexp/index") (type . "regexp")) ((name . "regexp.Compile()") (path . "regexp/index#Compile") (type . "regexp")) ((name . "regexp.CompilePOSIX()") (path . "regexp/index#CompilePOSIX") (type . "regexp")) ((name . "regexp.Match()") (path . "regexp/index#Match") (type . "regexp")) ((name . "regexp.MatchReader()") (path . "regexp/index#MatchReader") (type . "regexp")) ((name . "regexp.MatchString()") (path . "regexp/index#MatchString") (type . "regexp")) ((name . "regexp.MustCompile()") (path . "regexp/index#MustCompile") (type . "regexp")) ((name . "regexp.MustCompilePOSIX()") (path . "regexp/index#MustCompilePOSIX") (type . "regexp")) ((name . "regexp.QuoteMeta()") (path . "regexp/index#QuoteMeta") (type . "regexp")) ((name . "regexp.Regexp") (path . "regexp/index#Regexp") (type . "regexp")) ((name . "regexp.Regexp.Copy()") (path . "regexp/index#Regexp.Copy") (type . "regexp")) ((name . "regexp.Regexp.Expand()") (path . "regexp/index#Regexp.Expand") (type . "regexp")) ((name . "regexp.Regexp.ExpandString()") (path . "regexp/index#Regexp.ExpandString") (type . "regexp")) ((name . "regexp.Regexp.Find()") (path . "regexp/index#Regexp.Find") (type . "regexp")) ((name . "regexp.Regexp.FindAll()") (path . "regexp/index#Regexp.FindAll") (type . "regexp")) ((name . "regexp.Regexp.FindAllIndex()") (path . "regexp/index#Regexp.FindAllIndex") (type . "regexp")) ((name . "regexp.Regexp.FindAllString()") (path . "regexp/index#Regexp.FindAllString") (type . "regexp")) ((name . "regexp.Regexp.FindAllStringIndex()") (path . "regexp/index#Regexp.FindAllStringIndex") (type . "regexp")) ((name . "regexp.Regexp.FindAllStringSubmatch()") (path . "regexp/index#Regexp.FindAllStringSubmatch") (type . "regexp")) ((name . "regexp.Regexp.FindAllStringSubmatchIndex()") (path . "regexp/index#Regexp.FindAllStringSubmatchIndex") (type . "regexp")) ((name . "regexp.Regexp.FindAllSubmatch()") (path . "regexp/index#Regexp.FindAllSubmatch") (type . "regexp")) ((name . "regexp.Regexp.FindAllSubmatchIndex()") (path . "regexp/index#Regexp.FindAllSubmatchIndex") (type . "regexp")) ((name . "regexp.Regexp.FindIndex()") (path . "regexp/index#Regexp.FindIndex") (type . "regexp")) ((name . "regexp.Regexp.FindReaderIndex()") (path . "regexp/index#Regexp.FindReaderIndex") (type . "regexp")) ((name . "regexp.Regexp.FindReaderSubmatchIndex()") (path . "regexp/index#Regexp.FindReaderSubmatchIndex") (type . "regexp")) ((name . "regexp.Regexp.FindString()") (path . "regexp/index#Regexp.FindString") (type . "regexp")) ((name . "regexp.Regexp.FindStringIndex()") (path . "regexp/index#Regexp.FindStringIndex") (type . "regexp")) ((name . "regexp.Regexp.FindStringSubmatch()") (path . "regexp/index#Regexp.FindStringSubmatch") (type . "regexp")) ((name . "regexp.Regexp.FindStringSubmatchIndex()") (path . "regexp/index#Regexp.FindStringSubmatchIndex") (type . "regexp")) ((name . "regexp.Regexp.FindSubmatch()") (path . "regexp/index#Regexp.FindSubmatch") (type . "regexp")) ((name . "regexp.Regexp.FindSubmatchIndex()") (path . "regexp/index#Regexp.FindSubmatchIndex") (type . "regexp")) ((name . "regexp.Regexp.LiteralPrefix()") (path . "regexp/index#Regexp.LiteralPrefix") (type . "regexp")) ((name . "regexp.Regexp.Longest()") (path . "regexp/index#Regexp.Longest") (type . "regexp")) ((name . "regexp.Regexp.MarshalText()") (path . "regexp/index#Regexp.MarshalText") (type . "regexp")) ((name . "regexp.Regexp.Match()") (path . "regexp/index#Regexp.Match") (type . "regexp")) ((name . "regexp.Regexp.MatchReader()") (path . "regexp/index#Regexp.MatchReader") (type . "regexp")) ((name . "regexp.Regexp.MatchString()") (path . "regexp/index#Regexp.MatchString") (type . "regexp")) ((name . "regexp.Regexp.NumSubexp()") (path . "regexp/index#Regexp.NumSubexp") (type . "regexp")) ((name . "regexp.Regexp.ReplaceAll()") (path . "regexp/index#Regexp.ReplaceAll") (type . "regexp")) ((name . "regexp.Regexp.ReplaceAllFunc()") (path . "regexp/index#Regexp.ReplaceAllFunc") (type . "regexp")) ((name . "regexp.Regexp.ReplaceAllLiteral()") (path . "regexp/index#Regexp.ReplaceAllLiteral") (type . "regexp")) ((name . "regexp.Regexp.ReplaceAllLiteralString()") (path . "regexp/index#Regexp.ReplaceAllLiteralString") (type . "regexp")) ((name . "regexp.Regexp.ReplaceAllString()") (path . "regexp/index#Regexp.ReplaceAllString") (type . "regexp")) ((name . "regexp.Regexp.ReplaceAllStringFunc()") (path . "regexp/index#Regexp.ReplaceAllStringFunc") (type . "regexp")) ((name . "regexp.Regexp.Split()") (path . "regexp/index#Regexp.Split") (type . "regexp")) ((name . "regexp.Regexp.String()") (path . "regexp/index#Regexp.String") (type . "regexp")) ((name . "regexp.Regexp.SubexpIndex()") (path . "regexp/index#Regexp.SubexpIndex") (type . "regexp")) ((name . "regexp.Regexp.SubexpNames()") (path . "regexp/index#Regexp.SubexpNames") (type . "regexp")) ((name . "regexp.Regexp.UnmarshalText()") (path . "regexp/index#Regexp.UnmarshalText") (type . "regexp")) ((name . "regexp/syntax") (path . "regexp/syntax/index") (type . "regexp")) ((name . "ring.New()") (path . "container/ring/index#New") (type . "container")) ((name . "ring.Ring") (path . "container/ring/index#Ring") (type . "container")) ((name . "ring.Ring.Do()") (path . "container/ring/index#Ring.Do") (type . "container")) ((name . "ring.Ring.Len()") (path . "container/ring/index#Ring.Len") (type . "container")) ((name . "ring.Ring.Link()") (path . "container/ring/index#Ring.Link") (type . "container")) ((name . "ring.Ring.Move()") (path . "container/ring/index#Ring.Move") (type . "container")) ((name . "ring.Ring.Next()") (path . "container/ring/index#Ring.Next") (type . "container")) ((name . "ring.Ring.Prev()") (path . "container/ring/index#Ring.Prev") (type . "container")) ((name . "ring.Ring.Unlink()") (path . "container/ring/index#Ring.Unlink") (type . "container")) ((name . "rpc.Accept()") (path . "net/rpc/index#Accept") (type . "net/rpc")) ((name . "rpc.Call") (path . "net/rpc/index#Call") (type . "net/rpc")) ((name . "rpc.Client") (path . "net/rpc/index#Client") (type . "net/rpc")) ((name . "rpc.Client.Call()") (path . "net/rpc/index#Client.Call") (type . "net/rpc")) ((name . "rpc.Client.Close()") (path . "net/rpc/index#Client.Close") (type . "net/rpc")) ((name . "rpc.Client.Go()") (path . "net/rpc/index#Client.Go") (type . "net/rpc")) ((name . "rpc.ClientCodec") (path . "net/rpc/index#ClientCodec") (type . "net/rpc")) ((name . "rpc.Dial()") (path . "net/rpc/index#Dial") (type . "net/rpc")) ((name . "rpc.DialHTTP()") (path . "net/rpc/index#DialHTTP") (type . "net/rpc")) ((name . "rpc.DialHTTPPath()") (path . "net/rpc/index#DialHTTPPath") (type . "net/rpc")) ((name . "rpc.HandleHTTP()") (path . "net/rpc/index#HandleHTTP") (type . "net/rpc")) ((name . "rpc.NewClient()") (path . "net/rpc/index#NewClient") (type . "net/rpc")) ((name . "rpc.NewClientWithCodec()") (path . "net/rpc/index#NewClientWithCodec") (type . "net/rpc")) ((name . "rpc.NewServer()") (path . "net/rpc/index#NewServer") (type . "net/rpc")) ((name . "rpc.Register()") (path . "net/rpc/index#Register") (type . "net/rpc")) ((name . "rpc.RegisterName()") (path . "net/rpc/index#RegisterName") (type . "net/rpc")) ((name . "rpc.Request") (path . "net/rpc/index#Request") (type . "net/rpc")) ((name . "rpc.Response") (path . "net/rpc/index#Response") (type . "net/rpc")) ((name . "rpc.ServeCodec()") (path . "net/rpc/index#ServeCodec") (type . "net/rpc")) ((name . "rpc.ServeConn()") (path . "net/rpc/index#ServeConn") (type . "net/rpc")) ((name . "rpc.Server") (path . "net/rpc/index#Server") (type . "net/rpc")) ((name . "rpc.Server.Accept()") (path . "net/rpc/index#Server.Accept") (type . "net/rpc")) ((name . "rpc.Server.HandleHTTP()") (path . "net/rpc/index#Server.HandleHTTP") (type . "net/rpc")) ((name . "rpc.Server.Register()") (path . "net/rpc/index#Server.Register") (type . "net/rpc")) ((name . "rpc.Server.RegisterName()") (path . "net/rpc/index#Server.RegisterName") (type . "net/rpc")) ((name . "rpc.Server.ServeCodec()") (path . "net/rpc/index#Server.ServeCodec") (type . "net/rpc")) ((name . "rpc.Server.ServeConn()") (path . "net/rpc/index#Server.ServeConn") (type . "net/rpc")) ((name . "rpc.Server.ServeHTTP()") (path . "net/rpc/index#Server.ServeHTTP") (type . "net/rpc")) ((name . "rpc.Server.ServeRequest()") (path . "net/rpc/index#Server.ServeRequest") (type . "net/rpc")) ((name . "rpc.ServerCodec") (path . "net/rpc/index#ServerCodec") (type . "net/rpc")) ((name . "rpc.ServeRequest()") (path . "net/rpc/index#ServeRequest") (type . "net/rpc")) ((name . "rpc.ServerError") (path . "net/rpc/index#ServerError") (type . "net/rpc")) ((name . "rpc.ServerError.Error()") (path . "net/rpc/index#ServerError.Error") (type . "net/rpc")) ((name . "rsa.CRTValue") (path . "crypto/rsa/index#CRTValue") (type . "crypto")) ((name . "rsa.DecryptOAEP()") (path . "crypto/rsa/index#DecryptOAEP") (type . "crypto")) ((name . "rsa.DecryptPKCS1v15()") (path . "crypto/rsa/index#DecryptPKCS1v15") (type . "crypto")) ((name . "rsa.DecryptPKCS1v15SessionKey()") (path . "crypto/rsa/index#DecryptPKCS1v15SessionKey") (type . "crypto")) ((name . "rsa.EncryptOAEP()") (path . "crypto/rsa/index#EncryptOAEP") (type . "crypto")) ((name . "rsa.EncryptPKCS1v15()") (path . "crypto/rsa/index#EncryptPKCS1v15") (type . "crypto")) ((name . "rsa.GenerateKey()") (path . "crypto/rsa/index#GenerateKey") (type . "crypto")) ((name . "rsa.GenerateMultiPrimeKey()") (path . "crypto/rsa/index#GenerateMultiPrimeKey") (type . "crypto")) ((name . "rsa.OAEPOptions") (path . "crypto/rsa/index#OAEPOptions") (type . "crypto")) ((name . "rsa.PKCS1v15DecryptOptions") (path . "crypto/rsa/index#PKCS1v15DecryptOptions") (type . "crypto")) ((name . "rsa.PrecomputedValues") (path . "crypto/rsa/index#PrecomputedValues") (type . "crypto")) ((name . "rsa.PrivateKey") (path . "crypto/rsa/index#PrivateKey") (type . "crypto")) ((name . "rsa.PrivateKey.Decrypt()") (path . "crypto/rsa/index#PrivateKey.Decrypt") (type . "crypto")) ((name . "rsa.PrivateKey.Equal()") (path . "crypto/rsa/index#PrivateKey.Equal") (type . "crypto")) ((name . "rsa.PrivateKey.Precompute()") (path . "crypto/rsa/index#PrivateKey.Precompute") (type . "crypto")) ((name . "rsa.PrivateKey.Public()") (path . "crypto/rsa/index#PrivateKey.Public") (type . "crypto")) ((name . "rsa.PrivateKey.Sign()") (path . "crypto/rsa/index#PrivateKey.Sign") (type . "crypto")) ((name . "rsa.PrivateKey.Validate()") (path . "crypto/rsa/index#PrivateKey.Validate") (type . "crypto")) ((name . "rsa.PSSOptions") (path . "crypto/rsa/index#PSSOptions") (type . "crypto")) ((name . "rsa.PSSOptions.HashFunc()") (path . "crypto/rsa/index#PSSOptions.HashFunc") (type . "crypto")) ((name . "rsa.PublicKey") (path . "crypto/rsa/index#PublicKey") (type . "crypto")) ((name . "rsa.PublicKey.Equal()") (path . "crypto/rsa/index#PublicKey.Equal") (type . "crypto")) ((name . "rsa.PublicKey.Size()") (path . "crypto/rsa/index#PublicKey.Size") (type . "crypto")) ((name . "rsa.SignPKCS1v15()") (path . "crypto/rsa/index#SignPKCS1v15") (type . "crypto")) ((name . "rsa.SignPSS()") (path . "crypto/rsa/index#SignPSS") (type . "crypto")) ((name . "rsa.VerifyPKCS1v15()") (path . "crypto/rsa/index#VerifyPKCS1v15") (type . "crypto")) ((name . "rsa.VerifyPSS()") (path . "crypto/rsa/index#VerifyPSS") (type . "crypto")) ((name . "runtime") (path . "runtime/index") (type . "runtime")) ((name . "runtime constants") (path . "runtime/index#pkg-constants") (type . "runtime")) ((name . "runtime variables") (path . "runtime/index#pkg-variables") (type . "runtime")) ((name . "runtime.BlockProfile()") (path . "runtime/index#BlockProfile") (type . "runtime")) ((name . "runtime.BlockProfileRecord") (path . "runtime/index#BlockProfileRecord") (type . "runtime")) ((name . "runtime.Breakpoint()") (path . "runtime/index#Breakpoint") (type . "runtime")) ((name . "runtime.Caller()") (path . "runtime/index#Caller") (type . "runtime")) ((name . "runtime.Callers()") (path . "runtime/index#Callers") (type . "runtime")) ((name . "runtime.CallersFrames()") (path . "runtime/index#CallersFrames") (type . "runtime")) ((name . "runtime.CPUProfile()") (path . "runtime/index#CPUProfile") (type . "runtime")) ((name . "runtime.Error") (path . "runtime/index#Error") (type . "runtime")) ((name . "runtime.Frame") (path . "runtime/index#Frame") (type . "runtime")) ((name . "runtime.Frames") (path . "runtime/index#Frames") (type . "runtime")) ((name . "runtime.Frames.Next()") (path . "runtime/index#Frames.Next") (type . "runtime")) ((name . "runtime.Func") (path . "runtime/index#Func") (type . "runtime")) ((name . "runtime.Func.Entry()") (path . "runtime/index#Func.Entry") (type . "runtime")) ((name . "runtime.Func.FileLine()") (path . "runtime/index#Func.FileLine") (type . "runtime")) ((name . "runtime.Func.Name()") (path . "runtime/index#Func.Name") (type . "runtime")) ((name . "runtime.FuncForPC()") (path . "runtime/index#FuncForPC") (type . "runtime")) ((name . "runtime.GC()") (path . "runtime/index#GC") (type . "runtime")) ((name . "runtime.Goexit()") (path . "runtime/index#Goexit") (type . "runtime")) ((name . "runtime.GOMAXPROCS()") (path . "runtime/index#GOMAXPROCS") (type . "runtime")) ((name . "runtime.GOROOT()") (path . "runtime/index#GOROOT") (type . "runtime")) ((name . "runtime.GoroutineProfile()") (path . "runtime/index#GoroutineProfile") (type . "runtime")) ((name . "runtime.Gosched()") (path . "runtime/index#Gosched") (type . "runtime")) ((name . "runtime.KeepAlive()") (path . "runtime/index#KeepAlive") (type . "runtime")) ((name . "runtime.LockOSThread()") (path . "runtime/index#LockOSThread") (type . "runtime")) ((name . "runtime.MemProfile()") (path . "runtime/index#MemProfile") (type . "runtime")) ((name . "runtime.MemProfileRecord") (path . "runtime/index#MemProfileRecord") (type . "runtime")) ((name . "runtime.MemProfileRecord.InUseBytes()") (path . "runtime/index#MemProfileRecord.InUseBytes") (type . "runtime")) ((name . "runtime.MemProfileRecord.InUseObjects()") (path . "runtime/index#MemProfileRecord.InUseObjects") (type . "runtime")) ((name . "runtime.MemProfileRecord.Stack()") (path . "runtime/index#MemProfileRecord.Stack") (type . "runtime")) ((name . "runtime.MemStats") (path . "runtime/index#MemStats") (type . "runtime")) ((name . "runtime.MutexProfile()") (path . "runtime/index#MutexProfile") (type . "runtime")) ((name . "runtime.NumCgoCall()") (path . "runtime/index#NumCgoCall") (type . "runtime")) ((name . "runtime.NumCPU()") (path . "runtime/index#NumCPU") (type . "runtime")) ((name . "runtime.NumGoroutine()") (path . "runtime/index#NumGoroutine") (type . "runtime")) ((name . "runtime.PanicNilError") (path . "runtime/index#PanicNilError") (type . "runtime")) ((name . "runtime.PanicNilError.Error()") (path . "runtime/index#PanicNilError.Error") (type . "runtime")) ((name . "runtime.PanicNilError.RuntimeError()") (path . "runtime/index#PanicNilError.RuntimeError") (type . "runtime")) ((name . "runtime.Pinner") (path . "runtime/index#Pinner") (type . "runtime")) ((name . "runtime.Pinner.Pin()") (path . "runtime/index#Pinner.Pin") (type . "runtime")) ((name . "runtime.Pinner.Unpin()") (path . "runtime/index#Pinner.Unpin") (type . "runtime")) ((name . "runtime.ReadMemStats()") (path . "runtime/index#ReadMemStats") (type . "runtime")) ((name . "runtime.ReadTrace()") (path . "runtime/index#ReadTrace") (type . "runtime")) ((name . "runtime.SetBlockProfileRate()") (path . "runtime/index#SetBlockProfileRate") (type . "runtime")) ((name . "runtime.SetCgoTraceback()") (path . "runtime/index#SetCgoTraceback") (type . "runtime")) ((name . "runtime.SetCPUProfileRate()") (path . "runtime/index#SetCPUProfileRate") (type . "runtime")) ((name . "runtime.SetFinalizer()") (path . "runtime/index#SetFinalizer") (type . "runtime")) ((name . "runtime.SetMutexProfileFraction()") (path . "runtime/index#SetMutexProfileFraction") (type . "runtime")) ((name . "runtime.Stack()") (path . "runtime/index#Stack") (type . "runtime")) ((name . "runtime.StackRecord") (path . "runtime/index#StackRecord") (type . "runtime")) ((name . "runtime.StackRecord.Stack()") (path . "runtime/index#StackRecord.Stack") (type . "runtime")) ((name . "runtime.StartTrace()") (path . "runtime/index#StartTrace") (type . "runtime")) ((name . "runtime.StopTrace()") (path . "runtime/index#StopTrace") (type . "runtime")) ((name . "runtime.ThreadCreateProfile()") (path . "runtime/index#ThreadCreateProfile") (type . "runtime")) ((name . "runtime.TypeAssertionError") (path . "runtime/index#TypeAssertionError") (type . "runtime")) ((name . "runtime.TypeAssertionError.Error()") (path . "runtime/index#TypeAssertionError.Error") (type . "runtime")) ((name . "runtime.TypeAssertionError.RuntimeError()") (path . "runtime/index#TypeAssertionError.RuntimeError") (type . "runtime")) ((name . "runtime.UnlockOSThread()") (path . "runtime/index#UnlockOSThread") (type . "runtime")) ((name . "runtime.Version()") (path . "runtime/index#Version") (type . "runtime")) ((name . "runtime/cgo") (path . "runtime/cgo/index") (type . "runtime")) ((name . "runtime/coverage") (path . "runtime/coverage/index") (type . "runtime")) ((name . "runtime/debug") (path . "runtime/debug/index") (type . "runtime")) ((name . "runtime/metrics") (path . "runtime/metrics/index") (type . "runtime")) ((name . "runtime/pprof") (path . "runtime/pprof/index") (type . "runtime")) ((name . "runtime/race") (path . "runtime/race/index") (type . "runtime")) ((name . "runtime/trace") (path . "runtime/trace/index") (type . "runtime")) ((name . "scanner.Error") (path . "go/scanner/index#Error") (type . "go")) ((name . "scanner.Error.Error()") (path . "go/scanner/index#Error.Error") (type . "go")) ((name . "scanner.ErrorHandler") (path . "go/scanner/index#ErrorHandler") (type . "go")) ((name . "scanner.ErrorList") (path . "go/scanner/index#ErrorList") (type . "go")) ((name . "scanner.ErrorList.Add()") (path . "go/scanner/index#ErrorList.Add") (type . "go")) ((name . "scanner.ErrorList.Err()") (path . "go/scanner/index#ErrorList.Err") (type . "go")) ((name . "scanner.ErrorList.Error()") (path . "go/scanner/index#ErrorList.Error") (type . "go")) ((name . "scanner.ErrorList.Len()") (path . "go/scanner/index#ErrorList.Len") (type . "go")) ((name . "scanner.ErrorList.Less()") (path . "go/scanner/index#ErrorList.Less") (type . "go")) ((name . "scanner.ErrorList.RemoveMultiples()") (path . "go/scanner/index#ErrorList.RemoveMultiples") (type . "go")) ((name . "scanner.ErrorList.Reset()") (path . "go/scanner/index#ErrorList.Reset") (type . "go")) ((name . "scanner.ErrorList.Sort()") (path . "go/scanner/index#ErrorList.Sort") (type . "go")) ((name . "scanner.ErrorList.Swap()") (path . "go/scanner/index#ErrorList.Swap") (type . "go")) ((name . "scanner.Mode") (path . "go/scanner/index#Mode") (type . "go")) ((name . "scanner.Position") (path . "text/scanner/index#Position") (type . "text")) ((name . "scanner.Position.IsValid()") (path . "text/scanner/index#Position.IsValid") (type . "text")) ((name . "scanner.Position.String()") (path . "text/scanner/index#Position.String") (type . "text")) ((name . "scanner.PrintError()") (path . "go/scanner/index#PrintError") (type . "go")) ((name . "scanner.Scanner") (path . "go/scanner/index#Scanner") (type . "go")) ((name . "scanner.Scanner") (path . "text/scanner/index#Scanner") (type . "text")) ((name . "scanner.Scanner.Init()") (path . "go/scanner/index#Scanner.Init") (type . "go")) ((name . "scanner.Scanner.Init()") (path . "text/scanner/index#Scanner.Init") (type . "text")) ((name . "scanner.Scanner.Next()") (path . "text/scanner/index#Scanner.Next") (type . "text")) ((name . "scanner.Scanner.Peek()") (path . "text/scanner/index#Scanner.Peek") (type . "text")) ((name . "scanner.Scanner.Pos()") (path . "text/scanner/index#Scanner.Pos") (type . "text")) ((name . "scanner.Scanner.Scan()") (path . "text/scanner/index#Scanner.Scan") (type . "text")) ((name . "scanner.Scanner.Scan()") (path . "go/scanner/index#Scanner.Scan") (type . "go")) ((name . "scanner.Scanner.TokenText()") (path . "text/scanner/index#Scanner.TokenText") (type . "text")) ((name . "scanner.TokenString()") (path . "text/scanner/index#TokenString") (type . "text")) ((name . "sha1.New()") (path . "crypto/sha1/index#New") (type . "crypto")) ((name . "sha1.Sum()") (path . "crypto/sha1/index#Sum") (type . "crypto")) ((name . "sha256.New()") (path . "crypto/sha256/index#New") (type . "crypto")) ((name . "sha256.New224()") (path . "crypto/sha256/index#New224") (type . "crypto")) ((name . "sha256.Sum224()") (path . "crypto/sha256/index#Sum224") (type . "crypto")) ((name . "sha256.Sum256()") (path . "crypto/sha256/index#Sum256") (type . "crypto")) ((name . "sha512.New()") (path . "crypto/sha512/index#New") (type . "crypto")) ((name . "sha512.New384()") (path . "crypto/sha512/index#New384") (type . "crypto")) ((name . "sha512.New512_224()") (path . "crypto/sha512/index#New512_224") (type . "crypto")) ((name . "sha512.New512_256()") (path . "crypto/sha512/index#New512_256") (type . "crypto")) ((name . "sha512.Sum384()") (path . "crypto/sha512/index#Sum384") (type . "crypto")) ((name . "sha512.Sum512()") (path . "crypto/sha512/index#Sum512") (type . "crypto")) ((name . "sha512.Sum512_224()") (path . "crypto/sha512/index#Sum512_224") (type . "crypto")) ((name . "sha512.Sum512_256()") (path . "crypto/sha512/index#Sum512_256") (type . "crypto")) ((name . "signal.Ignore()") (path . "os/signal/index#Ignore") (type . "os")) ((name . "signal.Ignored()") (path . "os/signal/index#Ignored") (type . "os")) ((name . "signal.Notify()") (path . "os/signal/index#Notify") (type . "os")) ((name . "signal.NotifyContext()") (path . "os/signal/index#NotifyContext") (type . "os")) ((name . "signal.Reset()") (path . "os/signal/index#Reset") (type . "os")) ((name . "signal.Stop()") (path . "os/signal/index#Stop") (type . "os")) ((name . "slices") (path . "slices/index") (type . "slices")) ((name . "slices.BinarySearch()") (path . "slices/index#BinarySearch") (type . "slices")) ((name . "slices.BinarySearchFunc()") (path . "slices/index#BinarySearchFunc") (type . "slices")) ((name . "slices.Clip()") (path . "slices/index#Clip") (type . "slices")) ((name . "slices.Clone()") (path . "slices/index#Clone") (type . "slices")) ((name . "slices.Compact()") (path . "slices/index#Compact") (type . "slices")) ((name . "slices.CompactFunc()") (path . "slices/index#CompactFunc") (type . "slices")) ((name . "slices.Compare()") (path . "slices/index#Compare") (type . "slices")) ((name . "slices.CompareFunc()") (path . "slices/index#CompareFunc") (type . "slices")) ((name . "slices.Concat()") (path . "slices/index#Concat") (type . "slices")) ((name . "slices.Contains()") (path . "slices/index#Contains") (type . "slices")) ((name . "slices.ContainsFunc()") (path . "slices/index#ContainsFunc") (type . "slices")) ((name . "slices.Delete()") (path . "slices/index#Delete") (type . "slices")) ((name . "slices.DeleteFunc()") (path . "slices/index#DeleteFunc") (type . "slices")) ((name . "slices.Equal()") (path . "slices/index#Equal") (type . "slices")) ((name . "slices.EqualFunc()") (path . "slices/index#EqualFunc") (type . "slices")) ((name . "slices.Grow()") (path . "slices/index#Grow") (type . "slices")) ((name . "slices.Index()") (path . "slices/index#Index") (type . "slices")) ((name . "slices.IndexFunc()") (path . "slices/index#IndexFunc") (type . "slices")) ((name . "slices.Insert()") (path . "slices/index#Insert") (type . "slices")) ((name . "slices.IsSorted()") (path . "slices/index#IsSorted") (type . "slices")) ((name . "slices.IsSortedFunc()") (path . "slices/index#IsSortedFunc") (type . "slices")) ((name . "slices.Max()") (path . "slices/index#Max") (type . "slices")) ((name . "slices.MaxFunc()") (path . "slices/index#MaxFunc") (type . "slices")) ((name . "slices.Min()") (path . "slices/index#Min") (type . "slices")) ((name . "slices.MinFunc()") (path . "slices/index#MinFunc") (type . "slices")) ((name . "slices.Replace()") (path . "slices/index#Replace") (type . "slices")) ((name . "slices.Reverse()") (path . "slices/index#Reverse") (type . "slices")) ((name . "slices.Sort()") (path . "slices/index#Sort") (type . "slices")) ((name . "slices.SortFunc()") (path . "slices/index#SortFunc") (type . "slices")) ((name . "slices.SortStableFunc()") (path . "slices/index#SortStableFunc") (type . "slices")) ((name . "slog.Any()") (path . "log/slog/index#Any") (type . "log")) ((name . "slog.AnyValue()") (path . "log/slog/index#AnyValue") (type . "log")) ((name . "slog.Attr") (path . "log/slog/index#Attr") (type . "log")) ((name . "slog.Attr.Equal()") (path . "log/slog/index#Attr.Equal") (type . "log")) ((name . "slog.Attr.String()") (path . "log/slog/index#Attr.String") (type . "log")) ((name . "slog.Bool()") (path . "log/slog/index#Bool") (type . "log")) ((name . "slog.BoolValue()") (path . "log/slog/index#BoolValue") (type . "log")) ((name . "slog.Debug()") (path . "log/slog/index#Debug") (type . "log")) ((name . "slog.DebugContext()") (path . "log/slog/index#DebugContext") (type . "log")) ((name . "slog.Default()") (path . "log/slog/index#Default") (type . "log")) ((name . "slog.Duration()") (path . "log/slog/index#Duration") (type . "log")) ((name . "slog.DurationValue()") (path . "log/slog/index#DurationValue") (type . "log")) ((name . "slog.Error()") (path . "log/slog/index#Error") (type . "log")) ((name . "slog.ErrorContext()") (path . "log/slog/index#ErrorContext") (type . "log")) ((name . "slog.Float64()") (path . "log/slog/index#Float64") (type . "log")) ((name . "slog.Float64Value()") (path . "log/slog/index#Float64Value") (type . "log")) ((name . "slog.Group()") (path . "log/slog/index#Group") (type . "log")) ((name . "slog.GroupValue()") (path . "log/slog/index#GroupValue") (type . "log")) ((name . "slog.Handler") (path . "log/slog/index#Handler") (type . "log")) ((name . "slog.HandlerOptions") (path . "log/slog/index#HandlerOptions") (type . "log")) ((name . "slog.Info()") (path . "log/slog/index#Info") (type . "log")) ((name . "slog.InfoContext()") (path . "log/slog/index#InfoContext") (type . "log")) ((name . "slog.Int()") (path . "log/slog/index#Int") (type . "log")) ((name . "slog.Int64()") (path . "log/slog/index#Int64") (type . "log")) ((name . "slog.Int64Value()") (path . "log/slog/index#Int64Value") (type . "log")) ((name . "slog.IntValue()") (path . "log/slog/index#IntValue") (type . "log")) ((name . "slog.JSONHandler") (path . "log/slog/index#JSONHandler") (type . "log")) ((name . "slog.JSONHandler.Enabled()") (path . "log/slog/index#JSONHandler.Enabled") (type . "log")) ((name . "slog.JSONHandler.Handle()") (path . "log/slog/index#JSONHandler.Handle") (type . "log")) ((name . "slog.JSONHandler.WithAttrs()") (path . "log/slog/index#JSONHandler.WithAttrs") (type . "log")) ((name . "slog.JSONHandler.WithGroup()") (path . "log/slog/index#JSONHandler.WithGroup") (type . "log")) ((name . "slog.Kind") (path . "log/slog/index#Kind") (type . "log")) ((name . "slog.Kind.String()") (path . "log/slog/index#Kind.String") (type . "log")) ((name . "slog.Level") (path . "log/slog/index#Level") (type . "log")) ((name . "slog.Level.Level()") (path . "log/slog/index#Level.Level") (type . "log")) ((name . "slog.Level.MarshalJSON()") (path . "log/slog/index#Level.MarshalJSON") (type . "log")) ((name . "slog.Level.MarshalText()") (path . "log/slog/index#Level.MarshalText") (type . "log")) ((name . "slog.Level.String()") (path . "log/slog/index#Level.String") (type . "log")) ((name . "slog.Level.UnmarshalJSON()") (path . "log/slog/index#Level.UnmarshalJSON") (type . "log")) ((name . "slog.Level.UnmarshalText()") (path . "log/slog/index#Level.UnmarshalText") (type . "log")) ((name . "slog.Leveler") (path . "log/slog/index#Leveler") (type . "log")) ((name . "slog.LevelVar") (path . "log/slog/index#LevelVar") (type . "log")) ((name . "slog.LevelVar.Level()") (path . "log/slog/index#LevelVar.Level") (type . "log")) ((name . "slog.LevelVar.MarshalText()") (path . "log/slog/index#LevelVar.MarshalText") (type . "log")) ((name . "slog.LevelVar.Set()") (path . "log/slog/index#LevelVar.Set") (type . "log")) ((name . "slog.LevelVar.String()") (path . "log/slog/index#LevelVar.String") (type . "log")) ((name . "slog.LevelVar.UnmarshalText()") (path . "log/slog/index#LevelVar.UnmarshalText") (type . "log")) ((name . "slog.Log()") (path . "log/slog/index#Log") (type . "log")) ((name . "slog.LogAttrs()") (path . "log/slog/index#LogAttrs") (type . "log")) ((name . "slog.Logger") (path . "log/slog/index#Logger") (type . "log")) ((name . "slog.Logger.Debug()") (path . "log/slog/index#Logger.Debug") (type . "log")) ((name . "slog.Logger.DebugContext()") (path . "log/slog/index#Logger.DebugContext") (type . "log")) ((name . "slog.Logger.Enabled()") (path . "log/slog/index#Logger.Enabled") (type . "log")) ((name . "slog.Logger.Error()") (path . "log/slog/index#Logger.Error") (type . "log")) ((name . "slog.Logger.ErrorContext()") (path . "log/slog/index#Logger.ErrorContext") (type . "log")) ((name . "slog.Logger.Handler()") (path . "log/slog/index#Logger.Handler") (type . "log")) ((name . "slog.Logger.Info()") (path . "log/slog/index#Logger.Info") (type . "log")) ((name . "slog.Logger.InfoContext()") (path . "log/slog/index#Logger.InfoContext") (type . "log")) ((name . "slog.Logger.Log()") (path . "log/slog/index#Logger.Log") (type . "log")) ((name . "slog.Logger.LogAttrs()") (path . "log/slog/index#Logger.LogAttrs") (type . "log")) ((name . "slog.Logger.Warn()") (path . "log/slog/index#Logger.Warn") (type . "log")) ((name . "slog.Logger.WarnContext()") (path . "log/slog/index#Logger.WarnContext") (type . "log")) ((name . "slog.Logger.With()") (path . "log/slog/index#Logger.With") (type . "log")) ((name . "slog.Logger.WithGroup()") (path . "log/slog/index#Logger.WithGroup") (type . "log")) ((name . "slog.LogValuer") (path . "log/slog/index#LogValuer") (type . "log")) ((name . "slog.New()") (path . "log/slog/index#New") (type . "log")) ((name . "slog.NewJSONHandler()") (path . "log/slog/index#NewJSONHandler") (type . "log")) ((name . "slog.NewLogLogger()") (path . "log/slog/index#NewLogLogger") (type . "log")) ((name . "slog.NewRecord()") (path . "log/slog/index#NewRecord") (type . "log")) ((name . "slog.NewTextHandler()") (path . "log/slog/index#NewTextHandler") (type . "log")) ((name . "slog.Record") (path . "log/slog/index#Record") (type . "log")) ((name . "slog.Record.Add()") (path . "log/slog/index#Record.Add") (type . "log")) ((name . "slog.Record.AddAttrs()") (path . "log/slog/index#Record.AddAttrs") (type . "log")) ((name . "slog.Record.Attrs()") (path . "log/slog/index#Record.Attrs") (type . "log")) ((name . "slog.Record.Clone()") (path . "log/slog/index#Record.Clone") (type . "log")) ((name . "slog.Record.NumAttrs()") (path . "log/slog/index#Record.NumAttrs") (type . "log")) ((name . "slog.SetDefault()") (path . "log/slog/index#SetDefault") (type . "log")) ((name . "slog.SetLogLoggerLevel()") (path . "log/slog/index#SetLogLoggerLevel") (type . "log")) ((name . "slog.Source") (path . "log/slog/index#Source") (type . "log")) ((name . "slog.String()") (path . "log/slog/index#String") (type . "log")) ((name . "slog.StringValue()") (path . "log/slog/index#StringValue") (type . "log")) ((name . "slog.TextHandler") (path . "log/slog/index#TextHandler") (type . "log")) ((name . "slog.TextHandler.Enabled()") (path . "log/slog/index#TextHandler.Enabled") (type . "log")) ((name . "slog.TextHandler.Handle()") (path . "log/slog/index#TextHandler.Handle") (type . "log")) ((name . "slog.TextHandler.WithAttrs()") (path . "log/slog/index#TextHandler.WithAttrs") (type . "log")) ((name . "slog.TextHandler.WithGroup()") (path . "log/slog/index#TextHandler.WithGroup") (type . "log")) ((name . "slog.Time()") (path . "log/slog/index#Time") (type . "log")) ((name . "slog.TimeValue()") (path . "log/slog/index#TimeValue") (type . "log")) ((name . "slog.Uint64()") (path . "log/slog/index#Uint64") (type . "log")) ((name . "slog.Uint64Value()") (path . "log/slog/index#Uint64Value") (type . "log")) ((name . "slog.Value") (path . "log/slog/index#Value") (type . "log")) ((name . "slog.Value.Any()") (path . "log/slog/index#Value.Any") (type . "log")) ((name . "slog.Value.Bool()") (path . "log/slog/index#Value.Bool") (type . "log")) ((name . "slog.Value.Duration()") (path . "log/slog/index#Value.Duration") (type . "log")) ((name . "slog.Value.Equal()") (path . "log/slog/index#Value.Equal") (type . "log")) ((name . "slog.Value.Float64()") (path . "log/slog/index#Value.Float64") (type . "log")) ((name . "slog.Value.Group()") (path . "log/slog/index#Value.Group") (type . "log")) ((name . "slog.Value.Int64()") (path . "log/slog/index#Value.Int64") (type . "log")) ((name . "slog.Value.Kind()") (path . "log/slog/index#Value.Kind") (type . "log")) ((name . "slog.Value.LogValuer()") (path . "log/slog/index#Value.LogValuer") (type . "log")) ((name . "slog.Value.Resolve()") (path . "log/slog/index#Value.Resolve") (type . "log")) ((name . "slog.Value.String()") (path . "log/slog/index#Value.String") (type . "log")) ((name . "slog.Value.Time()") (path . "log/slog/index#Value.Time") (type . "log")) ((name . "slog.Value.Uint64()") (path . "log/slog/index#Value.Uint64") (type . "log")) ((name . "slog.Warn()") (path . "log/slog/index#Warn") (type . "log")) ((name . "slog.WarnContext()") (path . "log/slog/index#WarnContext") (type . "log")) ((name . "slog.With()") (path . "log/slog/index#With") (type . "log")) ((name . "slogtest.Run()") (path . "testing/slogtest/index#Run") (type . "testing")) ((name . "slogtest.TestHandler()") (path . "testing/slogtest/index#TestHandler") (type . "testing")) ((name . "smtp.Auth") (path . "net/smtp/index#Auth") (type . "net/smtp")) ((name . "smtp.Client") (path . "net/smtp/index#Client") (type . "net/smtp")) ((name . "smtp.Client.Auth()") (path . "net/smtp/index#Client.Auth") (type . "net/smtp")) ((name . "smtp.Client.Close()") (path . "net/smtp/index#Client.Close") (type . "net/smtp")) ((name . "smtp.Client.Data()") (path . "net/smtp/index#Client.Data") (type . "net/smtp")) ((name . "smtp.Client.Extension()") (path . "net/smtp/index#Client.Extension") (type . "net/smtp")) ((name . "smtp.Client.Hello()") (path . "net/smtp/index#Client.Hello") (type . "net/smtp")) ((name . "smtp.Client.Mail()") (path . "net/smtp/index#Client.Mail") (type . "net/smtp")) ((name . "smtp.Client.Noop()") (path . "net/smtp/index#Client.Noop") (type . "net/smtp")) ((name . "smtp.Client.Quit()") (path . "net/smtp/index#Client.Quit") (type . "net/smtp")) ((name . "smtp.Client.Rcpt()") (path . "net/smtp/index#Client.Rcpt") (type . "net/smtp")) ((name . "smtp.Client.Reset()") (path . "net/smtp/index#Client.Reset") (type . "net/smtp")) ((name . "smtp.Client.StartTLS()") (path . "net/smtp/index#Client.StartTLS") (type . "net/smtp")) ((name . "smtp.Client.TLSConnectionState()") (path . "net/smtp/index#Client.TLSConnectionState") (type . "net/smtp")) ((name . "smtp.Client.Verify()") (path . "net/smtp/index#Client.Verify") (type . "net/smtp")) ((name . "smtp.CRAMMD5Auth()") (path . "net/smtp/index#CRAMMD5Auth") (type . "net/smtp")) ((name . "smtp.Dial()") (path . "net/smtp/index#Dial") (type . "net/smtp")) ((name . "smtp.NewClient()") (path . "net/smtp/index#NewClient") (type . "net/smtp")) ((name . "smtp.PlainAuth()") (path . "net/smtp/index#PlainAuth") (type . "net/smtp")) ((name . "smtp.SendMail()") (path . "net/smtp/index#SendMail") (type . "net/smtp")) ((name . "smtp.ServerInfo") (path . "net/smtp/index#ServerInfo") (type . "net/smtp")) ((name . "sort") (path . "sort/index") (type . "sort")) ((name . "sort.Find()") (path . "sort/index#Find") (type . "sort")) ((name . "sort.Float64s()") (path . "sort/index#Float64s") (type . "sort")) ((name . "sort.Float64sAreSorted()") (path . "sort/index#Float64sAreSorted") (type . "sort")) ((name . "sort.Float64Slice") (path . "sort/index#Float64Slice") (type . "sort")) ((name . "sort.Float64Slice.Len()") (path . "sort/index#Float64Slice.Len") (type . "sort")) ((name . "sort.Float64Slice.Less()") (path . "sort/index#Float64Slice.Less") (type . "sort")) ((name . "sort.Float64Slice.Search()") (path . "sort/index#Float64Slice.Search") (type . "sort")) ((name . "sort.Float64Slice.Sort()") (path . "sort/index#Float64Slice.Sort") (type . "sort")) ((name . "sort.Float64Slice.Swap()") (path . "sort/index#Float64Slice.Swap") (type . "sort")) ((name . "sort.Interface") (path . "sort/index#Interface") (type . "sort")) ((name . "sort.Ints()") (path . "sort/index#Ints") (type . "sort")) ((name . "sort.IntsAreSorted()") (path . "sort/index#IntsAreSorted") (type . "sort")) ((name . "sort.IntSlice") (path . "sort/index#IntSlice") (type . "sort")) ((name . "sort.IntSlice.Len()") (path . "sort/index#IntSlice.Len") (type . "sort")) ((name . "sort.IntSlice.Less()") (path . "sort/index#IntSlice.Less") (type . "sort")) ((name . "sort.IntSlice.Search()") (path . "sort/index#IntSlice.Search") (type . "sort")) ((name . "sort.IntSlice.Sort()") (path . "sort/index#IntSlice.Sort") (type . "sort")) ((name . "sort.IntSlice.Swap()") (path . "sort/index#IntSlice.Swap") (type . "sort")) ((name . "sort.IsSorted()") (path . "sort/index#IsSorted") (type . "sort")) ((name . "sort.Reverse()") (path . "sort/index#Reverse") (type . "sort")) ((name . "sort.Search()") (path . "sort/index#Search") (type . "sort")) ((name . "sort.SearchFloat64s()") (path . "sort/index#SearchFloat64s") (type . "sort")) ((name . "sort.SearchInts()") (path . "sort/index#SearchInts") (type . "sort")) ((name . "sort.SearchStrings()") (path . "sort/index#SearchStrings") (type . "sort")) ((name . "sort.Slice()") (path . "sort/index#Slice") (type . "sort")) ((name . "sort.SliceIsSorted()") (path . "sort/index#SliceIsSorted") (type . "sort")) ((name . "sort.SliceStable()") (path . "sort/index#SliceStable") (type . "sort")) ((name . "sort.Sort()") (path . "sort/index#Sort") (type . "sort")) ((name . "sort.Stable()") (path . "sort/index#Stable") (type . "sort")) ((name . "sort.Strings()") (path . "sort/index#Strings") (type . "sort")) ((name . "sort.StringsAreSorted()") (path . "sort/index#StringsAreSorted") (type . "sort")) ((name . "sort.StringSlice") (path . "sort/index#StringSlice") (type . "sort")) ((name . "sort.StringSlice.Len()") (path . "sort/index#StringSlice.Len") (type . "sort")) ((name . "sort.StringSlice.Less()") (path . "sort/index#StringSlice.Less") (type . "sort")) ((name . "sort.StringSlice.Search()") (path . "sort/index#StringSlice.Search") (type . "sort")) ((name . "sort.StringSlice.Sort()") (path . "sort/index#StringSlice.Sort") (type . "sort")) ((name . "sort.StringSlice.Swap()") (path . "sort/index#StringSlice.Swap") (type . "sort")) ((name . "sql.ColumnType") (path . "database/sql/index#ColumnType") (type . "database")) ((name . "sql.ColumnType.DatabaseTypeName()") (path . "database/sql/index#ColumnType.DatabaseTypeName") (type . "database")) ((name . "sql.ColumnType.DecimalSize()") (path . "database/sql/index#ColumnType.DecimalSize") (type . "database")) ((name . "sql.ColumnType.Length()") (path . "database/sql/index#ColumnType.Length") (type . "database")) ((name . "sql.ColumnType.Name()") (path . "database/sql/index#ColumnType.Name") (type . "database")) ((name . "sql.ColumnType.Nullable()") (path . "database/sql/index#ColumnType.Nullable") (type . "database")) ((name . "sql.ColumnType.ScanType()") (path . "database/sql/index#ColumnType.ScanType") (type . "database")) ((name . "sql.Conn") (path . "database/sql/index#Conn") (type . "database")) ((name . "sql.Conn.BeginTx()") (path . "database/sql/index#Conn.BeginTx") (type . "database")) ((name . "sql.Conn.Close()") (path . "database/sql/index#Conn.Close") (type . "database")) ((name . "sql.Conn.ExecContext()") (path . "database/sql/index#Conn.ExecContext") (type . "database")) ((name . "sql.Conn.PingContext()") (path . "database/sql/index#Conn.PingContext") (type . "database")) ((name . "sql.Conn.PrepareContext()") (path . "database/sql/index#Conn.PrepareContext") (type . "database")) ((name . "sql.Conn.QueryContext()") (path . "database/sql/index#Conn.QueryContext") (type . "database")) ((name . "sql.Conn.QueryRowContext()") (path . "database/sql/index#Conn.QueryRowContext") (type . "database")) ((name . "sql.Conn.Raw()") (path . "database/sql/index#Conn.Raw") (type . "database")) ((name . "sql.DB") (path . "database/sql/index#DB") (type . "database")) ((name . "sql.DB.Begin()") (path . "database/sql/index#DB.Begin") (type . "database")) ((name . "sql.DB.BeginTx()") (path . "database/sql/index#DB.BeginTx") (type . "database")) ((name . "sql.DB.Close()") (path . "database/sql/index#DB.Close") (type . "database")) ((name . "sql.DB.Conn()") (path . "database/sql/index#DB.Conn") (type . "database")) ((name . "sql.DB.Driver()") (path . "database/sql/index#DB.Driver") (type . "database")) ((name . "sql.DB.Exec()") (path . "database/sql/index#DB.Exec") (type . "database")) ((name . "sql.DB.ExecContext()") (path . "database/sql/index#DB.ExecContext") (type . "database")) ((name . "sql.DB.Ping()") (path . "database/sql/index#DB.Ping") (type . "database")) ((name . "sql.DB.PingContext()") (path . "database/sql/index#DB.PingContext") (type . "database")) ((name . "sql.DB.Prepare()") (path . "database/sql/index#DB.Prepare") (type . "database")) ((name . "sql.DB.PrepareContext()") (path . "database/sql/index#DB.PrepareContext") (type . "database")) ((name . "sql.DB.Query()") (path . "database/sql/index#DB.Query") (type . "database")) ((name . "sql.DB.QueryContext()") (path . "database/sql/index#DB.QueryContext") (type . "database")) ((name . "sql.DB.QueryRow()") (path . "database/sql/index#DB.QueryRow") (type . "database")) ((name . "sql.DB.QueryRowContext()") (path . "database/sql/index#DB.QueryRowContext") (type . "database")) ((name . "sql.DB.SetConnMaxIdleTime()") (path . "database/sql/index#DB.SetConnMaxIdleTime") (type . "database")) ((name . "sql.DB.SetConnMaxLifetime()") (path . "database/sql/index#DB.SetConnMaxLifetime") (type . "database")) ((name . "sql.DB.SetMaxIdleConns()") (path . "database/sql/index#DB.SetMaxIdleConns") (type . "database")) ((name . "sql.DB.SetMaxOpenConns()") (path . "database/sql/index#DB.SetMaxOpenConns") (type . "database")) ((name . "sql.DB.Stats()") (path . "database/sql/index#DB.Stats") (type . "database")) ((name . "sql.DBStats") (path . "database/sql/index#DBStats") (type . "database")) ((name . "sql.Drivers()") (path . "database/sql/index#Drivers") (type . "database")) ((name . "sql.IsolationLevel") (path . "database/sql/index#IsolationLevel") (type . "database")) ((name . "sql.IsolationLevel.String()") (path . "database/sql/index#IsolationLevel.String") (type . "database")) ((name . "sql.Named()") (path . "database/sql/index#Named") (type . "database")) ((name . "sql.NamedArg") (path . "database/sql/index#NamedArg") (type . "database")) ((name . "sql.Null") (path . "database/sql/index#Null") (type . "database")) ((name . "sql.Null.Scan()") (path . "database/sql/index#Null.Scan") (type . "database")) ((name . "sql.Null.Value()") (path . "database/sql/index#Null.Value") (type . "database")) ((name . "sql.NullBool") (path . "database/sql/index#NullBool") (type . "database")) ((name . "sql.NullBool.Scan()") (path . "database/sql/index#NullBool.Scan") (type . "database")) ((name . "sql.NullBool.Value()") (path . "database/sql/index#NullBool.Value") (type . "database")) ((name . "sql.NullByte") (path . "database/sql/index#NullByte") (type . "database")) ((name . "sql.NullByte.Scan()") (path . "database/sql/index#NullByte.Scan") (type . "database")) ((name . "sql.NullByte.Value()") (path . "database/sql/index#NullByte.Value") (type . "database")) ((name . "sql.NullFloat64") (path . "database/sql/index#NullFloat64") (type . "database")) ((name . "sql.NullFloat64.Scan()") (path . "database/sql/index#NullFloat64.Scan") (type . "database")) ((name . "sql.NullFloat64.Value()") (path . "database/sql/index#NullFloat64.Value") (type . "database")) ((name . "sql.NullInt16") (path . "database/sql/index#NullInt16") (type . "database")) ((name . "sql.NullInt16.Scan()") (path . "database/sql/index#NullInt16.Scan") (type . "database")) ((name . "sql.NullInt16.Value()") (path . "database/sql/index#NullInt16.Value") (type . "database")) ((name . "sql.NullInt32") (path . "database/sql/index#NullInt32") (type . "database")) ((name . "sql.NullInt32.Scan()") (path . "database/sql/index#NullInt32.Scan") (type . "database")) ((name . "sql.NullInt32.Value()") (path . "database/sql/index#NullInt32.Value") (type . "database")) ((name . "sql.NullInt64") (path . "database/sql/index#NullInt64") (type . "database")) ((name . "sql.NullInt64.Scan()") (path . "database/sql/index#NullInt64.Scan") (type . "database")) ((name . "sql.NullInt64.Value()") (path . "database/sql/index#NullInt64.Value") (type . "database")) ((name . "sql.NullString") (path . "database/sql/index#NullString") (type . "database")) ((name . "sql.NullString.Scan()") (path . "database/sql/index#NullString.Scan") (type . "database")) ((name . "sql.NullString.Value()") (path . "database/sql/index#NullString.Value") (type . "database")) ((name . "sql.NullTime") (path . "database/sql/index#NullTime") (type . "database")) ((name . "sql.NullTime.Scan()") (path . "database/sql/index#NullTime.Scan") (type . "database")) ((name . "sql.NullTime.Value()") (path . "database/sql/index#NullTime.Value") (type . "database")) ((name . "sql.Open()") (path . "database/sql/index#Open") (type . "database")) ((name . "sql.OpenDB()") (path . "database/sql/index#OpenDB") (type . "database")) ((name . "sql.Out") (path . "database/sql/index#Out") (type . "database")) ((name . "sql.RawBytes") (path . "database/sql/index#RawBytes") (type . "database")) ((name . "sql.Register()") (path . "database/sql/index#Register") (type . "database")) ((name . "sql.Result") (path . "database/sql/index#Result") (type . "database")) ((name . "sql.Row") (path . "database/sql/index#Row") (type . "database")) ((name . "sql.Row.Err()") (path . "database/sql/index#Row.Err") (type . "database")) ((name . "sql.Row.Scan()") (path . "database/sql/index#Row.Scan") (type . "database")) ((name . "sql.Rows") (path . "database/sql/index#Rows") (type . "database")) ((name . "sql.Rows.Close()") (path . "database/sql/index#Rows.Close") (type . "database")) ((name . "sql.Rows.Columns()") (path . "database/sql/index#Rows.Columns") (type . "database")) ((name . "sql.Rows.ColumnTypes()") (path . "database/sql/index#Rows.ColumnTypes") (type . "database")) ((name . "sql.Rows.Err()") (path . "database/sql/index#Rows.Err") (type . "database")) ((name . "sql.Rows.Next()") (path . "database/sql/index#Rows.Next") (type . "database")) ((name . "sql.Rows.NextResultSet()") (path . "database/sql/index#Rows.NextResultSet") (type . "database")) ((name . "sql.Rows.Scan()") (path . "database/sql/index#Rows.Scan") (type . "database")) ((name . "sql.Scanner") (path . "database/sql/index#Scanner") (type . "database")) ((name . "sql.Stmt") (path . "database/sql/index#Stmt") (type . "database")) ((name . "sql.Stmt.Close()") (path . "database/sql/index#Stmt.Close") (type . "database")) ((name . "sql.Stmt.Exec()") (path . "database/sql/index#Stmt.Exec") (type . "database")) ((name . "sql.Stmt.ExecContext()") (path . "database/sql/index#Stmt.ExecContext") (type . "database")) ((name . "sql.Stmt.Query()") (path . "database/sql/index#Stmt.Query") (type . "database")) ((name . "sql.Stmt.QueryContext()") (path . "database/sql/index#Stmt.QueryContext") (type . "database")) ((name . "sql.Stmt.QueryRow()") (path . "database/sql/index#Stmt.QueryRow") (type . "database")) ((name . "sql.Stmt.QueryRowContext()") (path . "database/sql/index#Stmt.QueryRowContext") (type . "database")) ((name . "sql.Tx") (path . "database/sql/index#Tx") (type . "database")) ((name . "sql.Tx.Commit()") (path . "database/sql/index#Tx.Commit") (type . "database")) ((name . "sql.Tx.Exec()") (path . "database/sql/index#Tx.Exec") (type . "database")) ((name . "sql.Tx.ExecContext()") (path . "database/sql/index#Tx.ExecContext") (type . "database")) ((name . "sql.Tx.Prepare()") (path . "database/sql/index#Tx.Prepare") (type . "database")) ((name . "sql.Tx.PrepareContext()") (path . "database/sql/index#Tx.PrepareContext") (type . "database")) ((name . "sql.Tx.Query()") (path . "database/sql/index#Tx.Query") (type . "database")) ((name . "sql.Tx.QueryContext()") (path . "database/sql/index#Tx.QueryContext") (type . "database")) ((name . "sql.Tx.QueryRow()") (path . "database/sql/index#Tx.QueryRow") (type . "database")) ((name . "sql.Tx.QueryRowContext()") (path . "database/sql/index#Tx.QueryRowContext") (type . "database")) ((name . "sql.Tx.Rollback()") (path . "database/sql/index#Tx.Rollback") (type . "database")) ((name . "sql.Tx.Stmt()") (path . "database/sql/index#Tx.Stmt") (type . "database")) ((name . "sql.Tx.StmtContext()") (path . "database/sql/index#Tx.StmtContext") (type . "database")) ((name . "sql.TxOptions") (path . "database/sql/index#TxOptions") (type . "database")) ((name . "strconv") (path . "strconv/index") (type . "strconv")) ((name . "strconv constants") (path . "strconv/index#pkg-constants") (type . "strconv")) ((name . "strconv variables") (path . "strconv/index#pkg-variables") (type . "strconv")) ((name . "strconv.AppendBool()") (path . "strconv/index#AppendBool") (type . "strconv")) ((name . "strconv.AppendFloat()") (path . "strconv/index#AppendFloat") (type . "strconv")) ((name . "strconv.AppendInt()") (path . "strconv/index#AppendInt") (type . "strconv")) ((name . "strconv.AppendQuote()") (path . "strconv/index#AppendQuote") (type . "strconv")) ((name . "strconv.AppendQuoteRune()") (path . "strconv/index#AppendQuoteRune") (type . "strconv")) ((name . "strconv.AppendQuoteRuneToASCII()") (path . "strconv/index#AppendQuoteRuneToASCII") (type . "strconv")) ((name . "strconv.AppendQuoteRuneToGraphic()") (path . "strconv/index#AppendQuoteRuneToGraphic") (type . "strconv")) ((name . "strconv.AppendQuoteToASCII()") (path . "strconv/index#AppendQuoteToASCII") (type . "strconv")) ((name . "strconv.AppendQuoteToGraphic()") (path . "strconv/index#AppendQuoteToGraphic") (type . "strconv")) ((name . "strconv.AppendUint()") (path . "strconv/index#AppendUint") (type . "strconv")) ((name . "strconv.Atoi()") (path . "strconv/index#Atoi") (type . "strconv")) ((name . "strconv.CanBackquote()") (path . "strconv/index#CanBackquote") (type . "strconv")) ((name . "strconv.FormatBool()") (path . "strconv/index#FormatBool") (type . "strconv")) ((name . "strconv.FormatComplex()") (path . "strconv/index#FormatComplex") (type . "strconv")) ((name . "strconv.FormatFloat()") (path . "strconv/index#FormatFloat") (type . "strconv")) ((name . "strconv.FormatInt()") (path . "strconv/index#FormatInt") (type . "strconv")) ((name . "strconv.FormatUint()") (path . "strconv/index#FormatUint") (type . "strconv")) ((name . "strconv.IsGraphic()") (path . "strconv/index#IsGraphic") (type . "strconv")) ((name . "strconv.IsPrint()") (path . "strconv/index#IsPrint") (type . "strconv")) ((name . "strconv.Itoa()") (path . "strconv/index#Itoa") (type . "strconv")) ((name . "strconv.NumError") (path . "strconv/index#NumError") (type . "strconv")) ((name . "strconv.NumError.Error()") (path . "strconv/index#NumError.Error") (type . "strconv")) ((name . "strconv.NumError.Unwrap()") (path . "strconv/index#NumError.Unwrap") (type . "strconv")) ((name . "strconv.ParseBool()") (path . "strconv/index#ParseBool") (type . "strconv")) ((name . "strconv.ParseComplex()") (path . "strconv/index#ParseComplex") (type . "strconv")) ((name . "strconv.ParseFloat()") (path . "strconv/index#ParseFloat") (type . "strconv")) ((name . "strconv.ParseInt()") (path . "strconv/index#ParseInt") (type . "strconv")) ((name . "strconv.ParseUint()") (path . "strconv/index#ParseUint") (type . "strconv")) ((name . "strconv.Quote()") (path . "strconv/index#Quote") (type . "strconv")) ((name . "strconv.QuotedPrefix()") (path . "strconv/index#QuotedPrefix") (type . "strconv")) ((name . "strconv.QuoteRune()") (path . "strconv/index#QuoteRune") (type . "strconv")) ((name . "strconv.QuoteRuneToASCII()") (path . "strconv/index#QuoteRuneToASCII") (type . "strconv")) ((name . "strconv.QuoteRuneToGraphic()") (path . "strconv/index#QuoteRuneToGraphic") (type . "strconv")) ((name . "strconv.QuoteToASCII()") (path . "strconv/index#QuoteToASCII") (type . "strconv")) ((name . "strconv.QuoteToGraphic()") (path . "strconv/index#QuoteToGraphic") (type . "strconv")) ((name . "strconv.Unquote()") (path . "strconv/index#Unquote") (type . "strconv")) ((name . "strconv.UnquoteChar()") (path . "strconv/index#UnquoteChar") (type . "strconv")) ((name . "strings") (path . "strings/index") (type . "strings")) ((name . "strings.Builder") (path . "strings/index#Builder") (type . "strings")) ((name . "strings.Builder.Cap()") (path . "strings/index#Builder.Cap") (type . "strings")) ((name . "strings.Builder.Grow()") (path . "strings/index#Builder.Grow") (type . "strings")) ((name . "strings.Builder.Len()") (path . "strings/index#Builder.Len") (type . "strings")) ((name . "strings.Builder.Reset()") (path . "strings/index#Builder.Reset") (type . "strings")) ((name . "strings.Builder.String()") (path . "strings/index#Builder.String") (type . "strings")) ((name . "strings.Builder.Write()") (path . "strings/index#Builder.Write") (type . "strings")) ((name . "strings.Builder.WriteByte()") (path . "strings/index#Builder.WriteByte") (type . "strings")) ((name . "strings.Builder.WriteRune()") (path . "strings/index#Builder.WriteRune") (type . "strings")) ((name . "strings.Builder.WriteString()") (path . "strings/index#Builder.WriteString") (type . "strings")) ((name . "strings.Clone()") (path . "strings/index#Clone") (type . "strings")) ((name . "strings.Compare()") (path . "strings/index#Compare") (type . "strings")) ((name . "strings.Contains()") (path . "strings/index#Contains") (type . "strings")) ((name . "strings.ContainsAny()") (path . "strings/index#ContainsAny") (type . "strings")) ((name . "strings.ContainsFunc()") (path . "strings/index#ContainsFunc") (type . "strings")) ((name . "strings.ContainsRune()") (path . "strings/index#ContainsRune") (type . "strings")) ((name . "strings.Count()") (path . "strings/index#Count") (type . "strings")) ((name . "strings.Cut()") (path . "strings/index#Cut") (type . "strings")) ((name . "strings.CutPrefix()") (path . "strings/index#CutPrefix") (type . "strings")) ((name . "strings.CutSuffix()") (path . "strings/index#CutSuffix") (type . "strings")) ((name . "strings.EqualFold()") (path . "strings/index#EqualFold") (type . "strings")) ((name . "strings.Fields()") (path . "strings/index#Fields") (type . "strings")) ((name . "strings.FieldsFunc()") (path . "strings/index#FieldsFunc") (type . "strings")) ((name . "strings.HasPrefix()") (path . "strings/index#HasPrefix") (type . "strings")) ((name . "strings.HasSuffix()") (path . "strings/index#HasSuffix") (type . "strings")) ((name . "strings.Index()") (path . "strings/index#Index") (type . "strings")) ((name . "strings.IndexAny()") (path . "strings/index#IndexAny") (type . "strings")) ((name . "strings.IndexByte()") (path . "strings/index#IndexByte") (type . "strings")) ((name . "strings.IndexFunc()") (path . "strings/index#IndexFunc") (type . "strings")) ((name . "strings.IndexRune()") (path . "strings/index#IndexRune") (type . "strings")) ((name . "strings.Join()") (path . "strings/index#Join") (type . "strings")) ((name . "strings.LastIndex()") (path . "strings/index#LastIndex") (type . "strings")) ((name . "strings.LastIndexAny()") (path . "strings/index#LastIndexAny") (type . "strings")) ((name . "strings.LastIndexByte()") (path . "strings/index#LastIndexByte") (type . "strings")) ((name . "strings.LastIndexFunc()") (path . "strings/index#LastIndexFunc") (type . "strings")) ((name . "strings.Map()") (path . "strings/index#Map") (type . "strings")) ((name . "strings.NewReader()") (path . "strings/index#NewReader") (type . "strings")) ((name . "strings.NewReplacer()") (path . "strings/index#NewReplacer") (type . "strings")) ((name . "strings.Reader") (path . "strings/index#Reader") (type . "strings")) ((name . "strings.Reader.Len()") (path . "strings/index#Reader.Len") (type . "strings")) ((name . "strings.Reader.Read()") (path . "strings/index#Reader.Read") (type . "strings")) ((name . "strings.Reader.ReadAt()") (path . "strings/index#Reader.ReadAt") (type . "strings")) ((name . "strings.Reader.ReadByte()") (path . "strings/index#Reader.ReadByte") (type . "strings")) ((name . "strings.Reader.ReadRune()") (path . "strings/index#Reader.ReadRune") (type . "strings")) ((name . "strings.Reader.Reset()") (path . "strings/index#Reader.Reset") (type . "strings")) ((name . "strings.Reader.Seek()") (path . "strings/index#Reader.Seek") (type . "strings")) ((name . "strings.Reader.Size()") (path . "strings/index#Reader.Size") (type . "strings")) ((name . "strings.Reader.UnreadByte()") (path . "strings/index#Reader.UnreadByte") (type . "strings")) ((name . "strings.Reader.UnreadRune()") (path . "strings/index#Reader.UnreadRune") (type . "strings")) ((name . "strings.Reader.WriteTo()") (path . "strings/index#Reader.WriteTo") (type . "strings")) ((name . "strings.Repeat()") (path . "strings/index#Repeat") (type . "strings")) ((name . "strings.Replace()") (path . "strings/index#Replace") (type . "strings")) ((name . "strings.ReplaceAll()") (path . "strings/index#ReplaceAll") (type . "strings")) ((name . "strings.Replacer") (path . "strings/index#Replacer") (type . "strings")) ((name . "strings.Replacer.Replace()") (path . "strings/index#Replacer.Replace") (type . "strings")) ((name . "strings.Replacer.WriteString()") (path . "strings/index#Replacer.WriteString") (type . "strings")) ((name . "strings.Split()") (path . "strings/index#Split") (type . "strings")) ((name . "strings.SplitAfter()") (path . "strings/index#SplitAfter") (type . "strings")) ((name . "strings.SplitAfterN()") (path . "strings/index#SplitAfterN") (type . "strings")) ((name . "strings.SplitN()") (path . "strings/index#SplitN") (type . "strings")) ((name . "strings.Title()") (path . "strings/index#Title") (type . "strings")) ((name . "strings.ToLower()") (path . "strings/index#ToLower") (type . "strings")) ((name . "strings.ToLowerSpecial()") (path . "strings/index#ToLowerSpecial") (type . "strings")) ((name . "strings.ToTitle()") (path . "strings/index#ToTitle") (type . "strings")) ((name . "strings.ToTitleSpecial()") (path . "strings/index#ToTitleSpecial") (type . "strings")) ((name . "strings.ToUpper()") (path . "strings/index#ToUpper") (type . "strings")) ((name . "strings.ToUpperSpecial()") (path . "strings/index#ToUpperSpecial") (type . "strings")) ((name . "strings.ToValidUTF8()") (path . "strings/index#ToValidUTF8") (type . "strings")) ((name . "strings.Trim()") (path . "strings/index#Trim") (type . "strings")) ((name . "strings.TrimFunc()") (path . "strings/index#TrimFunc") (type . "strings")) ((name . "strings.TrimLeft()") (path . "strings/index#TrimLeft") (type . "strings")) ((name . "strings.TrimLeftFunc()") (path . "strings/index#TrimLeftFunc") (type . "strings")) ((name . "strings.TrimPrefix()") (path . "strings/index#TrimPrefix") (type . "strings")) ((name . "strings.TrimRight()") (path . "strings/index#TrimRight") (type . "strings")) ((name . "strings.TrimRightFunc()") (path . "strings/index#TrimRightFunc") (type . "strings")) ((name . "strings.TrimSpace()") (path . "strings/index#TrimSpace") (type . "strings")) ((name . "strings.TrimSuffix()") (path . "strings/index#TrimSuffix") (type . "strings")) ((name . "subtle.ConstantTimeByteEq()") (path . "crypto/subtle/index#ConstantTimeByteEq") (type . "crypto")) ((name . "subtle.ConstantTimeCompare()") (path . "crypto/subtle/index#ConstantTimeCompare") (type . "crypto")) ((name . "subtle.ConstantTimeCopy()") (path . "crypto/subtle/index#ConstantTimeCopy") (type . "crypto")) ((name . "subtle.ConstantTimeEq()") (path . "crypto/subtle/index#ConstantTimeEq") (type . "crypto")) ((name . "subtle.ConstantTimeLessOrEq()") (path . "crypto/subtle/index#ConstantTimeLessOrEq") (type . "crypto")) ((name . "subtle.ConstantTimeSelect()") (path . "crypto/subtle/index#ConstantTimeSelect") (type . "crypto")) ((name . "subtle.XORBytes()") (path . "crypto/subtle/index#XORBytes") (type . "crypto")) ((name . "suffixarray.Index") (path . "index/suffixarray/index#Index") (type . "index")) ((name . "suffixarray.Index.Bytes()") (path . "index/suffixarray/index#Index.Bytes") (type . "index")) ((name . "suffixarray.Index.FindAllIndex()") (path . "index/suffixarray/index#Index.FindAllIndex") (type . "index")) ((name . "suffixarray.Index.Lookup()") (path . "index/suffixarray/index#Index.Lookup") (type . "index")) ((name . "suffixarray.Index.Read()") (path . "index/suffixarray/index#Index.Read") (type . "index")) ((name . "suffixarray.Index.Write()") (path . "index/suffixarray/index#Index.Write") (type . "index")) ((name . "suffixarray.New()") (path . "index/suffixarray/index#New") (type . "index")) ((name . "sync") (path . "sync/index") (type . "sync")) ((name . "sync.Cond") (path . "sync/index#Cond") (type . "sync")) ((name . "sync.Cond.Broadcast()") (path . "sync/index#Cond.Broadcast") (type . "sync")) ((name . "sync.Cond.Signal()") (path . "sync/index#Cond.Signal") (type . "sync")) ((name . "sync.Cond.Wait()") (path . "sync/index#Cond.Wait") (type . "sync")) ((name . "sync.Locker") (path . "sync/index#Locker") (type . "sync")) ((name . "sync.Map") (path . "sync/index#Map") (type . "sync")) ((name . "sync.Map.CompareAndDelete()") (path . "sync/index#Map.CompareAndDelete") (type . "sync")) ((name . "sync.Map.CompareAndSwap()") (path . "sync/index#Map.CompareAndSwap") (type . "sync")) ((name . "sync.Map.Delete()") (path . "sync/index#Map.Delete") (type . "sync")) ((name . "sync.Map.Load()") (path . "sync/index#Map.Load") (type . "sync")) ((name . "sync.Map.LoadAndDelete()") (path . "sync/index#Map.LoadAndDelete") (type . "sync")) ((name . "sync.Map.LoadOrStore()") (path . "sync/index#Map.LoadOrStore") (type . "sync")) ((name . "sync.Map.Range()") (path . "sync/index#Map.Range") (type . "sync")) ((name . "sync.Map.Store()") (path . "sync/index#Map.Store") (type . "sync")) ((name . "sync.Map.Swap()") (path . "sync/index#Map.Swap") (type . "sync")) ((name . "sync.Mutex") (path . "sync/index#Mutex") (type . "sync")) ((name . "sync.Mutex.Lock()") (path . "sync/index#Mutex.Lock") (type . "sync")) ((name . "sync.Mutex.TryLock()") (path . "sync/index#Mutex.TryLock") (type . "sync")) ((name . "sync.Mutex.Unlock()") (path . "sync/index#Mutex.Unlock") (type . "sync")) ((name . "sync.NewCond()") (path . "sync/index#NewCond") (type . "sync")) ((name . "sync.Once") (path . "sync/index#Once") (type . "sync")) ((name . "sync.Once.Do()") (path . "sync/index#Once.Do") (type . "sync")) ((name . "sync.OnceFunc()") (path . "sync/index#OnceFunc") (type . "sync")) ((name . "sync.OnceValue()") (path . "sync/index#OnceValue") (type . "sync")) ((name . "sync.OnceValues()") (path . "sync/index#OnceValues") (type . "sync")) ((name . "sync.Pool") (path . "sync/index#Pool") (type . "sync")) ((name . "sync.Pool.Get()") (path . "sync/index#Pool.Get") (type . "sync")) ((name . "sync.Pool.Put()") (path . "sync/index#Pool.Put") (type . "sync")) ((name . "sync.RWMutex") (path . "sync/index#RWMutex") (type . "sync")) ((name . "sync.RWMutex.Lock()") (path . "sync/index#RWMutex.Lock") (type . "sync")) ((name . "sync.RWMutex.RLock()") (path . "sync/index#RWMutex.RLock") (type . "sync")) ((name . "sync.RWMutex.RLocker()") (path . "sync/index#RWMutex.RLocker") (type . "sync")) ((name . "sync.RWMutex.RUnlock()") (path . "sync/index#RWMutex.RUnlock") (type . "sync")) ((name . "sync.RWMutex.TryLock()") (path . "sync/index#RWMutex.TryLock") (type . "sync")) ((name . "sync.RWMutex.TryRLock()") (path . "sync/index#RWMutex.TryRLock") (type . "sync")) ((name . "sync.RWMutex.Unlock()") (path . "sync/index#RWMutex.Unlock") (type . "sync")) ((name . "sync.WaitGroup") (path . "sync/index#WaitGroup") (type . "sync")) ((name . "sync.WaitGroup.Add()") (path . "sync/index#WaitGroup.Add") (type . "sync")) ((name . "sync.WaitGroup.Done()") (path . "sync/index#WaitGroup.Done") (type . "sync")) ((name . "sync.WaitGroup.Wait()") (path . "sync/index#WaitGroup.Wait") (type . "sync")) ((name . "sync/atomic") (path . "sync/atomic/index") (type . "sync")) ((name . "syntax.Compile()") (path . "regexp/syntax/index#Compile") (type . "regexp")) ((name . "syntax.EmptyOp") (path . "regexp/syntax/index#EmptyOp") (type . "regexp")) ((name . "syntax.EmptyOpContext()") (path . "regexp/syntax/index#EmptyOpContext") (type . "regexp")) ((name . "syntax.Error") (path . "regexp/syntax/index#Error") (type . "regexp")) ((name . "syntax.Error.Error()") (path . "regexp/syntax/index#Error.Error") (type . "regexp")) ((name . "syntax.ErrorCode") (path . "regexp/syntax/index#ErrorCode") (type . "regexp")) ((name . "syntax.ErrorCode.String()") (path . "regexp/syntax/index#ErrorCode.String") (type . "regexp")) ((name . "syntax.Flags") (path . "regexp/syntax/index#Flags") (type . "regexp")) ((name . "syntax.Inst") (path . "regexp/syntax/index#Inst") (type . "regexp")) ((name . "syntax.Inst.MatchEmptyWidth()") (path . "regexp/syntax/index#Inst.MatchEmptyWidth") (type . "regexp")) ((name . "syntax.Inst.MatchRune()") (path . "regexp/syntax/index#Inst.MatchRune") (type . "regexp")) ((name . "syntax.Inst.MatchRunePos()") (path . "regexp/syntax/index#Inst.MatchRunePos") (type . "regexp")) ((name . "syntax.Inst.String()") (path . "regexp/syntax/index#Inst.String") (type . "regexp")) ((name . "syntax.InstOp") (path . "regexp/syntax/index#InstOp") (type . "regexp")) ((name . "syntax.InstOp.String()") (path . "regexp/syntax/index#InstOp.String") (type . "regexp")) ((name . "syntax.IsWordChar()") (path . "regexp/syntax/index#IsWordChar") (type . "regexp")) ((name . "syntax.Op") (path . "regexp/syntax/index#Op") (type . "regexp")) ((name . "syntax.Op.String()") (path . "regexp/syntax/index#Op.String") (type . "regexp")) ((name . "syntax.Parse()") (path . "regexp/syntax/index#Parse") (type . "regexp")) ((name . "syntax.Prog") (path . "regexp/syntax/index#Prog") (type . "regexp")) ((name . "syntax.Prog.Prefix()") (path . "regexp/syntax/index#Prog.Prefix") (type . "regexp")) ((name . "syntax.Prog.StartCond()") (path . "regexp/syntax/index#Prog.StartCond") (type . "regexp")) ((name . "syntax.Prog.String()") (path . "regexp/syntax/index#Prog.String") (type . "regexp")) ((name . "syntax.Regexp") (path . "regexp/syntax/index#Regexp") (type . "regexp")) ((name . "syntax.Regexp.CapNames()") (path . "regexp/syntax/index#Regexp.CapNames") (type . "regexp")) ((name . "syntax.Regexp.Equal()") (path . "regexp/syntax/index#Regexp.Equal") (type . "regexp")) ((name . "syntax.Regexp.MaxCap()") (path . "regexp/syntax/index#Regexp.MaxCap") (type . "regexp")) ((name . "syntax.Regexp.Simplify()") (path . "regexp/syntax/index#Regexp.Simplify") (type . "regexp")) ((name . "syntax.Regexp.String()") (path . "regexp/syntax/index#Regexp.String") (type . "regexp")) ((name . "syscall") (path . "syscall/index") (type . "syscall")) ((name . "syscall constants") (path . "syscall/index#pkg-constants") (type . "syscall")) ((name . "syscall variables") (path . "syscall/index#pkg-variables") (type . "syscall")) ((name . "syscall.Accept()") (path . "syscall/index#Accept") (type . "syscall")) ((name . "syscall.Accept4()") (path . "syscall/index#Accept4") (type . "syscall")) ((name . "syscall.Access()") (path . "syscall/index#Access") (type . "syscall")) ((name . "syscall.Acct()") (path . "syscall/index#Acct") (type . "syscall")) ((name . "syscall.Adjtimex()") (path . "syscall/index#Adjtimex") (type . "syscall")) ((name . "syscall.AllThreadsSyscall()") (path . "syscall/index#AllThreadsSyscall") (type . "syscall")) ((name . "syscall.AllThreadsSyscall6()") (path . "syscall/index#AllThreadsSyscall6") (type . "syscall")) ((name . "syscall.AttachLsf()") (path . "syscall/index#AttachLsf") (type . "syscall")) ((name . "syscall.Bind()") (path . "syscall/index#Bind") (type . "syscall")) ((name . "syscall.BindToDevice()") (path . "syscall/index#BindToDevice") (type . "syscall")) ((name . "syscall.BytePtrFromString()") (path . "syscall/index#BytePtrFromString") (type . "syscall")) ((name . "syscall.ByteSliceFromString()") (path . "syscall/index#ByteSliceFromString") (type . "syscall")) ((name . "syscall.Chdir()") (path . "syscall/index#Chdir") (type . "syscall")) ((name . "syscall.Chmod()") (path . "syscall/index#Chmod") (type . "syscall")) ((name . "syscall.Chown()") (path . "syscall/index#Chown") (type . "syscall")) ((name . "syscall.Chroot()") (path . "syscall/index#Chroot") (type . "syscall")) ((name . "syscall.Clearenv()") (path . "syscall/index#Clearenv") (type . "syscall")) ((name . "syscall.Close()") (path . "syscall/index#Close") (type . "syscall")) ((name . "syscall.CloseOnExec()") (path . "syscall/index#CloseOnExec") (type . "syscall")) ((name . "syscall.Cmsghdr") (path . "syscall/index#Cmsghdr") (type . "syscall")) ((name . "syscall.Cmsghdr.SetLen()") (path . "syscall/index#Cmsghdr.SetLen") (type . "syscall")) ((name . "syscall.CmsgLen()") (path . "syscall/index#CmsgLen") (type . "syscall")) ((name . "syscall.CmsgSpace()") (path . "syscall/index#CmsgSpace") (type . "syscall")) ((name . "syscall.Conn") (path . "syscall/index#Conn") (type . "syscall")) ((name . "syscall.Connect()") (path . "syscall/index#Connect") (type . "syscall")) ((name . "syscall.Creat()") (path . "syscall/index#Creat") (type . "syscall")) ((name . "syscall.Credential") (path . "syscall/index#Credential") (type . "syscall")) ((name . "syscall.DetachLsf()") (path . "syscall/index#DetachLsf") (type . "syscall")) ((name . "syscall.Dirent") (path . "syscall/index#Dirent") (type . "syscall")) ((name . "syscall.Dup()") (path . "syscall/index#Dup") (type . "syscall")) ((name . "syscall.Dup2()") (path . "syscall/index#Dup2") (type . "syscall")) ((name . "syscall.Dup3()") (path . "syscall/index#Dup3") (type . "syscall")) ((name . "syscall.Environ()") (path . "syscall/index#Environ") (type . "syscall")) ((name . "syscall.EpollCreate()") (path . "syscall/index#EpollCreate") (type . "syscall")) ((name . "syscall.EpollCreate1()") (path . "syscall/index#EpollCreate1") (type . "syscall")) ((name . "syscall.EpollCtl()") (path . "syscall/index#EpollCtl") (type . "syscall")) ((name . "syscall.EpollEvent") (path . "syscall/index#EpollEvent") (type . "syscall")) ((name . "syscall.EpollWait()") (path . "syscall/index#EpollWait") (type . "syscall")) ((name . "syscall.Errno") (path . "syscall/index#Errno") (type . "syscall")) ((name . "syscall.Errno.Error()") (path . "syscall/index#Errno.Error") (type . "syscall")) ((name . "syscall.Errno.Is()") (path . "syscall/index#Errno.Is") (type . "syscall")) ((name . "syscall.Errno.Temporary()") (path . "syscall/index#Errno.Temporary") (type . "syscall")) ((name . "syscall.Errno.Timeout()") (path . "syscall/index#Errno.Timeout") (type . "syscall")) ((name . "syscall.Exec()") (path . "syscall/index#Exec") (type . "syscall")) ((name . "syscall.Exit()") (path . "syscall/index#Exit") (type . "syscall")) ((name . "syscall.Faccessat()") (path . "syscall/index#Faccessat") (type . "syscall")) ((name . "syscall.Fallocate()") (path . "syscall/index#Fallocate") (type . "syscall")) ((name . "syscall.Fchdir()") (path . "syscall/index#Fchdir") (type . "syscall")) ((name . "syscall.Fchmod()") (path . "syscall/index#Fchmod") (type . "syscall")) ((name . "syscall.Fchmodat()") (path . "syscall/index#Fchmodat") (type . "syscall")) ((name . "syscall.Fchown()") (path . "syscall/index#Fchown") (type . "syscall")) ((name . "syscall.Fchownat()") (path . "syscall/index#Fchownat") (type . "syscall")) ((name . "syscall.FcntlFlock()") (path . "syscall/index#FcntlFlock") (type . "syscall")) ((name . "syscall.Fdatasync()") (path . "syscall/index#Fdatasync") (type . "syscall")) ((name . "syscall.FdSet") (path . "syscall/index#FdSet") (type . "syscall")) ((name . "syscall.Flock()") (path . "syscall/index#Flock") (type . "syscall")) ((name . "syscall.Flock_t") (path . "syscall/index#Flock_t") (type . "syscall")) ((name . "syscall.ForkExec()") (path . "syscall/index#ForkExec") (type . "syscall")) ((name . "syscall.Fsid") (path . "syscall/index#Fsid") (type . "syscall")) ((name . "syscall.Fstat()") (path . "syscall/index#Fstat") (type . "syscall")) ((name . "syscall.Fstatfs()") (path . "syscall/index#Fstatfs") (type . "syscall")) ((name . "syscall.Fsync()") (path . "syscall/index#Fsync") (type . "syscall")) ((name . "syscall.Ftruncate()") (path . "syscall/index#Ftruncate") (type . "syscall")) ((name . "syscall.Futimes()") (path . "syscall/index#Futimes") (type . "syscall")) ((name . "syscall.Futimesat()") (path . "syscall/index#Futimesat") (type . "syscall")) ((name . "syscall.Getcwd()") (path . "syscall/index#Getcwd") (type . "syscall")) ((name . "syscall.Getdents()") (path . "syscall/index#Getdents") (type . "syscall")) ((name . "syscall.Getegid()") (path . "syscall/index#Getegid") (type . "syscall")) ((name . "syscall.Getenv()") (path . "syscall/index#Getenv") (type . "syscall")) ((name . "syscall.Geteuid()") (path . "syscall/index#Geteuid") (type . "syscall")) ((name . "syscall.Getgid()") (path . "syscall/index#Getgid") (type . "syscall")) ((name . "syscall.Getgroups()") (path . "syscall/index#Getgroups") (type . "syscall")) ((name . "syscall.Getpagesize()") (path . "syscall/index#Getpagesize") (type . "syscall")) ((name . "syscall.Getpeername()") (path . "syscall/index#Getpeername") (type . "syscall")) ((name . "syscall.Getpgid()") (path . "syscall/index#Getpgid") (type . "syscall")) ((name . "syscall.Getpgrp()") (path . "syscall/index#Getpgrp") (type . "syscall")) ((name . "syscall.Getpid()") (path . "syscall/index#Getpid") (type . "syscall")) ((name . "syscall.Getppid()") (path . "syscall/index#Getppid") (type . "syscall")) ((name . "syscall.Getpriority()") (path . "syscall/index#Getpriority") (type . "syscall")) ((name . "syscall.Getrlimit()") (path . "syscall/index#Getrlimit") (type . "syscall")) ((name . "syscall.Getrusage()") (path . "syscall/index#Getrusage") (type . "syscall")) ((name . "syscall.Getsockname()") (path . "syscall/index#Getsockname") (type . "syscall")) ((name . "syscall.GetsockoptICMPv6Filter()") (path . "syscall/index#GetsockoptICMPv6Filter") (type . "syscall")) ((name . "syscall.GetsockoptInet4Addr()") (path . "syscall/index#GetsockoptInet4Addr") (type . "syscall")) ((name . "syscall.GetsockoptInt()") (path . "syscall/index#GetsockoptInt") (type . "syscall")) ((name . "syscall.GetsockoptIPMreq()") (path . "syscall/index#GetsockoptIPMreq") (type . "syscall")) ((name . "syscall.GetsockoptIPMreqn()") (path . "syscall/index#GetsockoptIPMreqn") (type . "syscall")) ((name . "syscall.GetsockoptIPv6Mreq()") (path . "syscall/index#GetsockoptIPv6Mreq") (type . "syscall")) ((name . "syscall.GetsockoptIPv6MTUInfo()") (path . "syscall/index#GetsockoptIPv6MTUInfo") (type . "syscall")) ((name . "syscall.GetsockoptUcred()") (path . "syscall/index#GetsockoptUcred") (type . "syscall")) ((name . "syscall.Gettid()") (path . "syscall/index#Gettid") (type . "syscall")) ((name . "syscall.Gettimeofday()") (path . "syscall/index#Gettimeofday") (type . "syscall")) ((name . "syscall.Getuid()") (path . "syscall/index#Getuid") (type . "syscall")) ((name . "syscall.Getwd()") (path . "syscall/index#Getwd") (type . "syscall")) ((name . "syscall.Getxattr()") (path . "syscall/index#Getxattr") (type . "syscall")) ((name . "syscall.ICMPv6Filter") (path . "syscall/index#ICMPv6Filter") (type . "syscall")) ((name . "syscall.IfAddrmsg") (path . "syscall/index#IfAddrmsg") (type . "syscall")) ((name . "syscall.IfInfomsg") (path . "syscall/index#IfInfomsg") (type . "syscall")) ((name . "syscall.Inet4Pktinfo") (path . "syscall/index#Inet4Pktinfo") (type . "syscall")) ((name . "syscall.Inet6Pktinfo") (path . "syscall/index#Inet6Pktinfo") (type . "syscall")) ((name . "syscall.InotifyAddWatch()") (path . "syscall/index#InotifyAddWatch") (type . "syscall")) ((name . "syscall.InotifyEvent") (path . "syscall/index#InotifyEvent") (type . "syscall")) ((name . "syscall.InotifyInit()") (path . "syscall/index#InotifyInit") (type . "syscall")) ((name . "syscall.InotifyInit1()") (path . "syscall/index#InotifyInit1") (type . "syscall")) ((name . "syscall.InotifyRmWatch()") (path . "syscall/index#InotifyRmWatch") (type . "syscall")) ((name . "syscall.Ioperm()") (path . "syscall/index#Ioperm") (type . "syscall")) ((name . "syscall.Iopl()") (path . "syscall/index#Iopl") (type . "syscall")) ((name . "syscall.Iovec") (path . "syscall/index#Iovec") (type . "syscall")) ((name . "syscall.Iovec.SetLen()") (path . "syscall/index#Iovec.SetLen") (type . "syscall")) ((name . "syscall.IPMreq") (path . "syscall/index#IPMreq") (type . "syscall")) ((name . "syscall.IPMreqn") (path . "syscall/index#IPMreqn") (type . "syscall")) ((name . "syscall.IPv6Mreq") (path . "syscall/index#IPv6Mreq") (type . "syscall")) ((name . "syscall.IPv6MTUInfo") (path . "syscall/index#IPv6MTUInfo") (type . "syscall")) ((name . "syscall.Kill()") (path . "syscall/index#Kill") (type . "syscall")) ((name . "syscall.Klogctl()") (path . "syscall/index#Klogctl") (type . "syscall")) ((name . "syscall.Lchown()") (path . "syscall/index#Lchown") (type . "syscall")) ((name . "syscall.Linger") (path . "syscall/index#Linger") (type . "syscall")) ((name . "syscall.Link()") (path . "syscall/index#Link") (type . "syscall")) ((name . "syscall.Listen()") (path . "syscall/index#Listen") (type . "syscall")) ((name . "syscall.Listxattr()") (path . "syscall/index#Listxattr") (type . "syscall")) ((name . "syscall.LsfJump()") (path . "syscall/index#LsfJump") (type . "syscall")) ((name . "syscall.LsfSocket()") (path . "syscall/index#LsfSocket") (type . "syscall")) ((name . "syscall.LsfStmt()") (path . "syscall/index#LsfStmt") (type . "syscall")) ((name . "syscall.Lstat()") (path . "syscall/index#Lstat") (type . "syscall")) ((name . "syscall.Madvise()") (path . "syscall/index#Madvise") (type . "syscall")) ((name . "syscall.Mkdir()") (path . "syscall/index#Mkdir") (type . "syscall")) ((name . "syscall.Mkdirat()") (path . "syscall/index#Mkdirat") (type . "syscall")) ((name . "syscall.Mkfifo()") (path . "syscall/index#Mkfifo") (type . "syscall")) ((name . "syscall.Mknod()") (path . "syscall/index#Mknod") (type . "syscall")) ((name . "syscall.Mknodat()") (path . "syscall/index#Mknodat") (type . "syscall")) ((name . "syscall.Mlock()") (path . "syscall/index#Mlock") (type . "syscall")) ((name . "syscall.Mlockall()") (path . "syscall/index#Mlockall") (type . "syscall")) ((name . "syscall.Mmap()") (path . "syscall/index#Mmap") (type . "syscall")) ((name . "syscall.Mprotect()") (path . "syscall/index#Mprotect") (type . "syscall")) ((name . "syscall.Msghdr") (path . "syscall/index#Msghdr") (type . "syscall")) ((name . "syscall.Msghdr.SetControllen()") (path . "syscall/index#Msghdr.SetControllen") (type . "syscall")) ((name . "syscall.Munlock()") (path . "syscall/index#Munlock") (type . "syscall")) ((name . "syscall.Munlockall()") (path . "syscall/index#Munlockall") (type . "syscall")) ((name . "syscall.Munmap()") (path . "syscall/index#Munmap") (type . "syscall")) ((name . "syscall.Nanosleep()") (path . "syscall/index#Nanosleep") (type . "syscall")) ((name . "syscall.NetlinkMessage") (path . "syscall/index#NetlinkMessage") (type . "syscall")) ((name . "syscall.NetlinkRIB()") (path . "syscall/index#NetlinkRIB") (type . "syscall")) ((name . "syscall.NetlinkRouteAttr") (path . "syscall/index#NetlinkRouteAttr") (type . "syscall")) ((name . "syscall.NetlinkRouteRequest") (path . "syscall/index#NetlinkRouteRequest") (type . "syscall")) ((name . "syscall.NlAttr") (path . "syscall/index#NlAttr") (type . "syscall")) ((name . "syscall.NlMsgerr") (path . "syscall/index#NlMsgerr") (type . "syscall")) ((name . "syscall.NlMsghdr") (path . "syscall/index#NlMsghdr") (type . "syscall")) ((name . "syscall.NsecToTimespec()") (path . "syscall/index#NsecToTimespec") (type . "syscall")) ((name . "syscall.NsecToTimeval()") (path . "syscall/index#NsecToTimeval") (type . "syscall")) ((name . "syscall.Open()") (path . "syscall/index#Open") (type . "syscall")) ((name . "syscall.Openat()") (path . "syscall/index#Openat") (type . "syscall")) ((name . "syscall.ParseDirent()") (path . "syscall/index#ParseDirent") (type . "syscall")) ((name . "syscall.ParseNetlinkMessage()") (path . "syscall/index#ParseNetlinkMessage") (type . "syscall")) ((name . "syscall.ParseNetlinkRouteAttr()") (path . "syscall/index#ParseNetlinkRouteAttr") (type . "syscall")) ((name . "syscall.ParseSocketControlMessage()") (path . "syscall/index#ParseSocketControlMessage") (type . "syscall")) ((name . "syscall.ParseUnixCredentials()") (path . "syscall/index#ParseUnixCredentials") (type . "syscall")) ((name . "syscall.ParseUnixRights()") (path . "syscall/index#ParseUnixRights") (type . "syscall")) ((name . "syscall.Pause()") (path . "syscall/index#Pause") (type . "syscall")) ((name . "syscall.Pipe()") (path . "syscall/index#Pipe") (type . "syscall")) ((name . "syscall.Pipe2()") (path . "syscall/index#Pipe2") (type . "syscall")) ((name . "syscall.PivotRoot()") (path . "syscall/index#PivotRoot") (type . "syscall")) ((name . "syscall.Pread()") (path . "syscall/index#Pread") (type . "syscall")) ((name . "syscall.ProcAttr") (path . "syscall/index#ProcAttr") (type . "syscall")) ((name . "syscall.PtraceAttach()") (path . "syscall/index#PtraceAttach") (type . "syscall")) ((name . "syscall.PtraceCont()") (path . "syscall/index#PtraceCont") (type . "syscall")) ((name . "syscall.PtraceDetach()") (path . "syscall/index#PtraceDetach") (type . "syscall")) ((name . "syscall.PtraceGetEventMsg()") (path . "syscall/index#PtraceGetEventMsg") (type . "syscall")) ((name . "syscall.PtraceGetRegs()") (path . "syscall/index#PtraceGetRegs") (type . "syscall")) ((name . "syscall.PtracePeekData()") (path . "syscall/index#PtracePeekData") (type . "syscall")) ((name . "syscall.PtracePeekText()") (path . "syscall/index#PtracePeekText") (type . "syscall")) ((name . "syscall.PtracePokeData()") (path . "syscall/index#PtracePokeData") (type . "syscall")) ((name . "syscall.PtracePokeText()") (path . "syscall/index#PtracePokeText") (type . "syscall")) ((name . "syscall.PtraceRegs") (path . "syscall/index#PtraceRegs") (type . "syscall")) ((name . "syscall.PtraceRegs.PC()") (path . "syscall/index#PtraceRegs.PC") (type . "syscall")) ((name . "syscall.PtraceRegs.SetPC()") (path . "syscall/index#PtraceRegs.SetPC") (type . "syscall")) ((name . "syscall.PtraceSetOptions()") (path . "syscall/index#PtraceSetOptions") (type . "syscall")) ((name . "syscall.PtraceSetRegs()") (path . "syscall/index#PtraceSetRegs") (type . "syscall")) ((name . "syscall.PtraceSingleStep()") (path . "syscall/index#PtraceSingleStep") (type . "syscall")) ((name . "syscall.PtraceSyscall()") (path . "syscall/index#PtraceSyscall") (type . "syscall")) ((name . "syscall.Pwrite()") (path . "syscall/index#Pwrite") (type . "syscall")) ((name . "syscall.RawConn") (path . "syscall/index#RawConn") (type . "syscall")) ((name . "syscall.RawSockaddr") (path . "syscall/index#RawSockaddr") (type . "syscall")) ((name . "syscall.RawSockaddrAny") (path . "syscall/index#RawSockaddrAny") (type . "syscall")) ((name . "syscall.RawSockaddrInet4") (path . "syscall/index#RawSockaddrInet4") (type . "syscall")) ((name . "syscall.RawSockaddrInet6") (path . "syscall/index#RawSockaddrInet6") (type . "syscall")) ((name . "syscall.RawSockaddrLinklayer") (path . "syscall/index#RawSockaddrLinklayer") (type . "syscall")) ((name . "syscall.RawSockaddrNetlink") (path . "syscall/index#RawSockaddrNetlink") (type . "syscall")) ((name . "syscall.RawSockaddrUnix") (path . "syscall/index#RawSockaddrUnix") (type . "syscall")) ((name . "syscall.RawSyscall()") (path . "syscall/index#RawSyscall") (type . "syscall")) ((name . "syscall.RawSyscall6()") (path . "syscall/index#RawSyscall6") (type . "syscall")) ((name . "syscall.Read()") (path . "syscall/index#Read") (type . "syscall")) ((name . "syscall.ReadDirent()") (path . "syscall/index#ReadDirent") (type . "syscall")) ((name . "syscall.Readlink()") (path . "syscall/index#Readlink") (type . "syscall")) ((name . "syscall.Reboot()") (path . "syscall/index#Reboot") (type . "syscall")) ((name . "syscall.Recvfrom()") (path . "syscall/index#Recvfrom") (type . "syscall")) ((name . "syscall.Recvmsg()") (path . "syscall/index#Recvmsg") (type . "syscall")) ((name . "syscall.Removexattr()") (path . "syscall/index#Removexattr") (type . "syscall")) ((name . "syscall.Rename()") (path . "syscall/index#Rename") (type . "syscall")) ((name . "syscall.Renameat()") (path . "syscall/index#Renameat") (type . "syscall")) ((name . "syscall.Rlimit") (path . "syscall/index#Rlimit") (type . "syscall")) ((name . "syscall.Rmdir()") (path . "syscall/index#Rmdir") (type . "syscall")) ((name . "syscall.RtAttr") (path . "syscall/index#RtAttr") (type . "syscall")) ((name . "syscall.RtGenmsg") (path . "syscall/index#RtGenmsg") (type . "syscall")) ((name . "syscall.RtMsg") (path . "syscall/index#RtMsg") (type . "syscall")) ((name . "syscall.RtNexthop") (path . "syscall/index#RtNexthop") (type . "syscall")) ((name . "syscall.Rusage") (path . "syscall/index#Rusage") (type . "syscall")) ((name . "syscall.Seek()") (path . "syscall/index#Seek") (type . "syscall")) ((name . "syscall.Select()") (path . "syscall/index#Select") (type . "syscall")) ((name . "syscall.Sendfile()") (path . "syscall/index#Sendfile") (type . "syscall")) ((name . "syscall.Sendmsg()") (path . "syscall/index#Sendmsg") (type . "syscall")) ((name . "syscall.SendmsgN()") (path . "syscall/index#SendmsgN") (type . "syscall")) ((name . "syscall.Sendto()") (path . "syscall/index#Sendto") (type . "syscall")) ((name . "syscall.Setdomainname()") (path . "syscall/index#Setdomainname") (type . "syscall")) ((name . "syscall.Setegid()") (path . "syscall/index#Setegid") (type . "syscall")) ((name . "syscall.Setenv()") (path . "syscall/index#Setenv") (type . "syscall")) ((name . "syscall.Seteuid()") (path . "syscall/index#Seteuid") (type . "syscall")) ((name . "syscall.Setfsgid()") (path . "syscall/index#Setfsgid") (type . "syscall")) ((name . "syscall.Setfsuid()") (path . "syscall/index#Setfsuid") (type . "syscall")) ((name . "syscall.Setgid()") (path . "syscall/index#Setgid") (type . "syscall")) ((name . "syscall.Setgroups()") (path . "syscall/index#Setgroups") (type . "syscall")) ((name . "syscall.Sethostname()") (path . "syscall/index#Sethostname") (type . "syscall")) ((name . "syscall.SetLsfPromisc()") (path . "syscall/index#SetLsfPromisc") (type . "syscall")) ((name . "syscall.SetNonblock()") (path . "syscall/index#SetNonblock") (type . "syscall")) ((name . "syscall.Setpgid()") (path . "syscall/index#Setpgid") (type . "syscall")) ((name . "syscall.Setpriority()") (path . "syscall/index#Setpriority") (type . "syscall")) ((name . "syscall.Setregid()") (path . "syscall/index#Setregid") (type . "syscall")) ((name . "syscall.Setresgid()") (path . "syscall/index#Setresgid") (type . "syscall")) ((name . "syscall.Setresuid()") (path . "syscall/index#Setresuid") (type . "syscall")) ((name . "syscall.Setreuid()") (path . "syscall/index#Setreuid") (type . "syscall")) ((name . "syscall.Setrlimit()") (path . "syscall/index#Setrlimit") (type . "syscall")) ((name . "syscall.Setsid()") (path . "syscall/index#Setsid") (type . "syscall")) ((name . "syscall.SetsockoptByte()") (path . "syscall/index#SetsockoptByte") (type . "syscall")) ((name . "syscall.SetsockoptICMPv6Filter()") (path . "syscall/index#SetsockoptICMPv6Filter") (type . "syscall")) ((name . "syscall.SetsockoptInet4Addr()") (path . "syscall/index#SetsockoptInet4Addr") (type . "syscall")) ((name . "syscall.SetsockoptInt()") (path . "syscall/index#SetsockoptInt") (type . "syscall")) ((name . "syscall.SetsockoptIPMreq()") (path . "syscall/index#SetsockoptIPMreq") (type . "syscall")) ((name . "syscall.SetsockoptIPMreqn()") (path . "syscall/index#SetsockoptIPMreqn") (type . "syscall")) ((name . "syscall.SetsockoptIPv6Mreq()") (path . "syscall/index#SetsockoptIPv6Mreq") (type . "syscall")) ((name . "syscall.SetsockoptLinger()") (path . "syscall/index#SetsockoptLinger") (type . "syscall")) ((name . "syscall.SetsockoptString()") (path . "syscall/index#SetsockoptString") (type . "syscall")) ((name . "syscall.SetsockoptTimeval()") (path . "syscall/index#SetsockoptTimeval") (type . "syscall")) ((name . "syscall.Settimeofday()") (path . "syscall/index#Settimeofday") (type . "syscall")) ((name . "syscall.Setuid()") (path . "syscall/index#Setuid") (type . "syscall")) ((name . "syscall.Setxattr()") (path . "syscall/index#Setxattr") (type . "syscall")) ((name . "syscall.Shutdown()") (path . "syscall/index#Shutdown") (type . "syscall")) ((name . "syscall.Signal") (path . "syscall/index#Signal") (type . "syscall")) ((name . "syscall.Signal.Signal()") (path . "syscall/index#Signal.Signal") (type . "syscall")) ((name . "syscall.Signal.String()") (path . "syscall/index#Signal.String") (type . "syscall")) ((name . "syscall.SlicePtrFromStrings()") (path . "syscall/index#SlicePtrFromStrings") (type . "syscall")) ((name . "syscall.Sockaddr") (path . "syscall/index#Sockaddr") (type . "syscall")) ((name . "syscall.SockaddrInet4") (path . "syscall/index#SockaddrInet4") (type . "syscall")) ((name . "syscall.SockaddrInet6") (path . "syscall/index#SockaddrInet6") (type . "syscall")) ((name . "syscall.SockaddrLinklayer") (path . "syscall/index#SockaddrLinklayer") (type . "syscall")) ((name . "syscall.SockaddrNetlink") (path . "syscall/index#SockaddrNetlink") (type . "syscall")) ((name . "syscall.SockaddrUnix") (path . "syscall/index#SockaddrUnix") (type . "syscall")) ((name . "syscall.Socket()") (path . "syscall/index#Socket") (type . "syscall")) ((name . "syscall.SocketControlMessage") (path . "syscall/index#SocketControlMessage") (type . "syscall")) ((name . "syscall.Socketpair()") (path . "syscall/index#Socketpair") (type . "syscall")) ((name . "syscall.SockFilter") (path . "syscall/index#SockFilter") (type . "syscall")) ((name . "syscall.SockFprog") (path . "syscall/index#SockFprog") (type . "syscall")) ((name . "syscall.Splice()") (path . "syscall/index#Splice") (type . "syscall")) ((name . "syscall.StartProcess()") (path . "syscall/index#StartProcess") (type . "syscall")) ((name . "syscall.Stat()") (path . "syscall/index#Stat") (type . "syscall")) ((name . "syscall.Stat_t") (path . "syscall/index#Stat_t") (type . "syscall")) ((name . "syscall.Statfs()") (path . "syscall/index#Statfs") (type . "syscall")) ((name . "syscall.Statfs_t") (path . "syscall/index#Statfs_t") (type . "syscall")) ((name . "syscall.string") (path . "syscall/index#Mount") (type . "syscall")) ((name . "syscall.StringBytePtr()") (path . "syscall/index#StringBytePtr") (type . "syscall")) ((name . "syscall.StringByteSlice()") (path . "syscall/index#StringByteSlice") (type . "syscall")) ((name . "syscall.StringSlicePtr()") (path . "syscall/index#StringSlicePtr") (type . "syscall")) ((name . "syscall.Symlink()") (path . "syscall/index#Symlink") (type . "syscall")) ((name . "syscall.Sync()") (path . "syscall/index#Sync") (type . "syscall")) ((name . "syscall.SyncFileRange()") (path . "syscall/index#SyncFileRange") (type . "syscall")) ((name . "syscall.Syscall()") (path . "syscall/index#Syscall") (type . "syscall")) ((name . "syscall.Syscall6()") (path . "syscall/index#Syscall6") (type . "syscall")) ((name . "syscall.Sysinfo()") (path . "syscall/index#Sysinfo") (type . "syscall")) ((name . "syscall.Sysinfo_t") (path . "syscall/index#Sysinfo_t") (type . "syscall")) ((name . "syscall.SysProcAttr") (path . "syscall/index#SysProcAttr") (type . "syscall")) ((name . "syscall.SysProcIDMap") (path . "syscall/index#SysProcIDMap") (type . "syscall")) ((name . "syscall.TCPInfo") (path . "syscall/index#TCPInfo") (type . "syscall")) ((name . "syscall.Tee()") (path . "syscall/index#Tee") (type . "syscall")) ((name . "syscall.Termios") (path . "syscall/index#Termios") (type . "syscall")) ((name . "syscall.Tgkill()") (path . "syscall/index#Tgkill") (type . "syscall")) ((name . "syscall.Time()") (path . "syscall/index#Time") (type . "syscall")) ((name . "syscall.Time_t") (path . "syscall/index#Time_t") (type . "syscall")) ((name . "syscall.Times()") (path . "syscall/index#Times") (type . "syscall")) ((name . "syscall.Timespec") (path . "syscall/index#Timespec") (type . "syscall")) ((name . "syscall.Timespec.Nano()") (path . "syscall/index#Timespec.Nano") (type . "syscall")) ((name . "syscall.Timespec.Unix()") (path . "syscall/index#Timespec.Unix") (type . "syscall")) ((name . "syscall.TimespecToNsec()") (path . "syscall/index#TimespecToNsec") (type . "syscall")) ((name . "syscall.Timeval") (path . "syscall/index#Timeval") (type . "syscall")) ((name . "syscall.Timeval.Nano()") (path . "syscall/index#Timeval.Nano") (type . "syscall")) ((name . "syscall.Timeval.Unix()") (path . "syscall/index#Timeval.Unix") (type . "syscall")) ((name . "syscall.TimevalToNsec()") (path . "syscall/index#TimevalToNsec") (type . "syscall")) ((name . "syscall.Timex") (path . "syscall/index#Timex") (type . "syscall")) ((name . "syscall.Tms") (path . "syscall/index#Tms") (type . "syscall")) ((name . "syscall.Truncate()") (path . "syscall/index#Truncate") (type . "syscall")) ((name . "syscall.Ucred") (path . "syscall/index#Ucred") (type . "syscall")) ((name . "syscall.Umask()") (path . "syscall/index#Umask") (type . "syscall")) ((name . "syscall.Uname()") (path . "syscall/index#Uname") (type . "syscall")) ((name . "syscall.UnixCredentials()") (path . "syscall/index#UnixCredentials") (type . "syscall")) ((name . "syscall.UnixRights()") (path . "syscall/index#UnixRights") (type . "syscall")) ((name . "syscall.Unlink()") (path . "syscall/index#Unlink") (type . "syscall")) ((name . "syscall.Unlinkat()") (path . "syscall/index#Unlinkat") (type . "syscall")) ((name . "syscall.Unmount()") (path . "syscall/index#Unmount") (type . "syscall")) ((name . "syscall.Unsetenv()") (path . "syscall/index#Unsetenv") (type . "syscall")) ((name . "syscall.Unshare()") (path . "syscall/index#Unshare") (type . "syscall")) ((name . "syscall.Ustat()") (path . "syscall/index#Ustat") (type . "syscall")) ((name . "syscall.Ustat_t") (path . "syscall/index#Ustat_t") (type . "syscall")) ((name . "syscall.Utimbuf") (path . "syscall/index#Utimbuf") (type . "syscall")) ((name . "syscall.Utime()") (path . "syscall/index#Utime") (type . "syscall")) ((name . "syscall.Utimes()") (path . "syscall/index#Utimes") (type . "syscall")) ((name . "syscall.UtimesNano()") (path . "syscall/index#UtimesNano") (type . "syscall")) ((name . "syscall.Utsname") (path . "syscall/index#Utsname") (type . "syscall")) ((name . "syscall.Wait4()") (path . "syscall/index#Wait4") (type . "syscall")) ((name . "syscall.WaitStatus") (path . "syscall/index#WaitStatus") (type . "syscall")) ((name . "syscall.WaitStatus.Continued()") (path . "syscall/index#WaitStatus.Continued") (type . "syscall")) ((name . "syscall.WaitStatus.CoreDump()") (path . "syscall/index#WaitStatus.CoreDump") (type . "syscall")) ((name . "syscall.WaitStatus.Exited()") (path . "syscall/index#WaitStatus.Exited") (type . "syscall")) ((name . "syscall.WaitStatus.ExitStatus()") (path . "syscall/index#WaitStatus.ExitStatus") (type . "syscall")) ((name . "syscall.WaitStatus.Signal()") (path . "syscall/index#WaitStatus.Signal") (type . "syscall")) ((name . "syscall.WaitStatus.Signaled()") (path . "syscall/index#WaitStatus.Signaled") (type . "syscall")) ((name . "syscall.WaitStatus.Stopped()") (path . "syscall/index#WaitStatus.Stopped") (type . "syscall")) ((name . "syscall.WaitStatus.StopSignal()") (path . "syscall/index#WaitStatus.StopSignal") (type . "syscall")) ((name . "syscall.WaitStatus.TrapCause()") (path . "syscall/index#WaitStatus.TrapCause") (type . "syscall")) ((name . "syscall.Write()") (path . "syscall/index#Write") (type . "syscall")) ((name . "syscall/js") (path . "syscall/js/index") (type . "syscall")) ((name . "syslog.Dial()") (path . "log/syslog/index#Dial") (type . "log")) ((name . "syslog.New()") (path . "log/syslog/index#New") (type . "log")) ((name . "syslog.NewLogger()") (path . "log/syslog/index#NewLogger") (type . "log")) ((name . "syslog.Priority") (path . "log/syslog/index#Priority") (type . "log")) ((name . "syslog.Writer") (path . "log/syslog/index#Writer") (type . "log")) ((name . "syslog.Writer.Alert()") (path . "log/syslog/index#Writer.Alert") (type . "log")) ((name . "syslog.Writer.Close()") (path . "log/syslog/index#Writer.Close") (type . "log")) ((name . "syslog.Writer.Crit()") (path . "log/syslog/index#Writer.Crit") (type . "log")) ((name . "syslog.Writer.Debug()") (path . "log/syslog/index#Writer.Debug") (type . "log")) ((name . "syslog.Writer.Emerg()") (path . "log/syslog/index#Writer.Emerg") (type . "log")) ((name . "syslog.Writer.Err()") (path . "log/syslog/index#Writer.Err") (type . "log")) ((name . "syslog.Writer.Info()") (path . "log/syslog/index#Writer.Info") (type . "log")) ((name . "syslog.Writer.Notice()") (path . "log/syslog/index#Writer.Notice") (type . "log")) ((name . "syslog.Writer.Warning()") (path . "log/syslog/index#Writer.Warning") (type . "log")) ((name . "syslog.Writer.Write()") (path . "log/syslog/index#Writer.Write") (type . "log")) ((name . "tabwriter.NewWriter()") (path . "text/tabwriter/index#NewWriter") (type . "text")) ((name . "tabwriter.Writer") (path . "text/tabwriter/index#Writer") (type . "text")) ((name . "tabwriter.Writer.Flush()") (path . "text/tabwriter/index#Writer.Flush") (type . "text")) ((name . "tabwriter.Writer.Init()") (path . "text/tabwriter/index#Writer.Init") (type . "text")) ((name . "tabwriter.Writer.Write()") (path . "text/tabwriter/index#Writer.Write") (type . "text")) ((name . "tar.FileInfoHeader()") (path . "archive/tar/index#FileInfoHeader") (type . "archive")) ((name . "tar.Format") (path . "archive/tar/index#Format") (type . "archive")) ((name . "tar.Format.String()") (path . "archive/tar/index#Format.String") (type . "archive")) ((name . "tar.Header") (path . "archive/tar/index#Header") (type . "archive")) ((name . "tar.Header.FileInfo()") (path . "archive/tar/index#Header.FileInfo") (type . "archive")) ((name . "tar.NewReader()") (path . "archive/tar/index#NewReader") (type . "archive")) ((name . "tar.NewWriter()") (path . "archive/tar/index#NewWriter") (type . "archive")) ((name . "tar.Reader") (path . "archive/tar/index#Reader") (type . "archive")) ((name . "tar.Reader.Next()") (path . "archive/tar/index#Reader.Next") (type . "archive")) ((name . "tar.Reader.Read()") (path . "archive/tar/index#Reader.Read") (type . "archive")) ((name . "tar.Writer") (path . "archive/tar/index#Writer") (type . "archive")) ((name . "tar.Writer.AddFS()") (path . "archive/tar/index#Writer.AddFS") (type . "archive")) ((name . "tar.Writer.Close()") (path . "archive/tar/index#Writer.Close") (type . "archive")) ((name . "tar.Writer.Flush()") (path . "archive/tar/index#Writer.Flush") (type . "archive")) ((name . "tar.Writer.Write()") (path . "archive/tar/index#Writer.Write") (type . "archive")) ((name . "tar.Writer.WriteHeader()") (path . "archive/tar/index#Writer.WriteHeader") (type . "archive")) ((name . "template.CSS") (path . "html/template/index#CSS") (type . "html")) ((name . "template.Error") (path . "html/template/index#Error") (type . "html")) ((name . "template.Error.Error()") (path . "html/template/index#Error.Error") (type . "html")) ((name . "template.ErrorCode") (path . "html/template/index#ErrorCode") (type . "html")) ((name . "template.ExecError") (path . "text/template/index#ExecError") (type . "text")) ((name . "template.ExecError.Error()") (path . "text/template/index#ExecError.Error") (type . "text")) ((name . "template.ExecError.Unwrap()") (path . "text/template/index#ExecError.Unwrap") (type . "text")) ((name . "template.FuncMap") (path . "html/template/index#FuncMap") (type . "html")) ((name . "template.FuncMap") (path . "text/template/index#FuncMap") (type . "text")) ((name . "template.HTML") (path . "html/template/index#HTML") (type . "html")) ((name . "template.HTMLAttr") (path . "html/template/index#HTMLAttr") (type . "html")) ((name . "template.HTMLEscape()") (path . "html/template/index#HTMLEscape") (type . "html")) ((name . "template.HTMLEscape()") (path . "text/template/index#HTMLEscape") (type . "text")) ((name . "template.HTMLEscaper()") (path . "text/template/index#HTMLEscaper") (type . "text")) ((name . "template.HTMLEscaper()") (path . "html/template/index#HTMLEscaper") (type . "html")) ((name . "template.HTMLEscapeString()") (path . "text/template/index#HTMLEscapeString") (type . "text")) ((name . "template.HTMLEscapeString()") (path . "html/template/index#HTMLEscapeString") (type . "html")) ((name . "template.IsTrue()") (path . "html/template/index#IsTrue") (type . "html")) ((name . "template.IsTrue()") (path . "text/template/index#IsTrue") (type . "text")) ((name . "template.JS") (path . "html/template/index#JS") (type . "html")) ((name . "template.JSEscape()") (path . "text/template/index#JSEscape") (type . "text")) ((name . "template.JSEscape()") (path . "html/template/index#JSEscape") (type . "html")) ((name . "template.JSEscaper()") (path . "text/template/index#JSEscaper") (type . "text")) ((name . "template.JSEscaper()") (path . "html/template/index#JSEscaper") (type . "html")) ((name . "template.JSEscapeString()") (path . "text/template/index#JSEscapeString") (type . "text")) ((name . "template.JSEscapeString()") (path . "html/template/index#JSEscapeString") (type . "html")) ((name . "template.JSStr") (path . "html/template/index#JSStr") (type . "html")) ((name . "template.Must()") (path . "text/template/index#Must") (type . "text")) ((name . "template.Must()") (path . "html/template/index#Must") (type . "html")) ((name . "template.New()") (path . "html/template/index#New") (type . "html")) ((name . "template.New()") (path . "text/template/index#New") (type . "text")) ((name . "template.ParseFiles()") (path . "text/template/index#ParseFiles") (type . "text")) ((name . "template.ParseFiles()") (path . "html/template/index#ParseFiles") (type . "html")) ((name . "template.ParseFS()") (path . "html/template/index#ParseFS") (type . "html")) ((name . "template.ParseFS()") (path . "text/template/index#ParseFS") (type . "text")) ((name . "template.ParseGlob()") (path . "html/template/index#ParseGlob") (type . "html")) ((name . "template.ParseGlob()") (path . "text/template/index#ParseGlob") (type . "text")) ((name . "template.Srcset") (path . "html/template/index#Srcset") (type . "html")) ((name . "template.Template") (path . "html/template/index#Template") (type . "html")) ((name . "template.Template") (path . "text/template/index#Template") (type . "text")) ((name . "template.Template.AddParseTree()") (path . "html/template/index#Template.AddParseTree") (type . "html")) ((name . "template.Template.AddParseTree()") (path . "text/template/index#Template.AddParseTree") (type . "text")) ((name . "template.Template.Clone()") (path . "text/template/index#Template.Clone") (type . "text")) ((name . "template.Template.Clone()") (path . "html/template/index#Template.Clone") (type . "html")) ((name . "template.Template.DefinedTemplates()") (path . "text/template/index#Template.DefinedTemplates") (type . "text")) ((name . "template.Template.DefinedTemplates()") (path . "html/template/index#Template.DefinedTemplates") (type . "html")) ((name . "template.Template.Delims()") (path . "text/template/index#Template.Delims") (type . "text")) ((name . "template.Template.Delims()") (path . "html/template/index#Template.Delims") (type . "html")) ((name . "template.Template.Execute()") (path . "html/template/index#Template.Execute") (type . "html")) ((name . "template.Template.Execute()") (path . "text/template/index#Template.Execute") (type . "text")) ((name . "template.Template.ExecuteTemplate()") (path . "html/template/index#Template.ExecuteTemplate") (type . "html")) ((name . "template.Template.ExecuteTemplate()") (path . "text/template/index#Template.ExecuteTemplate") (type . "text")) ((name . "template.Template.Funcs()") (path . "html/template/index#Template.Funcs") (type . "html")) ((name . "template.Template.Funcs()") (path . "text/template/index#Template.Funcs") (type . "text")) ((name . "template.Template.Lookup()") (path . "text/template/index#Template.Lookup") (type . "text")) ((name . "template.Template.Lookup()") (path . "html/template/index#Template.Lookup") (type . "html")) ((name . "template.Template.Name()") (path . "text/template/index#Template.Name") (type . "text")) ((name . "template.Template.Name()") (path . "html/template/index#Template.Name") (type . "html")) ((name . "template.Template.New()") (path . "html/template/index#Template.New") (type . "html")) ((name . "template.Template.New()") (path . "text/template/index#Template.New") (type . "text")) ((name . "template.Template.Option()") (path . "text/template/index#Template.Option") (type . "text")) ((name . "template.Template.Option()") (path . "html/template/index#Template.Option") (type . "html")) ((name . "template.Template.Parse()") (path . "html/template/index#Template.Parse") (type . "html")) ((name . "template.Template.Parse()") (path . "text/template/index#Template.Parse") (type . "text")) ((name . "template.Template.ParseFiles()") (path . "html/template/index#Template.ParseFiles") (type . "html")) ((name . "template.Template.ParseFiles()") (path . "text/template/index#Template.ParseFiles") (type . "text")) ((name . "template.Template.ParseFS()") (path . "text/template/index#Template.ParseFS") (type . "text")) ((name . "template.Template.ParseFS()") (path . "html/template/index#Template.ParseFS") (type . "html")) ((name . "template.Template.ParseGlob()") (path . "html/template/index#Template.ParseGlob") (type . "html")) ((name . "template.Template.ParseGlob()") (path . "text/template/index#Template.ParseGlob") (type . "text")) ((name . "template.Template.Templates()") (path . "text/template/index#Template.Templates") (type . "text")) ((name . "template.Template.Templates()") (path . "html/template/index#Template.Templates") (type . "html")) ((name . "template.URL") (path . "html/template/index#URL") (type . "html")) ((name . "template.URLQueryEscaper()") (path . "html/template/index#URLQueryEscaper") (type . "html")) ((name . "template.URLQueryEscaper()") (path . "text/template/index#URLQueryEscaper") (type . "text")) ((name . "testing") (path . "testing/index") (type . "testing")) ((name . "testing.AllocsPerRun()") (path . "testing/index#AllocsPerRun") (type . "testing")) ((name . "testing.B") (path . "testing/index#B") (type . "testing")) ((name . "testing.B.Cleanup()") (path . "testing/index#B.Cleanup") (type . "testing")) ((name . "testing.B.Elapsed()") (path . "testing/index#B.Elapsed") (type . "testing")) ((name . "testing.B.Error()") (path . "testing/index#B.Error") (type . "testing")) ((name . "testing.B.Errorf()") (path . "testing/index#B.Errorf") (type . "testing")) ((name . "testing.B.Fail()") (path . "testing/index#B.Fail") (type . "testing")) ((name . "testing.B.Failed()") (path . "testing/index#B.Failed") (type . "testing")) ((name . "testing.B.FailNow()") (path . "testing/index#B.FailNow") (type . "testing")) ((name . "testing.B.Fatal()") (path . "testing/index#B.Fatal") (type . "testing")) ((name . "testing.B.Fatalf()") (path . "testing/index#B.Fatalf") (type . "testing")) ((name . "testing.B.Helper()") (path . "testing/index#B.Helper") (type . "testing")) ((name . "testing.B.Log()") (path . "testing/index#B.Log") (type . "testing")) ((name . "testing.B.Logf()") (path . "testing/index#B.Logf") (type . "testing")) ((name . "testing.B.Name()") (path . "testing/index#B.Name") (type . "testing")) ((name . "testing.B.ReportAllocs()") (path . "testing/index#B.ReportAllocs") (type . "testing")) ((name . "testing.B.ReportMetric()") (path . "testing/index#B.ReportMetric") (type . "testing")) ((name . "testing.B.ResetTimer()") (path . "testing/index#B.ResetTimer") (type . "testing")) ((name . "testing.B.Run()") (path . "testing/index#B.Run") (type . "testing")) ((name . "testing.B.RunParallel()") (path . "testing/index#B.RunParallel") (type . "testing")) ((name . "testing.B.SetBytes()") (path . "testing/index#B.SetBytes") (type . "testing")) ((name . "testing.B.Setenv()") (path . "testing/index#B.Setenv") (type . "testing")) ((name . "testing.B.SetParallelism()") (path . "testing/index#B.SetParallelism") (type . "testing")) ((name . "testing.B.Skip()") (path . "testing/index#B.Skip") (type . "testing")) ((name . "testing.B.Skipf()") (path . "testing/index#B.Skipf") (type . "testing")) ((name . "testing.B.SkipNow()") (path . "testing/index#B.SkipNow") (type . "testing")) ((name . "testing.B.Skipped()") (path . "testing/index#B.Skipped") (type . "testing")) ((name . "testing.B.StartTimer()") (path . "testing/index#B.StartTimer") (type . "testing")) ((name . "testing.B.StopTimer()") (path . "testing/index#B.StopTimer") (type . "testing")) ((name . "testing.B.TempDir()") (path . "testing/index#B.TempDir") (type . "testing")) ((name . "testing.Benchmark()") (path . "testing/index#Benchmark") (type . "testing")) ((name . "testing.BenchmarkResult") (path . "testing/index#BenchmarkResult") (type . "testing")) ((name . "testing.BenchmarkResult.AllocedBytesPerOp()") (path . "testing/index#BenchmarkResult.AllocedBytesPerOp") (type . "testing")) ((name . "testing.BenchmarkResult.AllocsPerOp()") (path . "testing/index#BenchmarkResult.AllocsPerOp") (type . "testing")) ((name . "testing.BenchmarkResult.MemString()") (path . "testing/index#BenchmarkResult.MemString") (type . "testing")) ((name . "testing.BenchmarkResult.NsPerOp()") (path . "testing/index#BenchmarkResult.NsPerOp") (type . "testing")) ((name . "testing.BenchmarkResult.String()") (path . "testing/index#BenchmarkResult.String") (type . "testing")) ((name . "testing.Cover") (path . "testing/index#Cover") (type . "testing")) ((name . "testing.Coverage()") (path . "testing/index#Coverage") (type . "testing")) ((name . "testing.CoverBlock") (path . "testing/index#CoverBlock") (type . "testing")) ((name . "testing.CoverMode()") (path . "testing/index#CoverMode") (type . "testing")) ((name . "testing.F") (path . "testing/index#F") (type . "testing")) ((name . "testing.F.Add()") (path . "testing/index#F.Add") (type . "testing")) ((name . "testing.F.Cleanup()") (path . "testing/index#F.Cleanup") (type . "testing")) ((name . "testing.F.Error()") (path . "testing/index#F.Error") (type . "testing")) ((name . "testing.F.Errorf()") (path . "testing/index#F.Errorf") (type . "testing")) ((name . "testing.F.Fail()") (path . "testing/index#F.Fail") (type . "testing")) ((name . "testing.F.Failed()") (path . "testing/index#F.Failed") (type . "testing")) ((name . "testing.F.FailNow()") (path . "testing/index#F.FailNow") (type . "testing")) ((name . "testing.F.Fatal()") (path . "testing/index#F.Fatal") (type . "testing")) ((name . "testing.F.Fatalf()") (path . "testing/index#F.Fatalf") (type . "testing")) ((name . "testing.F.Fuzz()") (path . "testing/index#F.Fuzz") (type . "testing")) ((name . "testing.F.Helper()") (path . "testing/index#F.Helper") (type . "testing")) ((name . "testing.F.Log()") (path . "testing/index#F.Log") (type . "testing")) ((name . "testing.F.Logf()") (path . "testing/index#F.Logf") (type . "testing")) ((name . "testing.F.Name()") (path . "testing/index#F.Name") (type . "testing")) ((name . "testing.F.Setenv()") (path . "testing/index#F.Setenv") (type . "testing")) ((name . "testing.F.Skip()") (path . "testing/index#F.Skip") (type . "testing")) ((name . "testing.F.Skipf()") (path . "testing/index#F.Skipf") (type . "testing")) ((name . "testing.F.SkipNow()") (path . "testing/index#F.SkipNow") (type . "testing")) ((name . "testing.F.Skipped()") (path . "testing/index#F.Skipped") (type . "testing")) ((name . "testing.F.TempDir()") (path . "testing/index#F.TempDir") (type . "testing")) ((name . "testing.Init()") (path . "testing/index#Init") (type . "testing")) ((name . "testing.InternalBenchmark") (path . "testing/index#InternalBenchmark") (type . "testing")) ((name . "testing.InternalExample") (path . "testing/index#InternalExample") (type . "testing")) ((name . "testing.InternalFuzzTarget") (path . "testing/index#InternalFuzzTarget") (type . "testing")) ((name . "testing.InternalTest") (path . "testing/index#InternalTest") (type . "testing")) ((name . "testing.M") (path . "testing/index#M") (type . "testing")) ((name . "testing.M.Run()") (path . "testing/index#M.Run") (type . "testing")) ((name . "testing.Main()") (path . "testing/index#Main") (type . "testing")) ((name . "testing.MainStart()") (path . "testing/index#MainStart") (type . "testing")) ((name . "testing.PB") (path . "testing/index#PB") (type . "testing")) ((name . "testing.PB.Next()") (path . "testing/index#PB.Next") (type . "testing")) ((name . "testing.RegisterCover()") (path . "testing/index#RegisterCover") (type . "testing")) ((name . "testing.RunBenchmarks()") (path . "testing/index#RunBenchmarks") (type . "testing")) ((name . "testing.RunExamples()") (path . "testing/index#RunExamples") (type . "testing")) ((name . "testing.RunTests()") (path . "testing/index#RunTests") (type . "testing")) ((name . "testing.Short()") (path . "testing/index#Short") (type . "testing")) ((name . "testing.T") (path . "testing/index#T") (type . "testing")) ((name . "testing.T.Cleanup()") (path . "testing/index#T.Cleanup") (type . "testing")) ((name . "testing.T.Deadline()") (path . "testing/index#T.Deadline") (type . "testing")) ((name . "testing.T.Error()") (path . "testing/index#T.Error") (type . "testing")) ((name . "testing.T.Errorf()") (path . "testing/index#T.Errorf") (type . "testing")) ((name . "testing.T.Fail()") (path . "testing/index#T.Fail") (type . "testing")) ((name . "testing.T.Failed()") (path . "testing/index#T.Failed") (type . "testing")) ((name . "testing.T.FailNow()") (path . "testing/index#T.FailNow") (type . "testing")) ((name . "testing.T.Fatal()") (path . "testing/index#T.Fatal") (type . "testing")) ((name . "testing.T.Fatalf()") (path . "testing/index#T.Fatalf") (type . "testing")) ((name . "testing.T.Helper()") (path . "testing/index#T.Helper") (type . "testing")) ((name . "testing.T.Log()") (path . "testing/index#T.Log") (type . "testing")) ((name . "testing.T.Logf()") (path . "testing/index#T.Logf") (type . "testing")) ((name . "testing.T.Name()") (path . "testing/index#T.Name") (type . "testing")) ((name . "testing.T.Parallel()") (path . "testing/index#T.Parallel") (type . "testing")) ((name . "testing.T.Run()") (path . "testing/index#T.Run") (type . "testing")) ((name . "testing.T.Setenv()") (path . "testing/index#T.Setenv") (type . "testing")) ((name . "testing.T.Skip()") (path . "testing/index#T.Skip") (type . "testing")) ((name . "testing.T.Skipf()") (path . "testing/index#T.Skipf") (type . "testing")) ((name . "testing.T.SkipNow()") (path . "testing/index#T.SkipNow") (type . "testing")) ((name . "testing.T.Skipped()") (path . "testing/index#T.Skipped") (type . "testing")) ((name . "testing.T.TempDir()") (path . "testing/index#T.TempDir") (type . "testing")) ((name . "testing.TB") (path . "testing/index#TB") (type . "testing")) ((name . "testing.Testing()") (path . "testing/index#Testing") (type . "testing")) ((name . "testing.Verbose()") (path . "testing/index#Verbose") (type . "testing")) ((name . "testing/fstest") (path . "testing/fstest/index") (type . "testing")) ((name . "testing/iotest") (path . "testing/iotest/index") (type . "testing")) ((name . "testing/iotest variables") (path . "testing/iotest/index#pkg-variables") (type . "testing")) ((name . "testing/quick") (path . "testing/quick/index") (type . "testing")) ((name . "testing/slogtest") (path . "testing/slogtest/index") (type . "testing")) ((name . "text/scanner") (path . "text/scanner/index") (type . "text")) ((name . "text/scanner constants") (path . "text/scanner/index#pkg-constants") (type . "text")) ((name . "text/tabwriter") (path . "text/tabwriter/index") (type . "text")) ((name . "text/tabwriter constants") (path . "text/tabwriter/index#pkg-constants") (type . "text")) ((name . "text/template") (path . "text/template/index") (type . "text")) ((name . "text/template/parse") (path . "text/template/parse/index") (type . "text")) ((name . "textproto.CanonicalMIMEHeaderKey()") (path . "net/textproto/index#CanonicalMIMEHeaderKey") (type . "net/textproto")) ((name . "textproto.Conn") (path . "net/textproto/index#Conn") (type . "net/textproto")) ((name . "textproto.Conn.Close()") (path . "net/textproto/index#Conn.Close") (type . "net/textproto")) ((name . "textproto.Conn.Cmd()") (path . "net/textproto/index#Conn.Cmd") (type . "net/textproto")) ((name . "textproto.Dial()") (path . "net/textproto/index#Dial") (type . "net/textproto")) ((name . "textproto.Error") (path . "net/textproto/index#Error") (type . "net/textproto")) ((name . "textproto.Error.Error()") (path . "net/textproto/index#Error.Error") (type . "net/textproto")) ((name . "textproto.MIMEHeader") (path . "net/textproto/index#MIMEHeader") (type . "net/textproto")) ((name . "textproto.MIMEHeader.Add()") (path . "net/textproto/index#MIMEHeader.Add") (type . "net/textproto")) ((name . "textproto.MIMEHeader.Del()") (path . "net/textproto/index#MIMEHeader.Del") (type . "net/textproto")) ((name . "textproto.MIMEHeader.Get()") (path . "net/textproto/index#MIMEHeader.Get") (type . "net/textproto")) ((name . "textproto.MIMEHeader.Set()") (path . "net/textproto/index#MIMEHeader.Set") (type . "net/textproto")) ((name . "textproto.MIMEHeader.Values()") (path . "net/textproto/index#MIMEHeader.Values") (type . "net/textproto")) ((name . "textproto.NewConn()") (path . "net/textproto/index#NewConn") (type . "net/textproto")) ((name . "textproto.NewReader()") (path . "net/textproto/index#NewReader") (type . "net/textproto")) ((name . "textproto.NewWriter()") (path . "net/textproto/index#NewWriter") (type . "net/textproto")) ((name . "textproto.Pipeline") (path . "net/textproto/index#Pipeline") (type . "net/textproto")) ((name . "textproto.Pipeline.EndRequest()") (path . "net/textproto/index#Pipeline.EndRequest") (type . "net/textproto")) ((name . "textproto.Pipeline.EndResponse()") (path . "net/textproto/index#Pipeline.EndResponse") (type . "net/textproto")) ((name . "textproto.Pipeline.Next()") (path . "net/textproto/index#Pipeline.Next") (type . "net/textproto")) ((name . "textproto.Pipeline.StartRequest()") (path . "net/textproto/index#Pipeline.StartRequest") (type . "net/textproto")) ((name . "textproto.Pipeline.StartResponse()") (path . "net/textproto/index#Pipeline.StartResponse") (type . "net/textproto")) ((name . "textproto.ProtocolError") (path . "net/textproto/index#ProtocolError") (type . "net/textproto")) ((name . "textproto.ProtocolError.Error()") (path . "net/textproto/index#ProtocolError.Error") (type . "net/textproto")) ((name . "textproto.Reader") (path . "net/textproto/index#Reader") (type . "net/textproto")) ((name . "textproto.Reader.DotReader()") (path . "net/textproto/index#Reader.DotReader") (type . "net/textproto")) ((name . "textproto.Reader.ReadCodeLine()") (path . "net/textproto/index#Reader.ReadCodeLine") (type . "net/textproto")) ((name . "textproto.Reader.ReadContinuedLine()") (path . "net/textproto/index#Reader.ReadContinuedLine") (type . "net/textproto")) ((name . "textproto.Reader.ReadContinuedLineBytes()") (path . "net/textproto/index#Reader.ReadContinuedLineBytes") (type . "net/textproto")) ((name . "textproto.Reader.ReadDotBytes()") (path . "net/textproto/index#Reader.ReadDotBytes") (type . "net/textproto")) ((name . "textproto.Reader.ReadDotLines()") (path . "net/textproto/index#Reader.ReadDotLines") (type . "net/textproto")) ((name . "textproto.Reader.ReadLine()") (path . "net/textproto/index#Reader.ReadLine") (type . "net/textproto")) ((name . "textproto.Reader.ReadLineBytes()") (path . "net/textproto/index#Reader.ReadLineBytes") (type . "net/textproto")) ((name . "textproto.Reader.ReadMIMEHeader()") (path . "net/textproto/index#Reader.ReadMIMEHeader") (type . "net/textproto")) ((name . "textproto.Reader.ReadResponse()") (path . "net/textproto/index#Reader.ReadResponse") (type . "net/textproto")) ((name . "textproto.TrimBytes()") (path . "net/textproto/index#TrimBytes") (type . "net/textproto")) ((name . "textproto.TrimString()") (path . "net/textproto/index#TrimString") (type . "net/textproto")) ((name . "textproto.Writer") (path . "net/textproto/index#Writer") (type . "net/textproto")) ((name . "textproto.Writer.DotWriter()") (path . "net/textproto/index#Writer.DotWriter") (type . "net/textproto")) ((name . "textproto.Writer.PrintfLine()") (path . "net/textproto/index#Writer.PrintfLine") (type . "net/textproto")) ((name . "time") (path . "time/index") (type . "time")) ((name . "time constants") (path . "time/index#pkg-constants") (type . "time")) ((name . "time.After()") (path . "time/index#After") (type . "time")) ((name . "time.AfterFunc()") (path . "time/index#AfterFunc") (type . "time")) ((name . "time.Date()") (path . "time/index#Date") (type . "time")) ((name . "time.Duration") (path . "time/index#Duration") (type . "time")) ((name . "time.Duration.Abs()") (path . "time/index#Duration.Abs") (type . "time")) ((name . "time.Duration.Hours()") (path . "time/index#Duration.Hours") (type . "time")) ((name . "time.Duration.Microseconds()") (path . "time/index#Duration.Microseconds") (type . "time")) ((name . "time.Duration.Milliseconds()") (path . "time/index#Duration.Milliseconds") (type . "time")) ((name . "time.Duration.Minutes()") (path . "time/index#Duration.Minutes") (type . "time")) ((name . "time.Duration.Nanoseconds()") (path . "time/index#Duration.Nanoseconds") (type . "time")) ((name . "time.Duration.Round()") (path . "time/index#Duration.Round") (type . "time")) ((name . "time.Duration.Seconds()") (path . "time/index#Duration.Seconds") (type . "time")) ((name . "time.Duration.String()") (path . "time/index#Duration.String") (type . "time")) ((name . "time.Duration.Truncate()") (path . "time/index#Duration.Truncate") (type . "time")) ((name . "time.FixedZone()") (path . "time/index#FixedZone") (type . "time")) ((name . "time.LoadLocation()") (path . "time/index#LoadLocation") (type . "time")) ((name . "time.LoadLocationFromTZData()") (path . "time/index#LoadLocationFromTZData") (type . "time")) ((name . "time.Location") (path . "time/index#Location") (type . "time")) ((name . "time.Location.String()") (path . "time/index#Location.String") (type . "time")) ((name . "time.Month") (path . "time/index#Month") (type . "time")) ((name . "time.Month.String()") (path . "time/index#Month.String") (type . "time")) ((name . "time.NewTicker()") (path . "time/index#NewTicker") (type . "time")) ((name . "time.NewTimer()") (path . "time/index#NewTimer") (type . "time")) ((name . "time.Now()") (path . "time/index#Now") (type . "time")) ((name . "time.Parse()") (path . "time/index#Parse") (type . "time")) ((name . "time.ParseDuration()") (path . "time/index#ParseDuration") (type . "time")) ((name . "time.ParseError") (path . "time/index#ParseError") (type . "time")) ((name . "time.ParseError.Error()") (path . "time/index#ParseError.Error") (type . "time")) ((name . "time.ParseInLocation()") (path . "time/index#ParseInLocation") (type . "time")) ((name . "time.Since()") (path . "time/index#Since") (type . "time")) ((name . "time.Sleep()") (path . "time/index#Sleep") (type . "time")) ((name . "time.Tick()") (path . "time/index#Tick") (type . "time")) ((name . "time.Ticker") (path . "time/index#Ticker") (type . "time")) ((name . "time.Ticker.Reset()") (path . "time/index#Ticker.Reset") (type . "time")) ((name . "time.Ticker.Stop()") (path . "time/index#Ticker.Stop") (type . "time")) ((name . "time.Time") (path . "time/index#Time") (type . "time")) ((name . "time.Time.Add()") (path . "time/index#Time.Add") (type . "time")) ((name . "time.Time.AddDate()") (path . "time/index#Time.AddDate") (type . "time")) ((name . "time.Time.After()") (path . "time/index#Time.After") (type . "time")) ((name . "time.Time.AppendFormat()") (path . "time/index#Time.AppendFormat") (type . "time")) ((name . "time.Time.Before()") (path . "time/index#Time.Before") (type . "time")) ((name . "time.Time.Clock()") (path . "time/index#Time.Clock") (type . "time")) ((name . "time.Time.Compare()") (path . "time/index#Time.Compare") (type . "time")) ((name . "time.Time.Date()") (path . "time/index#Time.Date") (type . "time")) ((name . "time.Time.Day()") (path . "time/index#Time.Day") (type . "time")) ((name . "time.Time.Equal()") (path . "time/index#Time.Equal") (type . "time")) ((name . "time.Time.Format()") (path . "time/index#Time.Format") (type . "time")) ((name . "time.Time.GobDecode()") (path . "time/index#Time.GobDecode") (type . "time")) ((name . "time.Time.GobEncode()") (path . "time/index#Time.GobEncode") (type . "time")) ((name . "time.Time.GoString()") (path . "time/index#Time.GoString") (type . "time")) ((name . "time.Time.Hour()") (path . "time/index#Time.Hour") (type . "time")) ((name . "time.Time.In()") (path . "time/index#Time.In") (type . "time")) ((name . "time.Time.IsDST()") (path . "time/index#Time.IsDST") (type . "time")) ((name . "time.Time.ISOWeek()") (path . "time/index#Time.ISOWeek") (type . "time")) ((name . "time.Time.IsZero()") (path . "time/index#Time.IsZero") (type . "time")) ((name . "time.Time.Local()") (path . "time/index#Time.Local") (type . "time")) ((name . "time.Time.Location()") (path . "time/index#Time.Location") (type . "time")) ((name . "time.Time.MarshalBinary()") (path . "time/index#Time.MarshalBinary") (type . "time")) ((name . "time.Time.MarshalJSON()") (path . "time/index#Time.MarshalJSON") (type . "time")) ((name . "time.Time.MarshalText()") (path . "time/index#Time.MarshalText") (type . "time")) ((name . "time.Time.Minute()") (path . "time/index#Time.Minute") (type . "time")) ((name . "time.Time.Month()") (path . "time/index#Time.Month") (type . "time")) ((name . "time.Time.Nanosecond()") (path . "time/index#Time.Nanosecond") (type . "time")) ((name . "time.Time.Round()") (path . "time/index#Time.Round") (type . "time")) ((name . "time.Time.Second()") (path . "time/index#Time.Second") (type . "time")) ((name . "time.Time.String()") (path . "time/index#Time.String") (type . "time")) ((name . "time.Time.Sub()") (path . "time/index#Time.Sub") (type . "time")) ((name . "time.Time.Truncate()") (path . "time/index#Time.Truncate") (type . "time")) ((name . "time.Time.Unix()") (path . "time/index#Time.Unix") (type . "time")) ((name . "time.Time.UnixMicro()") (path . "time/index#Time.UnixMicro") (type . "time")) ((name . "time.Time.UnixMilli()") (path . "time/index#Time.UnixMilli") (type . "time")) ((name . "time.Time.UnixNano()") (path . "time/index#Time.UnixNano") (type . "time")) ((name . "time.Time.UnmarshalBinary()") (path . "time/index#Time.UnmarshalBinary") (type . "time")) ((name . "time.Time.UnmarshalJSON()") (path . "time/index#Time.UnmarshalJSON") (type . "time")) ((name . "time.Time.UnmarshalText()") (path . "time/index#Time.UnmarshalText") (type . "time")) ((name . "time.Time.UTC()") (path . "time/index#Time.UTC") (type . "time")) ((name . "time.Time.Weekday()") (path . "time/index#Time.Weekday") (type . "time")) ((name . "time.Time.Year()") (path . "time/index#Time.Year") (type . "time")) ((name . "time.Time.YearDay()") (path . "time/index#Time.YearDay") (type . "time")) ((name . "time.Time.Zone()") (path . "time/index#Time.Zone") (type . "time")) ((name . "time.Time.ZoneBounds()") (path . "time/index#Time.ZoneBounds") (type . "time")) ((name . "time.Timer") (path . "time/index#Timer") (type . "time")) ((name . "time.Timer.Reset()") (path . "time/index#Timer.Reset") (type . "time")) ((name . "time.Timer.Stop()") (path . "time/index#Timer.Stop") (type . "time")) ((name . "time.Unix()") (path . "time/index#Unix") (type . "time")) ((name . "time.UnixMicro()") (path . "time/index#UnixMicro") (type . "time")) ((name . "time.UnixMilli()") (path . "time/index#UnixMilli") (type . "time")) ((name . "time.Until()") (path . "time/index#Until") (type . "time")) ((name . "time.Weekday") (path . "time/index#Weekday") (type . "time")) ((name . "time.Weekday.String()") (path . "time/index#Weekday.String") (type . "time")) ((name . "time/tzdata") (path . "time/tzdata/index") (type . "time")) ((name . "tls.AlertError") (path . "crypto/tls/index#AlertError") (type . "crypto")) ((name . "tls.AlertError.Error()") (path . "crypto/tls/index#AlertError.Error") (type . "crypto")) ((name . "tls.Certificate") (path . "crypto/tls/index#Certificate") (type . "crypto")) ((name . "tls.CertificateRequestInfo") (path . "crypto/tls/index#CertificateRequestInfo") (type . "crypto")) ((name . "tls.CertificateRequestInfo.Context()") (path . "crypto/tls/index#CertificateRequestInfo.Context") (type . "crypto")) ((name . "tls.CertificateRequestInfo.SupportsCertificate()") (path . "crypto/tls/index#CertificateRequestInfo.SupportsCertificate") (type . "crypto")) ((name . "tls.CertificateVerificationError") (path . "crypto/tls/index#CertificateVerificationError") (type . "crypto")) ((name . "tls.CertificateVerificationError.Error()") (path . "crypto/tls/index#CertificateVerificationError.Error") (type . "crypto")) ((name . "tls.CertificateVerificationError.Unwrap()") (path . "crypto/tls/index#CertificateVerificationError.Unwrap") (type . "crypto")) ((name . "tls.CipherSuite") (path . "crypto/tls/index#CipherSuite") (type . "crypto")) ((name . "tls.CipherSuiteName()") (path . "crypto/tls/index#CipherSuiteName") (type . "crypto")) ((name . "tls.CipherSuites()") (path . "crypto/tls/index#CipherSuites") (type . "crypto")) ((name . "tls.Client()") (path . "crypto/tls/index#Client") (type . "crypto")) ((name . "tls.ClientAuthType") (path . "crypto/tls/index#ClientAuthType") (type . "crypto")) ((name . "tls.ClientAuthType.String()") (path . "crypto/tls/index#ClientAuthType.String") (type . "crypto")) ((name . "tls.ClientHelloInfo") (path . "crypto/tls/index#ClientHelloInfo") (type . "crypto")) ((name . "tls.ClientHelloInfo.Context()") (path . "crypto/tls/index#ClientHelloInfo.Context") (type . "crypto")) ((name . "tls.ClientHelloInfo.SupportsCertificate()") (path . "crypto/tls/index#ClientHelloInfo.SupportsCertificate") (type . "crypto")) ((name . "tls.ClientSessionCache") (path . "crypto/tls/index#ClientSessionCache") (type . "crypto")) ((name . "tls.ClientSessionState") (path . "crypto/tls/index#ClientSessionState") (type . "crypto")) ((name . "tls.ClientSessionState.ResumptionState()") (path . "crypto/tls/index#ClientSessionState.ResumptionState") (type . "crypto")) ((name . "tls.Config") (path . "crypto/tls/index#Config") (type . "crypto")) ((name . "tls.Config.BuildNameToCertificate()") (path . "crypto/tls/index#Config.BuildNameToCertificate") (type . "crypto")) ((name . "tls.Config.Clone()") (path . "crypto/tls/index#Config.Clone") (type . "crypto")) ((name . "tls.Config.DecryptTicket()") (path . "crypto/tls/index#Config.DecryptTicket") (type . "crypto")) ((name . "tls.Config.EncryptTicket()") (path . "crypto/tls/index#Config.EncryptTicket") (type . "crypto")) ((name . "tls.Config.SetSessionTicketKeys()") (path . "crypto/tls/index#Config.SetSessionTicketKeys") (type . "crypto")) ((name . "tls.Conn") (path . "crypto/tls/index#Conn") (type . "crypto")) ((name . "tls.Conn.Close()") (path . "crypto/tls/index#Conn.Close") (type . "crypto")) ((name . "tls.Conn.CloseWrite()") (path . "crypto/tls/index#Conn.CloseWrite") (type . "crypto")) ((name . "tls.Conn.ConnectionState()") (path . "crypto/tls/index#Conn.ConnectionState") (type . "crypto")) ((name . "tls.Conn.Handshake()") (path . "crypto/tls/index#Conn.Handshake") (type . "crypto")) ((name . "tls.Conn.HandshakeContext()") (path . "crypto/tls/index#Conn.HandshakeContext") (type . "crypto")) ((name . "tls.Conn.LocalAddr()") (path . "crypto/tls/index#Conn.LocalAddr") (type . "crypto")) ((name . "tls.Conn.NetConn()") (path . "crypto/tls/index#Conn.NetConn") (type . "crypto")) ((name . "tls.Conn.OCSPResponse()") (path . "crypto/tls/index#Conn.OCSPResponse") (type . "crypto")) ((name . "tls.Conn.Read()") (path . "crypto/tls/index#Conn.Read") (type . "crypto")) ((name . "tls.Conn.RemoteAddr()") (path . "crypto/tls/index#Conn.RemoteAddr") (type . "crypto")) ((name . "tls.Conn.SetDeadline()") (path . "crypto/tls/index#Conn.SetDeadline") (type . "crypto")) ((name . "tls.Conn.SetReadDeadline()") (path . "crypto/tls/index#Conn.SetReadDeadline") (type . "crypto")) ((name . "tls.Conn.SetWriteDeadline()") (path . "crypto/tls/index#Conn.SetWriteDeadline") (type . "crypto")) ((name . "tls.Conn.VerifyHostname()") (path . "crypto/tls/index#Conn.VerifyHostname") (type . "crypto")) ((name . "tls.Conn.Write()") (path . "crypto/tls/index#Conn.Write") (type . "crypto")) ((name . "tls.ConnectionState") (path . "crypto/tls/index#ConnectionState") (type . "crypto")) ((name . "tls.ConnectionState.ExportKeyingMaterial()") (path . "crypto/tls/index#ConnectionState.ExportKeyingMaterial") (type . "crypto")) ((name . "tls.CurveID") (path . "crypto/tls/index#CurveID") (type . "crypto")) ((name . "tls.CurveID.String()") (path . "crypto/tls/index#CurveID.String") (type . "crypto")) ((name . "tls.Dial()") (path . "crypto/tls/index#Dial") (type . "crypto")) ((name . "tls.Dialer") (path . "crypto/tls/index#Dialer") (type . "crypto")) ((name . "tls.Dialer.Dial()") (path . "crypto/tls/index#Dialer.Dial") (type . "crypto")) ((name . "tls.Dialer.DialContext()") (path . "crypto/tls/index#Dialer.DialContext") (type . "crypto")) ((name . "tls.DialWithDialer()") (path . "crypto/tls/index#DialWithDialer") (type . "crypto")) ((name . "tls.InsecureCipherSuites()") (path . "crypto/tls/index#InsecureCipherSuites") (type . "crypto")) ((name . "tls.Listen()") (path . "crypto/tls/index#Listen") (type . "crypto")) ((name . "tls.LoadX509KeyPair()") (path . "crypto/tls/index#LoadX509KeyPair") (type . "crypto")) ((name . "tls.NewListener()") (path . "crypto/tls/index#NewListener") (type . "crypto")) ((name . "tls.NewLRUClientSessionCache()") (path . "crypto/tls/index#NewLRUClientSessionCache") (type . "crypto")) ((name . "tls.NewResumptionState()") (path . "crypto/tls/index#NewResumptionState") (type . "crypto")) ((name . "tls.ParseSessionState()") (path . "crypto/tls/index#ParseSessionState") (type . "crypto")) ((name . "tls.QUICClient()") (path . "crypto/tls/index#QUICClient") (type . "crypto")) ((name . "tls.QUICConfig") (path . "crypto/tls/index#QUICConfig") (type . "crypto")) ((name . "tls.QUICConn") (path . "crypto/tls/index#QUICConn") (type . "crypto")) ((name . "tls.QUICConn.Close()") (path . "crypto/tls/index#QUICConn.Close") (type . "crypto")) ((name . "tls.QUICConn.ConnectionState()") (path . "crypto/tls/index#QUICConn.ConnectionState") (type . "crypto")) ((name . "tls.QUICConn.HandleData()") (path . "crypto/tls/index#QUICConn.HandleData") (type . "crypto")) ((name . "tls.QUICConn.NextEvent()") (path . "crypto/tls/index#QUICConn.NextEvent") (type . "crypto")) ((name . "tls.QUICConn.SendSessionTicket()") (path . "crypto/tls/index#QUICConn.SendSessionTicket") (type . "crypto")) ((name . "tls.QUICConn.SetTransportParameters()") (path . "crypto/tls/index#QUICConn.SetTransportParameters") (type . "crypto")) ((name . "tls.QUICConn.Start()") (path . "crypto/tls/index#QUICConn.Start") (type . "crypto")) ((name . "tls.QUICEncryptionLevel") (path . "crypto/tls/index#QUICEncryptionLevel") (type . "crypto")) ((name . "tls.QUICEncryptionLevel.String()") (path . "crypto/tls/index#QUICEncryptionLevel.String") (type . "crypto")) ((name . "tls.QUICEvent") (path . "crypto/tls/index#QUICEvent") (type . "crypto")) ((name . "tls.QUICEventKind") (path . "crypto/tls/index#QUICEventKind") (type . "crypto")) ((name . "tls.QUICServer()") (path . "crypto/tls/index#QUICServer") (type . "crypto")) ((name . "tls.QUICSessionTicketOptions") (path . "crypto/tls/index#QUICSessionTicketOptions") (type . "crypto")) ((name . "tls.RecordHeaderError") (path . "crypto/tls/index#RecordHeaderError") (type . "crypto")) ((name . "tls.RecordHeaderError.Error()") (path . "crypto/tls/index#RecordHeaderError.Error") (type . "crypto")) ((name . "tls.RenegotiationSupport") (path . "crypto/tls/index#RenegotiationSupport") (type . "crypto")) ((name . "tls.Server()") (path . "crypto/tls/index#Server") (type . "crypto")) ((name . "tls.SessionState") (path . "crypto/tls/index#SessionState") (type . "crypto")) ((name . "tls.SessionState.Bytes()") (path . "crypto/tls/index#SessionState.Bytes") (type . "crypto")) ((name . "tls.SignatureScheme") (path . "crypto/tls/index#SignatureScheme") (type . "crypto")) ((name . "tls.SignatureScheme.String()") (path . "crypto/tls/index#SignatureScheme.String") (type . "crypto")) ((name . "tls.VersionName()") (path . "crypto/tls/index#VersionName") (type . "crypto")) ((name . "tls.X509KeyPair()") (path . "crypto/tls/index#X509KeyPair") (type . "crypto")) ((name . "token.File") (path . "go/token/index#File") (type . "go")) ((name . "token.File.AddLine()") (path . "go/token/index#File.AddLine") (type . "go")) ((name . "token.File.AddLineColumnInfo()") (path . "go/token/index#File.AddLineColumnInfo") (type . "go")) ((name . "token.File.AddLineInfo()") (path . "go/token/index#File.AddLineInfo") (type . "go")) ((name . "token.File.Base()") (path . "go/token/index#File.Base") (type . "go")) ((name . "token.File.Line()") (path . "go/token/index#File.Line") (type . "go")) ((name . "token.File.LineCount()") (path . "go/token/index#File.LineCount") (type . "go")) ((name . "token.File.Lines()") (path . "go/token/index#File.Lines") (type . "go")) ((name . "token.File.LineStart()") (path . "go/token/index#File.LineStart") (type . "go")) ((name . "token.File.MergeLine()") (path . "go/token/index#File.MergeLine") (type . "go")) ((name . "token.File.Name()") (path . "go/token/index#File.Name") (type . "go")) ((name . "token.File.Offset()") (path . "go/token/index#File.Offset") (type . "go")) ((name . "token.File.Pos()") (path . "go/token/index#File.Pos") (type . "go")) ((name . "token.File.Position()") (path . "go/token/index#File.Position") (type . "go")) ((name . "token.File.PositionFor()") (path . "go/token/index#File.PositionFor") (type . "go")) ((name . "token.File.SetLines()") (path . "go/token/index#File.SetLines") (type . "go")) ((name . "token.File.SetLinesForContent()") (path . "go/token/index#File.SetLinesForContent") (type . "go")) ((name . "token.File.Size()") (path . "go/token/index#File.Size") (type . "go")) ((name . "token.FileSet") (path . "go/token/index#FileSet") (type . "go")) ((name . "token.FileSet.AddFile()") (path . "go/token/index#FileSet.AddFile") (type . "go")) ((name . "token.FileSet.Base()") (path . "go/token/index#FileSet.Base") (type . "go")) ((name . "token.FileSet.File()") (path . "go/token/index#FileSet.File") (type . "go")) ((name . "token.FileSet.Iterate()") (path . "go/token/index#FileSet.Iterate") (type . "go")) ((name . "token.FileSet.Position()") (path . "go/token/index#FileSet.Position") (type . "go")) ((name . "token.FileSet.PositionFor()") (path . "go/token/index#FileSet.PositionFor") (type . "go")) ((name . "token.FileSet.Read()") (path . "go/token/index#FileSet.Read") (type . "go")) ((name . "token.FileSet.RemoveFile()") (path . "go/token/index#FileSet.RemoveFile") (type . "go")) ((name . "token.FileSet.Write()") (path . "go/token/index#FileSet.Write") (type . "go")) ((name . "token.IsExported()") (path . "go/token/index#IsExported") (type . "go")) ((name . "token.IsIdentifier()") (path . "go/token/index#IsIdentifier") (type . "go")) ((name . "token.IsKeyword()") (path . "go/token/index#IsKeyword") (type . "go")) ((name . "token.Lookup()") (path . "go/token/index#Lookup") (type . "go")) ((name . "token.NewFileSet()") (path . "go/token/index#NewFileSet") (type . "go")) ((name . "token.Pos") (path . "go/token/index#Pos") (type . "go")) ((name . "token.Pos.IsValid()") (path . "go/token/index#Pos.IsValid") (type . "go")) ((name . "token.Position") (path . "go/token/index#Position") (type . "go")) ((name . "token.Position.IsValid()") (path . "go/token/index#Position.IsValid") (type . "go")) ((name . "token.Position.String()") (path . "go/token/index#Position.String") (type . "go")) ((name . "token.Token") (path . "go/token/index#Token") (type . "go")) ((name . "token.Token.IsKeyword()") (path . "go/token/index#Token.IsKeyword") (type . "go")) ((name . "token.Token.IsLiteral()") (path . "go/token/index#Token.IsLiteral") (type . "go")) ((name . "token.Token.IsOperator()") (path . "go/token/index#Token.IsOperator") (type . "go")) ((name . "token.Token.Precedence()") (path . "go/token/index#Token.Precedence") (type . "go")) ((name . "token.Token.String()") (path . "go/token/index#Token.String") (type . "go")) ((name . "trace.IsEnabled()") (path . "runtime/trace/index#IsEnabled") (type . "runtime")) ((name . "trace.Log()") (path . "runtime/trace/index#Log") (type . "runtime")) ((name . "trace.Logf()") (path . "runtime/trace/index#Logf") (type . "runtime")) ((name . "trace.NewTask()") (path . "runtime/trace/index#NewTask") (type . "runtime")) ((name . "trace.Region") (path . "runtime/trace/index#Region") (type . "runtime")) ((name . "trace.Region.End()") (path . "runtime/trace/index#Region.End") (type . "runtime")) ((name . "trace.Start()") (path . "runtime/trace/index#Start") (type . "runtime")) ((name . "trace.StartRegion()") (path . "runtime/trace/index#StartRegion") (type . "runtime")) ((name . "trace.Stop()") (path . "runtime/trace/index#Stop") (type . "runtime")) ((name . "trace.Task") (path . "runtime/trace/index#Task") (type . "runtime")) ((name . "trace.Task.End()") (path . "runtime/trace/index#Task.End") (type . "runtime")) ((name . "trace.WithRegion()") (path . "runtime/trace/index#WithRegion") (type . "runtime")) ((name . "types.Alias") (path . "go/types/index#Alias") (type . "go")) ((name . "types.Alias.Obj()") (path . "go/types/index#Alias.Obj") (type . "go")) ((name . "types.Alias.String()") (path . "go/types/index#Alias.String") (type . "go")) ((name . "types.Alias.Underlying()") (path . "go/types/index#Alias.Underlying") (type . "go")) ((name . "types.ArgumentError") (path . "go/types/index#ArgumentError") (type . "go")) ((name . "types.ArgumentError.Error()") (path . "go/types/index#ArgumentError.Error") (type . "go")) ((name . "types.ArgumentError.Unwrap()") (path . "go/types/index#ArgumentError.Unwrap") (type . "go")) ((name . "types.Array") (path . "go/types/index#Array") (type . "go")) ((name . "types.Array.Elem()") (path . "go/types/index#Array.Elem") (type . "go")) ((name . "types.Array.Len()") (path . "go/types/index#Array.Len") (type . "go")) ((name . "types.Array.String()") (path . "go/types/index#Array.String") (type . "go")) ((name . "types.Array.Underlying()") (path . "go/types/index#Array.Underlying") (type . "go")) ((name . "types.AssertableTo()") (path . "go/types/index#AssertableTo") (type . "go")) ((name . "types.AssignableTo()") (path . "go/types/index#AssignableTo") (type . "go")) ((name . "types.Basic") (path . "go/types/index#Basic") (type . "go")) ((name . "types.Basic.Info()") (path . "go/types/index#Basic.Info") (type . "go")) ((name . "types.Basic.Kind()") (path . "go/types/index#Basic.Kind") (type . "go")) ((name . "types.Basic.Name()") (path . "go/types/index#Basic.Name") (type . "go")) ((name . "types.Basic.String()") (path . "go/types/index#Basic.String") (type . "go")) ((name . "types.Basic.Underlying()") (path . "go/types/index#Basic.Underlying") (type . "go")) ((name . "types.BasicInfo") (path . "go/types/index#BasicInfo") (type . "go")) ((name . "types.BasicKind") (path . "go/types/index#BasicKind") (type . "go")) ((name . "types.Builtin") (path . "go/types/index#Builtin") (type . "go")) ((name . "types.Builtin.Exported()") (path . "go/types/index#Builtin.Exported") (type . "go")) ((name . "types.Builtin.Id()") (path . "go/types/index#Builtin.Id") (type . "go")) ((name . "types.Builtin.Name()") (path . "go/types/index#Builtin.Name") (type . "go")) ((name . "types.Builtin.Parent()") (path . "go/types/index#Builtin.Parent") (type . "go")) ((name . "types.Builtin.Pkg()") (path . "go/types/index#Builtin.Pkg") (type . "go")) ((name . "types.Builtin.Pos()") (path . "go/types/index#Builtin.Pos") (type . "go")) ((name . "types.Builtin.String()") (path . "go/types/index#Builtin.String") (type . "go")) ((name . "types.Builtin.Type()") (path . "go/types/index#Builtin.Type") (type . "go")) ((name . "types.Chan") (path . "go/types/index#Chan") (type . "go")) ((name . "types.Chan.Dir()") (path . "go/types/index#Chan.Dir") (type . "go")) ((name . "types.Chan.Elem()") (path . "go/types/index#Chan.Elem") (type . "go")) ((name . "types.Chan.String()") (path . "go/types/index#Chan.String") (type . "go")) ((name . "types.Chan.Underlying()") (path . "go/types/index#Chan.Underlying") (type . "go")) ((name . "types.ChanDir") (path . "go/types/index#ChanDir") (type . "go")) ((name . "types.Checker") (path . "go/types/index#Checker") (type . "go")) ((name . "types.Checker.Files()") (path . "go/types/index#Checker.Files") (type . "go")) ((name . "types.CheckExpr()") (path . "go/types/index#CheckExpr") (type . "go")) ((name . "types.Comparable()") (path . "go/types/index#Comparable") (type . "go")) ((name . "types.Config") (path . "go/types/index#Config") (type . "go")) ((name . "types.Config.Check()") (path . "go/types/index#Config.Check") (type . "go")) ((name . "types.Const") (path . "go/types/index#Const") (type . "go")) ((name . "types.Const.Exported()") (path . "go/types/index#Const.Exported") (type . "go")) ((name . "types.Const.Id()") (path . "go/types/index#Const.Id") (type . "go")) ((name . "types.Const.Name()") (path . "go/types/index#Const.Name") (type . "go")) ((name . "types.Const.Parent()") (path . "go/types/index#Const.Parent") (type . "go")) ((name . "types.Const.Pkg()") (path . "go/types/index#Const.Pkg") (type . "go")) ((name . "types.Const.Pos()") (path . "go/types/index#Const.Pos") (type . "go")) ((name . "types.Const.String()") (path . "go/types/index#Const.String") (type . "go")) ((name . "types.Const.Type()") (path . "go/types/index#Const.Type") (type . "go")) ((name . "types.Const.Val()") (path . "go/types/index#Const.Val") (type . "go")) ((name . "types.Context") (path . "go/types/index#Context") (type . "go")) ((name . "types.ConvertibleTo()") (path . "go/types/index#ConvertibleTo") (type . "go")) ((name . "types.Default()") (path . "go/types/index#Default") (type . "go")) ((name . "types.DefPredeclaredTestFuncs()") (path . "go/types/index#DefPredeclaredTestFuncs") (type . "go")) ((name . "types.Error") (path . "go/types/index#Error") (type . "go")) ((name . "types.Error.Error()") (path . "go/types/index#Error.Error") (type . "go")) ((name . "types.Eval()") (path . "go/types/index#Eval") (type . "go")) ((name . "types.ExprString()") (path . "go/types/index#ExprString") (type . "go")) ((name . "types.Func") (path . "go/types/index#Func") (type . "go")) ((name . "types.Func.Exported()") (path . "go/types/index#Func.Exported") (type . "go")) ((name . "types.Func.FullName()") (path . "go/types/index#Func.FullName") (type . "go")) ((name . "types.Func.Id()") (path . "go/types/index#Func.Id") (type . "go")) ((name . "types.Func.Name()") (path . "go/types/index#Func.Name") (type . "go")) ((name . "types.Func.Origin()") (path . "go/types/index#Func.Origin") (type . "go")) ((name . "types.Func.Parent()") (path . "go/types/index#Func.Parent") (type . "go")) ((name . "types.Func.Pkg()") (path . "go/types/index#Func.Pkg") (type . "go")) ((name . "types.Func.Pos()") (path . "go/types/index#Func.Pos") (type . "go")) ((name . "types.Func.Scope()") (path . "go/types/index#Func.Scope") (type . "go")) ((name . "types.Func.String()") (path . "go/types/index#Func.String") (type . "go")) ((name . "types.Func.Type()") (path . "go/types/index#Func.Type") (type . "go")) ((name . "types.Id()") (path . "go/types/index#Id") (type . "go")) ((name . "types.Identical()") (path . "go/types/index#Identical") (type . "go")) ((name . "types.IdenticalIgnoreTags()") (path . "go/types/index#IdenticalIgnoreTags") (type . "go")) ((name . "types.Implements()") (path . "go/types/index#Implements") (type . "go")) ((name . "types.Importer") (path . "go/types/index#Importer") (type . "go")) ((name . "types.ImporterFrom") (path . "go/types/index#ImporterFrom") (type . "go")) ((name . "types.ImportMode") (path . "go/types/index#ImportMode") (type . "go")) ((name . "types.Info") (path . "go/types/index#Info") (type . "go")) ((name . "types.Info.ObjectOf()") (path . "go/types/index#Info.ObjectOf") (type . "go")) ((name . "types.Info.PkgNameOf()") (path . "go/types/index#Info.PkgNameOf") (type . "go")) ((name . "types.Info.TypeOf()") (path . "go/types/index#Info.TypeOf") (type . "go")) ((name . "types.Initializer") (path . "go/types/index#Initializer") (type . "go")) ((name . "types.Initializer.String()") (path . "go/types/index#Initializer.String") (type . "go")) ((name . "types.Instance") (path . "go/types/index#Instance") (type . "go")) ((name . "types.Instantiate()") (path . "go/types/index#Instantiate") (type . "go")) ((name . "types.Interface") (path . "go/types/index#Interface") (type . "go")) ((name . "types.Interface.Complete()") (path . "go/types/index#Interface.Complete") (type . "go")) ((name . "types.Interface.Embedded()") (path . "go/types/index#Interface.Embedded") (type . "go")) ((name . "types.Interface.EmbeddedType()") (path . "go/types/index#Interface.EmbeddedType") (type . "go")) ((name . "types.Interface.Empty()") (path . "go/types/index#Interface.Empty") (type . "go")) ((name . "types.Interface.ExplicitMethod()") (path . "go/types/index#Interface.ExplicitMethod") (type . "go")) ((name . "types.Interface.IsComparable()") (path . "go/types/index#Interface.IsComparable") (type . "go")) ((name . "types.Interface.IsImplicit()") (path . "go/types/index#Interface.IsImplicit") (type . "go")) ((name . "types.Interface.IsMethodSet()") (path . "go/types/index#Interface.IsMethodSet") (type . "go")) ((name . "types.Interface.MarkImplicit()") (path . "go/types/index#Interface.MarkImplicit") (type . "go")) ((name . "types.Interface.Method()") (path . "go/types/index#Interface.Method") (type . "go")) ((name . "types.Interface.NumEmbeddeds()") (path . "go/types/index#Interface.NumEmbeddeds") (type . "go")) ((name . "types.Interface.NumExplicitMethods()") (path . "go/types/index#Interface.NumExplicitMethods") (type . "go")) ((name . "types.Interface.NumMethods()") (path . "go/types/index#Interface.NumMethods") (type . "go")) ((name . "types.Interface.String()") (path . "go/types/index#Interface.String") (type . "go")) ((name . "types.Interface.Underlying()") (path . "go/types/index#Interface.Underlying") (type . "go")) ((name . "types.IsInterface()") (path . "go/types/index#IsInterface") (type . "go")) ((name . "types.Label") (path . "go/types/index#Label") (type . "go")) ((name . "types.Label.Exported()") (path . "go/types/index#Label.Exported") (type . "go")) ((name . "types.Label.Id()") (path . "go/types/index#Label.Id") (type . "go")) ((name . "types.Label.Name()") (path . "go/types/index#Label.Name") (type . "go")) ((name . "types.Label.Parent()") (path . "go/types/index#Label.Parent") (type . "go")) ((name . "types.Label.Pkg()") (path . "go/types/index#Label.Pkg") (type . "go")) ((name . "types.Label.Pos()") (path . "go/types/index#Label.Pos") (type . "go")) ((name . "types.Label.String()") (path . "go/types/index#Label.String") (type . "go")) ((name . "types.Label.Type()") (path . "go/types/index#Label.Type") (type . "go")) ((name . "types.LookupFieldOrMethod()") (path . "go/types/index#LookupFieldOrMethod") (type . "go")) ((name . "types.Map") (path . "go/types/index#Map") (type . "go")) ((name . "types.Map.Elem()") (path . "go/types/index#Map.Elem") (type . "go")) ((name . "types.Map.Key()") (path . "go/types/index#Map.Key") (type . "go")) ((name . "types.Map.String()") (path . "go/types/index#Map.String") (type . "go")) ((name . "types.Map.Underlying()") (path . "go/types/index#Map.Underlying") (type . "go")) ((name . "types.MethodSet") (path . "go/types/index#MethodSet") (type . "go")) ((name . "types.MethodSet.At()") (path . "go/types/index#MethodSet.At") (type . "go")) ((name . "types.MethodSet.Len()") (path . "go/types/index#MethodSet.Len") (type . "go")) ((name . "types.MethodSet.Lookup()") (path . "go/types/index#MethodSet.Lookup") (type . "go")) ((name . "types.MethodSet.String()") (path . "go/types/index#MethodSet.String") (type . "go")) ((name . "types.MissingMethod()") (path . "go/types/index#MissingMethod") (type . "go")) ((name . "types.Named") (path . "go/types/index#Named") (type . "go")) ((name . "types.Named.AddMethod()") (path . "go/types/index#Named.AddMethod") (type . "go")) ((name . "types.Named.Method()") (path . "go/types/index#Named.Method") (type . "go")) ((name . "types.Named.NumMethods()") (path . "go/types/index#Named.NumMethods") (type . "go")) ((name . "types.Named.Obj()") (path . "go/types/index#Named.Obj") (type . "go")) ((name . "types.Named.Origin()") (path . "go/types/index#Named.Origin") (type . "go")) ((name . "types.Named.SetTypeParams()") (path . "go/types/index#Named.SetTypeParams") (type . "go")) ((name . "types.Named.SetUnderlying()") (path . "go/types/index#Named.SetUnderlying") (type . "go")) ((name . "types.Named.String()") (path . "go/types/index#Named.String") (type . "go")) ((name . "types.Named.TypeArgs()") (path . "go/types/index#Named.TypeArgs") (type . "go")) ((name . "types.Named.TypeParams()") (path . "go/types/index#Named.TypeParams") (type . "go")) ((name . "types.Named.Underlying()") (path . "go/types/index#Named.Underlying") (type . "go")) ((name . "types.NewAlias()") (path . "go/types/index#NewAlias") (type . "go")) ((name . "types.NewArray()") (path . "go/types/index#NewArray") (type . "go")) ((name . "types.NewChan()") (path . "go/types/index#NewChan") (type . "go")) ((name . "types.NewChecker()") (path . "go/types/index#NewChecker") (type . "go")) ((name . "types.NewConst()") (path . "go/types/index#NewConst") (type . "go")) ((name . "types.NewContext()") (path . "go/types/index#NewContext") (type . "go")) ((name . "types.NewField()") (path . "go/types/index#NewField") (type . "go")) ((name . "types.NewFunc()") (path . "go/types/index#NewFunc") (type . "go")) ((name . "types.NewInterface()") (path . "go/types/index#NewInterface") (type . "go")) ((name . "types.NewInterfaceType()") (path . "go/types/index#NewInterfaceType") (type . "go")) ((name . "types.NewLabel()") (path . "go/types/index#NewLabel") (type . "go")) ((name . "types.NewMap()") (path . "go/types/index#NewMap") (type . "go")) ((name . "types.NewMethodSet()") (path . "go/types/index#NewMethodSet") (type . "go")) ((name . "types.NewNamed()") (path . "go/types/index#NewNamed") (type . "go")) ((name . "types.NewPackage()") (path . "go/types/index#NewPackage") (type . "go")) ((name . "types.NewParam()") (path . "go/types/index#NewParam") (type . "go")) ((name . "types.NewPkgName()") (path . "go/types/index#NewPkgName") (type . "go")) ((name . "types.NewPointer()") (path . "go/types/index#NewPointer") (type . "go")) ((name . "types.NewScope()") (path . "go/types/index#NewScope") (type . "go")) ((name . "types.NewSignature()") (path . "go/types/index#NewSignature") (type . "go")) ((name . "types.NewSignatureType()") (path . "go/types/index#NewSignatureType") (type . "go")) ((name . "types.NewSlice()") (path . "go/types/index#NewSlice") (type . "go")) ((name . "types.NewStruct()") (path . "go/types/index#NewStruct") (type . "go")) ((name . "types.NewTerm()") (path . "go/types/index#NewTerm") (type . "go")) ((name . "types.NewTuple()") (path . "go/types/index#NewTuple") (type . "go")) ((name . "types.NewTypeName()") (path . "go/types/index#NewTypeName") (type . "go")) ((name . "types.NewTypeParam()") (path . "go/types/index#NewTypeParam") (type . "go")) ((name . "types.NewUnion()") (path . "go/types/index#NewUnion") (type . "go")) ((name . "types.NewVar()") (path . "go/types/index#NewVar") (type . "go")) ((name . "types.Nil") (path . "go/types/index#Nil") (type . "go")) ((name . "types.Nil.Exported()") (path . "go/types/index#Nil.Exported") (type . "go")) ((name . "types.Nil.Id()") (path . "go/types/index#Nil.Id") (type . "go")) ((name . "types.Nil.Name()") (path . "go/types/index#Nil.Name") (type . "go")) ((name . "types.Nil.Parent()") (path . "go/types/index#Nil.Parent") (type . "go")) ((name . "types.Nil.Pkg()") (path . "go/types/index#Nil.Pkg") (type . "go")) ((name . "types.Nil.Pos()") (path . "go/types/index#Nil.Pos") (type . "go")) ((name . "types.Nil.String()") (path . "go/types/index#Nil.String") (type . "go")) ((name . "types.Nil.Type()") (path . "go/types/index#Nil.Type") (type . "go")) ((name . "types.Object") (path . "go/types/index#Object") (type . "go")) ((name . "types.ObjectString()") (path . "go/types/index#ObjectString") (type . "go")) ((name . "types.Package") (path . "go/types/index#Package") (type . "go")) ((name . "types.Package.Complete()") (path . "go/types/index#Package.Complete") (type . "go")) ((name . "types.Package.GoVersion()") (path . "go/types/index#Package.GoVersion") (type . "go")) ((name . "types.Package.Imports()") (path . "go/types/index#Package.Imports") (type . "go")) ((name . "types.Package.MarkComplete()") (path . "go/types/index#Package.MarkComplete") (type . "go")) ((name . "types.Package.Name()") (path . "go/types/index#Package.Name") (type . "go")) ((name . "types.Package.Path()") (path . "go/types/index#Package.Path") (type . "go")) ((name . "types.Package.Scope()") (path . "go/types/index#Package.Scope") (type . "go")) ((name . "types.Package.SetImports()") (path . "go/types/index#Package.SetImports") (type . "go")) ((name . "types.Package.SetName()") (path . "go/types/index#Package.SetName") (type . "go")) ((name . "types.Package.String()") (path . "go/types/index#Package.String") (type . "go")) ((name . "types.PkgName") (path . "go/types/index#PkgName") (type . "go")) ((name . "types.PkgName.Exported()") (path . "go/types/index#PkgName.Exported") (type . "go")) ((name . "types.PkgName.Id()") (path . "go/types/index#PkgName.Id") (type . "go")) ((name . "types.PkgName.Imported()") (path . "go/types/index#PkgName.Imported") (type . "go")) ((name . "types.PkgName.Name()") (path . "go/types/index#PkgName.Name") (type . "go")) ((name . "types.PkgName.Parent()") (path . "go/types/index#PkgName.Parent") (type . "go")) ((name . "types.PkgName.Pkg()") (path . "go/types/index#PkgName.Pkg") (type . "go")) ((name . "types.PkgName.Pos()") (path . "go/types/index#PkgName.Pos") (type . "go")) ((name . "types.PkgName.String()") (path . "go/types/index#PkgName.String") (type . "go")) ((name . "types.PkgName.Type()") (path . "go/types/index#PkgName.Type") (type . "go")) ((name . "types.Pointer") (path . "go/types/index#Pointer") (type . "go")) ((name . "types.Pointer.Elem()") (path . "go/types/index#Pointer.Elem") (type . "go")) ((name . "types.Pointer.String()") (path . "go/types/index#Pointer.String") (type . "go")) ((name . "types.Pointer.Underlying()") (path . "go/types/index#Pointer.Underlying") (type . "go")) ((name . "types.Qualifier") (path . "go/types/index#Qualifier") (type . "go")) ((name . "types.RelativeTo()") (path . "go/types/index#RelativeTo") (type . "go")) ((name . "types.Satisfies()") (path . "go/types/index#Satisfies") (type . "go")) ((name . "types.Scope") (path . "go/types/index#Scope") (type . "go")) ((name . "types.Scope.Child()") (path . "go/types/index#Scope.Child") (type . "go")) ((name . "types.Scope.Contains()") (path . "go/types/index#Scope.Contains") (type . "go")) ((name . "types.Scope.End()") (path . "go/types/index#Scope.End") (type . "go")) ((name . "types.Scope.Innermost()") (path . "go/types/index#Scope.Innermost") (type . "go")) ((name . "types.Scope.Insert()") (path . "go/types/index#Scope.Insert") (type . "go")) ((name . "types.Scope.Len()") (path . "go/types/index#Scope.Len") (type . "go")) ((name . "types.Scope.Lookup()") (path . "go/types/index#Scope.Lookup") (type . "go")) ((name . "types.Scope.LookupParent()") (path . "go/types/index#Scope.LookupParent") (type . "go")) ((name . "types.Scope.Names()") (path . "go/types/index#Scope.Names") (type . "go")) ((name . "types.Scope.NumChildren()") (path . "go/types/index#Scope.NumChildren") (type . "go")) ((name . "types.Scope.Parent()") (path . "go/types/index#Scope.Parent") (type . "go")) ((name . "types.Scope.Pos()") (path . "go/types/index#Scope.Pos") (type . "go")) ((name . "types.Scope.String()") (path . "go/types/index#Scope.String") (type . "go")) ((name . "types.Scope.WriteTo()") (path . "go/types/index#Scope.WriteTo") (type . "go")) ((name . "types.Selection") (path . "go/types/index#Selection") (type . "go")) ((name . "types.Selection.Index()") (path . "go/types/index#Selection.Index") (type . "go")) ((name . "types.Selection.Indirect()") (path . "go/types/index#Selection.Indirect") (type . "go")) ((name . "types.Selection.Kind()") (path . "go/types/index#Selection.Kind") (type . "go")) ((name . "types.Selection.Obj()") (path . "go/types/index#Selection.Obj") (type . "go")) ((name . "types.Selection.Recv()") (path . "go/types/index#Selection.Recv") (type . "go")) ((name . "types.Selection.String()") (path . "go/types/index#Selection.String") (type . "go")) ((name . "types.Selection.Type()") (path . "go/types/index#Selection.Type") (type . "go")) ((name . "types.SelectionKind") (path . "go/types/index#SelectionKind") (type . "go")) ((name . "types.SelectionString()") (path . "go/types/index#SelectionString") (type . "go")) ((name . "types.Signature") (path . "go/types/index#Signature") (type . "go")) ((name . "types.Signature.Params()") (path . "go/types/index#Signature.Params") (type . "go")) ((name . "types.Signature.Recv()") (path . "go/types/index#Signature.Recv") (type . "go")) ((name . "types.Signature.RecvTypeParams()") (path . "go/types/index#Signature.RecvTypeParams") (type . "go")) ((name . "types.Signature.Results()") (path . "go/types/index#Signature.Results") (type . "go")) ((name . "types.Signature.String()") (path . "go/types/index#Signature.String") (type . "go")) ((name . "types.Signature.TypeParams()") (path . "go/types/index#Signature.TypeParams") (type . "go")) ((name . "types.Signature.Underlying()") (path . "go/types/index#Signature.Underlying") (type . "go")) ((name . "types.Signature.Variadic()") (path . "go/types/index#Signature.Variadic") (type . "go")) ((name . "types.Sizes") (path . "go/types/index#Sizes") (type . "go")) ((name . "types.SizesFor()") (path . "go/types/index#SizesFor") (type . "go")) ((name . "types.Slice") (path . "go/types/index#Slice") (type . "go")) ((name . "types.Slice.Elem()") (path . "go/types/index#Slice.Elem") (type . "go")) ((name . "types.Slice.String()") (path . "go/types/index#Slice.String") (type . "go")) ((name . "types.Slice.Underlying()") (path . "go/types/index#Slice.Underlying") (type . "go")) ((name . "types.StdSizes") (path . "go/types/index#StdSizes") (type . "go")) ((name . "types.StdSizes.Alignof()") (path . "go/types/index#StdSizes.Alignof") (type . "go")) ((name . "types.StdSizes.Offsetsof()") (path . "go/types/index#StdSizes.Offsetsof") (type . "go")) ((name . "types.StdSizes.Sizeof()") (path . "go/types/index#StdSizes.Sizeof") (type . "go")) ((name . "types.Struct") (path . "go/types/index#Struct") (type . "go")) ((name . "types.Struct.Field()") (path . "go/types/index#Struct.Field") (type . "go")) ((name . "types.Struct.NumFields()") (path . "go/types/index#Struct.NumFields") (type . "go")) ((name . "types.Struct.String()") (path . "go/types/index#Struct.String") (type . "go")) ((name . "types.Struct.Tag()") (path . "go/types/index#Struct.Tag") (type . "go")) ((name . "types.Struct.Underlying()") (path . "go/types/index#Struct.Underlying") (type . "go")) ((name . "types.Term") (path . "go/types/index#Term") (type . "go")) ((name . "types.Term.String()") (path . "go/types/index#Term.String") (type . "go")) ((name . "types.Term.Tilde()") (path . "go/types/index#Term.Tilde") (type . "go")) ((name . "types.Term.Type()") (path . "go/types/index#Term.Type") (type . "go")) ((name . "types.Tuple") (path . "go/types/index#Tuple") (type . "go")) ((name . "types.Tuple.At()") (path . "go/types/index#Tuple.At") (type . "go")) ((name . "types.Tuple.Len()") (path . "go/types/index#Tuple.Len") (type . "go")) ((name . "types.Tuple.String()") (path . "go/types/index#Tuple.String") (type . "go")) ((name . "types.Tuple.Underlying()") (path . "go/types/index#Tuple.Underlying") (type . "go")) ((name . "types.Type") (path . "go/types/index#Type") (type . "go")) ((name . "types.TypeAndValue") (path . "go/types/index#TypeAndValue") (type . "go")) ((name . "types.TypeAndValue.Addressable()") (path . "go/types/index#TypeAndValue.Addressable") (type . "go")) ((name . "types.TypeAndValue.Assignable()") (path . "go/types/index#TypeAndValue.Assignable") (type . "go")) ((name . "types.TypeAndValue.HasOk()") (path . "go/types/index#TypeAndValue.HasOk") (type . "go")) ((name . "types.TypeAndValue.IsBuiltin()") (path . "go/types/index#TypeAndValue.IsBuiltin") (type . "go")) ((name . "types.TypeAndValue.IsNil()") (path . "go/types/index#TypeAndValue.IsNil") (type . "go")) ((name . "types.TypeAndValue.IsType()") (path . "go/types/index#TypeAndValue.IsType") (type . "go")) ((name . "types.TypeAndValue.IsValue()") (path . "go/types/index#TypeAndValue.IsValue") (type . "go")) ((name . "types.TypeAndValue.IsVoid()") (path . "go/types/index#TypeAndValue.IsVoid") (type . "go")) ((name . "types.TypeList") (path . "go/types/index#TypeList") (type . "go")) ((name . "types.TypeList.At()") (path . "go/types/index#TypeList.At") (type . "go")) ((name . "types.TypeList.Len()") (path . "go/types/index#TypeList.Len") (type . "go")) ((name . "types.TypeName") (path . "go/types/index#TypeName") (type . "go")) ((name . "types.TypeName.Exported()") (path . "go/types/index#TypeName.Exported") (type . "go")) ((name . "types.TypeName.Id()") (path . "go/types/index#TypeName.Id") (type . "go")) ((name . "types.TypeName.IsAlias()") (path . "go/types/index#TypeName.IsAlias") (type . "go")) ((name . "types.TypeName.Name()") (path . "go/types/index#TypeName.Name") (type . "go")) ((name . "types.TypeName.Parent()") (path . "go/types/index#TypeName.Parent") (type . "go")) ((name . "types.TypeName.Pkg()") (path . "go/types/index#TypeName.Pkg") (type . "go")) ((name . "types.TypeName.Pos()") (path . "go/types/index#TypeName.Pos") (type . "go")) ((name . "types.TypeName.String()") (path . "go/types/index#TypeName.String") (type . "go")) ((name . "types.TypeName.Type()") (path . "go/types/index#TypeName.Type") (type . "go")) ((name . "types.TypeParam") (path . "go/types/index#TypeParam") (type . "go")) ((name . "types.TypeParam.Constraint()") (path . "go/types/index#TypeParam.Constraint") (type . "go")) ((name . "types.TypeParam.Index()") (path . "go/types/index#TypeParam.Index") (type . "go")) ((name . "types.TypeParam.Obj()") (path . "go/types/index#TypeParam.Obj") (type . "go")) ((name . "types.TypeParam.SetConstraint()") (path . "go/types/index#TypeParam.SetConstraint") (type . "go")) ((name . "types.TypeParam.String()") (path . "go/types/index#TypeParam.String") (type . "go")) ((name . "types.TypeParam.Underlying()") (path . "go/types/index#TypeParam.Underlying") (type . "go")) ((name . "types.TypeParamList") (path . "go/types/index#TypeParamList") (type . "go")) ((name . "types.TypeParamList.At()") (path . "go/types/index#TypeParamList.At") (type . "go")) ((name . "types.TypeParamList.Len()") (path . "go/types/index#TypeParamList.Len") (type . "go")) ((name . "types.TypeString()") (path . "go/types/index#TypeString") (type . "go")) ((name . "types.Unalias()") (path . "go/types/index#Unalias") (type . "go")) ((name . "types.Union") (path . "go/types/index#Union") (type . "go")) ((name . "types.Union.Len()") (path . "go/types/index#Union.Len") (type . "go")) ((name . "types.Union.String()") (path . "go/types/index#Union.String") (type . "go")) ((name . "types.Union.Term()") (path . "go/types/index#Union.Term") (type . "go")) ((name . "types.Union.Underlying()") (path . "go/types/index#Union.Underlying") (type . "go")) ((name . "types.Var") (path . "go/types/index#Var") (type . "go")) ((name . "types.Var.Anonymous()") (path . "go/types/index#Var.Anonymous") (type . "go")) ((name . "types.Var.Embedded()") (path . "go/types/index#Var.Embedded") (type . "go")) ((name . "types.Var.Exported()") (path . "go/types/index#Var.Exported") (type . "go")) ((name . "types.Var.Id()") (path . "go/types/index#Var.Id") (type . "go")) ((name . "types.Var.IsField()") (path . "go/types/index#Var.IsField") (type . "go")) ((name . "types.Var.Name()") (path . "go/types/index#Var.Name") (type . "go")) ((name . "types.Var.Origin()") (path . "go/types/index#Var.Origin") (type . "go")) ((name . "types.Var.Parent()") (path . "go/types/index#Var.Parent") (type . "go")) ((name . "types.Var.Pkg()") (path . "go/types/index#Var.Pkg") (type . "go")) ((name . "types.Var.Pos()") (path . "go/types/index#Var.Pos") (type . "go")) ((name . "types.Var.String()") (path . "go/types/index#Var.String") (type . "go")) ((name . "types.Var.Type()") (path . "go/types/index#Var.Type") (type . "go")) ((name . "types.WriteExpr()") (path . "go/types/index#WriteExpr") (type . "go")) ((name . "types.WriteSignature()") (path . "go/types/index#WriteSignature") (type . "go")) ((name . "types.WriteType()") (path . "go/types/index#WriteType") (type . "go")) ((name . "unicode") (path . "unicode/index") (type . "unicode")) ((name . "unicode constants") (path . "unicode/index#pkg-constants") (type . "unicode")) ((name . "unicode variables") (path . "unicode/index#pkg-variables") (type . "unicode")) ((name . "unicode.CaseRange") (path . "unicode/index#CaseRange") (type . "unicode")) ((name . "unicode.In()") (path . "unicode/index#In") (type . "unicode")) ((name . "unicode.Is()") (path . "unicode/index#Is") (type . "unicode")) ((name . "unicode.IsControl()") (path . "unicode/index#IsControl") (type . "unicode")) ((name . "unicode.IsDigit()") (path . "unicode/index#IsDigit") (type . "unicode")) ((name . "unicode.IsGraphic()") (path . "unicode/index#IsGraphic") (type . "unicode")) ((name . "unicode.IsLetter()") (path . "unicode/index#IsLetter") (type . "unicode")) ((name . "unicode.IsLower()") (path . "unicode/index#IsLower") (type . "unicode")) ((name . "unicode.IsMark()") (path . "unicode/index#IsMark") (type . "unicode")) ((name . "unicode.IsNumber()") (path . "unicode/index#IsNumber") (type . "unicode")) ((name . "unicode.IsOneOf()") (path . "unicode/index#IsOneOf") (type . "unicode")) ((name . "unicode.IsPrint()") (path . "unicode/index#IsPrint") (type . "unicode")) ((name . "unicode.IsPunct()") (path . "unicode/index#IsPunct") (type . "unicode")) ((name . "unicode.IsSpace()") (path . "unicode/index#IsSpace") (type . "unicode")) ((name . "unicode.IsSymbol()") (path . "unicode/index#IsSymbol") (type . "unicode")) ((name . "unicode.IsTitle()") (path . "unicode/index#IsTitle") (type . "unicode")) ((name . "unicode.IsUpper()") (path . "unicode/index#IsUpper") (type . "unicode")) ((name . "unicode.Range16") (path . "unicode/index#Range16") (type . "unicode")) ((name . "unicode.Range32") (path . "unicode/index#Range32") (type . "unicode")) ((name . "unicode.RangeTable") (path . "unicode/index#RangeTable") (type . "unicode")) ((name . "unicode.SimpleFold()") (path . "unicode/index#SimpleFold") (type . "unicode")) ((name . "unicode.SpecialCase") (path . "unicode/index#SpecialCase") (type . "unicode")) ((name . "unicode.SpecialCase.ToLower()") (path . "unicode/index#SpecialCase.ToLower") (type . "unicode")) ((name . "unicode.SpecialCase.ToTitle()") (path . "unicode/index#SpecialCase.ToTitle") (type . "unicode")) ((name . "unicode.SpecialCase.ToUpper()") (path . "unicode/index#SpecialCase.ToUpper") (type . "unicode")) ((name . "unicode.To()") (path . "unicode/index#To") (type . "unicode")) ((name . "unicode.ToLower()") (path . "unicode/index#ToLower") (type . "unicode")) ((name . "unicode.ToTitle()") (path . "unicode/index#ToTitle") (type . "unicode")) ((name . "unicode.ToUpper()") (path . "unicode/index#ToUpper") (type . "unicode")) ((name . "unicode/utf16") (path . "unicode/utf16/index") (type . "unicode")) ((name . "unicode/utf8") (path . "unicode/utf8/index") (type . "unicode")) ((name . "unicode/utf8 constants") (path . "unicode/utf8/index#pkg-constants") (type . "unicode")) ((name . "unsafe") (path . "unsafe/index") (type . "unsafe")) ((name . "unsafe.Add()") (path . "unsafe/index#Add") (type . "unsafe")) ((name . "unsafe.Alignof()") (path . "unsafe/index#Alignof") (type . "unsafe")) ((name . "unsafe.ArbitraryType") (path . "unsafe/index#ArbitraryType") (type . "unsafe")) ((name . "unsafe.IntegerType") (path . "unsafe/index#IntegerType") (type . "unsafe")) ((name . "unsafe.Offsetof()") (path . "unsafe/index#Offsetof") (type . "unsafe")) ((name . "unsafe.Pointer") (path . "unsafe/index#Pointer") (type . "unsafe")) ((name . "unsafe.Sizeof()") (path . "unsafe/index#Sizeof") (type . "unsafe")) ((name . "unsafe.Slice()") (path . "unsafe/index#Slice") (type . "unsafe")) ((name . "unsafe.SliceData()") (path . "unsafe/index#SliceData") (type . "unsafe")) ((name . "unsafe.String()") (path . "unsafe/index#String") (type . "unsafe")) ((name . "unsafe.StringData()") (path . "unsafe/index#StringData") (type . "unsafe")) ((name . "url.Error") (path . "net/url/index#Error") (type . "net/url")) ((name . "url.Error.Error()") (path . "net/url/index#Error.Error") (type . "net/url")) ((name . "url.Error.Temporary()") (path . "net/url/index#Error.Temporary") (type . "net/url")) ((name . "url.Error.Timeout()") (path . "net/url/index#Error.Timeout") (type . "net/url")) ((name . "url.Error.Unwrap()") (path . "net/url/index#Error.Unwrap") (type . "net/url")) ((name . "url.EscapeError") (path . "net/url/index#EscapeError") (type . "net/url")) ((name . "url.EscapeError.Error()") (path . "net/url/index#EscapeError.Error") (type . "net/url")) ((name . "url.InvalidHostError") (path . "net/url/index#InvalidHostError") (type . "net/url")) ((name . "url.InvalidHostError.Error()") (path . "net/url/index#InvalidHostError.Error") (type . "net/url")) ((name . "url.JoinPath()") (path . "net/url/index#JoinPath") (type . "net/url")) ((name . "url.Parse()") (path . "net/url/index#Parse") (type . "net/url")) ((name . "url.ParseQuery()") (path . "net/url/index#ParseQuery") (type . "net/url")) ((name . "url.ParseRequestURI()") (path . "net/url/index#ParseRequestURI") (type . "net/url")) ((name . "url.PathEscape()") (path . "net/url/index#PathEscape") (type . "net/url")) ((name . "url.PathUnescape()") (path . "net/url/index#PathUnescape") (type . "net/url")) ((name . "url.QueryEscape()") (path . "net/url/index#QueryEscape") (type . "net/url")) ((name . "url.QueryUnescape()") (path . "net/url/index#QueryUnescape") (type . "net/url")) ((name . "url.URL") (path . "net/url/index#URL") (type . "net/url")) ((name . "url.URL.EscapedFragment()") (path . "net/url/index#URL.EscapedFragment") (type . "net/url")) ((name . "url.URL.EscapedPath()") (path . "net/url/index#URL.EscapedPath") (type . "net/url")) ((name . "url.URL.Hostname()") (path . "net/url/index#URL.Hostname") (type . "net/url")) ((name . "url.URL.IsAbs()") (path . "net/url/index#URL.IsAbs") (type . "net/url")) ((name . "url.URL.JoinPath()") (path . "net/url/index#URL.JoinPath") (type . "net/url")) ((name . "url.URL.MarshalBinary()") (path . "net/url/index#URL.MarshalBinary") (type . "net/url")) ((name . "url.URL.Parse()") (path . "net/url/index#URL.Parse") (type . "net/url")) ((name . "url.URL.Port()") (path . "net/url/index#URL.Port") (type . "net/url")) ((name . "url.URL.Query()") (path . "net/url/index#URL.Query") (type . "net/url")) ((name . "url.URL.Redacted()") (path . "net/url/index#URL.Redacted") (type . "net/url")) ((name . "url.URL.RequestURI()") (path . "net/url/index#URL.RequestURI") (type . "net/url")) ((name . "url.URL.ResolveReference()") (path . "net/url/index#URL.ResolveReference") (type . "net/url")) ((name . "url.URL.String()") (path . "net/url/index#URL.String") (type . "net/url")) ((name . "url.URL.UnmarshalBinary()") (path . "net/url/index#URL.UnmarshalBinary") (type . "net/url")) ((name . "url.User()") (path . "net/url/index#User") (type . "net/url")) ((name . "url.Userinfo") (path . "net/url/index#Userinfo") (type . "net/url")) ((name . "url.Userinfo.Password()") (path . "net/url/index#Userinfo.Password") (type . "net/url")) ((name . "url.Userinfo.String()") (path . "net/url/index#Userinfo.String") (type . "net/url")) ((name . "url.Userinfo.Username()") (path . "net/url/index#Userinfo.Username") (type . "net/url")) ((name . "url.UserPassword()") (path . "net/url/index#UserPassword") (type . "net/url")) ((name . "url.Values") (path . "net/url/index#Values") (type . "net/url")) ((name . "url.Values.Add()") (path . "net/url/index#Values.Add") (type . "net/url")) ((name . "url.Values.Del()") (path . "net/url/index#Values.Del") (type . "net/url")) ((name . "url.Values.Encode()") (path . "net/url/index#Values.Encode") (type . "net/url")) ((name . "url.Values.Get()") (path . "net/url/index#Values.Get") (type . "net/url")) ((name . "url.Values.Has()") (path . "net/url/index#Values.Has") (type . "net/url")) ((name . "url.Values.Set()") (path . "net/url/index#Values.Set") (type . "net/url")) ((name . "user.Current()") (path . "os/user/index#Current") (type . "os")) ((name . "user.Group") (path . "os/user/index#Group") (type . "os")) ((name . "user.Lookup()") (path . "os/user/index#Lookup") (type . "os")) ((name . "user.LookupGroup()") (path . "os/user/index#LookupGroup") (type . "os")) ((name . "user.LookupGroupId()") (path . "os/user/index#LookupGroupId") (type . "os")) ((name . "user.LookupId()") (path . "os/user/index#LookupId") (type . "os")) ((name . "user.UnknownGroupError") (path . "os/user/index#UnknownGroupError") (type . "os")) ((name . "user.UnknownGroupError.Error()") (path . "os/user/index#UnknownGroupError.Error") (type . "os")) ((name . "user.UnknownGroupIdError") (path . "os/user/index#UnknownGroupIdError") (type . "os")) ((name . "user.UnknownGroupIdError.Error()") (path . "os/user/index#UnknownGroupIdError.Error") (type . "os")) ((name . "user.UnknownUserError") (path . "os/user/index#UnknownUserError") (type . "os")) ((name . "user.UnknownUserError.Error()") (path . "os/user/index#UnknownUserError.Error") (type . "os")) ((name . "user.UnknownUserIdError") (path . "os/user/index#UnknownUserIdError") (type . "os")) ((name . "user.UnknownUserIdError.Error()") (path . "os/user/index#UnknownUserIdError.Error") (type . "os")) ((name . "user.User") (path . "os/user/index#User") (type . "os")) ((name . "user.User.GroupIds()") (path . "os/user/index#User.GroupIds") (type . "os")) ((name . "utf16.AppendRune()") (path . "unicode/utf16/index#AppendRune") (type . "unicode")) ((name . "utf16.Decode()") (path . "unicode/utf16/index#Decode") (type . "unicode")) ((name . "utf16.DecodeRune()") (path . "unicode/utf16/index#DecodeRune") (type . "unicode")) ((name . "utf16.Encode()") (path . "unicode/utf16/index#Encode") (type . "unicode")) ((name . "utf16.EncodeRune()") (path . "unicode/utf16/index#EncodeRune") (type . "unicode")) ((name . "utf16.IsSurrogate()") (path . "unicode/utf16/index#IsSurrogate") (type . "unicode")) ((name . "utf8.AppendRune()") (path . "unicode/utf8/index#AppendRune") (type . "unicode")) ((name . "utf8.DecodeLastRune()") (path . "unicode/utf8/index#DecodeLastRune") (type . "unicode")) ((name . "utf8.DecodeLastRuneInString()") (path . "unicode/utf8/index#DecodeLastRuneInString") (type . "unicode")) ((name . "utf8.DecodeRune()") (path . "unicode/utf8/index#DecodeRune") (type . "unicode")) ((name . "utf8.DecodeRuneInString()") (path . "unicode/utf8/index#DecodeRuneInString") (type . "unicode")) ((name . "utf8.EncodeRune()") (path . "unicode/utf8/index#EncodeRune") (type . "unicode")) ((name . "utf8.FullRune()") (path . "unicode/utf8/index#FullRune") (type . "unicode")) ((name . "utf8.FullRuneInString()") (path . "unicode/utf8/index#FullRuneInString") (type . "unicode")) ((name . "utf8.RuneCount()") (path . "unicode/utf8/index#RuneCount") (type . "unicode")) ((name . "utf8.RuneCountInString()") (path . "unicode/utf8/index#RuneCountInString") (type . "unicode")) ((name . "utf8.RuneLen()") (path . "unicode/utf8/index#RuneLen") (type . "unicode")) ((name . "utf8.RuneStart()") (path . "unicode/utf8/index#RuneStart") (type . "unicode")) ((name . "utf8.Valid()") (path . "unicode/utf8/index#Valid") (type . "unicode")) ((name . "utf8.ValidRune()") (path . "unicode/utf8/index#ValidRune") (type . "unicode")) ((name . "utf8.ValidString()") (path . "unicode/utf8/index#ValidString") (type . "unicode")) ((name . "v2.ChaCha8") (path . "math/rand/v2/index#ChaCha8") (type . "math/rand")) ((name . "v2.ChaCha8.MarshalBinary()") (path . "math/rand/v2/index#ChaCha8.MarshalBinary") (type . "math/rand")) ((name . "v2.ChaCha8.Seed()") (path . "math/rand/v2/index#ChaCha8.Seed") (type . "math/rand")) ((name . "v2.ChaCha8.Uint64()") (path . "math/rand/v2/index#ChaCha8.Uint64") (type . "math/rand")) ((name . "v2.ChaCha8.UnmarshalBinary()") (path . "math/rand/v2/index#ChaCha8.UnmarshalBinary") (type . "math/rand")) ((name . "v2.ExpFloat64()") (path . "math/rand/v2/index#ExpFloat64") (type . "math/rand")) ((name . "v2.Float32()") (path . "math/rand/v2/index#Float32") (type . "math/rand")) ((name . "v2.Float64()") (path . "math/rand/v2/index#Float64") (type . "math/rand")) ((name . "v2.Int()") (path . "math/rand/v2/index#Int") (type . "math/rand")) ((name . "v2.Int32()") (path . "math/rand/v2/index#Int32") (type . "math/rand")) ((name . "v2.Int32N()") (path . "math/rand/v2/index#Int32N") (type . "math/rand")) ((name . "v2.Int64()") (path . "math/rand/v2/index#Int64") (type . "math/rand")) ((name . "v2.Int64N()") (path . "math/rand/v2/index#Int64N") (type . "math/rand")) ((name . "v2.IntN()") (path . "math/rand/v2/index#IntN") (type . "math/rand")) ((name . "v2.N()") (path . "math/rand/v2/index#N") (type . "math/rand")) ((name . "v2.New()") (path . "math/rand/v2/index#New") (type . "math/rand")) ((name . "v2.NewChaCha8()") (path . "math/rand/v2/index#NewChaCha8") (type . "math/rand")) ((name . "v2.NewPCG()") (path . "math/rand/v2/index#NewPCG") (type . "math/rand")) ((name . "v2.NewZipf()") (path . "math/rand/v2/index#NewZipf") (type . "math/rand")) ((name . "v2.NormFloat64()") (path . "math/rand/v2/index#NormFloat64") (type . "math/rand")) ((name . "v2.PCG") (path . "math/rand/v2/index#PCG") (type . "math/rand")) ((name . "v2.PCG.MarshalBinary()") (path . "math/rand/v2/index#PCG.MarshalBinary") (type . "math/rand")) ((name . "v2.PCG.Seed()") (path . "math/rand/v2/index#PCG.Seed") (type . "math/rand")) ((name . "v2.PCG.Uint64()") (path . "math/rand/v2/index#PCG.Uint64") (type . "math/rand")) ((name . "v2.PCG.UnmarshalBinary()") (path . "math/rand/v2/index#PCG.UnmarshalBinary") (type . "math/rand")) ((name . "v2.Perm()") (path . "math/rand/v2/index#Perm") (type . "math/rand")) ((name . "v2.Rand") (path . "math/rand/v2/index#Rand") (type . "math/rand")) ((name . "v2.Rand.ExpFloat64()") (path . "math/rand/v2/index#Rand.ExpFloat64") (type . "math/rand")) ((name . "v2.Rand.Float32()") (path . "math/rand/v2/index#Rand.Float32") (type . "math/rand")) ((name . "v2.Rand.Float64()") (path . "math/rand/v2/index#Rand.Float64") (type . "math/rand")) ((name . "v2.Rand.Int()") (path . "math/rand/v2/index#Rand.Int") (type . "math/rand")) ((name . "v2.Rand.Int32()") (path . "math/rand/v2/index#Rand.Int32") (type . "math/rand")) ((name . "v2.Rand.Int32N()") (path . "math/rand/v2/index#Rand.Int32N") (type . "math/rand")) ((name . "v2.Rand.Int64()") (path . "math/rand/v2/index#Rand.Int64") (type . "math/rand")) ((name . "v2.Rand.Int64N()") (path . "math/rand/v2/index#Rand.Int64N") (type . "math/rand")) ((name . "v2.Rand.IntN()") (path . "math/rand/v2/index#Rand.IntN") (type . "math/rand")) ((name . "v2.Rand.NormFloat64()") (path . "math/rand/v2/index#Rand.NormFloat64") (type . "math/rand")) ((name . "v2.Rand.Perm()") (path . "math/rand/v2/index#Rand.Perm") (type . "math/rand")) ((name . "v2.Rand.Shuffle()") (path . "math/rand/v2/index#Rand.Shuffle") (type . "math/rand")) ((name . "v2.Rand.Uint32()") (path . "math/rand/v2/index#Rand.Uint32") (type . "math/rand")) ((name . "v2.Rand.Uint32N()") (path . "math/rand/v2/index#Rand.Uint32N") (type . "math/rand")) ((name . "v2.Rand.Uint64()") (path . "math/rand/v2/index#Rand.Uint64") (type . "math/rand")) ((name . "v2.Rand.Uint64N()") (path . "math/rand/v2/index#Rand.Uint64N") (type . "math/rand")) ((name . "v2.Rand.UintN()") (path . "math/rand/v2/index#Rand.UintN") (type . "math/rand")) ((name . "v2.Shuffle()") (path . "math/rand/v2/index#Shuffle") (type . "math/rand")) ((name . "v2.Source") (path . "math/rand/v2/index#Source") (type . "math/rand")) ((name . "v2.Uint32()") (path . "math/rand/v2/index#Uint32") (type . "math/rand")) ((name . "v2.Uint32N()") (path . "math/rand/v2/index#Uint32N") (type . "math/rand")) ((name . "v2.Uint64()") (path . "math/rand/v2/index#Uint64") (type . "math/rand")) ((name . "v2.Uint64N()") (path . "math/rand/v2/index#Uint64N") (type . "math/rand")) ((name . "v2.UintN()") (path . "math/rand/v2/index#UintN") (type . "math/rand")) ((name . "v2.Zipf") (path . "math/rand/v2/index#Zipf") (type . "math/rand")) ((name . "v2.Zipf.Uint64()") (path . "math/rand/v2/index#Zipf.Uint64") (type . "math/rand")) ((name . "version.Compare()") (path . "go/version/index#Compare") (type . "go")) ((name . "version.IsValid()") (path . "go/version/index#IsValid") (type . "go")) ((name . "version.Lang()") (path . "go/version/index#Lang") (type . "go")) ((name . "x509.Certificate") (path . "crypto/x509/index#Certificate") (type . "crypto")) ((name . "x509.Certificate.CheckCRLSignature()") (path . "crypto/x509/index#Certificate.CheckCRLSignature") (type . "crypto")) ((name . "x509.Certificate.CheckSignature()") (path . "crypto/x509/index#Certificate.CheckSignature") (type . "crypto")) ((name . "x509.Certificate.CheckSignatureFrom()") (path . "crypto/x509/index#Certificate.CheckSignatureFrom") (type . "crypto")) ((name . "x509.Certificate.CreateCRL()") (path . "crypto/x509/index#Certificate.CreateCRL") (type . "crypto")) ((name . "x509.Certificate.Equal()") (path . "crypto/x509/index#Certificate.Equal") (type . "crypto")) ((name . "x509.Certificate.Verify()") (path . "crypto/x509/index#Certificate.Verify") (type . "crypto")) ((name . "x509.Certificate.VerifyHostname()") (path . "crypto/x509/index#Certificate.VerifyHostname") (type . "crypto")) ((name . "x509.CertificateInvalidError") (path . "crypto/x509/index#CertificateInvalidError") (type . "crypto")) ((name . "x509.CertificateInvalidError.Error()") (path . "crypto/x509/index#CertificateInvalidError.Error") (type . "crypto")) ((name . "x509.CertificateRequest") (path . "crypto/x509/index#CertificateRequest") (type . "crypto")) ((name . "x509.CertificateRequest.CheckSignature()") (path . "crypto/x509/index#CertificateRequest.CheckSignature") (type . "crypto")) ((name . "x509.CertPool") (path . "crypto/x509/index#CertPool") (type . "crypto")) ((name . "x509.CertPool.AddCert()") (path . "crypto/x509/index#CertPool.AddCert") (type . "crypto")) ((name . "x509.CertPool.AddCertWithConstraint()") (path . "crypto/x509/index#CertPool.AddCertWithConstraint") (type . "crypto")) ((name . "x509.CertPool.AppendCertsFromPEM()") (path . "crypto/x509/index#CertPool.AppendCertsFromPEM") (type . "crypto")) ((name . "x509.CertPool.Clone()") (path . "crypto/x509/index#CertPool.Clone") (type . "crypto")) ((name . "x509.CertPool.Equal()") (path . "crypto/x509/index#CertPool.Equal") (type . "crypto")) ((name . "x509.CertPool.Subjects()") (path . "crypto/x509/index#CertPool.Subjects") (type . "crypto")) ((name . "x509.ConstraintViolationError") (path . "crypto/x509/index#ConstraintViolationError") (type . "crypto")) ((name . "x509.ConstraintViolationError.Error()") (path . "crypto/x509/index#ConstraintViolationError.Error") (type . "crypto")) ((name . "x509.CreateCertificate()") (path . "crypto/x509/index#CreateCertificate") (type . "crypto")) ((name . "x509.CreateCertificateRequest()") (path . "crypto/x509/index#CreateCertificateRequest") (type . "crypto")) ((name . "x509.CreateRevocationList()") (path . "crypto/x509/index#CreateRevocationList") (type . "crypto")) ((name . "x509.DecryptPEMBlock()") (path . "crypto/x509/index#DecryptPEMBlock") (type . "crypto")) ((name . "x509.EncryptPEMBlock()") (path . "crypto/x509/index#EncryptPEMBlock") (type . "crypto")) ((name . "x509.ExtKeyUsage") (path . "crypto/x509/index#ExtKeyUsage") (type . "crypto")) ((name . "x509.HostnameError") (path . "crypto/x509/index#HostnameError") (type . "crypto")) ((name . "x509.HostnameError.Error()") (path . "crypto/x509/index#HostnameError.Error") (type . "crypto")) ((name . "x509.InsecureAlgorithmError") (path . "crypto/x509/index#InsecureAlgorithmError") (type . "crypto")) ((name . "x509.InsecureAlgorithmError.Error()") (path . "crypto/x509/index#InsecureAlgorithmError.Error") (type . "crypto")) ((name . "x509.InvalidReason") (path . "crypto/x509/index#InvalidReason") (type . "crypto")) ((name . "x509.IsEncryptedPEMBlock()") (path . "crypto/x509/index#IsEncryptedPEMBlock") (type . "crypto")) ((name . "x509.KeyUsage") (path . "crypto/x509/index#KeyUsage") (type . "crypto")) ((name . "x509.MarshalECPrivateKey()") (path . "crypto/x509/index#MarshalECPrivateKey") (type . "crypto")) ((name . "x509.MarshalPKCS1PrivateKey()") (path . "crypto/x509/index#MarshalPKCS1PrivateKey") (type . "crypto")) ((name . "x509.MarshalPKCS1PublicKey()") (path . "crypto/x509/index#MarshalPKCS1PublicKey") (type . "crypto")) ((name . "x509.MarshalPKCS8PrivateKey()") (path . "crypto/x509/index#MarshalPKCS8PrivateKey") (type . "crypto")) ((name . "x509.MarshalPKIXPublicKey()") (path . "crypto/x509/index#MarshalPKIXPublicKey") (type . "crypto")) ((name . "x509.NewCertPool()") (path . "crypto/x509/index#NewCertPool") (type . "crypto")) ((name . "x509.OID") (path . "crypto/x509/index#OID") (type . "crypto")) ((name . "x509.OID.Equal()") (path . "crypto/x509/index#OID.Equal") (type . "crypto")) ((name . "x509.OID.EqualASN1OID()") (path . "crypto/x509/index#OID.EqualASN1OID") (type . "crypto")) ((name . "x509.OID.String()") (path . "crypto/x509/index#OID.String") (type . "crypto")) ((name . "x509.OIDFromInts()") (path . "crypto/x509/index#OIDFromInts") (type . "crypto")) ((name . "x509.ParseCertificate()") (path . "crypto/x509/index#ParseCertificate") (type . "crypto")) ((name . "x509.ParseCertificateRequest()") (path . "crypto/x509/index#ParseCertificateRequest") (type . "crypto")) ((name . "x509.ParseCertificates()") (path . "crypto/x509/index#ParseCertificates") (type . "crypto")) ((name . "x509.ParseCRL()") (path . "crypto/x509/index#ParseCRL") (type . "crypto")) ((name . "x509.ParseDERCRL()") (path . "crypto/x509/index#ParseDERCRL") (type . "crypto")) ((name . "x509.ParseECPrivateKey()") (path . "crypto/x509/index#ParseECPrivateKey") (type . "crypto")) ((name . "x509.ParsePKCS1PrivateKey()") (path . "crypto/x509/index#ParsePKCS1PrivateKey") (type . "crypto")) ((name . "x509.ParsePKCS1PublicKey()") (path . "crypto/x509/index#ParsePKCS1PublicKey") (type . "crypto")) ((name . "x509.ParsePKCS8PrivateKey()") (path . "crypto/x509/index#ParsePKCS8PrivateKey") (type . "crypto")) ((name . "x509.ParsePKIXPublicKey()") (path . "crypto/x509/index#ParsePKIXPublicKey") (type . "crypto")) ((name . "x509.ParseRevocationList()") (path . "crypto/x509/index#ParseRevocationList") (type . "crypto")) ((name . "x509.PEMCipher") (path . "crypto/x509/index#PEMCipher") (type . "crypto")) ((name . "x509.PublicKeyAlgorithm") (path . "crypto/x509/index#PublicKeyAlgorithm") (type . "crypto")) ((name . "x509.PublicKeyAlgorithm.String()") (path . "crypto/x509/index#PublicKeyAlgorithm.String") (type . "crypto")) ((name . "x509.RevocationList") (path . "crypto/x509/index#RevocationList") (type . "crypto")) ((name . "x509.RevocationList.CheckSignatureFrom()") (path . "crypto/x509/index#RevocationList.CheckSignatureFrom") (type . "crypto")) ((name . "x509.RevocationListEntry") (path . "crypto/x509/index#RevocationListEntry") (type . "crypto")) ((name . "x509.SetFallbackRoots()") (path . "crypto/x509/index#SetFallbackRoots") (type . "crypto")) ((name . "x509.SignatureAlgorithm") (path . "crypto/x509/index#SignatureAlgorithm") (type . "crypto")) ((name . "x509.SignatureAlgorithm.String()") (path . "crypto/x509/index#SignatureAlgorithm.String") (type . "crypto")) ((name . "x509.SystemCertPool()") (path . "crypto/x509/index#SystemCertPool") (type . "crypto")) ((name . "x509.SystemRootsError") (path . "crypto/x509/index#SystemRootsError") (type . "crypto")) ((name . "x509.SystemRootsError.Error()") (path . "crypto/x509/index#SystemRootsError.Error") (type . "crypto")) ((name . "x509.SystemRootsError.Unwrap()") (path . "crypto/x509/index#SystemRootsError.Unwrap") (type . "crypto")) ((name . "x509.UnhandledCriticalExtension") (path . "crypto/x509/index#UnhandledCriticalExtension") (type . "crypto")) ((name . "x509.UnhandledCriticalExtension.Error()") (path . "crypto/x509/index#UnhandledCriticalExtension.Error") (type . "crypto")) ((name . "x509.UnknownAuthorityError") (path . "crypto/x509/index#UnknownAuthorityError") (type . "crypto")) ((name . "x509.UnknownAuthorityError.Error()") (path . "crypto/x509/index#UnknownAuthorityError.Error") (type . "crypto")) ((name . "x509.VerifyOptions") (path . "crypto/x509/index#VerifyOptions") (type . "crypto")) ((name . "xml.Attr") (path . "encoding/xml/index#Attr") (type . "encoding")) ((name . "xml.CharData") (path . "encoding/xml/index#CharData") (type . "encoding")) ((name . "xml.CharData.Copy()") (path . "encoding/xml/index#CharData.Copy") (type . "encoding")) ((name . "xml.Comment") (path . "encoding/xml/index#Comment") (type . "encoding")) ((name . "xml.Comment.Copy()") (path . "encoding/xml/index#Comment.Copy") (type . "encoding")) ((name . "xml.CopyToken()") (path . "encoding/xml/index#CopyToken") (type . "encoding")) ((name . "xml.Decoder") (path . "encoding/xml/index#Decoder") (type . "encoding")) ((name . "xml.Decoder.Decode()") (path . "encoding/xml/index#Decoder.Decode") (type . "encoding")) ((name . "xml.Decoder.DecodeElement()") (path . "encoding/xml/index#Decoder.DecodeElement") (type . "encoding")) ((name . "xml.Decoder.InputOffset()") (path . "encoding/xml/index#Decoder.InputOffset") (type . "encoding")) ((name . "xml.Decoder.InputPos()") (path . "encoding/xml/index#Decoder.InputPos") (type . "encoding")) ((name . "xml.Decoder.RawToken()") (path . "encoding/xml/index#Decoder.RawToken") (type . "encoding")) ((name . "xml.Decoder.Skip()") (path . "encoding/xml/index#Decoder.Skip") (type . "encoding")) ((name . "xml.Decoder.Token()") (path . "encoding/xml/index#Decoder.Token") (type . "encoding")) ((name . "xml.Directive") (path . "encoding/xml/index#Directive") (type . "encoding")) ((name . "xml.Directive.Copy()") (path . "encoding/xml/index#Directive.Copy") (type . "encoding")) ((name . "xml.Encoder") (path . "encoding/xml/index#Encoder") (type . "encoding")) ((name . "xml.Encoder.Close()") (path . "encoding/xml/index#Encoder.Close") (type . "encoding")) ((name . "xml.Encoder.Encode()") (path . "encoding/xml/index#Encoder.Encode") (type . "encoding")) ((name . "xml.Encoder.EncodeElement()") (path . "encoding/xml/index#Encoder.EncodeElement") (type . "encoding")) ((name . "xml.Encoder.EncodeToken()") (path . "encoding/xml/index#Encoder.EncodeToken") (type . "encoding")) ((name . "xml.Encoder.Flush()") (path . "encoding/xml/index#Encoder.Flush") (type . "encoding")) ((name . "xml.Encoder.Indent()") (path . "encoding/xml/index#Encoder.Indent") (type . "encoding")) ((name . "xml.EndElement") (path . "encoding/xml/index#EndElement") (type . "encoding")) ((name . "xml.Escape()") (path . "encoding/xml/index#Escape") (type . "encoding")) ((name . "xml.EscapeText()") (path . "encoding/xml/index#EscapeText") (type . "encoding")) ((name . "xml.Marshal()") (path . "encoding/xml/index#Marshal") (type . "encoding")) ((name . "xml.Marshaler") (path . "encoding/xml/index#Marshaler") (type . "encoding")) ((name . "xml.MarshalerAttr") (path . "encoding/xml/index#MarshalerAttr") (type . "encoding")) ((name . "xml.MarshalIndent()") (path . "encoding/xml/index#MarshalIndent") (type . "encoding")) ((name . "xml.Name") (path . "encoding/xml/index#Name") (type . "encoding")) ((name . "xml.NewDecoder()") (path . "encoding/xml/index#NewDecoder") (type . "encoding")) ((name . "xml.NewEncoder()") (path . "encoding/xml/index#NewEncoder") (type . "encoding")) ((name . "xml.NewTokenDecoder()") (path . "encoding/xml/index#NewTokenDecoder") (type . "encoding")) ((name . "xml.ProcInst") (path . "encoding/xml/index#ProcInst") (type . "encoding")) ((name . "xml.ProcInst.Copy()") (path . "encoding/xml/index#ProcInst.Copy") (type . "encoding")) ((name . "xml.StartElement") (path . "encoding/xml/index#StartElement") (type . "encoding")) ((name . "xml.StartElement.Copy()") (path . "encoding/xml/index#StartElement.Copy") (type . "encoding")) ((name . "xml.StartElement.End()") (path . "encoding/xml/index#StartElement.End") (type . "encoding")) ((name . "xml.SyntaxError") (path . "encoding/xml/index#SyntaxError") (type . "encoding")) ((name . "xml.SyntaxError.Error()") (path . "encoding/xml/index#SyntaxError.Error") (type . "encoding")) ((name . "xml.TagPathError") (path . "encoding/xml/index#TagPathError") (type . "encoding")) ((name . "xml.TagPathError.Error()") (path . "encoding/xml/index#TagPathError.Error") (type . "encoding")) ((name . "xml.Token") (path . "encoding/xml/index#Token") (type . "encoding")) ((name . "xml.TokenReader") (path . "encoding/xml/index#TokenReader") (type . "encoding")) ((name . "xml.Unmarshal()") (path . "encoding/xml/index#Unmarshal") (type . "encoding")) ((name . "xml.Unmarshaler") (path . "encoding/xml/index#Unmarshaler") (type . "encoding")) ((name . "xml.UnmarshalerAttr") (path . "encoding/xml/index#UnmarshalerAttr") (type . "encoding")) ((name . "xml.UnmarshalError") (path . "encoding/xml/index#UnmarshalError") (type . "encoding")) ((name . "xml.UnmarshalError.Error()") (path . "encoding/xml/index#UnmarshalError.Error") (type . "encoding")) ((name . "xml.UnsupportedTypeError") (path . "encoding/xml/index#UnsupportedTypeError") (type . "encoding")) ((name . "xml.UnsupportedTypeError.Error()") (path . "encoding/xml/index#UnsupportedTypeError.Error") (type . "encoding")) ((name . "zip.Compressor") (path . "archive/zip/index#Compressor") (type . "archive")) ((name . "zip.Decompressor") (path . "archive/zip/index#Decompressor") (type . "archive")) ((name . "zip.File") (path . "archive/zip/index#File") (type . "archive")) ((name . "zip.File.DataOffset()") (path . "archive/zip/index#File.DataOffset") (type . "archive")) ((name . "zip.File.Open()") (path . "archive/zip/index#File.Open") (type . "archive")) ((name . "zip.File.OpenRaw()") (path . "archive/zip/index#File.OpenRaw") (type . "archive")) ((name . "zip.FileHeader") (path . "archive/zip/index#FileHeader") (type . "archive")) ((name . "zip.FileHeader.FileInfo()") (path . "archive/zip/index#FileHeader.FileInfo") (type . "archive")) ((name . "zip.FileHeader.Mode()") (path . "archive/zip/index#FileHeader.Mode") (type . "archive")) ((name . "zip.FileHeader.ModTime()") (path . "archive/zip/index#FileHeader.ModTime") (type . "archive")) ((name . "zip.FileHeader.SetMode()") (path . "archive/zip/index#FileHeader.SetMode") (type . "archive")) ((name . "zip.FileHeader.SetModTime()") (path . "archive/zip/index#FileHeader.SetModTime") (type . "archive")) ((name . "zip.FileInfoHeader()") (path . "archive/zip/index#FileInfoHeader") (type . "archive")) ((name . "zip.NewReader()") (path . "archive/zip/index#NewReader") (type . "archive")) ((name . "zip.NewWriter()") (path . "archive/zip/index#NewWriter") (type . "archive")) ((name . "zip.OpenReader()") (path . "archive/zip/index#OpenReader") (type . "archive")) ((name . "zip.ReadCloser") (path . "archive/zip/index#ReadCloser") (type . "archive")) ((name . "zip.ReadCloser.Close()") (path . "archive/zip/index#ReadCloser.Close") (type . "archive")) ((name . "zip.Reader") (path . "archive/zip/index#Reader") (type . "archive")) ((name . "zip.Reader.Open()") (path . "archive/zip/index#Reader.Open") (type . "archive")) ((name . "zip.Reader.RegisterDecompressor()") (path . "archive/zip/index#Reader.RegisterDecompressor") (type . "archive")) ((name . "zip.RegisterCompressor()") (path . "archive/zip/index#RegisterCompressor") (type . "archive")) ((name . "zip.RegisterDecompressor()") (path . "archive/zip/index#RegisterDecompressor") (type . "archive")) ((name . "zip.Writer") (path . "archive/zip/index#Writer") (type . "archive")) ((name . "zip.Writer.AddFS()") (path . "archive/zip/index#Writer.AddFS") (type . "archive")) ((name . "zip.Writer.Close()") (path . "archive/zip/index#Writer.Close") (type . "archive")) ((name . "zip.Writer.Copy()") (path . "archive/zip/index#Writer.Copy") (type . "archive")) ((name . "zip.Writer.Create()") (path . "archive/zip/index#Writer.Create") (type . "archive")) ((name . "zip.Writer.CreateHeader()") (path . "archive/zip/index#Writer.CreateHeader") (type . "archive")) ((name . "zip.Writer.CreateRaw()") (path . "archive/zip/index#Writer.CreateRaw") (type . "archive")) ((name . "zip.Writer.Flush()") (path . "archive/zip/index#Writer.Flush") (type . "archive")) ((name . "zip.Writer.RegisterCompressor()") (path . "archive/zip/index#Writer.RegisterCompressor") (type . "archive")) ((name . "zip.Writer.SetComment()") (path . "archive/zip/index#Writer.SetComment") (type . "archive")) ((name . "zip.Writer.SetOffset()") (path . "archive/zip/index#Writer.SetOffset") (type . "archive")) ((name . "zlib.NewReader()") (path . "compress/zlib/index#NewReader") (type . "compress")) ((name . "zlib.NewReaderDict()") (path . "compress/zlib/index#NewReaderDict") (type . "compress")) ((name . "zlib.NewWriter()") (path . "compress/zlib/index#NewWriter") (type . "compress")) ((name . "zlib.NewWriterLevel()") (path . "compress/zlib/index#NewWriterLevel") (type . "compress")) ((name . "zlib.NewWriterLevelDict()") (path . "compress/zlib/index#NewWriterLevelDict") (type . "compress")) ((name . "zlib.Resetter") (path . "compress/zlib/index#Resetter") (type . "compress")) ((name . "zlib.Writer") (path . "compress/zlib/index#Writer") (type . "compress")) ((name . "zlib.Writer.Close()") (path . "compress/zlib/index#Writer.Close") (type . "compress")) ((name . "zlib.Writer.Flush()") (path . "compress/zlib/index#Writer.Flush") (type . "compress")) ((name . "zlib.Writer.Reset()") (path . "compress/zlib/index#Writer.Reset") (type . "compress")) ((name . "zlib.Writer.Write()") (path . "compress/zlib/index#Writer.Write") (type . "compress"))]) (types . [((name . "archive") (count . 56) (slug . "archive")) ((name . "arena") (count . 1) (slug . "arena")) ((name . "bufio") (count . 50) (slug . "bufio")) ((name . "builtin") (count . 48) (slug . "builtin")) ((name . "bytes") (count . 94) (slug . "bytes")) ((name . "cmp") (count . 5) (slug . "cmp")) ((name . "compress") (count . 68) (slug . "compress")) ((name . "container") (count . 38) (slug . "container")) ((name . "context") (count . 17) (slug . "context")) ((name . "crypto") (count . 377) (slug . "crypto")) ((name . "database") (count . 156) (slug . "database")) ((name . "debug") (count . 379) (slug . "debug")) ((name . "embed") (count . 5) (slug . "embed")) ((name . "encoding") (count . 245) (slug . "encoding")) ((name . "errors") (count . 7) (slug . "errors")) ((name . "expvar") (count . 37) (slug . "expvar")) ((name . "flag") (count . 76) (slug . "flag")) ((name . "fmt") (count . 30) (slug . "fmt")) ((name . "go") (count . 754) (slug . "go")) ((name . "hash") (count . 48) (slug . "hash")) ((name . "html") (count . 45) (slug . "html")) ((name . "image") (count . 276) (slug . "image")) ((name . "index") (count . 8) (slug . "index")) ((name . "internal") (count . 5) (slug . "internal")) ((name . "io") (count . 102) (slug . "io")) ((name . "iter") (count . 1) (slug . "iter")) ((name . "log") (count . 162) (slug . "log")) ((name . "maps") (count . 6) (slug . "maps")) ((name . "math") (count . 69) (slug . "math")) ((name . "math/big") (count . 152) (slug . "math-big")) ((name . "math/bits") (count . 51) (slug . "math-bits")) ((name . "math/cmplx") (count . 28) (slug . "math-cmplx")) ((name . "math/rand") (count . 95) (slug . "math-rand")) ((name . "mime") (count . 48) (slug . "mime")) ((name . "net") (count . 258) (slug . "net")) ((name . "net/http") (count . 228) (slug . "net-http")) ((name . "net/mail") (count . 16) (slug . "net-mail")) ((name . "net/netip") (count . 74) (slug . "net-netip")) ((name . "net/rpc") (count . 42) (slug . "net-rpc")) ((name . "net/smtp") (count . 22) (slug . "net-smtp")) ((name . "net/textproto") (count . 41) (slug . "net-textproto")) ((name . "net/url") (count . 46) (slug . "net-url")) ((name . "os") (count . 161) (slug . "os")) ((name . "path") (count . 34) (slug . "path")) ((name . "plugin") (count . 5) (slug . "plugin")) ((name . "reflect") (count . 128) (slug . "reflect")) ((name . "regexp") (count . 79) (slug . "regexp")) ((name . "runtime") (count . 139) (slug . "runtime")) ((name . "slices") (count . 31) (slug . "slices")) ((name . "sort") (count . 38) (slug . "sort")) ((name . "strconv") (count . 40) (slug . "strconv")) ((name . "strings") (count . 78) (slug . "strings")) ((name . "sync") (count . 116) (slug . "sync")) ((name . "syscall") (count . 366) (slug . "syscall")) ((name . "testing") (count . 140) (slug . "testing")) ((name . "text") (count . 140) (slug . "text")) ((name . "time") (count . 93) (slug . "time")) ((name . "unicode") (count . 56) (slug . "unicode")) ((name . "unsafe") (count . 12) (slug . "unsafe"))])) \ No newline at end of file diff --git a/devdocs/go/index%2Fsuffixarray%2Findex.html b/devdocs/go/index%2Fsuffixarray%2Findex.html new file mode 100644 index 00000000..39fab1b8 --- /dev/null +++ b/devdocs/go/index%2Fsuffixarray%2Findex.html @@ -0,0 +1,50 @@ +

Package suffixarray

Overview

Package suffixarray implements substring search in logarithmic time using an in-memory suffix array.

+

Example use:

+
// create index for some data
+index := suffixarray.New(data)
+
+// lookup byte slice s
+offsets1 := index.Lookup(s, -1) // the list of all indices where s occurs in data
+offsets2 := index.Lookup(s, 3)  // the list of at most 3 indices where s occurs in data
+

Index

Examples

Index.Lookup

Package files

sais.go sais2.go suffixarray.go

type Index

Index implements a suffix array for fast substring search.

+
type Index struct {
+    // contains filtered or unexported fields
+}
+

func New

func New(data []byte) *Index

New creates a new Index for data. Index creation time is O(N) for N = len(data).

+

func (*Index) Bytes

func (x *Index) Bytes() []byte

Bytes returns the data over which the index was created. It must not be modified.

+

func (*Index) FindAllIndex

func (x *Index) FindAllIndex(r *regexp.Regexp, n int) (result [][]int)

FindAllIndex returns a sorted list of non-overlapping matches of the regular expression r, where a match is a pair of indices specifying the matched slice of x.Bytes(). If n < 0, all matches are returned in successive order. Otherwise, at most n matches are returned and they may not be successive. The result is nil if there are no matches, or if n == 0.

+

func (*Index) Lookup

func (x *Index) Lookup(s []byte, n int) (result []int)

Lookup returns an unsorted list of at most n indices where the byte string s occurs in the indexed data. If n < 0, all occurrences are returned. The result is nil if s is empty, s is not found, or n == 0. Lookup time is O(log(N)*len(s) + len(result)) where N is the size of the indexed data.

Example +

Code:

index := suffixarray.New([]byte("banana"))
+offsets := index.Lookup([]byte("ana"), -1)
+for _, off := range offsets {
+    fmt.Println(off)
+}
+
+

Output:

1
+3
+

func (*Index) Read

func (x *Index) Read(r io.Reader) error

Read reads the index from r into x; x must not be nil.

+

func (*Index) Write

func (x *Index) Write(w io.Writer) error

Write writes the index x to w.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/index/suffixarray/ +

+
diff --git a/devdocs/go/index.html b/devdocs/go/index.html new file mode 100644 index 00000000..74e0c2ee --- /dev/null +++ b/devdocs/go/index.html @@ -0,0 +1,29 @@ +

Go Programming Language

Standard library

Name
tar
zip
arena
bufio
builtin
bytes
cmp
compress
bzip2
flate
gzip
lzw
zlib
container
heap
list
ring
context
crypto
aes
boring
cipher
des
dsa
ecdh
ecdsa
ed25519
elliptic
hmac
md5
rand
rc4
rsa
sha1
sha256
sha512
subtle
tls
fipsonly
x509
pkix
database
sql
driver
debug
buildinfo
dwarf
elf
gosym
macho
pe
plan9obj
embed
encoding
ascii85
asn1
base32
base64
binary
csv
gob
hex
json
pem
xml
errors
expvar
flag
fmt
go
ast
build
constraint
constant
doc
comment
format
importer
parser
printer
scanner
token
types
version
hash
adler32
crc32
crc64
fnv
maphash
html
template
image
color
palette
draw
gif
jpeg
png
index
suffixarray
io
fs
ioutil
iter
log
slog
syslog
maps
math
big
bits
cmplx
rand
v2
mime
multipart
quotedprintable
net
http
cgi
cookiejar
fcgi
httptest
httptrace
httputil
pprof
mail
netip
rpc
jsonrpc
smtp
textproto
url
os
exec
signal
user
path
filepath
plugin
reflect
regexp
syntax
runtime
asan
cgo
coverage
debug
metrics
msan
pprof
race
trace
slices
sort
strconv
strings
sync
atomic
syscall
js
testing
fstest
iotest
quick
slogtest
text
scanner
tabwriter
template
parse
time
tzdata
unicode
utf16
utf8
unsafe

Other packages

Sub-repositories

These packages are part of the Go Project but outside the main Go tree. They are developed under looser compatibility requirements than the Go core. Install them with "go get".

Community

These services can help you find Open Source packages provided by the community.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg// +

+
diff --git a/devdocs/go/internal%2Fgoarch%2Findex.html b/devdocs/go/internal%2Fgoarch%2Findex.html new file mode 100644 index 00000000..e7fa752f --- /dev/null +++ b/devdocs/go/internal%2Fgoarch%2Findex.html @@ -0,0 +1,33 @@ +

Package goarch

Overview

package goarch contains GOARCH-specific constants.

Index

Package files

goarch.go goarch_amd64.go zgoarch_amd64.go

Constants

BigEndian reports whether the architecture is big-endian.

+
const BigEndian = IsArmbe|IsArm64be|IsMips|IsMips64|IsPpc|IsPpc64|IsS390|IsS390x|IsSparc|IsSparc64 == 1

DefaultPhysPageSize is the default physical page size.

+
const DefaultPhysPageSize = _DefaultPhysPageSize
const GOARCH = `amd64`

Int64Align is the required alignment for a 64-bit integer (4 on 32-bit systems, 8 on 64-bit).

+
const Int64Align = PtrSize
const Is386 = 0
const IsAmd64 = 1
const IsAmd64p32 = 0
const IsArm = 0
const IsArm64 = 0
const IsArm64be = 0
const IsArmbe = 0
const IsLoong64 = 0
const IsMips = 0
const IsMips64 = 0
const IsMips64le = 0
const IsMips64p32 = 0
const IsMips64p32le = 0
const IsMipsle = 0
const IsPpc = 0
const IsPpc64 = 0
const IsPpc64le = 0
const IsRiscv = 0
const IsRiscv64 = 0
const IsS390 = 0
const IsS390x = 0
const IsSparc = 0
const IsSparc64 = 0
const IsWasm = 0

MinFrameSize is the size of the system-reserved words at the bottom of a frame (just above the architectural stack pointer). It is zero on x86 and PtrSize on most non-x86 (LR-based) systems. On PowerPC it is larger, to cover three more reserved words: the compiler word, the link editor word, and the TOC save word.

+
const MinFrameSize = _MinFrameSize

PCQuantum is the minimal unit for a program counter (1 on x86, 4 on most other systems). The various PC tables record PC deltas pre-divided by PCQuantum.

+
const PCQuantum = _PCQuantum

PtrSize is the size of a pointer in bytes - unsafe.Sizeof(uintptr(0)) but as an ideal constant. It is also the size of the machine's native word size (that is, 4 on 32-bit systems, 8 on 64-bit).

+
const PtrSize = 4 << (^uintptr(0) >> 63)

StackAlign is the required alignment of the SP register. The stack must be at least word aligned, but some architectures require more.

+
const StackAlign = _StackAlign

type ArchFamilyType

type ArchFamilyType int
const (
+    AMD64 ArchFamilyType = iota
+    ARM
+    ARM64
+    I386
+    LOONG64
+    MIPS
+    MIPS64
+    PPC64
+    RISCV64
+    S390X
+    WASM
+)

ArchFamily is the architecture family (AMD64, ARM, ...)

+
const ArchFamily ArchFamilyType = _ArchFamily
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/internal/goarch/ +

+
diff --git a/devdocs/go/internal%2Fgoos%2Findex.html b/devdocs/go/internal%2Fgoos%2Findex.html new file mode 100644 index 00000000..dbc8d171 --- /dev/null +++ b/devdocs/go/internal%2Fgoos%2Findex.html @@ -0,0 +1,10 @@ +

Package goos

Overview

package goos contains GOOS-specific constants.

Index

Package files

goos.go unix.go zgoos_linux.go

Constants

const GOOS = `linux`
const IsAix = 0
const IsAndroid = 0
const IsDarwin = 0
const IsDragonfly = 0
const IsFreebsd = 0
const IsHurd = 0
const IsIllumos = 0
const IsIos = 0
const IsJs = 0
const IsLinux = 1
const IsNacl = 0
const IsNetbsd = 0
const IsOpenbsd = 0
const IsPlan9 = 0
const IsSolaris = 0
const IsUnix = true
const IsWasip1 = 0
const IsWindows = 0
const IsZos = 0
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/internal/goos/ +

+
diff --git a/devdocs/go/io%2Ffs%2Findex.html b/devdocs/go/io%2Ffs%2Findex.html new file mode 100644 index 00000000..4b0094cb --- /dev/null +++ b/devdocs/go/io%2Ffs%2Findex.html @@ -0,0 +1,256 @@ +

Package fs

Overview

Package fs defines basic interfaces to a file system. A file system can be provided by the host operating system but also by other packages.

+

See the testing/fstest package for support with testing implementations of file systems.

Index

Examples

WalkDir

Package files

format.go fs.go glob.go readdir.go readfile.go stat.go sub.go walk.go

Variables

Generic file system errors. Errors returned by file systems can be tested against these errors using errors.Is.

+
var (
+    ErrInvalid    = errInvalid()    // "invalid argument"
+    ErrPermission = errPermission() // "permission denied"
+    ErrExist      = errExist()      // "file already exists"
+    ErrNotExist   = errNotExist()   // "file does not exist"
+    ErrClosed     = errClosed()     // "file already closed"
+)

SkipAll is used as a return value from WalkDirFunc to indicate that all remaining files and directories are to be skipped. It is not returned as an error by any function.

+
var SkipAll = errors.New("skip everything and stop the walk")

SkipDir is used as a return value from WalkDirFunc to indicate that the directory named in the call is to be skipped. It is not returned as an error by any function.

+
var SkipDir = errors.New("skip this directory")

func FormatDirEntry 1.21

func FormatDirEntry(dir DirEntry) string

FormatDirEntry returns a formatted version of dir for human readability. Implementations of DirEntry can call this from a String method. The outputs for a directory named subdir and a file named hello.go are:

+
d subdir/
+- hello.go
+

func FormatFileInfo 1.21

func FormatFileInfo(info FileInfo) string

FormatFileInfo returns a formatted version of info for human readability. Implementations of FileInfo can call this from a String method. The output for a file named "hello.go", 100 bytes, mode 0o644, created January 1, 1970 at noon is

+
-rw-r--r-- 100 1970-01-01 12:00:00 hello.go
+

func Glob 1.16

func Glob(fsys FS, pattern string) (matches []string, err error)

Glob returns the names of all files matching pattern or nil if there is no matching file. The syntax of patterns is the same as in path.Match. The pattern may describe hierarchical names such as usr/*/bin/ed.

+

Glob ignores file system errors such as I/O errors reading directories. The only possible returned error is path.ErrBadPattern, reporting that the pattern is malformed.

+

If fs implements GlobFS, Glob calls fs.Glob. Otherwise, Glob uses ReadDir to traverse the directory tree and look for matches for the pattern.

+

func ReadFile 1.16

func ReadFile(fsys FS, name string) ([]byte, error)

ReadFile reads the named file from the file system fs and returns its contents. A successful call returns a nil error, not io.EOF. (Because ReadFile reads the whole file, the expected EOF from the final Read is not treated as an error to be reported.)

+

If fs implements ReadFileFS, ReadFile calls fs.ReadFile. Otherwise ReadFile calls fs.Open and uses Read and Close on the returned File.

+

func ValidPath 1.16

func ValidPath(name string) bool

ValidPath reports whether the given path name is valid for use in a call to Open.

+

Path names passed to open are UTF-8-encoded, unrooted, slash-separated sequences of path elements, like “x/y/z”. Path names must not contain an element that is “.” or “..” or the empty string, except for the special case that the root directory is named “.”. Paths must not start or end with a slash: “/x” and “x/” are invalid.

+

Note that paths are slash-separated on all systems, even Windows. Paths containing other characters such as backslash and colon are accepted as valid, but those characters must never be interpreted by an FS implementation as path element separators.

+

func WalkDir 1.16

func WalkDir(fsys FS, root string, fn WalkDirFunc) error

WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.

+

All errors that arise visiting files and directories are filtered by fn: see the fs.WalkDirFunc documentation for details.

+

The files are walked in lexical order, which makes the output deterministic but requires WalkDir to read an entire directory into memory before proceeding to walk that directory.

+

WalkDir does not follow symbolic links found in directories, but if root itself is a symbolic link, its target will be walked.

Example +

Code:

+root := "/usr/local/go/bin"
+fileSystem := os.DirFS(root)
+
+fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
+    if err != nil {
+        log.Fatal(err)
+    }
+    fmt.Println(path)
+    return nil
+})
+

type DirEntry 1.16

A DirEntry is an entry read from a directory (using the ReadDir function or a ReadDirFile's ReadDir method).

+
type DirEntry interface {
+    // Name returns the name of the file (or subdirectory) described by the entry.
+    // This name is only the final element of the path (the base name), not the entire path.
+    // For example, Name would return "hello.go" not "home/gopher/hello.go".
+    Name() string
+
+    // IsDir reports whether the entry describes a directory.
+    IsDir() bool
+
+    // Type returns the type bits for the entry.
+    // The type bits are a subset of the usual FileMode bits, those returned by the FileMode.Type method.
+    Type() FileMode
+
+    // Info returns the FileInfo for the file or subdirectory described by the entry.
+    // The returned FileInfo may be from the time of the original directory read
+    // or from the time of the call to Info. If the file has been removed or renamed
+    // since the directory read, Info may return an error satisfying errors.Is(err, ErrNotExist).
+    // If the entry denotes a symbolic link, Info reports the information about the link itself,
+    // not the link's target.
+    Info() (FileInfo, error)
+}

func FileInfoToDirEntry 1.17

func FileInfoToDirEntry(info FileInfo) DirEntry

FileInfoToDirEntry returns a DirEntry that returns information from info. If info is nil, FileInfoToDirEntry returns nil.

+

func ReadDir 1.16

func ReadDir(fsys FS, name string) ([]DirEntry, error)

ReadDir reads the named directory and returns a list of directory entries sorted by filename.

+

If fs implements ReadDirFS, ReadDir calls fs.ReadDir. Otherwise ReadDir calls fs.Open and uses ReadDir and Close on the returned file.

+

type FS 1.16

An FS provides access to a hierarchical file system.

+

The FS interface is the minimum implementation required of the file system. A file system may implement additional interfaces, such as ReadFileFS, to provide additional or optimized functionality.

+

testing/fstest.TestFS may be used to test implementations of an FS for correctness.

+
type FS interface {
+    // Open opens the named file.
+    //
+    // When Open returns an error, it should be of type *PathError
+    // with the Op field set to "open", the Path field set to name,
+    // and the Err field describing the problem.
+    //
+    // Open should reject attempts to open names that do not satisfy
+    // ValidPath(name), returning a *PathError with Err set to
+    // ErrInvalid or ErrNotExist.
+    Open(name string) (File, error)
+}

func Sub 1.16

func Sub(fsys FS, dir string) (FS, error)

Sub returns an FS corresponding to the subtree rooted at fsys's dir.

+

If dir is ".", Sub returns fsys unchanged. Otherwise, if fs implements SubFS, Sub returns fsys.Sub(dir). Otherwise, Sub returns a new FS implementation sub that, in effect, implements sub.Open(name) as fsys.Open(path.Join(dir, name)). The implementation also translates calls to ReadDir, ReadFile, and Glob appropriately.

+

Note that Sub(os.DirFS("/"), "prefix") is equivalent to os.DirFS("/prefix") and that neither of them guarantees to avoid operating system accesses outside "/prefix", because the implementation of os.DirFS does not check for symbolic links inside "/prefix" that point to other directories. That is, os.DirFS is not a general substitute for a chroot-style security mechanism, and Sub does not change that fact.

+

type File 1.16

A File provides access to a single file. The File interface is the minimum implementation required of the file. Directory files should also implement ReadDirFile. A file may implement io.ReaderAt or io.Seeker as optimizations.

+
type File interface {
+    Stat() (FileInfo, error)
+    Read([]byte) (int, error)
+    Close() error
+}

type FileInfo 1.16

A FileInfo describes a file and is returned by Stat.

+
type FileInfo interface {
+    Name() string       // base name of the file
+    Size() int64        // length in bytes for regular files; system-dependent for others
+    Mode() FileMode     // file mode bits
+    ModTime() time.Time // modification time
+    IsDir() bool        // abbreviation for Mode().IsDir()
+    Sys() any           // underlying data source (can return nil)
+}

func Stat 1.16

func Stat(fsys FS, name string) (FileInfo, error)

Stat returns a FileInfo describing the named file from the file system.

+

If fs implements StatFS, Stat calls fs.Stat. Otherwise, Stat opens the File to stat it.

+

type FileMode 1.16

A FileMode represents a file's mode and permission bits. The bits have the same definition on all systems, so that information about files can be moved from one system to another portably. Not all bits apply to all systems. The only required bit is ModeDir for directories.

+
type FileMode uint32

The defined file mode bits are the most significant bits of the FileMode. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

+
const (
+    // The single letters are the abbreviations
+    // used by the String method's formatting.
+    ModeDir        FileMode = 1 << (32 - 1 - iota) // d: is a directory
+    ModeAppend                                     // a: append-only
+    ModeExclusive                                  // l: exclusive use
+    ModeTemporary                                  // T: temporary file; Plan 9 only
+    ModeSymlink                                    // L: symbolic link
+    ModeDevice                                     // D: device file
+    ModeNamedPipe                                  // p: named pipe (FIFO)
+    ModeSocket                                     // S: Unix domain socket
+    ModeSetuid                                     // u: setuid
+    ModeSetgid                                     // g: setgid
+    ModeCharDevice                                 // c: Unix character device, when ModeDevice is set
+    ModeSticky                                     // t: sticky
+    ModeIrregular                                  // ?: non-regular file; nothing else is known about this file
+
+    // Mask for the type bits. For regular files, none will be set.
+    ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice | ModeCharDevice | ModeIrregular
+
+    ModePerm FileMode = 0777 // Unix permission bits
+)

func (FileMode) IsDir 1.16

func (m FileMode) IsDir() bool

IsDir reports whether m describes a directory. That is, it tests for the ModeDir bit being set in m.

+

func (FileMode) IsRegular 1.16

func (m FileMode) IsRegular() bool

IsRegular reports whether m describes a regular file. That is, it tests that no mode type bits are set.

+

func (FileMode) Perm 1.16

func (m FileMode) Perm() FileMode

Perm returns the Unix permission bits in m (m & ModePerm).

+

func (FileMode) String 1.16

func (m FileMode) String() string

func (FileMode) Type 1.16

func (m FileMode) Type() FileMode

Type returns type bits in m (m & ModeType).

+

type GlobFS 1.16

A GlobFS is a file system with a Glob method.

+
type GlobFS interface {
+    FS
+
+    // Glob returns the names of all files matching pattern,
+    // providing an implementation of the top-level
+    // Glob function.
+    Glob(pattern string) ([]string, error)
+}

type PathError 1.16

PathError records an error and the operation and file path that caused it.

+
type PathError struct {
+    Op   string
+    Path string
+    Err  error
+}
+

func (*PathError) Error 1.16

func (e *PathError) Error() string

func (*PathError) Timeout 1.16

func (e *PathError) Timeout() bool

Timeout reports whether this error represents a timeout.

+

func (*PathError) Unwrap 1.16

func (e *PathError) Unwrap() error

type ReadDirFS 1.16

ReadDirFS is the interface implemented by a file system that provides an optimized implementation of ReadDir.

+
type ReadDirFS interface {
+    FS
+
+    // ReadDir reads the named directory
+    // and returns a list of directory entries sorted by filename.
+    ReadDir(name string) ([]DirEntry, error)
+}

type ReadDirFile 1.16

A ReadDirFile is a directory file whose entries can be read with the ReadDir method. Every directory file should implement this interface. (It is permissible for any file to implement this interface, but if so ReadDir should return an error for non-directories.)

+
type ReadDirFile interface {
+    File
+
+    // ReadDir reads the contents of the directory and returns
+    // a slice of up to n DirEntry values in directory order.
+    // Subsequent calls on the same file will yield further DirEntry values.
+    //
+    // If n > 0, ReadDir returns at most n DirEntry structures.
+    // In this case, if ReadDir returns an empty slice, it will return
+    // a non-nil error explaining why.
+    // At the end of a directory, the error is io.EOF.
+    // (ReadDir must return io.EOF itself, not an error wrapping io.EOF.)
+    //
+    // If n <= 0, ReadDir returns all the DirEntry values from the directory
+    // in a single slice. In this case, if ReadDir succeeds (reads all the way
+    // to the end of the directory), it returns the slice and a nil error.
+    // If it encounters an error before the end of the directory,
+    // ReadDir returns the DirEntry list read until that point and a non-nil error.
+    ReadDir(n int) ([]DirEntry, error)
+}

type ReadFileFS 1.16

ReadFileFS is the interface implemented by a file system that provides an optimized implementation of ReadFile.

+
type ReadFileFS interface {
+    FS
+
+    // ReadFile reads the named file and returns its contents.
+    // A successful call returns a nil error, not io.EOF.
+    // (Because ReadFile reads the whole file, the expected EOF
+    // from the final Read is not treated as an error to be reported.)
+    //
+    // The caller is permitted to modify the returned byte slice.
+    // This method should return a copy of the underlying data.
+    ReadFile(name string) ([]byte, error)
+}

type StatFS 1.16

A StatFS is a file system with a Stat method.

+
type StatFS interface {
+    FS
+
+    // Stat returns a FileInfo describing the file.
+    // If there is an error, it should be of type *PathError.
+    Stat(name string) (FileInfo, error)
+}

type SubFS 1.16

A SubFS is a file system with a Sub method.

+
type SubFS interface {
+    FS
+
+    // Sub returns an FS corresponding to the subtree rooted at dir.
+    Sub(dir string) (FS, error)
+}

type WalkDirFunc 1.16

WalkDirFunc is the type of the function called by WalkDir to visit each file or directory.

+

The path argument contains the argument to WalkDir as a prefix. That is, if WalkDir is called with root argument "dir" and finds a file named "a" in that directory, the walk function will be called with argument "dir/a".

+

The d argument is the DirEntry for the named path.

+

The error result returned by the function controls how WalkDir continues. If the function returns the special value SkipDir, WalkDir skips the current directory (path if d.IsDir() is true, otherwise path's parent directory). If the function returns the special value SkipAll, WalkDir skips all remaining files and directories. Otherwise, if the function returns a non-nil error, WalkDir stops entirely and returns that error.

+

The err argument reports an error related to path, signaling that WalkDir will not walk into that directory. The function can decide how to handle that error; as described earlier, returning the error will cause WalkDir to stop walking the entire tree.

+

WalkDir calls the function with a non-nil err argument in two cases.

+

First, if the initial Stat on the root directory fails, WalkDir calls the function with path set to root, d set to nil, and err set to the error from fs.Stat.

+

Second, if a directory's ReadDir method (see ReadDirFile) fails, WalkDir calls the function with path set to the directory's path, d set to an DirEntry describing the directory, and err set to the error from ReadDir. In this second case, the function is called twice with the path of the directory: the first call is before the directory read is attempted and has err set to nil, giving the function a chance to return SkipDir or SkipAll and avoid the ReadDir entirely. The second call is after a failed ReadDir and reports the error from ReadDir. (If ReadDir succeeds, there is no second call.)

+

The differences between WalkDirFunc compared to path/filepath.WalkFunc are:

+
type WalkDirFunc func(path string, d DirEntry, err error) error
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/io/fs/ +

+
diff --git a/devdocs/go/io%2Findex.html b/devdocs/go/io%2Findex.html new file mode 100644 index 00000000..c06f3459 --- /dev/null +++ b/devdocs/go/io%2Findex.html @@ -0,0 +1,461 @@ +

Package io

Overview

Package io provides basic interfaces to I/O primitives. Its primary job is to wrap existing implementations of such primitives, such as those in package os, into shared public interfaces that abstract the functionality, plus some other related primitives.

+

Because these interfaces and primitives wrap lower-level operations with various implementations, unless otherwise informed clients should not assume they are safe for parallel execution.

Index

Examples

Copy
CopyBuffer
CopyN
LimitReader
MultiReader
MultiWriter
Pipe
ReadAll
ReadAtLeast
ReadFull
SectionReader
SectionReader.Read
SectionReader.ReadAt
SectionReader.Seek
SectionReader.Size
TeeReader
WriteString

Package files

io.go multi.go pipe.go

Constants

Seek whence values.

+
const (
+    SeekStart   = 0 // seek relative to the origin of the file
+    SeekCurrent = 1 // seek relative to the current offset
+    SeekEnd     = 2 // seek relative to the end
+)

Variables

EOF is the error returned by Read when no more input is available. (Read must return EOF itself, not an error wrapping EOF, because callers will test for EOF using ==.) Functions should return EOF only to signal a graceful end of input. If the EOF occurs unexpectedly in a structured data stream, the appropriate error is either ErrUnexpectedEOF or some other error giving more detail.

+
var EOF = errors.New("EOF")

ErrClosedPipe is the error used for read or write operations on a closed pipe.

+
var ErrClosedPipe = errors.New("io: read/write on closed pipe")

ErrNoProgress is returned by some clients of a Reader when many calls to Read have failed to return any data or error, usually the sign of a broken Reader implementation.

+
var ErrNoProgress = errors.New("multiple Read calls return no data or error")

ErrShortBuffer means that a read required a longer buffer than was provided.

+
var ErrShortBuffer = errors.New("short buffer")

ErrShortWrite means that a write accepted fewer bytes than requested but failed to return an explicit error.

+
var ErrShortWrite = errors.New("short write")

ErrUnexpectedEOF means that EOF was encountered in the middle of reading a fixed-size block or data structure.

+
var ErrUnexpectedEOF = errors.New("unexpected EOF")

func Copy

func Copy(dst Writer, src Reader) (written int64, err error)

Copy copies from src to dst until either EOF is reached on src or an error occurs. It returns the number of bytes copied and the first error encountered while copying, if any.

+

A successful Copy returns err == nil, not err == EOF. Because Copy is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.

+

If src implements WriterTo, the copy is implemented by calling src.WriteTo(dst). Otherwise, if dst implements ReaderFrom, the copy is implemented by calling dst.ReadFrom(src).

Example +

Code:

r := strings.NewReader("some io.Reader stream to be read\n")
+
+if _, err := io.Copy(os.Stdout, r); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

some io.Reader stream to be read
+

func CopyBuffer 1.5

func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)

CopyBuffer is identical to Copy except that it stages through the provided buffer (if one is required) rather than allocating a temporary one. If buf is nil, one is allocated; otherwise if it has zero length, CopyBuffer panics.

+

If either src implements WriterTo or dst implements ReaderFrom, buf will not be used to perform the copy.

Example +

Code:

r1 := strings.NewReader("first reader\n")
+r2 := strings.NewReader("second reader\n")
+buf := make([]byte, 8)
+
+// buf is used here...
+if _, err := io.CopyBuffer(os.Stdout, r1, buf); err != nil {
+    log.Fatal(err)
+}
+
+// ... reused here also. No need to allocate an extra buffer.
+if _, err := io.CopyBuffer(os.Stdout, r2, buf); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

first reader
+second reader
+

func CopyN

func CopyN(dst Writer, src Reader, n int64) (written int64, err error)

CopyN copies n bytes (or until an error) from src to dst. It returns the number of bytes copied and the earliest error encountered while copying. On return, written == n if and only if err == nil.

+

If dst implements ReaderFrom, the copy is implemented using it.

Example +

Code:

r := strings.NewReader("some io.Reader stream to be read")
+
+if _, err := io.CopyN(os.Stdout, r, 4); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

some
+

func Pipe

func Pipe() (*PipeReader, *PipeWriter)

Pipe creates a synchronous in-memory pipe. It can be used to connect code expecting an io.Reader with code expecting an io.Writer.

+

Reads and Writes on the pipe are matched one to one except when multiple Reads are needed to consume a single Write. That is, each Write to the PipeWriter blocks until it has satisfied one or more Reads from the PipeReader that fully consume the written data. The data is copied directly from the Write to the corresponding Read (or Reads); there is no internal buffering.

+

It is safe to call Read and Write in parallel with each other or with Close. Parallel calls to Read and parallel calls to Write are also safe: the individual calls will be gated sequentially.

Example +

Code:

r, w := io.Pipe()
+
+go func() {
+    fmt.Fprint(w, "some io.Reader stream to be read\n")
+    w.Close()
+}()
+
+if _, err := io.Copy(os.Stdout, r); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

some io.Reader stream to be read
+

func ReadAll 1.16

func ReadAll(r Reader) ([]byte, error)

ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.

Example +

Code:

r := strings.NewReader("Go is a general-purpose language designed with systems programming in mind.")
+
+b, err := io.ReadAll(r)
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%s", b)
+
+

Output:

Go is a general-purpose language designed with systems programming in mind.
+

func ReadAtLeast

func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error)

ReadAtLeast reads from r into buf until it has read at least min bytes. It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read. If an EOF happens after reading fewer than min bytes, ReadAtLeast returns ErrUnexpectedEOF. If min is greater than the length of buf, ReadAtLeast returns ErrShortBuffer. On return, n >= min if and only if err == nil. If r returns an error having read at least min bytes, the error is dropped.

Example +

Code:

r := strings.NewReader("some io.Reader stream to be read\n")
+
+buf := make([]byte, 14)
+if _, err := io.ReadAtLeast(r, buf, 4); err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%s\n", buf)
+
+// buffer smaller than minimal read size.
+shortBuf := make([]byte, 3)
+if _, err := io.ReadAtLeast(r, shortBuf, 4); err != nil {
+    fmt.Println("error:", err)
+}
+
+// minimal read size bigger than io.Reader stream
+longBuf := make([]byte, 64)
+if _, err := io.ReadAtLeast(r, longBuf, 64); err != nil {
+    fmt.Println("error:", err)
+}
+
+

Output:

some io.Reader
+error: short buffer
+error: unexpected EOF
+

func ReadFull

func ReadFull(r Reader, buf []byte) (n int, err error)

ReadFull reads exactly len(buf) bytes from r into buf. It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadFull returns ErrUnexpectedEOF. On return, n == len(buf) if and only if err == nil. If r returns an error having read at least len(buf) bytes, the error is dropped.

Example +

Code:

r := strings.NewReader("some io.Reader stream to be read\n")
+
+buf := make([]byte, 4)
+if _, err := io.ReadFull(r, buf); err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%s\n", buf)
+
+// minimal read size bigger than io.Reader stream
+longBuf := make([]byte, 64)
+if _, err := io.ReadFull(r, longBuf); err != nil {
+    fmt.Println("error:", err)
+}
+
+

Output:

some
+error: unexpected EOF
+

func WriteString

func WriteString(w Writer, s string) (n int, err error)

WriteString writes the contents of the string s to w, which accepts a slice of bytes. If w implements StringWriter, [StringWriter.WriteString] is invoked directly. Otherwise, [Writer.Write] is called exactly once.

Example +

Code:

if _, err := io.WriteString(os.Stdout, "Hello World"); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

Hello World
+

type ByteReader

ByteReader is the interface that wraps the ReadByte method.

+

ReadByte reads and returns the next byte from the input or any error encountered. If ReadByte returns an error, no input byte was consumed, and the returned byte value is undefined.

+

ReadByte provides an efficient interface for byte-at-time processing. A Reader that does not implement ByteReader can be wrapped using bufio.NewReader to add this method.

+
type ByteReader interface {
+    ReadByte() (byte, error)
+}

type ByteScanner

ByteScanner is the interface that adds the UnreadByte method to the basic ReadByte method.

+

UnreadByte causes the next call to ReadByte to return the last byte read. If the last operation was not a successful call to ReadByte, UnreadByte may return an error, unread the last byte read (or the byte prior to the last-unread byte), or (in implementations that support the Seeker interface) seek to one byte before the current offset.

+
type ByteScanner interface {
+    ByteReader
+    UnreadByte() error
+}

type ByteWriter 1.1

ByteWriter is the interface that wraps the WriteByte method.

+
type ByteWriter interface {
+    WriteByte(c byte) error
+}

type Closer

Closer is the interface that wraps the basic Close method.

+

The behavior of Close after the first call is undefined. Specific implementations may document their own behavior.

+
type Closer interface {
+    Close() error
+}

type LimitedReader

A LimitedReader reads from R but limits the amount of data returned to just N bytes. Each call to Read updates N to reflect the new amount remaining. Read returns EOF when N <= 0 or when the underlying R returns EOF.

+
type LimitedReader struct {
+    R Reader // underlying reader
+    N int64  // max bytes remaining
+}
+

func (*LimitedReader) Read

func (l *LimitedReader) Read(p []byte) (n int, err error)

type OffsetWriter 1.20

An OffsetWriter maps writes at offset base to offset base+off in the underlying writer.

+
type OffsetWriter struct {
+    // contains filtered or unexported fields
+}
+

func NewOffsetWriter 1.20

func NewOffsetWriter(w WriterAt, off int64) *OffsetWriter

NewOffsetWriter returns an OffsetWriter that writes to w starting at offset off.

+

func (*OffsetWriter) Seek 1.20

func (o *OffsetWriter) Seek(offset int64, whence int) (int64, error)

func (*OffsetWriter) Write 1.20

func (o *OffsetWriter) Write(p []byte) (n int, err error)

func (*OffsetWriter) WriteAt 1.20

func (o *OffsetWriter) WriteAt(p []byte, off int64) (n int, err error)

type PipeReader

A PipeReader is the read half of a pipe.

+
type PipeReader struct {
+    // contains filtered or unexported fields
+}
+

func (*PipeReader) Close

func (r *PipeReader) Close() error

Close closes the reader; subsequent writes to the write half of the pipe will return the error ErrClosedPipe.

+

func (*PipeReader) CloseWithError

func (r *PipeReader) CloseWithError(err error) error

CloseWithError closes the reader; subsequent writes to the write half of the pipe will return the error err.

+

CloseWithError never overwrites the previous error if it exists and always returns nil.

+

func (*PipeReader) Read

func (r *PipeReader) Read(data []byte) (n int, err error)

Read implements the standard Read interface: it reads data from the pipe, blocking until a writer arrives or the write end is closed. If the write end is closed with an error, that error is returned as err; otherwise err is EOF.

+

type PipeWriter

A PipeWriter is the write half of a pipe.

+
type PipeWriter struct {
+    // contains filtered or unexported fields
+}
+

func (*PipeWriter) Close

func (w *PipeWriter) Close() error

Close closes the writer; subsequent reads from the read half of the pipe will return no bytes and EOF.

+

func (*PipeWriter) CloseWithError

func (w *PipeWriter) CloseWithError(err error) error

CloseWithError closes the writer; subsequent reads from the read half of the pipe will return no bytes and the error err, or EOF if err is nil.

+

CloseWithError never overwrites the previous error if it exists and always returns nil.

+

func (*PipeWriter) Write

func (w *PipeWriter) Write(data []byte) (n int, err error)

Write implements the standard Write interface: it writes data to the pipe, blocking until one or more readers have consumed all the data or the read end is closed. If the read end is closed with an error, that err is returned as err; otherwise err is ErrClosedPipe.

+

type ReadCloser

ReadCloser is the interface that groups the basic Read and Close methods.

+
type ReadCloser interface {
+    Reader
+    Closer
+}

func NopCloser 1.16

func NopCloser(r Reader) ReadCloser

NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r. If r implements WriterTo, the returned ReadCloser will implement WriterTo by forwarding calls to r.

+

type ReadSeekCloser 1.16

ReadSeekCloser is the interface that groups the basic Read, Seek and Close methods.

+
type ReadSeekCloser interface {
+    Reader
+    Seeker
+    Closer
+}

type ReadSeeker

ReadSeeker is the interface that groups the basic Read and Seek methods.

+
type ReadSeeker interface {
+    Reader
+    Seeker
+}

type ReadWriteCloser

ReadWriteCloser is the interface that groups the basic Read, Write and Close methods.

+
type ReadWriteCloser interface {
+    Reader
+    Writer
+    Closer
+}

type ReadWriteSeeker

ReadWriteSeeker is the interface that groups the basic Read, Write and Seek methods.

+
type ReadWriteSeeker interface {
+    Reader
+    Writer
+    Seeker
+}

type ReadWriter

ReadWriter is the interface that groups the basic Read and Write methods.

+
type ReadWriter interface {
+    Reader
+    Writer
+}

type Reader

Reader is the interface that wraps the basic Read method.

+

Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.

+

When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == EOF or err == nil. The next Read should return 0, EOF.

+

Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed EOF behaviors.

+

If len(p) == 0, Read should always return n == 0. It may return a non-nil error if some error condition is known, such as EOF.

+

Implementations of Read are discouraged from returning a zero byte count with a nil error, except when len(p) == 0. Callers should treat a return of 0 and nil as indicating that nothing happened; in particular it does not indicate EOF.

+

Implementations must not retain p.

+
type Reader interface {
+    Read(p []byte) (n int, err error)
+}

func LimitReader

func LimitReader(r Reader, n int64) Reader

LimitReader returns a Reader that reads from r but stops with EOF after n bytes. The underlying implementation is a *LimitedReader.

Example +

Code:

r := strings.NewReader("some io.Reader stream to be read\n")
+lr := io.LimitReader(r, 4)
+
+if _, err := io.Copy(os.Stdout, lr); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

some
+

func MultiReader

func MultiReader(readers ...Reader) Reader

MultiReader returns a Reader that's the logical concatenation of the provided input readers. They're read sequentially. Once all inputs have returned EOF, Read will return EOF. If any of the readers return a non-nil, non-EOF error, Read will return that error.

Example +

Code:

r1 := strings.NewReader("first reader ")
+r2 := strings.NewReader("second reader ")
+r3 := strings.NewReader("third reader\n")
+r := io.MultiReader(r1, r2, r3)
+
+if _, err := io.Copy(os.Stdout, r); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

first reader second reader third reader
+

func TeeReader

func TeeReader(r Reader, w Writer) Reader

TeeReader returns a Reader that writes to w what it reads from r. All reads from r performed through it are matched with corresponding writes to w. There is no internal buffering - the write must complete before the read completes. Any error encountered while writing is reported as a read error.

Example +

Code:

var r io.Reader = strings.NewReader("some io.Reader stream to be read\n")
+
+r = io.TeeReader(r, os.Stdout)
+
+// Everything read from r will be copied to stdout.
+if _, err := io.ReadAll(r); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

some io.Reader stream to be read
+

type ReaderAt

ReaderAt is the interface that wraps the basic ReadAt method.

+

ReadAt reads len(p) bytes into p starting at offset off in the underlying input source. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered.

+

When ReadAt returns n < len(p), it returns a non-nil error explaining why more bytes were not returned. In this respect, ReadAt is stricter than Read.

+

Even if ReadAt returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, ReadAt blocks until either all the data is available or an error occurs. In this respect ReadAt is different from Read.

+

If the n = len(p) bytes returned by ReadAt are at the end of the input source, ReadAt may return either err == EOF or err == nil.

+

If ReadAt is reading from an input source with a seek offset, ReadAt should not affect nor be affected by the underlying seek offset.

+

Clients of ReadAt can execute parallel ReadAt calls on the same input source.

+

Implementations must not retain p.

+
type ReaderAt interface {
+    ReadAt(p []byte, off int64) (n int, err error)
+}

type ReaderFrom

ReaderFrom is the interface that wraps the ReadFrom method.

+

ReadFrom reads data from r until EOF or error. The return value n is the number of bytes read. Any error except EOF encountered during the read is also returned.

+

The Copy function uses ReaderFrom if available.

+
type ReaderFrom interface {
+    ReadFrom(r Reader) (n int64, err error)
+}

type RuneReader

RuneReader is the interface that wraps the ReadRune method.

+

ReadRune reads a single encoded Unicode character and returns the rune and its size in bytes. If no character is available, err will be set.

+
type RuneReader interface {
+    ReadRune() (r rune, size int, err error)
+}

type RuneScanner

RuneScanner is the interface that adds the UnreadRune method to the basic ReadRune method.

+

UnreadRune causes the next call to ReadRune to return the last rune read. If the last operation was not a successful call to ReadRune, UnreadRune may return an error, unread the last rune read (or the rune prior to the last-unread rune), or (in implementations that support the Seeker interface) seek to the start of the rune before the current offset.

+
type RuneScanner interface {
+    RuneReader
+    UnreadRune() error
+}

type SectionReader

SectionReader implements Read, Seek, and ReadAt on a section of an underlying ReaderAt.

+
type SectionReader struct {
+    // contains filtered or unexported fields
+}
+

Example +

Code:

r := strings.NewReader("some io.Reader stream to be read\n")
+s := io.NewSectionReader(r, 5, 17)
+
+if _, err := io.Copy(os.Stdout, s); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

io.Reader stream
+

func NewSectionReader

func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader

NewSectionReader returns a SectionReader that reads from r starting at offset off and stops with EOF after n bytes.

+

func (*SectionReader) Outer 1.22

func (s *SectionReader) Outer() (r ReaderAt, off int64, n int64)

Outer returns the underlying ReaderAt and offsets for the section.

+

The returned values are the same that were passed to NewSectionReader when the SectionReader was created.

+

func (*SectionReader) Read

func (s *SectionReader) Read(p []byte) (n int, err error)

Example +

Code:

r := strings.NewReader("some io.Reader stream to be read\n")
+s := io.NewSectionReader(r, 5, 17)
+
+buf := make([]byte, 9)
+if _, err := s.Read(buf); err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%s\n", buf)
+
+

Output:

io.Reader
+

func (*SectionReader) ReadAt

func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error)

Example +

Code:

r := strings.NewReader("some io.Reader stream to be read\n")
+s := io.NewSectionReader(r, 5, 17)
+
+buf := make([]byte, 6)
+if _, err := s.ReadAt(buf, 10); err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%s\n", buf)
+
+

Output:

stream
+

func (*SectionReader) Seek

func (s *SectionReader) Seek(offset int64, whence int) (int64, error)

Example +

Code:

r := strings.NewReader("some io.Reader stream to be read\n")
+s := io.NewSectionReader(r, 5, 17)
+
+if _, err := s.Seek(10, io.SeekStart); err != nil {
+    log.Fatal(err)
+}
+
+if _, err := io.Copy(os.Stdout, s); err != nil {
+    log.Fatal(err)
+}
+
+

Output:

stream
+

func (*SectionReader) Size

func (s *SectionReader) Size() int64

Size returns the size of the section in bytes.

Example +

Code:

r := strings.NewReader("some io.Reader stream to be read\n")
+s := io.NewSectionReader(r, 5, 17)
+
+fmt.Println(s.Size())
+
+

Output:

17
+

type Seeker

Seeker is the interface that wraps the basic Seek method.

+

Seek sets the offset for the next Read or Write to offset, interpreted according to whence: SeekStart means relative to the start of the file, SeekCurrent means relative to the current offset, and SeekEnd means relative to the end (for example, offset = -2 specifies the penultimate byte of the file). Seek returns the new offset relative to the start of the file or an error, if any.

+

Seeking to an offset before the start of the file is an error. Seeking to any positive offset may be allowed, but if the new offset exceeds the size of the underlying object the behavior of subsequent I/O operations is implementation-dependent.

+
type Seeker interface {
+    Seek(offset int64, whence int) (int64, error)
+}

type StringWriter 1.12

StringWriter is the interface that wraps the WriteString method.

+
type StringWriter interface {
+    WriteString(s string) (n int, err error)
+}

type WriteCloser

WriteCloser is the interface that groups the basic Write and Close methods.

+
type WriteCloser interface {
+    Writer
+    Closer
+}

type WriteSeeker

WriteSeeker is the interface that groups the basic Write and Seek methods.

+
type WriteSeeker interface {
+    Writer
+    Seeker
+}

type Writer

Writer is the interface that wraps the basic Write method.

+

Write writes len(p) bytes from p to the underlying data stream. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. Write must return a non-nil error if it returns n < len(p). Write must not modify the slice data, even temporarily.

+

Implementations must not retain p.

+
type Writer interface {
+    Write(p []byte) (n int, err error)
+}

Discard is a Writer on which all Write calls succeed without doing anything.

+
var Discard Writer = discard{}

func MultiWriter

func MultiWriter(writers ...Writer) Writer

MultiWriter creates a writer that duplicates its writes to all the provided writers, similar to the Unix tee(1) command.

+

Each write is written to each listed writer, one at a time. If a listed writer returns an error, that overall write operation stops and returns the error; it does not continue down the list.

Example +

Code:

r := strings.NewReader("some io.Reader stream to be read\n")
+
+var buf1, buf2 strings.Builder
+w := io.MultiWriter(&buf1, &buf2)
+
+if _, err := io.Copy(w, r); err != nil {
+    log.Fatal(err)
+}
+
+fmt.Print(buf1.String())
+fmt.Print(buf2.String())
+
+

Output:

some io.Reader stream to be read
+some io.Reader stream to be read
+

type WriterAt

WriterAt is the interface that wraps the basic WriteAt method.

+

WriteAt writes len(p) bytes from p to the underlying data stream at offset off. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. WriteAt must return a non-nil error if it returns n < len(p).

+

If WriteAt is writing to a destination with a seek offset, WriteAt should not affect nor be affected by the underlying seek offset.

+

Clients of WriteAt can execute parallel WriteAt calls on the same destination if the ranges do not overlap.

+

Implementations must not retain p.

+
type WriterAt interface {
+    WriteAt(p []byte, off int64) (n int, err error)
+}

type WriterTo

WriterTo is the interface that wraps the WriteTo method.

+

WriteTo writes data to w until there's no more data to write or when an error occurs. The return value n is the number of bytes written. Any error encountered during the write is also returned.

+

The Copy function uses WriterTo if available.

+
type WriterTo interface {
+    WriteTo(w Writer) (n int64, err error)
+}

Subdirectories

Name Synopsis
..
fs Package fs defines basic interfaces to a file system.
ioutil Package ioutil implements some I/O utility functions.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/io/ +

+
diff --git a/devdocs/go/io%2Fioutil%2Findex.html b/devdocs/go/io%2Fioutil%2Findex.html new file mode 100644 index 00000000..072cc201 --- /dev/null +++ b/devdocs/go/io%2Fioutil%2Findex.html @@ -0,0 +1,147 @@ +

Package ioutil

Overview

Package ioutil implements some I/O utility functions.

+

Deprecated: As of Go 1.16, the same functionality is now provided by package io or package os, and those implementations should be preferred in new code. See the specific function documentation for details.

Index

Examples

ReadAll
ReadDir
ReadFile
TempDir
TempDir (Suffix)
TempFile
TempFile (Suffix)
WriteFile

Package files

ioutil.go tempfile.go

Variables

Discard is an io.Writer on which all Write calls succeed without doing anything.

+

Deprecated: As of Go 1.16, this value is simply io.Discard.

+
var Discard io.Writer = io.Discard

func NopCloser

func NopCloser(r io.Reader) io.ReadCloser

NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r.

+

Deprecated: As of Go 1.16, this function simply calls io.NopCloser.

+

func ReadAll

func ReadAll(r io.Reader) ([]byte, error)

ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.

+

Deprecated: As of Go 1.16, this function simply calls io.ReadAll.

Example +

Code:

r := strings.NewReader("Go is a general-purpose language designed with systems programming in mind.")
+
+b, err := ioutil.ReadAll(r)
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%s", b)
+
+

Output:

Go is a general-purpose language designed with systems programming in mind.
+

func ReadDir

func ReadDir(dirname string) ([]fs.FileInfo, error)

ReadDir reads the directory named by dirname and returns a list of fs.FileInfo for the directory's contents, sorted by filename. If an error occurs reading the directory, ReadDir returns no directory entries along with the error.

+

Deprecated: As of Go 1.16, os.ReadDir is a more efficient and correct choice: it returns a list of fs.DirEntry instead of fs.FileInfo, and it returns partial results in the case of an error midway through reading a directory.

+

If you must continue obtaining a list of fs.FileInfo, you still can:

+
entries, err := os.ReadDir(dirname)
+if err != nil { ... }
+infos := make([]fs.FileInfo, 0, len(entries))
+for _, entry := range entries {
+	info, err := entry.Info()
+	if err != nil { ... }
+	infos = append(infos, info)
+}
+

Example +

Code:

+files, err := ioutil.ReadDir(".")
+if err != nil {
+    log.Fatal(err)
+}
+
+for _, file := range files {
+    fmt.Println(file.Name())
+}
+

func ReadFile

func ReadFile(filename string) ([]byte, error)

ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

+

Deprecated: As of Go 1.16, this function simply calls os.ReadFile.

Example +

Code:

content, err := ioutil.ReadFile("testdata/hello")
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("File contents: %s", content)
+
+

Output:

File contents: Hello, Gophers!
+

func TempDir

func TempDir(dir, pattern string) (name string, err error)

TempDir creates a new temporary directory in the directory dir. The directory name is generated by taking pattern and applying a random string to the end. If pattern includes a "*", the random string replaces the last "*". TempDir returns the name of the new directory. If dir is the empty string, TempDir uses the default directory for temporary files (see os.TempDir). Multiple programs calling TempDir simultaneously will not choose the same directory. It is the caller's responsibility to remove the directory when no longer needed.

+

Deprecated: As of Go 1.17, this function simply calls os.MkdirTemp.

Example +

Code:

+content := []byte("temporary file's content")
+dir, err := ioutil.TempDir("", "example")
+if err != nil {
+    log.Fatal(err)
+}
+
+defer os.RemoveAll(dir) // clean up
+
+tmpfn := filepath.Join(dir, "tmpfile")
+if err := ioutil.WriteFile(tmpfn, content, 0666); err != nil {
+    log.Fatal(err)
+}
+

Example (Suffix) +

Code:

+parentDir := os.TempDir()
+logsDir, err := ioutil.TempDir(parentDir, "*-logs")
+if err != nil {
+    log.Fatal(err)
+}
+defer os.RemoveAll(logsDir) // clean up
+
+// Logs can be cleaned out earlier if needed by searching
+// for all directories whose suffix ends in *-logs.
+globPattern := filepath.Join(parentDir, "*-logs")
+matches, err := filepath.Glob(globPattern)
+if err != nil {
+    log.Fatalf("Failed to match %q: %v", globPattern, err)
+}
+
+for _, match := range matches {
+    if err := os.RemoveAll(match); err != nil {
+        log.Printf("Failed to remove %q: %v", match, err)
+    }
+}
+

func TempFile

func TempFile(dir, pattern string) (f *os.File, err error)

TempFile creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting *os.File. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a "*", the random string replaces the last "*". If dir is the empty string, TempFile uses the default directory for temporary files (see os.TempDir). Multiple programs calling TempFile simultaneously will not choose the same file. The caller can use f.Name() to find the pathname of the file. It is the caller's responsibility to remove the file when no longer needed.

+

Deprecated: As of Go 1.17, this function simply calls os.CreateTemp.

Example +

Code:

+content := []byte("temporary file's content")
+tmpfile, err := ioutil.TempFile("", "example")
+if err != nil {
+    log.Fatal(err)
+}
+
+defer os.Remove(tmpfile.Name()) // clean up
+
+if _, err := tmpfile.Write(content); err != nil {
+    log.Fatal(err)
+}
+if err := tmpfile.Close(); err != nil {
+    log.Fatal(err)
+}
+

Example (Suffix) +

Code:

+content := []byte("temporary file's content")
+tmpfile, err := ioutil.TempFile("", "example.*.txt")
+if err != nil {
+    log.Fatal(err)
+}
+
+defer os.Remove(tmpfile.Name()) // clean up
+
+if _, err := tmpfile.Write(content); err != nil {
+    tmpfile.Close()
+    log.Fatal(err)
+}
+if err := tmpfile.Close(); err != nil {
+    log.Fatal(err)
+}
+

func WriteFile

func WriteFile(filename string, data []byte, perm fs.FileMode) error

WriteFile writes data to a file named by filename. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions.

+

Deprecated: As of Go 1.16, this function simply calls os.WriteFile.

Example +

Code:

+message := []byte("Hello, Gophers!")
+err := ioutil.WriteFile("hello", message, 0644)
+if err != nil {
+    log.Fatal(err)
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/io/ioutil/ +

+
diff --git a/devdocs/go/iter%2Findex.html b/devdocs/go/iter%2Findex.html new file mode 100644 index 00000000..4fb4cc84 --- /dev/null +++ b/devdocs/go/iter%2Findex.html @@ -0,0 +1,7 @@ +

Command iter

Package iter provides basic definitions and operations related to iteration in Go.

+

This package is experimental and can only be imported when building with GOEXPERIMENT=rangefunc.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/iter/ +

+
diff --git a/devdocs/go/log%2Findex.html b/devdocs/go/log%2Findex.html new file mode 100644 index 00000000..74b005a4 --- /dev/null +++ b/devdocs/go/log%2Findex.html @@ -0,0 +1,141 @@ +

Package log

Overview

Package log implements a simple logging package. It defines a type, Logger, with methods for formatting output. It also has a predefined 'standard' Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and Panic[f|ln], which are easier to use than creating a Logger manually. That logger writes to standard error and prints the date and time of each logged message. Every log message is output on a separate line: if the message being printed does not end in a newline, the logger will add one. The Fatal functions call os.Exit(1) after writing the log message. The Panic functions call panic after writing the log message.

Index

Examples

Logger
Logger.Output

Package files

log.go

Constants

These flags define which text to prefix to each log entry generated by the Logger. Bits are or'ed together to control what's printed. With the exception of the Lmsgprefix flag, there is no control over the order they appear (the order listed here) or the format they present (as described in the comments). The prefix is followed by a colon only when Llongfile or Lshortfile is specified. For example, flags Ldate | Ltime (or LstdFlags) produce,

+
2009/01/23 01:23:23 message
+

while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,

+
2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
+
const (
+    Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
+    Ltime                         // the time in the local time zone: 01:23:23
+    Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
+    Llongfile                     // full file name and line number: /a/b/c/d.go:23
+    Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
+    LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
+    Lmsgprefix                    // move the "prefix" from the beginning of the line to before the message
+    LstdFlags     = Ldate | Ltime // initial values for the standard logger
+)

func Fatal

func Fatal(v ...any)

Fatal is equivalent to Print followed by a call to os.Exit(1).

+

func Fatalf

func Fatalf(format string, v ...any)

Fatalf is equivalent to Printf followed by a call to os.Exit(1).

+

func Fatalln

func Fatalln(v ...any)

Fatalln is equivalent to Println followed by a call to os.Exit(1).

+

func Flags

func Flags() int

Flags returns the output flags for the standard logger. The flag bits are Ldate, Ltime, and so on.

+

func Output 1.5

func Output(calldepth int, s string) error

Output writes the output for a logging event. The string s contains the text to print after the prefix specified by the flags of the Logger. A newline is appended if the last character of s is not already a newline. Calldepth is the count of the number of frames to skip when computing the file name and line number if Llongfile or Lshortfile is set; a value of 1 will print the details for the caller of Output.

+

func Panic

func Panic(v ...any)

Panic is equivalent to Print followed by a call to panic().

+

func Panicf

func Panicf(format string, v ...any)

Panicf is equivalent to Printf followed by a call to panic().

+

func Panicln

func Panicln(v ...any)

Panicln is equivalent to Println followed by a call to panic().

+

func Prefix

func Prefix() string

Prefix returns the output prefix for the standard logger.

+

func Print

func Print(v ...any)

Print calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Print.

+

func Printf

func Printf(format string, v ...any)

Printf calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Printf.

+

func Println

func Println(v ...any)

Println calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Println.

+

func SetFlags

func SetFlags(flag int)

SetFlags sets the output flags for the standard logger. The flag bits are Ldate, Ltime, and so on.

+

func SetOutput

func SetOutput(w io.Writer)

SetOutput sets the output destination for the standard logger.

+

func SetPrefix

func SetPrefix(prefix string)

SetPrefix sets the output prefix for the standard logger.

+

func Writer 1.13

func Writer() io.Writer

Writer returns the output destination for the standard logger.

+

type Logger

A Logger represents an active logging object that generates lines of output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer.

+
type Logger struct {
+    // contains filtered or unexported fields
+}
+

Example +

Code:

var (
+    buf    bytes.Buffer
+    logger = log.New(&buf, "logger: ", log.Lshortfile)
+)
+
+logger.Print("Hello, log file!")
+
+fmt.Print(&buf)
+

Output:

logger: example_test.go:19: Hello, log file!
+

func Default 1.16

func Default() *Logger

Default returns the standard logger used by the package-level output functions.

+

func New

func New(out io.Writer, prefix string, flag int) *Logger

New creates a new Logger. The out variable sets the destination to which log data will be written. The prefix appears at the beginning of each generated log line, or after the log header if the Lmsgprefix flag is provided. The flag argument defines the logging properties.

+

func (*Logger) Fatal

func (l *Logger) Fatal(v ...any)

Fatal is equivalent to l.Print() followed by a call to os.Exit(1).

+

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, v ...any)

Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1).

+

func (*Logger) Fatalln

func (l *Logger) Fatalln(v ...any)

Fatalln is equivalent to l.Println() followed by a call to os.Exit(1).

+

func (*Logger) Flags

func (l *Logger) Flags() int

Flags returns the output flags for the logger. The flag bits are Ldate, Ltime, and so on.

+

func (*Logger) Output

func (l *Logger) Output(calldepth int, s string) error

Output writes the output for a logging event. The string s contains the text to print after the prefix specified by the flags of the Logger. A newline is appended if the last character of s is not already a newline. Calldepth is used to recover the PC and is provided for generality, although at the moment on all pre-defined paths it will be 2.

Example +

Code:

var (
+    buf    bytes.Buffer
+    logger = log.New(&buf, "INFO: ", log.Lshortfile)
+
+    infof = func(info string) {
+        logger.Output(2, info)
+    }
+)
+
+infof("Hello world")
+
+fmt.Print(&buf)
+

Output:

INFO: example_test.go:36: Hello world
+

func (*Logger) Panic

func (l *Logger) Panic(v ...any)

Panic is equivalent to l.Print() followed by a call to panic().

+

func (*Logger) Panicf

func (l *Logger) Panicf(format string, v ...any)

Panicf is equivalent to l.Printf() followed by a call to panic().

+

func (*Logger) Panicln

func (l *Logger) Panicln(v ...any)

Panicln is equivalent to l.Println() followed by a call to panic().

+

func (*Logger) Prefix

func (l *Logger) Prefix() string

Prefix returns the output prefix for the logger.

+

func (*Logger) Print

func (l *Logger) Print(v ...any)

Print calls l.Output to print to the logger. Arguments are handled in the manner of fmt.Print.

+

func (*Logger) Printf

func (l *Logger) Printf(format string, v ...any)

Printf calls l.Output to print to the logger. Arguments are handled in the manner of fmt.Printf.

+

func (*Logger) Println

func (l *Logger) Println(v ...any)

Println calls l.Output to print to the logger. Arguments are handled in the manner of fmt.Println.

+

func (*Logger) SetFlags

func (l *Logger) SetFlags(flag int)

SetFlags sets the output flags for the logger. The flag bits are Ldate, Ltime, and so on.

+

func (*Logger) SetOutput 1.5

func (l *Logger) SetOutput(w io.Writer)

SetOutput sets the output destination for the logger.

+

func (*Logger) SetPrefix

func (l *Logger) SetPrefix(prefix string)

SetPrefix sets the output prefix for the logger.

+

func (*Logger) Writer 1.12

func (l *Logger) Writer() io.Writer

Writer returns the output destination for the logger.

+

Subdirectories

Name Synopsis
..
slog Package slog provides structured logging, in which log records include a message, a severity level, and various other attributes expressed as key-value pairs.
syslog Package syslog provides a simple interface to the system log service.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/log/ +

+
diff --git a/devdocs/go/log%2Fslog%2Findex.html b/devdocs/go/log%2Fslog%2Findex.html new file mode 100644 index 00000000..4c81a471 --- /dev/null +++ b/devdocs/go/log%2Fslog%2Findex.html @@ -0,0 +1,931 @@ +

Package slog

Overview

Package slog provides structured logging, in which log records include a message, a severity level, and various other attributes expressed as key-value pairs.

+

It defines a type, Logger, which provides several methods (such as Logger.Info and Logger.Error) for reporting events of interest.

+

Each Logger is associated with a Handler. A Logger output method creates a Record from the method arguments and passes it to the Handler, which decides how to handle it. There is a default Logger accessible through top-level functions (such as Info and Error) that call the corresponding Logger methods.

+

A log record consists of a time, a level, a message, and a set of key-value pairs, where the keys are strings and the values may be of any type. As an example,

+
slog.Info("hello", "count", 3)
+

creates a record containing the time of the call, a level of Info, the message "hello", and a single pair with key "count" and value 3.

+

The Info top-level function calls the Logger.Info method on the default Logger. In addition to Logger.Info, there are methods for Debug, Warn and Error levels. Besides these convenience methods for common levels, there is also a Logger.Log method which takes the level as an argument. Each of these methods has a corresponding top-level function that uses the default logger.

+

The default handler formats the log record's message, time, level, and attributes as a string and passes it to the log package.

+
2022/11/08 15:28:26 INFO hello count=3
+

For more control over the output format, create a logger with a different handler. This statement uses New to create a new logger with a TextHandler that writes structured records in text form to standard error:

+
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
+

TextHandler output is a sequence of key=value pairs, easily and unambiguously parsed by machine. This statement:

+
logger.Info("hello", "count", 3)
+

produces this output:

+
time=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3
+

The package also provides JSONHandler, whose output is line-delimited JSON:

+
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
+logger.Info("hello", "count", 3)
+

produces this output:

+
{"time":"2022-11-08T15:28:26.000000000-05:00","level":"INFO","msg":"hello","count":3}
+

Both TextHandler and JSONHandler can be configured with HandlerOptions. There are options for setting the minimum level (see Levels, below), displaying the source file and line of the log call, and modifying attributes before they are logged.

+

Setting a logger as the default with

+
slog.SetDefault(logger)
+

will cause the top-level functions like Info to use it. SetDefault also updates the default logger used by the log package, so that existing applications that use log.Printf and related functions will send log records to the logger's handler without needing to be rewritten.

+

Some attributes are common to many log calls. For example, you may wish to include the URL or trace identifier of a server request with all log events arising from the request. Rather than repeat the attribute with every log call, you can use Logger.With to construct a new Logger containing the attributes:

+
logger2 := logger.With("url", r.URL)
+

The arguments to With are the same key-value pairs used in Logger.Info. The result is a new Logger with the same handler as the original, but additional attributes that will appear in the output of every call.

+

Levels

A Level is an integer representing the importance or severity of a log event. The higher the level, the more severe the event. This package defines constants for the most common levels, but any int can be used as a level.

+

In an application, you may wish to log messages only at a certain level or greater. One common configuration is to log messages at Info or higher levels, suppressing debug logging until it is needed. The built-in handlers can be configured with the minimum level to output by setting [HandlerOptions.Level]. The program's `main` function typically does this. The default value is LevelInfo.

+

Setting the [HandlerOptions.Level] field to a Level value fixes the handler's minimum level throughout its lifetime. Setting it to a LevelVar allows the level to be varied dynamically. A LevelVar holds a Level and is safe to read or write from multiple goroutines. To vary the level dynamically for an entire program, first initialize a global LevelVar:

+
var programLevel = new(slog.LevelVar) // Info by default
+

Then use the LevelVar to construct a handler, and make it the default:

+
h := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel})
+slog.SetDefault(slog.New(h))
+

Now the program can change its logging level with a single statement:

+
programLevel.Set(slog.LevelDebug)
+

Groups

Attributes can be collected into groups. A group has a name that is used to qualify the names of its attributes. How this qualification is displayed depends on the handler. TextHandler separates the group and attribute names with a dot. JSONHandler treats each group as a separate JSON object, with the group name as the key.

+

Use Group to create a Group attribute from a name and a list of key-value pairs:

+
slog.Group("request",
+    "method", r.Method,
+    "url", r.URL)
+

TextHandler would display this group as

+
request.method=GET request.url=http://example.com
+

JSONHandler would display it as

+
"request":{"method":"GET","url":"http://example.com"}
+

Use Logger.WithGroup to qualify all of a Logger's output with a group name. Calling WithGroup on a Logger results in a new Logger with the same Handler as the original, but with all its attributes qualified by the group name.

+

This can help prevent duplicate attribute keys in large systems, where subsystems might use the same keys. Pass each subsystem a different Logger with its own group name so that potential duplicates are qualified:

+
logger := slog.Default().With("id", systemID)
+parserLogger := logger.WithGroup("parser")
+parseInput(input, parserLogger)
+

When parseInput logs with parserLogger, its keys will be qualified with "parser", so even if it uses the common key "id", the log line will have distinct keys.

+

Contexts

Some handlers may wish to include information from the context.Context that is available at the call site. One example of such information is the identifier for the current span when tracing is enabled.

+

The Logger.Log and Logger.LogAttrs methods take a context as a first argument, as do their corresponding top-level functions.

+

Although the convenience methods on Logger (Info and so on) and the corresponding top-level functions do not take a context, the alternatives ending in "Context" do. For example,

+
slog.InfoContext(ctx, "message")
+

It is recommended to pass a context to an output method if one is available.

+

Attrs and Values

An Attr is a key-value pair. The Logger output methods accept Attrs as well as alternating keys and values. The statement

+
slog.Info("hello", slog.Int("count", 3))
+

behaves the same as

+
slog.Info("hello", "count", 3)
+

There are convenience constructors for Attr such as Int, String, and Bool for common types, as well as the function Any for constructing Attrs of any type.

+

The value part of an Attr is a type called Value. Like an [any], a Value can hold any Go value, but it can represent typical values, including all numbers and strings, without an allocation.

+

For the most efficient log output, use Logger.LogAttrs. It is similar to Logger.Log but accepts only Attrs, not alternating keys and values; this allows it, too, to avoid allocation.

+

The call

+
logger.LogAttrs(ctx, slog.LevelInfo, "hello", slog.Int("count", 3))
+

is the most efficient way to achieve the same output as

+
slog.InfoContext(ctx, "hello", "count", 3)
+

Customizing a type's logging behavior

If a type implements the LogValuer interface, the Value returned from its LogValue method is used for logging. You can use this to control how values of the type appear in logs. For example, you can redact secret information like passwords, or gather a struct's fields in a Group. See the examples under LogValuer for details.

+

A LogValue method may return a Value that itself implements LogValuer. The Value.Resolve method handles these cases carefully, avoiding infinite loops and unbounded recursion. Handler authors and others may wish to use Value.Resolve instead of calling LogValue directly.

+

Wrapping output methods

The logger functions use reflection over the call stack to find the file name and line number of the logging call within the application. This can produce incorrect source information for functions that wrap slog. For instance, if you define this function in file mylog.go:

+
func Infof(logger *slog.Logger, format string, args ...any) {
+    logger.Info(fmt.Sprintf(format, args...))
+}
+

and you call it like this in main.go:

+
Infof(slog.Default(), "hello, %s", "world")
+

then slog will report the source file as mylog.go, not main.go.

+

A correct implementation of Infof will obtain the source location (pc) and pass it to NewRecord. The Infof function in the package-level example called "wrapping" demonstrates how to do this.

+

Working with Records

Sometimes a Handler will need to modify a Record before passing it on to another Handler or backend. A Record contains a mixture of simple public fields (e.g. Time, Level, Message) and hidden fields that refer to state (such as attributes) indirectly. This means that modifying a simple copy of a Record (e.g. by calling Record.Add or Record.AddAttrs to add attributes) may have unexpected effects on the original. Before modifying a Record, use Record.Clone to create a copy that shares no state with the original, or create a new Record with NewRecord and build up its Attrs by traversing the old ones with Record.Attrs.

+

Performance considerations

If profiling your application demonstrates that logging is taking significant time, the following suggestions may help.

+

If many log lines have a common attribute, use Logger.With to create a Logger with that attribute. The built-in handlers will format that attribute only once, at the call to Logger.With. The Handler interface is designed to allow that optimization, and a well-written Handler should take advantage of it.

+

The arguments to a log call are always evaluated, even if the log event is discarded. If possible, defer computation so that it happens only if the value is actually logged. For example, consider the call

+
slog.Info("starting request", "url", r.URL.String())  // may compute String unnecessarily
+

The URL.String method will be called even if the logger discards Info-level events. Instead, pass the URL directly:

+
slog.Info("starting request", "url", &r.URL) // calls URL.String only if needed
+

The built-in TextHandler will call its String method, but only if the log event is enabled. Avoiding the call to String also preserves the structure of the underlying value. For example JSONHandler emits the components of the parsed URL as a JSON object. If you want to avoid eagerly paying the cost of the String call without causing the handler to potentially inspect the structure of the value, wrap the value in a fmt.Stringer implementation that hides its Marshal methods.

+

You can also use the LogValuer interface to avoid unnecessary work in disabled log calls. Say you need to log some expensive value:

+
slog.Debug("frobbing", "value", computeExpensiveValue(arg))
+

Even if this line is disabled, computeExpensiveValue will be called. To avoid that, define a type implementing LogValuer:

+
type expensive struct { arg int }
+
+func (e expensive) LogValue() slog.Value {
+    return slog.AnyValue(computeExpensiveValue(e.arg))
+}
+

Then use a value of that type in log calls:

+
slog.Debug("frobbing", "value", expensive{arg})
+

Now computeExpensiveValue will only be called when the line is enabled.

+

The built-in handlers acquire a lock before calling io.Writer.Write to ensure that each record is written in one piece. User-defined handlers are responsible for their own locking.

+

Writing a handler

For a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide.

Example (Wrapping) +

Code:

package slog_test
+
+import (
+    "context"
+    "fmt"
+    "log/slog"
+    "os"
+    "path/filepath"
+    "runtime"
+    "time"
+)
+
+// Infof is an example of a user-defined logging function that wraps slog.
+// The log record contains the source position of the caller of Infof.
+func Infof(logger *slog.Logger, format string, args ...any) {
+    if !logger.Enabled(context.Background(), slog.LevelInfo) {
+        return
+    }
+    var pcs [1]uintptr
+    runtime.Callers(2, pcs[:]) // skip [Callers, Infof]
+    r := slog.NewRecord(time.Now(), slog.LevelInfo, fmt.Sprintf(format, args...), pcs[0])
+    _ = logger.Handler().Handle(context.Background(), r)
+}
+
+func Example_wrapping() {
+    replace := func(groups []string, a slog.Attr) slog.Attr {
+        // Remove time.
+        if a.Key == slog.TimeKey && len(groups) == 0 {
+            return slog.Attr{}
+        }
+        // Remove the directory from the source's filename.
+        if a.Key == slog.SourceKey {
+            source := a.Value.Any().(*slog.Source)
+            source.File = filepath.Base(source.File)
+        }
+        return a
+    }
+    logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
+    Infof(logger, "message, %s", "formatted")
+
+    // Output:
+    // level=INFO source=example_wrap_test.go:43 msg="message, formatted"
+}
+

Index

Examples

Group
HandlerOptions (CustomLevels)
Handler (LevelHandler)
LogValuer (Group)
LogValuer (Secret)
SetLogLoggerLevel (Log)
SetLogLoggerLevel (Slog)
Package (Wrapping)

Package files

attr.go doc.go handler.go json_handler.go level.go logger.go record.go text_handler.go value.go

Constants

Keys for "built-in" attributes.

+
const (
+    // TimeKey is the key used by the built-in handlers for the time
+    // when the log method is called. The associated Value is a [time.Time].
+    TimeKey = "time"
+    // LevelKey is the key used by the built-in handlers for the level
+    // of the log call. The associated value is a [Level].
+    LevelKey = "level"
+    // MessageKey is the key used by the built-in handlers for the
+    // message of the log call. The associated value is a string.
+    MessageKey = "msg"
+    // SourceKey is the key used by the built-in handlers for the source file
+    // and line of the log call. The associated value is a *[Source].
+    SourceKey = "source"
+)

func Debug 1.21

func Debug(msg string, args ...any)

Debug calls Logger.Debug on the default logger.

+

func DebugContext 1.21

func DebugContext(ctx context.Context, msg string, args ...any)

DebugContext calls Logger.DebugContext on the default logger.

+

func Error 1.21

func Error(msg string, args ...any)

Error calls Logger.Error on the default logger.

+

func ErrorContext 1.21

func ErrorContext(ctx context.Context, msg string, args ...any)

ErrorContext calls Logger.ErrorContext on the default logger.

+

func Info 1.21

func Info(msg string, args ...any)

Info calls Logger.Info on the default logger.

+

func InfoContext 1.21

func InfoContext(ctx context.Context, msg string, args ...any)

InfoContext calls Logger.InfoContext on the default logger.

+

func Log 1.21

func Log(ctx context.Context, level Level, msg string, args ...any)

Log calls Logger.Log on the default logger.

+

func LogAttrs 1.21

func LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)

LogAttrs calls Logger.LogAttrs on the default logger.

+

func NewLogLogger 1.21

func NewLogLogger(h Handler, level Level) *log.Logger

NewLogLogger returns a new log.Logger such that each call to its Output method dispatches a Record to the specified handler. The logger acts as a bridge from the older log API to newer structured logging handlers.

+

func SetDefault 1.21

func SetDefault(l *Logger)

SetDefault makes l the default Logger, which is used by the top-level functions Info, Debug and so on. After this call, output from the log package's default Logger (as with log.Print, etc.) will be logged using l's Handler, at a level controlled by SetLogLoggerLevel.

+

func Warn 1.21

func Warn(msg string, args ...any)

Warn calls Logger.Warn on the default logger.

+

func WarnContext 1.21

func WarnContext(ctx context.Context, msg string, args ...any)

WarnContext calls Logger.WarnContext on the default logger.

+

type Attr 1.21

An Attr is a key-value pair.

+
type Attr struct {
+    Key   string
+    Value Value
+}
+

func Any 1.21

func Any(key string, value any) Attr

Any returns an Attr for the supplied value. See AnyValue for how values are treated.

+

func Bool 1.21

func Bool(key string, v bool) Attr

Bool returns an Attr for a bool.

+

func Duration 1.21

func Duration(key string, v time.Duration) Attr

Duration returns an Attr for a time.Duration.

+

func Float64 1.21

func Float64(key string, v float64) Attr

Float64 returns an Attr for a floating-point number.

+

func Group 1.21

func Group(key string, args ...any) Attr

Group returns an Attr for a Group Value. The first argument is the key; the remaining arguments are converted to Attrs as in Logger.Log.

+

Use Group to collect several key-value pairs under a single key on a log line, or as the result of LogValue in order to log a single value as multiple Attrs.

Example +

Code:

r, _ := http.NewRequest("GET", "localhost", nil)
+// ...
+
+logger := slog.New(
+    slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
+        ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
+            if a.Key == slog.TimeKey && len(groups) == 0 {
+                return slog.Attr{}
+            }
+            return a
+        },
+    }),
+)
+logger.Info("finished",
+    slog.Group("req",
+        slog.String("method", r.Method),
+        slog.String("url", r.URL.String())),
+    slog.Int("status", http.StatusOK),
+    slog.Duration("duration", time.Second))
+
+

Output:

level=INFO msg=finished req.method=GET req.url=localhost status=200 duration=1s
+

func Int 1.21

func Int(key string, value int) Attr

Int converts an int to an int64 and returns an Attr with that value.

+

func Int64 1.21

func Int64(key string, value int64) Attr

Int64 returns an Attr for an int64.

+

func String 1.21

func String(key, value string) Attr

String returns an Attr for a string value.

+

func Time 1.21

func Time(key string, v time.Time) Attr

Time returns an Attr for a time.Time. It discards the monotonic portion.

+

func Uint64 1.21

func Uint64(key string, v uint64) Attr

Uint64 returns an Attr for a uint64.

+

func (Attr) Equal 1.21

func (a Attr) Equal(b Attr) bool

Equal reports whether a and b have equal keys and values.

+

func (Attr) String 1.21

func (a Attr) String() string

type Handler 1.21

A Handler handles log records produced by a Logger.

+

A typical handler may print log records to standard error, or write them to a file or database, or perhaps augment them with additional attributes and pass them on to another handler.

+

Any of the Handler's methods may be called concurrently with itself or with other methods. It is the responsibility of the Handler to manage this concurrency.

+

Users of the slog package should not invoke Handler methods directly. They should use the methods of Logger instead.

+
type Handler interface {
+    // Enabled reports whether the handler handles records at the given level.
+    // The handler ignores records whose level is lower.
+    // It is called early, before any arguments are processed,
+    // to save effort if the log event should be discarded.
+    // If called from a Logger method, the first argument is the context
+    // passed to that method, or context.Background() if nil was passed
+    // or the method does not take a context.
+    // The context is passed so Enabled can use its values
+    // to make a decision.
+    Enabled(context.Context, Level) bool
+
+    // Handle handles the Record.
+    // It will only be called when Enabled returns true.
+    // The Context argument is as for Enabled.
+    // It is present solely to provide Handlers access to the context's values.
+    // Canceling the context should not affect record processing.
+    // (Among other things, log messages may be necessary to debug a
+    // cancellation-related problem.)
+    //
+    // Handle methods that produce output should observe the following rules:
+    //   - If r.Time is the zero time, ignore the time.
+    //   - If r.PC is zero, ignore it.
+    //   - Attr's values should be resolved.
+    //   - If an Attr's key and value are both the zero value, ignore the Attr.
+    //     This can be tested with attr.Equal(Attr{}).
+    //   - If a group's key is empty, inline the group's Attrs.
+    //   - If a group has no Attrs (even if it has a non-empty key),
+    //     ignore it.
+    Handle(context.Context, Record) error
+
+    // WithAttrs returns a new Handler whose attributes consist of
+    // both the receiver's attributes and the arguments.
+    // The Handler owns the slice: it may retain, modify or discard it.
+    WithAttrs(attrs []Attr) Handler
+
+    // WithGroup returns a new Handler with the given group appended to
+    // the receiver's existing groups.
+    // The keys of all subsequent attributes, whether added by With or in a
+    // Record, should be qualified by the sequence of group names.
+    //
+    // How this qualification happens is up to the Handler, so long as
+    // this Handler's attribute keys differ from those of another Handler
+    // with a different sequence of group names.
+    //
+    // A Handler should treat WithGroup as starting a Group of Attrs that ends
+    // at the end of the log event. That is,
+    //
+    //     logger.WithGroup("s").LogAttrs(ctx, level, msg, slog.Int("a", 1), slog.Int("b", 2))
+    //
+    // should behave like
+    //
+    //     logger.LogAttrs(ctx, level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2)))
+    //
+    // If the name is empty, WithGroup returns the receiver.
+    WithGroup(name string) Handler
+}

Example (LevelHandler) +

This example shows how to Use a LevelHandler to change the level of an existing Handler while preserving its other behavior. This example demonstrates increasing the log level to reduce a logger's output. Another typical use would be to decrease the log level (to LevelDebug, say) during a part of the program that was suspected of containing a bug.

Code:

package slog_test
+
+import (
+    "context"
+    "log/slog"
+    "log/slog/internal/slogtest"
+    "os"
+)
+
+// A LevelHandler wraps a Handler with an Enabled method
+// that returns false for levels below a minimum.
+type LevelHandler struct {
+    level   slog.Leveler
+    handler slog.Handler
+}
+
+// NewLevelHandler returns a LevelHandler with the given level.
+// All methods except Enabled delegate to h.
+func NewLevelHandler(level slog.Leveler, h slog.Handler) *LevelHandler {
+    // Optimization: avoid chains of LevelHandlers.
+    if lh, ok := h.(*LevelHandler); ok {
+        h = lh.Handler()
+    }
+    return &LevelHandler{level, h}
+}
+
+// Enabled implements Handler.Enabled by reporting whether
+// level is at least as large as h's level.
+func (h *LevelHandler) Enabled(_ context.Context, level slog.Level) bool {
+    return level >= h.level.Level()
+}
+
+// Handle implements Handler.Handle.
+func (h *LevelHandler) Handle(ctx context.Context, r slog.Record) error {
+    return h.handler.Handle(ctx, r)
+}
+
+// WithAttrs implements Handler.WithAttrs.
+func (h *LevelHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
+    return NewLevelHandler(h.level, h.handler.WithAttrs(attrs))
+}
+
+// WithGroup implements Handler.WithGroup.
+func (h *LevelHandler) WithGroup(name string) slog.Handler {
+    return NewLevelHandler(h.level, h.handler.WithGroup(name))
+}
+
+// Handler returns the Handler wrapped by h.
+func (h *LevelHandler) Handler() slog.Handler {
+    return h.handler
+}
+
+// This example shows how to Use a LevelHandler to change the level of an
+// existing Handler while preserving its other behavior.
+//
+// This example demonstrates increasing the log level to reduce a logger's
+// output.
+//
+// Another typical use would be to decrease the log level (to LevelDebug, say)
+// during a part of the program that was suspected of containing a bug.
+func ExampleHandler_levelHandler() {
+    th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime})
+    logger := slog.New(NewLevelHandler(slog.LevelWarn, th))
+    logger.Info("not printed")
+    logger.Warn("printed")
+
+    // Output:
+    // level=WARN msg=printed
+}
+

type HandlerOptions 1.21

HandlerOptions are options for a TextHandler or JSONHandler. A zero HandlerOptions consists entirely of default values.

+
type HandlerOptions struct {
+    // AddSource causes the handler to compute the source code position
+    // of the log statement and add a SourceKey attribute to the output.
+    AddSource bool
+
+    // Level reports the minimum record level that will be logged.
+    // The handler discards records with lower levels.
+    // If Level is nil, the handler assumes LevelInfo.
+    // The handler calls Level.Level for each record processed;
+    // to adjust the minimum level dynamically, use a LevelVar.
+    Level Leveler
+
+    // ReplaceAttr is called to rewrite each non-group attribute before it is logged.
+    // The attribute's value has been resolved (see [Value.Resolve]).
+    // If ReplaceAttr returns a zero Attr, the attribute is discarded.
+    //
+    // The built-in attributes with keys "time", "level", "source", and "msg"
+    // are passed to this function, except that time is omitted
+    // if zero, and source is omitted if AddSource is false.
+    //
+    // The first argument is a list of currently open groups that contain the
+    // Attr. It must not be retained or modified. ReplaceAttr is never called
+    // for Group attributes, only their contents. For example, the attribute
+    // list
+    //
+    //     Int("a", 1), Group("g", Int("b", 2)), Int("c", 3)
+    //
+    // results in consecutive calls to ReplaceAttr with the following arguments:
+    //
+    //     nil, Int("a", 1)
+    //     []string{"g"}, Int("b", 2)
+    //     nil, Int("c", 3)
+    //
+    // ReplaceAttr can be used to change the default keys of the built-in
+    // attributes, convert types (for example, to replace a `time.Time` with the
+    // integer seconds since the Unix epoch), sanitize personal information, or
+    // remove attributes from the output.
+    ReplaceAttr func(groups []string, a Attr) Attr
+}
+

Example (CustomLevels) +

This example demonstrates using custom log levels and custom log level names. In addition to the default log levels, it introduces Trace, Notice, and Emergency levels. The ReplaceAttr changes the way levels are printed for both the standard log levels and the custom log levels.

Code:

// Exported constants from a custom logging package.
+const (
+    LevelTrace     = slog.Level(-8)
+    LevelDebug     = slog.LevelDebug
+    LevelInfo      = slog.LevelInfo
+    LevelNotice    = slog.Level(2)
+    LevelWarning   = slog.LevelWarn
+    LevelError     = slog.LevelError
+    LevelEmergency = slog.Level(12)
+)
+
+th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
+    // Set a custom level to show all log output. The default value is
+    // LevelInfo, which would drop Debug and Trace logs.
+    Level: LevelTrace,
+
+    ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
+        // Remove time from the output for predictable test output.
+        if a.Key == slog.TimeKey {
+            return slog.Attr{}
+        }
+
+        // Customize the name of the level key and the output string, including
+        // custom level values.
+        if a.Key == slog.LevelKey {
+            // Rename the level key from "level" to "sev".
+            a.Key = "sev"
+
+            // Handle custom level values.
+            level := a.Value.Any().(slog.Level)
+
+            // This could also look up the name from a map or other structure, but
+            // this demonstrates using a switch statement to rename levels. For
+            // maximum performance, the string values should be constants, but this
+            // example uses the raw strings for readability.
+            switch {
+            case level < LevelDebug:
+                a.Value = slog.StringValue("TRACE")
+            case level < LevelInfo:
+                a.Value = slog.StringValue("DEBUG")
+            case level < LevelNotice:
+                a.Value = slog.StringValue("INFO")
+            case level < LevelWarning:
+                a.Value = slog.StringValue("NOTICE")
+            case level < LevelError:
+                a.Value = slog.StringValue("WARNING")
+            case level < LevelEmergency:
+                a.Value = slog.StringValue("ERROR")
+            default:
+                a.Value = slog.StringValue("EMERGENCY")
+            }
+        }
+
+        return a
+    },
+})
+
+logger := slog.New(th)
+ctx := context.Background()
+logger.Log(ctx, LevelEmergency, "missing pilots")
+logger.Error("failed to start engines", "err", "missing fuel")
+logger.Warn("falling back to default value")
+logger.Log(ctx, LevelNotice, "all systems are running")
+logger.Info("initiating launch")
+logger.Debug("starting background job")
+logger.Log(ctx, LevelTrace, "button clicked")
+
+

Output:

sev=EMERGENCY msg="missing pilots"
+sev=ERROR msg="failed to start engines" err="missing fuel"
+sev=WARNING msg="falling back to default value"
+sev=NOTICE msg="all systems are running"
+sev=INFO msg="initiating launch"
+sev=DEBUG msg="starting background job"
+sev=TRACE msg="button clicked"
+

type JSONHandler 1.21

JSONHandler is a Handler that writes Records to an io.Writer as line-delimited JSON objects.

+
type JSONHandler struct {
+    // contains filtered or unexported fields
+}
+

func NewJSONHandler 1.21

func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler

NewJSONHandler creates a JSONHandler that writes to w, using the given options. If opts is nil, the default options are used.

+

func (*JSONHandler) Enabled 1.21

func (h *JSONHandler) Enabled(_ context.Context, level Level) bool

Enabled reports whether the handler handles records at the given level. The handler ignores records whose level is lower.

+

func (*JSONHandler) Handle 1.21

func (h *JSONHandler) Handle(_ context.Context, r Record) error

Handle formats its argument Record as a JSON object on a single line.

+

If the Record's time is zero, the time is omitted. Otherwise, the key is "time" and the value is output as with json.Marshal.

+

If the Record's level is zero, the level is omitted. Otherwise, the key is "level" and the value of Level.String is output.

+

If the AddSource option is set and source information is available, the key is "source", and the value is a record of type Source.

+

The message's key is "msg".

+

To modify these or other attributes, or remove them from the output, use [HandlerOptions.ReplaceAttr].

+

Values are formatted as with an encoding/json.Encoder with SetEscapeHTML(false), with two exceptions.

+

First, an Attr whose Value is of type error is formatted as a string, by calling its Error method. Only errors in Attrs receive this special treatment, not errors embedded in structs, slices, maps or other data structures that are processed by the encoding/json package.

+

Second, an encoding failure does not cause Handle to return an error. Instead, the error message is formatted as a string.

+

Each call to Handle results in a single serialized call to io.Writer.Write.

+

func (*JSONHandler) WithAttrs 1.21

func (h *JSONHandler) WithAttrs(attrs []Attr) Handler

WithAttrs returns a new JSONHandler whose attributes consists of h's attributes followed by attrs.

+

func (*JSONHandler) WithGroup 1.21

func (h *JSONHandler) WithGroup(name string) Handler

type Kind 1.21

Kind is the kind of a Value.

+
type Kind int
const (
+    KindAny Kind = iota
+    KindBool
+    KindDuration
+    KindFloat64
+    KindInt64
+    KindString
+    KindTime
+    KindUint64
+    KindGroup
+    KindLogValuer
+)

func (Kind) String 1.21

func (k Kind) String() string

type Level 1.21

A Level is the importance or severity of a log event. The higher the level, the more important or severe the event.

+
type Level int

Names for common levels.

+

Level numbers are inherently arbitrary, but we picked them to satisfy three constraints. Any system can map them to another numbering scheme if it wishes.

+

First, we wanted the default level to be Info, Since Levels are ints, Info is the default value for int, zero.

+

Second, we wanted to make it easy to use levels to specify logger verbosity. Since a larger level means a more severe event, a logger that accepts events with smaller (or more negative) level means a more verbose logger. Logger verbosity is thus the negation of event severity, and the default verbosity of 0 accepts all events at least as severe as INFO.

+

Third, we wanted some room between levels to accommodate schemes with named levels between ours. For example, Google Cloud Logging defines a Notice level between Info and Warn. Since there are only a few of these intermediate levels, the gap between the numbers need not be large. Our gap of 4 matches OpenTelemetry's mapping. Subtracting 9 from an OpenTelemetry level in the DEBUG, INFO, WARN and ERROR ranges converts it to the corresponding slog Level range. OpenTelemetry also has the names TRACE and FATAL, which slog does not. But those OpenTelemetry levels can still be represented as slog Levels by using the appropriate integers.

+
const (
+    LevelDebug Level = -4
+    LevelInfo  Level = 0
+    LevelWarn  Level = 4
+    LevelError Level = 8
+)

func SetLogLoggerLevel 1.22

func SetLogLoggerLevel(level Level) (oldLevel Level)

SetLogLoggerLevel controls the level for the bridge to the log package.

+

Before SetDefault is called, slog top-level logging functions call the default log.Logger. In that mode, SetLogLoggerLevel sets the minimum level for those calls. By default, the minimum level is Info, so calls to Debug (as well as top-level logging calls at lower levels) will not be passed to the log.Logger. After calling

+
slog.SetLogLoggerLevel(slog.LevelDebug)
+

calls to Debug will be passed to the log.Logger.

+

After SetDefault is called, calls to the default log.Logger are passed to the slog default handler. In that mode, SetLogLoggerLevel sets the level at which those calls are logged. That is, after calling

+
slog.SetLogLoggerLevel(slog.LevelDebug)
+

A call to log.Printf will result in output at level LevelDebug.

+

SetLogLoggerLevel returns the previous value.

Example (Log) +

This example shows how to use slog.SetLogLoggerLevel to change the minimal level of the internal default handler for slog package before calling slog.SetDefault.

Code:

defer log.SetFlags(log.Flags()) // revert changes after the example
+log.SetFlags(0)
+defer log.SetOutput(log.Writer()) // revert changes after the example
+log.SetOutput(os.Stdout)
+
+// Default logging level is slog.LevelInfo.
+log.Print("log debug") // log debug
+slog.Debug("debug")    // no output
+slog.Info("info")      // INFO info
+
+// Set the default logging level to slog.LevelDebug.
+currentLogLevel := slog.SetLogLoggerLevel(slog.LevelDebug)
+defer slog.SetLogLoggerLevel(currentLogLevel) // revert changes after the example
+
+log.Print("log debug") // log debug
+slog.Debug("debug")    // DEBUG debug
+slog.Info("info")      // INFO info
+
+

Output:

log debug
+INFO info
+log debug
+DEBUG debug
+INFO info
+

Example (Slog) +

This example shows how to use slog.SetLogLoggerLevel to change the minimal level of the internal writer that uses the custom handler for log package after calling slog.SetDefault.

Code:

// Set the default logging level to slog.LevelError.
+currentLogLevel := slog.SetLogLoggerLevel(slog.LevelError)
+defer slog.SetLogLoggerLevel(currentLogLevel) // revert changes after the example
+
+defer slog.SetDefault(slog.Default()) // revert changes after the example
+slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime})))
+
+log.Print("error") // level=ERROR msg=error
+
+

Output:

level=ERROR msg=error
+

func (Level) Level 1.21

func (l Level) Level() Level

Level returns the receiver. It implements Leveler.

+

func (Level) MarshalJSON 1.21

func (l Level) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler by quoting the output of Level.String.

+

func (Level) MarshalText 1.21

func (l Level) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler by calling Level.String.

+

func (Level) String 1.21

func (l Level) String() string

String returns a name for the level. If the level has a name, then that name in uppercase is returned. If the level is between named values, then an integer is appended to the uppercased name. Examples:

+
LevelWarn.String() => "WARN"
+(LevelInfo+2).String() => "INFO+2"
+

func (*Level) UnmarshalJSON 1.21

func (l *Level) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler It accepts any string produced by Level.MarshalJSON, ignoring case. It also accepts numeric offsets that would result in a different string on output. For example, "Error-8" would marshal as "INFO".

+

func (*Level) UnmarshalText 1.21

func (l *Level) UnmarshalText(data []byte) error

UnmarshalText implements encoding.TextUnmarshaler. It accepts any string produced by Level.MarshalText, ignoring case. It also accepts numeric offsets that would result in a different string on output. For example, "Error-8" would marshal as "INFO".

+

type LevelVar 1.21

A LevelVar is a Level variable, to allow a Handler level to change dynamically. It implements Leveler as well as a Set method, and it is safe for use by multiple goroutines. The zero LevelVar corresponds to LevelInfo.

+
type LevelVar struct {
+    // contains filtered or unexported fields
+}
+

func (*LevelVar) Level 1.21

func (v *LevelVar) Level() Level

Level returns v's level.

+

func (*LevelVar) MarshalText 1.21

func (v *LevelVar) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler by calling Level.MarshalText.

+

func (*LevelVar) Set 1.21

func (v *LevelVar) Set(l Level)

Set sets v's level to l.

+

func (*LevelVar) String 1.21

func (v *LevelVar) String() string

func (*LevelVar) UnmarshalText 1.21

func (v *LevelVar) UnmarshalText(data []byte) error

UnmarshalText implements encoding.TextUnmarshaler by calling Level.UnmarshalText.

+

type Leveler 1.21

A Leveler provides a Level value.

+

As Level itself implements Leveler, clients typically supply a Level value wherever a Leveler is needed, such as in HandlerOptions. Clients who need to vary the level dynamically can provide a more complex Leveler implementation such as *LevelVar.

+
type Leveler interface {
+    Level() Level
+}

type LogValuer 1.21

A LogValuer is any Go value that can convert itself into a Value for logging.

+

This mechanism may be used to defer expensive operations until they are needed, or to expand a single value into a sequence of components.

+
type LogValuer interface {
+    LogValue() Value
+}

Example (Group) +

Code:

package slog_test
+
+import "log/slog"
+
+type Name struct {
+    First, Last string
+}
+
+// LogValue implements slog.LogValuer.
+// It returns a group containing the fields of
+// the Name, so that they appear together in the log output.
+func (n Name) LogValue() slog.Value {
+    return slog.GroupValue(
+        slog.String("first", n.First),
+        slog.String("last", n.Last))
+}
+
+func ExampleLogValuer_group() {
+    n := Name{"Perry", "Platypus"}
+    slog.Info("mission accomplished", "agent", n)
+
+    // JSON Output would look in part like:
+    // {
+    //     ...
+    //     "msg": "mission accomplished",
+    //     "agent": {
+    //         "first": "Perry",
+    //         "last": "Platypus"
+    //     }
+    // }
+}
+

Example (Secret) +

This example demonstrates a Value that replaces itself with an alternative representation to avoid revealing secrets.

Code:

package slog_test
+
+import (
+    "log/slog"
+    "log/slog/internal/slogtest"
+    "os"
+)
+
+// A token is a secret value that grants permissions.
+type Token string
+
+// LogValue implements slog.LogValuer.
+// It avoids revealing the token.
+func (Token) LogValue() slog.Value {
+    return slog.StringValue("REDACTED_TOKEN")
+}
+
+// This example demonstrates a Value that replaces itself
+// with an alternative representation to avoid revealing secrets.
+func ExampleLogValuer_secret() {
+    t := Token("shhhh!")
+    logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}))
+    logger.Info("permission granted", "user", "Perry", "token", t)
+
+    // Output:
+    // level=INFO msg="permission granted" user=Perry token=REDACTED_TOKEN
+}
+

type Logger 1.21

A Logger records structured information about each call to its Log, Debug, Info, Warn, and Error methods. For each call, it creates a Record and passes it to a Handler.

+

To create a new Logger, call New or a Logger method that begins "With".

+
type Logger struct {
+    // contains filtered or unexported fields
+}
+

func Default 1.21

func Default() *Logger

Default returns the default Logger.

+

func New 1.21

func New(h Handler) *Logger

New creates a new Logger with the given non-nil Handler.

+

func With 1.21

func With(args ...any) *Logger

With calls Logger.With on the default logger.

+

func (*Logger) Debug 1.21

func (l *Logger) Debug(msg string, args ...any)

Debug logs at LevelDebug.

+

func (*Logger) DebugContext 1.21

func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any)

DebugContext logs at LevelDebug with the given context.

+

func (*Logger) Enabled 1.21

func (l *Logger) Enabled(ctx context.Context, level Level) bool

Enabled reports whether l emits log records at the given context and level.

+

func (*Logger) Error 1.21

func (l *Logger) Error(msg string, args ...any)

Error logs at LevelError.

+

func (*Logger) ErrorContext 1.21

func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any)

ErrorContext logs at LevelError with the given context.

+

func (*Logger) Handler 1.21

func (l *Logger) Handler() Handler

Handler returns l's Handler.

+

func (*Logger) Info 1.21

func (l *Logger) Info(msg string, args ...any)

Info logs at LevelInfo.

+

func (*Logger) InfoContext 1.21

func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any)

InfoContext logs at LevelInfo with the given context.

+

func (*Logger) Log 1.21

func (l *Logger) Log(ctx context.Context, level Level, msg string, args ...any)

Log emits a log record with the current time and the given level and message. The Record's Attrs consist of the Logger's attributes followed by the Attrs specified by args.

+

The attribute arguments are processed as follows:

+

func (*Logger) LogAttrs 1.21

func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)

LogAttrs is a more efficient version of Logger.Log that accepts only Attrs.

+

func (*Logger) Warn 1.21

func (l *Logger) Warn(msg string, args ...any)

Warn logs at LevelWarn.

+

func (*Logger) WarnContext 1.21

func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any)

WarnContext logs at LevelWarn with the given context.

+

func (*Logger) With 1.21

func (l *Logger) With(args ...any) *Logger

With returns a Logger that includes the given attributes in each output operation. Arguments are converted to attributes as if by Logger.Log.

+

func (*Logger) WithGroup 1.21

func (l *Logger) WithGroup(name string) *Logger

WithGroup returns a Logger that starts a group, if name is non-empty. The keys of all attributes added to the Logger will be qualified by the given name. (How that qualification happens depends on the [Handler.WithGroup] method of the Logger's Handler.)

+

If name is empty, WithGroup returns the receiver.

+

type Record 1.21

A Record holds information about a log event. Copies of a Record share state. Do not modify a Record after handing out a copy to it. Call NewRecord to create a new Record. Use Record.Clone to create a copy with no shared state.

+
type Record struct {
+    // The time at which the output method (Log, Info, etc.) was called.
+    Time time.Time
+
+    // The log message.
+    Message string
+
+    // The level of the event.
+    Level Level
+
+    // The program counter at the time the record was constructed, as determined
+    // by runtime.Callers. If zero, no program counter is available.
+    //
+    // The only valid use for this value is as an argument to
+    // [runtime.CallersFrames]. In particular, it must not be passed to
+    // [runtime.FuncForPC].
+    PC uintptr
+    // contains filtered or unexported fields
+}
+

func NewRecord 1.21

func NewRecord(t time.Time, level Level, msg string, pc uintptr) Record

NewRecord creates a Record from the given arguments. Use Record.AddAttrs to add attributes to the Record.

+

NewRecord is intended for logging APIs that want to support a Handler as a backend.

+

func (*Record) Add 1.21

func (r *Record) Add(args ...any)

Add converts the args to Attrs as described in Logger.Log, then appends the Attrs to the Record's list of Attrs. It omits empty groups.

+

func (*Record) AddAttrs 1.21

func (r *Record) AddAttrs(attrs ...Attr)

AddAttrs appends the given Attrs to the Record's list of Attrs. It omits empty groups.

+

func (Record) Attrs 1.21

func (r Record) Attrs(f func(Attr) bool)

Attrs calls f on each Attr in the Record. Iteration stops if f returns false.

+

func (Record) Clone 1.21

func (r Record) Clone() Record

Clone returns a copy of the record with no shared state. The original record and the clone can both be modified without interfering with each other.

+

func (Record) NumAttrs 1.21

func (r Record) NumAttrs() int

NumAttrs returns the number of attributes in the Record.

+

type Source 1.21

Source describes the location of a line of source code.

+
type Source struct {
+    // Function is the package path-qualified function name containing the
+    // source line. If non-empty, this string uniquely identifies a single
+    // function in the program. This may be the empty string if not known.
+    Function string `json:"function"`
+    // File and Line are the file name and line number (1-based) of the source
+    // line. These may be the empty string and zero, respectively, if not known.
+    File string `json:"file"`
+    Line int    `json:"line"`
+}
+

type TextHandler 1.21

TextHandler is a Handler that writes Records to an io.Writer as a sequence of key=value pairs separated by spaces and followed by a newline.

+
type TextHandler struct {
+    // contains filtered or unexported fields
+}
+

func NewTextHandler 1.21

func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler

NewTextHandler creates a TextHandler that writes to w, using the given options. If opts is nil, the default options are used.

+

func (*TextHandler) Enabled 1.21

func (h *TextHandler) Enabled(_ context.Context, level Level) bool

Enabled reports whether the handler handles records at the given level. The handler ignores records whose level is lower.

+

func (*TextHandler) Handle 1.21

func (h *TextHandler) Handle(_ context.Context, r Record) error

Handle formats its argument Record as a single line of space-separated key=value items.

+

If the Record's time is zero, the time is omitted. Otherwise, the key is "time" and the value is output in RFC3339 format with millisecond precision.

+

If the Record's level is zero, the level is omitted. Otherwise, the key is "level" and the value of Level.String is output.

+

If the AddSource option is set and source information is available, the key is "source" and the value is output as FILE:LINE.

+

The message's key is "msg".

+

To modify these or other attributes, or remove them from the output, use [HandlerOptions.ReplaceAttr].

+

If a value implements encoding.TextMarshaler, the result of MarshalText is written. Otherwise, the result of fmt.Sprint is written.

+

Keys and values are quoted with strconv.Quote if they contain Unicode space characters, non-printing characters, '"' or '='.

+

Keys inside groups consist of components (keys or group names) separated by dots. No further escaping is performed. Thus there is no way to determine from the key "a.b.c" whether there are two groups "a" and "b" and a key "c", or a single group "a.b" and a key "c", or single group "a" and a key "b.c". If it is necessary to reconstruct the group structure of a key even in the presence of dots inside components, use [HandlerOptions.ReplaceAttr] to encode that information in the key.

+

Each call to Handle results in a single serialized call to io.Writer.Write.

+

func (*TextHandler) WithAttrs 1.21

func (h *TextHandler) WithAttrs(attrs []Attr) Handler

WithAttrs returns a new TextHandler whose attributes consists of h's attributes followed by attrs.

+

func (*TextHandler) WithGroup 1.21

func (h *TextHandler) WithGroup(name string) Handler

type Value 1.21

A Value can represent any Go value, but unlike type any, it can represent most small values without an allocation. The zero Value corresponds to nil.

+
type Value struct {
+    // contains filtered or unexported fields
+}
+

func AnyValue 1.21

func AnyValue(v any) Value

AnyValue returns a Value for the supplied value.

+

If the supplied value is of type Value, it is returned unmodified.

+

Given a value of one of Go's predeclared string, bool, or (non-complex) numeric types, AnyValue returns a Value of kind KindString, KindBool, KindUint64, KindInt64, or KindFloat64. The width of the original numeric type is not preserved.

+

Given a time.Time or time.Duration value, AnyValue returns a Value of kind KindTime or KindDuration. The monotonic time is not preserved.

+

For nil, or values of all other types, including named types whose underlying type is numeric, AnyValue returns a value of kind KindAny.

+

func BoolValue 1.21

func BoolValue(v bool) Value

BoolValue returns a Value for a bool.

+

func DurationValue 1.21

func DurationValue(v time.Duration) Value

DurationValue returns a Value for a time.Duration.

+

func Float64Value 1.21

func Float64Value(v float64) Value

Float64Value returns a Value for a floating-point number.

+

func GroupValue 1.21

func GroupValue(as ...Attr) Value

GroupValue returns a new Value for a list of Attrs. The caller must not subsequently mutate the argument slice.

+

func Int64Value 1.21

func Int64Value(v int64) Value

Int64Value returns a Value for an int64.

+

func IntValue 1.21

func IntValue(v int) Value

IntValue returns a Value for an int.

+

func StringValue 1.21

func StringValue(value string) Value

StringValue returns a new Value for a string.

+

func TimeValue 1.21

func TimeValue(v time.Time) Value

TimeValue returns a Value for a time.Time. It discards the monotonic portion.

+

func Uint64Value 1.21

func Uint64Value(v uint64) Value

Uint64Value returns a Value for a uint64.

+

func (Value) Any 1.21

func (v Value) Any() any

Any returns v's value as an any.

+

func (Value) Bool 1.21

func (v Value) Bool() bool

Bool returns v's value as a bool. It panics if v is not a bool.

+

func (Value) Duration 1.21

func (v Value) Duration() time.Duration

Duration returns v's value as a time.Duration. It panics if v is not a time.Duration.

+

func (Value) Equal 1.21

func (v Value) Equal(w Value) bool

Equal reports whether v and w represent the same Go value.

+

func (Value) Float64 1.21

func (v Value) Float64() float64

Float64 returns v's value as a float64. It panics if v is not a float64.

+

func (Value) Group 1.21

func (v Value) Group() []Attr

Group returns v's value as a []Attr. It panics if v's Kind is not KindGroup.

+

func (Value) Int64 1.21

func (v Value) Int64() int64

Int64 returns v's value as an int64. It panics if v is not a signed integer.

+

func (Value) Kind 1.21

func (v Value) Kind() Kind

Kind returns v's Kind.

+

func (Value) LogValuer 1.21

func (v Value) LogValuer() LogValuer

LogValuer returns v's value as a LogValuer. It panics if v is not a LogValuer.

+

func (Value) Resolve 1.21

func (v Value) Resolve() (rv Value)

Resolve repeatedly calls LogValue on v while it implements LogValuer, and returns the result. If v resolves to a group, the group's attributes' values are not recursively resolved. If the number of LogValue calls exceeds a threshold, a Value containing an error is returned. Resolve's return value is guaranteed not to be of Kind KindLogValuer.

+

func (Value) String 1.21

func (v Value) String() string

String returns Value's value as a string, formatted like fmt.Sprint. Unlike the methods Int64, Float64, and so on, which panic if v is of the wrong kind, String never panics.

+

func (Value) Time 1.21

func (v Value) Time() time.Time

Time returns v's value as a time.Time. It panics if v is not a time.Time.

+

func (Value) Uint64 1.21

func (v Value) Uint64() uint64

Uint64 returns v's value as a uint64. It panics if v is not an unsigned integer.

+

Subdirectories

Name Synopsis
..
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/log/slog/ +

+
diff --git a/devdocs/go/log%2Fsyslog%2Findex.html b/devdocs/go/log%2Fsyslog%2Findex.html new file mode 100644 index 00000000..e33c270c --- /dev/null +++ b/devdocs/go/log%2Fsyslog%2Findex.html @@ -0,0 +1,109 @@ +

Package syslog

Overview

Package syslog provides a simple interface to the system log service. It can send messages to the syslog daemon using UNIX domain sockets, UDP or TCP.

+

Only one call to Dial is necessary. On write failures, the syslog client will attempt to reconnect to the server and write again.

+

The syslog package is frozen and is not accepting new features. Some external packages provide more functionality. See:

+
https://godoc.org/?q=syslog
+

Index

Examples

Dial

Package files

doc.go syslog.go syslog_unix.go

func NewLogger

func NewLogger(p Priority, logFlag int) (*log.Logger, error)

NewLogger creates a log.Logger whose output is written to the system log service with the specified priority, a combination of the syslog facility and severity. The logFlag argument is the flag set passed through to log.New to create the Logger.

+

type Priority

The Priority is a combination of the syslog facility and severity. For example, LOG_ALERT | LOG_FTP sends an alert severity message from the FTP facility. The default severity is LOG_EMERG; the default facility is LOG_KERN.

+
type Priority int
const (
+
+    // From /usr/include/sys/syslog.h.
+    // These are the same on Linux, BSD, and OS X.
+    LOG_EMERG Priority = iota
+    LOG_ALERT
+    LOG_CRIT
+    LOG_ERR
+    LOG_WARNING
+    LOG_NOTICE
+    LOG_INFO
+    LOG_DEBUG
+)
const (
+
+    // From /usr/include/sys/syslog.h.
+    // These are the same up to LOG_FTP on Linux, BSD, and OS X.
+    LOG_KERN Priority = iota << 3
+    LOG_USER
+    LOG_MAIL
+    LOG_DAEMON
+    LOG_AUTH
+    LOG_SYSLOG
+    LOG_LPR
+    LOG_NEWS
+    LOG_UUCP
+    LOG_CRON
+    LOG_AUTHPRIV
+    LOG_FTP
+
+    LOG_LOCAL0
+    LOG_LOCAL1
+    LOG_LOCAL2
+    LOG_LOCAL3
+    LOG_LOCAL4
+    LOG_LOCAL5
+    LOG_LOCAL6
+    LOG_LOCAL7
+)

type Writer

A Writer is a connection to a syslog server.

+
type Writer struct {
+    // contains filtered or unexported fields
+}
+

func Dial

func Dial(network, raddr string, priority Priority, tag string) (*Writer, error)

Dial establishes a connection to a log daemon by connecting to address raddr on the specified network. Each write to the returned writer sends a log message with the facility and severity (from priority) and tag. If tag is empty, the os.Args[0] is used. If network is empty, Dial will connect to the local syslog server. Otherwise, see the documentation for net.Dial for valid values of network and raddr.

Example +

Code:

+sysLog, err := syslog.Dial("tcp", "localhost:1234",
+    syslog.LOG_WARNING|syslog.LOG_DAEMON, "demotag")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Fprintf(sysLog, "This is a daemon warning with demotag.")
+sysLog.Emerg("And this is a daemon emergency with demotag.")
+

func New

func New(priority Priority, tag string) (*Writer, error)

New establishes a new connection to the system log daemon. Each write to the returned writer sends a log message with the given priority (a combination of the syslog facility and severity) and prefix tag. If tag is empty, the os.Args[0] is used.

+

func (*Writer) Alert

func (w *Writer) Alert(m string) error

Alert logs a message with severity LOG_ALERT, ignoring the severity passed to New.

+

func (*Writer) Close

func (w *Writer) Close() error

Close closes a connection to the syslog daemon.

+

func (*Writer) Crit

func (w *Writer) Crit(m string) error

Crit logs a message with severity LOG_CRIT, ignoring the severity passed to New.

+

func (*Writer) Debug

func (w *Writer) Debug(m string) error

Debug logs a message with severity LOG_DEBUG, ignoring the severity passed to New.

+

func (*Writer) Emerg

func (w *Writer) Emerg(m string) error

Emerg logs a message with severity LOG_EMERG, ignoring the severity passed to New.

+

func (*Writer) Err

func (w *Writer) Err(m string) error

Err logs a message with severity LOG_ERR, ignoring the severity passed to New.

+

func (*Writer) Info

func (w *Writer) Info(m string) error

Info logs a message with severity LOG_INFO, ignoring the severity passed to New.

+

func (*Writer) Notice

func (w *Writer) Notice(m string) error

Notice logs a message with severity LOG_NOTICE, ignoring the severity passed to New.

+

func (*Writer) Warning

func (w *Writer) Warning(m string) error

Warning logs a message with severity LOG_WARNING, ignoring the severity passed to New.

+

func (*Writer) Write

func (w *Writer) Write(b []byte) (int, error)

Write sends a log message to the syslog daemon.

+

Bugs

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/log/syslog/ +

+
diff --git a/devdocs/go/maps%2Findex.html b/devdocs/go/maps%2Findex.html new file mode 100644 index 00000000..3d751a7d --- /dev/null +++ b/devdocs/go/maps%2Findex.html @@ -0,0 +1,126 @@ +

Package maps

Overview

Package maps defines various functions useful with maps of any type.

Index

Examples

Clone
Copy
DeleteFunc
Equal
EqualFunc

Package files

maps.go

func Clone

func Clone[M ~map[K]V, K comparable, V any](m M) M

Clone returns a copy of m. This is a shallow clone: the new keys and values are set using ordinary assignment.

Example +

Code:

m1 := map[string]int{
+    "key": 1,
+}
+m2 := maps.Clone(m1)
+m2["key"] = 100
+fmt.Println(m1["key"])
+fmt.Println(m2["key"])
+
+m3 := map[string][]int{
+    "key": {1, 2, 3},
+}
+m4 := maps.Clone(m3)
+fmt.Println(m4["key"][0])
+m4["key"][0] = 100
+fmt.Println(m3["key"][0])
+fmt.Println(m4["key"][0])
+
+

Output:

1
+100
+1
+100
+100
+

func Copy

func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2)

Copy copies all key/value pairs in src adding them to dst. When a key in src is already present in dst, the value in dst will be overwritten by the value associated with the key in src.

Example +

Code:

m1 := map[string]int{
+    "one": 1,
+    "two": 2,
+}
+m2 := map[string]int{
+    "one": 10,
+}
+
+maps.Copy(m2, m1)
+fmt.Println("m2 is:", m2)
+
+m2["one"] = 100
+fmt.Println("m1 is:", m1)
+fmt.Println("m2 is:", m2)
+
+m3 := map[string][]int{
+    "one": {1, 2, 3},
+    "two": {4, 5, 6},
+}
+m4 := map[string][]int{
+    "one": {7, 8, 9},
+}
+
+maps.Copy(m4, m3)
+fmt.Println("m4 is:", m4)
+
+m4["one"][0] = 100
+fmt.Println("m3 is:", m3)
+fmt.Println("m4 is:", m4)
+
+

Output:

m2 is: map[one:1 two:2]
+m1 is: map[one:1 two:2]
+m2 is: map[one:100 two:2]
+m4 is: map[one:[1 2 3] two:[4 5 6]]
+m3 is: map[one:[100 2 3] two:[4 5 6]]
+m4 is: map[one:[100 2 3] two:[4 5 6]]
+

func DeleteFunc

func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool)

DeleteFunc deletes any key/value pairs from m for which del returns true.

Example +

Code:

m := map[string]int{
+    "one":   1,
+    "two":   2,
+    "three": 3,
+    "four":  4,
+}
+maps.DeleteFunc(m, func(k string, v int) bool {
+    return v%2 != 0 // delete odd values
+})
+fmt.Println(m)
+

Output:

map[four:4 two:2]
+

func Equal

func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool

Equal reports whether two maps contain the same key/value pairs. Values are compared using ==.

Example +

Code:

m1 := map[int]string{
+    1:    "one",
+    10:   "Ten",
+    1000: "THOUSAND",
+}
+m2 := map[int]string{
+    1:    "one",
+    10:   "Ten",
+    1000: "THOUSAND",
+}
+m3 := map[int]string{
+    1:    "one",
+    10:   "ten",
+    1000: "thousand",
+}
+
+fmt.Println(maps.Equal(m1, m2))
+fmt.Println(maps.Equal(m1, m3))
+

Output:

true
+false
+

func EqualFunc

func EqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](m1 M1, m2 M2, eq func(V1, V2) bool) bool

EqualFunc is like Equal, but compares values using eq. Keys are still compared with ==.

Example +

Code:

m1 := map[int]string{
+    1:    "one",
+    10:   "Ten",
+    1000: "THOUSAND",
+}
+m2 := map[int][]byte{
+    1:    []byte("One"),
+    10:   []byte("Ten"),
+    1000: []byte("Thousand"),
+}
+eq := maps.EqualFunc(m1, m2, func(v1 string, v2 []byte) bool {
+    return strings.ToLower(v1) == strings.ToLower(string(v2))
+})
+fmt.Println(eq)
+

Output:

true
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/maps/ +

+
diff --git a/devdocs/go/math%2Fbig%2Findex.html b/devdocs/go/math%2Fbig%2Findex.html new file mode 100644 index 00000000..1c1d9c2b --- /dev/null +++ b/devdocs/go/math%2Fbig%2Findex.html @@ -0,0 +1,912 @@ +

Package big

Overview

Package big implements arbitrary-precision arithmetic (big numbers). The following numeric types are supported:

+
Int    signed integers
+Rat    rational numbers
+Float  floating-point numbers
+

The zero value for an Int, Rat, or Float correspond to 0. Thus, new values can be declared in the usual ways and denote 0 without further initialization:

+
var x Int        // &x is an *Int of value 0
+var r = &Rat{}   // r is a *Rat of value 0
+y := new(Float)  // y is a *Float of value 0
+

Alternatively, new values can be allocated and initialized with factory functions of the form:

+
func NewT(v V) *T
+

For instance, NewInt(x) returns an *Int set to the value of the int64 argument x, NewRat(a, b) returns a *Rat set to the fraction a/b where a and b are int64 values, and NewFloat(f) returns a *Float initialized to the float64 argument f. More flexibility is provided with explicit setters, for instance:

+
var z1 Int
+z1.SetUint64(123)                 // z1 := 123
+z2 := new(Rat).SetFloat64(1.25)   // z2 := 5/4
+z3 := new(Float).SetInt(z1)       // z3 := 123.0
+

Setters, numeric operations and predicates are represented as methods of the form:

+
func (z *T) SetV(v V) *T          // z = v
+func (z *T) Unary(x *T) *T        // z = unary x
+func (z *T) Binary(x, y *T) *T    // z = x binary y
+func (x *T) Pred() P              // p = pred(x)
+

with T one of Int, Rat, or Float. For unary and binary operations, the result is the receiver (usually named z in that case; see below); if it is one of the operands x or y it may be safely overwritten (and its memory reused).

+

Arithmetic expressions are typically written as a sequence of individual method calls, with each call corresponding to an operation. The receiver denotes the result and the method arguments are the operation's operands. For instance, given three *Int values a, b and c, the invocation

+
c.Add(a, b)
+

computes the sum a + b and stores the result in c, overwriting whatever value was held in c before. Unless specified otherwise, operations permit aliasing of parameters, so it is perfectly ok to write

+
sum.Add(sum, x)
+

to accumulate values x in a sum.

+

(By always passing in a result value via the receiver, memory use can be much better controlled. Instead of having to allocate new memory for each result, an operation can reuse the space allocated for the result value, and overwrite that value with the new result in the process.)

+

Notational convention: Incoming method parameters (including the receiver) are named consistently in the API to clarify their use. Incoming operands are usually named x, y, a, b, and so on, but never z. A parameter specifying the result is named z (typically the receiver).

+

For instance, the arguments for (*Int).Add are named x and y, and because the receiver specifies the result destination, it is called z:

+
func (z *Int) Add(x, y *Int) *Int
+

Methods of this form typically return the incoming receiver as well, to enable simple call chaining.

+

Methods which don't require a result value to be passed in (for instance, Int.Sign), simply return the result. In this case, the receiver is typically the first operand, named x:

+
func (x *Int) Sign() int
+

Various methods support conversions between strings and corresponding numeric values, and vice versa: *Int, *Rat, and *Float values implement the Stringer interface for a (default) string representation of the value, but also provide SetString methods to initialize a value from a string in a variety of supported formats (see the respective SetString documentation).

+

Finally, *Int, *Rat, and *Float satisfy fmt.Scanner for scanning and (except for *Rat) the Formatter interface for formatted printing.

Example (EConvergents) +

This example demonstrates how to use big.Rat to compute the first 15 terms in the sequence of rational convergents for the constant e (base of natural logarithm).

Code:

package big_test
+
+import (
+    "fmt"
+    "math/big"
+)
+
+// Use the classic continued fraction for e
+//
+//	e = [1; 0, 1, 1, 2, 1, 1, ... 2n, 1, 1, ...]
+//
+// i.e., for the nth term, use
+//
+//	   1          if   n mod 3 != 1
+//	(n-1)/3 * 2   if   n mod 3 == 1
+func recur(n, lim int64) *big.Rat {
+    term := new(big.Rat)
+    if n%3 != 1 {
+        term.SetInt64(1)
+    } else {
+        term.SetInt64((n - 1) / 3 * 2)
+    }
+
+    if n > lim {
+        return term
+    }
+
+    // Directly initialize frac as the fractional
+    // inverse of the result of recur.
+    frac := new(big.Rat).Inv(recur(n+1, lim))
+
+    return term.Add(term, frac)
+}
+
+// This example demonstrates how to use big.Rat to compute the
+// first 15 terms in the sequence of rational convergents for
+// the constant e (base of natural logarithm).
+func Example_eConvergents() {
+    for i := 1; i <= 15; i++ {
+        r := recur(0, int64(i))
+
+        // Print r both as a fraction and as a floating-point number.
+        // Since big.Rat implements fmt.Formatter, we can use %-13s to
+        // get a left-aligned string representation of the fraction.
+        fmt.Printf("%-13s = %s\n", r, r.FloatString(8))
+    }
+
+    // Output:
+    // 2/1           = 2.00000000
+    // 3/1           = 3.00000000
+    // 8/3           = 2.66666667
+    // 11/4          = 2.75000000
+    // 19/7          = 2.71428571
+    // 87/32         = 2.71875000
+    // 106/39        = 2.71794872
+    // 193/71        = 2.71830986
+    // 1264/465      = 2.71827957
+    // 1457/536      = 2.71828358
+    // 2721/1001     = 2.71828172
+    // 23225/8544    = 2.71828184
+    // 25946/9545    = 2.71828182
+    // 49171/18089   = 2.71828183
+    // 517656/190435 = 2.71828183
+}
+

Example (Fibonacci) +

This example demonstrates how to use big.Int to compute the smallest Fibonacci number with 100 decimal digits and to test whether it is prime.

Code:

// Initialize two big ints with the first two numbers in the sequence.
+a := big.NewInt(0)
+b := big.NewInt(1)
+
+// Initialize limit as 10^99, the smallest integer with 100 digits.
+var limit big.Int
+limit.Exp(big.NewInt(10), big.NewInt(99), nil)
+
+// Loop while a is smaller than 1e100.
+for a.Cmp(&limit) < 0 {
+    // Compute the next Fibonacci number, storing it in a.
+    a.Add(a, b)
+    // Swap a and b so that b is the next number in the sequence.
+    a, b = b, a
+}
+fmt.Println(a) // 100-digit Fibonacci number
+
+// Test a for primality.
+// (ProbablyPrimes' argument sets the number of Miller-Rabin
+// rounds to be performed. 20 is a good value.)
+fmt.Println(a.ProbablyPrime(20))
+
+

Output:

1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757
+false
+

Example (Sqrt2) +

This example shows how to use big.Float to compute the square root of 2 with a precision of 200 bits, and how to print the result as a decimal number.

Code:

// We'll do computations with 200 bits of precision in the mantissa.
+const prec = 200
+
+// Compute the square root of 2 using Newton's Method. We start with
+// an initial estimate for sqrt(2), and then iterate:
+//     x_{n+1} = 1/2 * ( x_n + (2.0 / x_n) )
+
+// Since Newton's Method doubles the number of correct digits at each
+// iteration, we need at least log_2(prec) steps.
+steps := int(math.Log2(prec))
+
+// Initialize values we need for the computation.
+two := new(big.Float).SetPrec(prec).SetInt64(2)
+half := new(big.Float).SetPrec(prec).SetFloat64(0.5)
+
+// Use 1 as the initial estimate.
+x := new(big.Float).SetPrec(prec).SetInt64(1)
+
+// We use t as a temporary variable. There's no need to set its precision
+// since big.Float values with unset (== 0) precision automatically assume
+// the largest precision of the arguments when used as the result (receiver)
+// of a big.Float operation.
+t := new(big.Float)
+
+// Iterate.
+for i := 0; i <= steps; i++ {
+    t.Quo(two, x)  // t = 2.0 / x_n
+    t.Add(x, t)    // t = x_n + (2.0 / x_n)
+    x.Mul(half, t) // x_{n+1} = 0.5 * t
+}
+
+// We can use the usual fmt.Printf verbs since big.Float implements fmt.Formatter
+fmt.Printf("sqrt(2) = %.50f\n", x)
+
+// Print the error between 2 and x*x.
+t.Mul(x, x) // t = x*x
+fmt.Printf("error = %e\n", t.Sub(two, t))
+
+

Output:

sqrt(2) = 1.41421356237309504880168872420969807856967187537695
+error = 0.000000e+00
+

Index

Examples

Float.Add
Float.Cmp
Float.Scan
Float.SetString
Float (Shift)
Int.Scan
Int.SetString
Rat.Scan
Rat.SetString
RoundingMode
Package (EConvergents)
Package (Fibonacci)
Package (Sqrt2)

Package files

accuracy_string.go arith.go arith_amd64.go arith_decl.go decimal.go doc.go float.go floatconv.go floatmarsh.go ftoa.go int.go intconv.go intmarsh.go nat.go natconv.go natdiv.go prime.go rat.go ratconv.go ratmarsh.go roundingmode_string.go sqrt.go

Constants

Exponent and precision limits.

+
const (
+    MaxExp  = math.MaxInt32  // largest supported exponent
+    MinExp  = math.MinInt32  // smallest supported exponent
+    MaxPrec = math.MaxUint32 // largest (theoretically) supported precision; likely memory-limited
+)

MaxBase is the largest number base accepted for string conversions.

+
const MaxBase = 10 + ('z' - 'a' + 1) + ('Z' - 'A' + 1)

func Jacobi 1.5

func Jacobi(x, y *Int) int

Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0. The y argument must be an odd integer.

+

type Accuracy 1.5

Accuracy describes the rounding error produced by the most recent operation that generated a Float value, relative to the exact value.

+
type Accuracy int8

Constants describing the Accuracy of a Float.

+
const (
+    Below Accuracy = -1
+    Exact Accuracy = 0
+    Above Accuracy = +1
+)

func (Accuracy) String 1.5

func (i Accuracy) String() string

type ErrNaN 1.5

An ErrNaN panic is raised by a Float operation that would lead to a NaN under IEEE-754 rules. An ErrNaN implements the error interface.

+
type ErrNaN struct {
+    // contains filtered or unexported fields
+}
+

func (ErrNaN) Error 1.5

func (err ErrNaN) Error() string

type Float 1.5

A nonzero finite Float represents a multi-precision floating point number

+
sign × mantissa × 2**exponent
+

with 0.5 <= mantissa < 1.0, and MinExp <= exponent <= MaxExp. A Float may also be zero (+0, -0) or infinite (+Inf, -Inf). All Floats are ordered, and the ordering of two Floats x and y is defined by x.Cmp(y).

+

Each Float value also has a precision, rounding mode, and accuracy. The precision is the maximum number of mantissa bits available to represent the value. The rounding mode specifies how a result should be rounded to fit into the mantissa bits, and accuracy describes the rounding error with respect to the exact result.

+

Unless specified otherwise, all operations (including setters) that specify a *Float variable for the result (usually via the receiver with the exception of Float.MantExp), round the numeric result according to the precision and rounding mode of the result variable.

+

If the provided result precision is 0 (see below), it is set to the precision of the argument with the largest precision value before any rounding takes place, and the rounding mode remains unchanged. Thus, uninitialized Floats provided as result arguments will have their precision set to a reasonable value determined by the operands, and their mode is the zero value for RoundingMode (ToNearestEven).

+

By setting the desired precision to 24 or 53 and using matching rounding mode (typically ToNearestEven), Float operations produce the same results as the corresponding float32 or float64 IEEE-754 arithmetic for operands that correspond to normal (i.e., not denormal) float32 or float64 numbers. Exponent underflow and overflow lead to a 0 or an Infinity for different values than IEEE-754 because Float exponents have a much larger range.

+

The zero (uninitialized) value for a Float is ready to use and represents the number +0.0 exactly, with precision 0 and rounding mode ToNearestEven.

+

Operations always take pointer arguments (*Float) rather than Float values, and each unique Float value requires its own unique *Float pointer. To "copy" a Float value, an existing (or newly allocated) Float must be set to a new value using the Float.Set method; shallow copies of Floats are not supported and may lead to errors.

+
type Float struct {
+    // contains filtered or unexported fields
+}
+

Example (Shift) +

Code:

// Implement Float "shift" by modifying the (binary) exponents directly.
+for s := -5; s <= 5; s++ {
+    x := big.NewFloat(0.5)
+    x.SetMantExp(x, x.MantExp(nil)+s) // shift x by s
+    fmt.Println(x)
+}
+

Output:

0.015625
+0.03125
+0.0625
+0.125
+0.25
+0.5
+1
+2
+4
+8
+16
+

func NewFloat 1.5

func NewFloat(x float64) *Float

NewFloat allocates and returns a new Float set to x, with precision 53 and rounding mode ToNearestEven. NewFloat panics with ErrNaN if x is a NaN.

+

func ParseFloat 1.5

func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error)

ParseFloat is like f.Parse(s, base) with f set to the given precision and rounding mode.

+

func (*Float) Abs 1.5

func (z *Float) Abs(x *Float) *Float

Abs sets z to the (possibly rounded) value |x| (the absolute value of x) and returns z.

+

func (*Float) Acc 1.5

func (x *Float) Acc() Accuracy

Acc returns the accuracy of x produced by the most recent operation, unless explicitly documented otherwise by that operation.

+

func (*Float) Add 1.5

func (z *Float) Add(x, y *Float) *Float

Add sets z to the rounded sum x+y and returns z. If z's precision is 0, it is changed to the larger of x's or y's precision before the operation. Rounding is performed according to z's precision and rounding mode; and z's accuracy reports the result error relative to the exact (not rounded) result. Add panics with ErrNaN if x and y are infinities with opposite signs. The value of z is undefined in that case.

Example +

Code:

// Operate on numbers of different precision.
+var x, y, z big.Float
+x.SetInt64(1000)          // x is automatically set to 64bit precision
+y.SetFloat64(2.718281828) // y is automatically set to 53bit precision
+z.SetPrec(32)
+z.Add(&x, &y)
+fmt.Printf("x = %.10g (%s, prec = %d, acc = %s)\n", &x, x.Text('p', 0), x.Prec(), x.Acc())
+fmt.Printf("y = %.10g (%s, prec = %d, acc = %s)\n", &y, y.Text('p', 0), y.Prec(), y.Acc())
+fmt.Printf("z = %.10g (%s, prec = %d, acc = %s)\n", &z, z.Text('p', 0), z.Prec(), z.Acc())
+

Output:

x = 1000 (0x.fap+10, prec = 64, acc = Exact)
+y = 2.718281828 (0x.adf85458248cd8p+2, prec = 53, acc = Exact)
+z = 1002.718282 (0x.faadf854p+10, prec = 32, acc = Below)
+

func (*Float) Append 1.5

func (x *Float) Append(buf []byte, fmt byte, prec int) []byte

Append appends to buf the string form of the floating-point number x, as generated by x.Text, and returns the extended buffer.

+

func (*Float) Cmp 1.5

func (x *Float) Cmp(y *Float) int

Cmp compares x and y and returns:

+
-1 if x <  y
+ 0 if x == y (incl. -0 == 0, -Inf == -Inf, and +Inf == +Inf)
++1 if x >  y
+

Example +

Code:

inf := math.Inf(1)
+zero := 0.0
+
+operands := []float64{-inf, -1.2, -zero, 0, +1.2, +inf}
+
+fmt.Println("   x     y  cmp")
+fmt.Println("---------------")
+for _, x64 := range operands {
+    x := big.NewFloat(x64)
+    for _, y64 := range operands {
+        y := big.NewFloat(y64)
+        fmt.Printf("%4g  %4g  %3d\n", x, y, x.Cmp(y))
+    }
+    fmt.Println()
+}
+
+

Output:

   x     y  cmp
+---------------
+-Inf  -Inf    0
+-Inf  -1.2   -1
+-Inf    -0   -1
+-Inf     0   -1
+-Inf   1.2   -1
+-Inf  +Inf   -1
+
+-1.2  -Inf    1
+-1.2  -1.2    0
+-1.2    -0   -1
+-1.2     0   -1
+-1.2   1.2   -1
+-1.2  +Inf   -1
+
+  -0  -Inf    1
+  -0  -1.2    1
+  -0    -0    0
+  -0     0    0
+  -0   1.2   -1
+  -0  +Inf   -1
+
+   0  -Inf    1
+   0  -1.2    1
+   0    -0    0
+   0     0    0
+   0   1.2   -1
+   0  +Inf   -1
+
+ 1.2  -Inf    1
+ 1.2  -1.2    1
+ 1.2    -0    1
+ 1.2     0    1
+ 1.2   1.2    0
+ 1.2  +Inf   -1
+
++Inf  -Inf    1
++Inf  -1.2    1
++Inf    -0    1
++Inf     0    1
++Inf   1.2    1
++Inf  +Inf    0
+

func (*Float) Copy 1.5

func (z *Float) Copy(x *Float) *Float

Copy sets z to x, with the same precision, rounding mode, and accuracy as x, and returns z. x is not changed even if z and x are the same.

+

func (*Float) Float32 1.5

func (x *Float) Float32() (float32, Accuracy)

Float32 returns the float32 value nearest to x. If x is too small to be represented by a float32 (|x| < math.SmallestNonzeroFloat32), the result is (0, Below) or (-0, Above), respectively, depending on the sign of x. If x is too large to be represented by a float32 (|x| > math.MaxFloat32), the result is (+Inf, Above) or (-Inf, Below), depending on the sign of x.

+

func (*Float) Float64 1.5

func (x *Float) Float64() (float64, Accuracy)

Float64 returns the float64 value nearest to x. If x is too small to be represented by a float64 (|x| < math.SmallestNonzeroFloat64), the result is (0, Below) or (-0, Above), respectively, depending on the sign of x. If x is too large to be represented by a float64 (|x| > math.MaxFloat64), the result is (+Inf, Above) or (-Inf, Below), depending on the sign of x.

+

func (*Float) Format 1.5

func (x *Float) Format(s fmt.State, format rune)

Format implements fmt.Formatter. It accepts all the regular formats for floating-point numbers ('b', 'e', 'E', 'f', 'F', 'g', 'G', 'x') as well as 'p' and 'v'. See (*Float).Text for the interpretation of 'p'. The 'v' format is handled like 'g'. Format also supports specification of the minimum precision in digits, the output field width, as well as the format flags '+' and ' ' for sign control, '0' for space or zero padding, and '-' for left or right justification. See the fmt package for details.

+

func (*Float) GobDecode 1.7

func (z *Float) GobDecode(buf []byte) error

GobDecode implements the encoding/gob.GobDecoder interface. The result is rounded per the precision and rounding mode of z unless z's precision is 0, in which case z is set exactly to the decoded value.

+

func (*Float) GobEncode 1.7

func (x *Float) GobEncode() ([]byte, error)

GobEncode implements the encoding/gob.GobEncoder interface. The Float value and all its attributes (precision, rounding mode, accuracy) are marshaled.

+

func (*Float) Int 1.5

func (x *Float) Int(z *Int) (*Int, Accuracy)

Int returns the result of truncating x towards zero; or nil if x is an infinity. The result is Exact if x.IsInt(); otherwise it is Below for x > 0, and Above for x < 0. If a non-nil *Int argument z is provided, Int stores the result in z instead of allocating a new Int.

+

func (*Float) Int64 1.5

func (x *Float) Int64() (int64, Accuracy)

Int64 returns the integer resulting from truncating x towards zero. If math.MinInt64 <= x <= math.MaxInt64, the result is Exact if x is an integer, and Above (x < 0) or Below (x > 0) otherwise. The result is (math.MinInt64, Above) for x < math.MinInt64, and (math.MaxInt64, Below) for x > math.MaxInt64.

+

func (*Float) IsInf 1.5

func (x *Float) IsInf() bool

IsInf reports whether x is +Inf or -Inf.

+

func (*Float) IsInt 1.5

func (x *Float) IsInt() bool

IsInt reports whether x is an integer. ±Inf values are not integers.

+

func (*Float) MantExp 1.5

func (x *Float) MantExp(mant *Float) (exp int)

MantExp breaks x into its mantissa and exponent components and returns the exponent. If a non-nil mant argument is provided its value is set to the mantissa of x, with the same precision and rounding mode as x. The components satisfy x == mant × 2**exp, with 0.5 <= |mant| < 1.0. Calling MantExp with a nil argument is an efficient way to get the exponent of the receiver.

+

Special cases are:

+
(  ±0).MantExp(mant) = 0, with mant set to   ±0
+(±Inf).MantExp(mant) = 0, with mant set to ±Inf
+

x and mant may be the same in which case x is set to its mantissa value.

+

func (*Float) MarshalText 1.6

func (x *Float) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface. Only the Float value is marshaled (in full precision), other attributes such as precision or accuracy are ignored.

+

func (*Float) MinPrec 1.5

func (x *Float) MinPrec() uint

MinPrec returns the minimum precision required to represent x exactly (i.e., the smallest prec before x.SetPrec(prec) would start rounding x). The result is 0 for |x| == 0 and |x| == Inf.

+

func (*Float) Mode 1.5

func (x *Float) Mode() RoundingMode

Mode returns the rounding mode of x.

+

func (*Float) Mul 1.5

func (z *Float) Mul(x, y *Float) *Float

Mul sets z to the rounded product x*y and returns z. Precision, rounding, and accuracy reporting are as for Float.Add. Mul panics with ErrNaN if one operand is zero and the other operand an infinity. The value of z is undefined in that case.

+

func (*Float) Neg 1.5

func (z *Float) Neg(x *Float) *Float

Neg sets z to the (possibly rounded) value of x with its sign negated, and returns z.

+

func (*Float) Parse 1.5

func (z *Float) Parse(s string, base int) (f *Float, b int, err error)

Parse parses s which must contain a text representation of a floating- point number with a mantissa in the given conversion base (the exponent is always a decimal number), or a string representing an infinite value.

+

For base 0, an underscore character “_” may appear between a base prefix and an adjacent digit, and between successive digits; such underscores do not change the value of the number, or the returned digit count. Incorrect placement of underscores is reported as an error if there are no other errors. If base != 0, underscores are not recognized and thus terminate scanning like any other character that is not a valid radix point or digit.

+

It sets z to the (possibly rounded) value of the corresponding floating- point value, and returns z, the actual base b, and an error err, if any. The entire string (not just a prefix) must be consumed for success. If z's precision is 0, it is changed to 64 before rounding takes effect. The number must be of the form:

+
number    = [ sign ] ( float | "inf" | "Inf" ) .
+sign      = "+" | "-" .
+float     = ( mantissa | prefix pmantissa ) [ exponent ] .
+prefix    = "0" [ "b" | "B" | "o" | "O" | "x" | "X" ] .
+mantissa  = digits "." [ digits ] | digits | "." digits .
+pmantissa = [ "_" ] digits "." [ digits ] | [ "_" ] digits | "." digits .
+exponent  = ( "e" | "E" | "p" | "P" ) [ sign ] digits .
+digits    = digit { [ "_" ] digit } .
+digit     = "0" ... "9" | "a" ... "z" | "A" ... "Z" .
+

The base argument must be 0, 2, 8, 10, or 16. Providing an invalid base argument will lead to a run-time panic.

+

For base 0, the number prefix determines the actual base: A prefix of “0b” or “0B” selects base 2, “0o” or “0O” selects base 8, and “0x” or “0X” selects base 16. Otherwise, the actual base is 10 and no prefix is accepted. The octal prefix "0" is not supported (a leading "0" is simply considered a "0").

+

A "p" or "P" exponent indicates a base 2 (rather than base 10) exponent; for instance, "0x1.fffffffffffffp1023" (using base 0) represents the maximum float64 value. For hexadecimal mantissae, the exponent character must be one of 'p' or 'P', if present (an "e" or "E" exponent indicator cannot be distinguished from a mantissa digit).

+

The returned *Float f is nil and the value of z is valid but not defined if an error is reported.

+

func (*Float) Prec 1.5

func (x *Float) Prec() uint

Prec returns the mantissa precision of x in bits. The result may be 0 for |x| == 0 and |x| == Inf.

+

func (*Float) Quo 1.5

func (z *Float) Quo(x, y *Float) *Float

Quo sets z to the rounded quotient x/y and returns z. Precision, rounding, and accuracy reporting are as for Float.Add. Quo panics with ErrNaN if both operands are zero or infinities. The value of z is undefined in that case.

+

func (*Float) Rat 1.5

func (x *Float) Rat(z *Rat) (*Rat, Accuracy)

Rat returns the rational number corresponding to x; or nil if x is an infinity. The result is Exact if x is not an Inf. If a non-nil *Rat argument z is provided, Rat stores the result in z instead of allocating a new Rat.

+

func (*Float) Scan 1.8

func (z *Float) Scan(s fmt.ScanState, ch rune) error

Scan is a support routine for fmt.Scanner; it sets z to the value of the scanned number. It accepts formats whose verbs are supported by fmt.Scan for floating point values, which are: 'b' (binary), 'e', 'E', 'f', 'F', 'g' and 'G'. Scan doesn't handle ±Inf.

Example +

Code:

// The Scan function is rarely used directly;
+// the fmt package recognizes it as an implementation of fmt.Scanner.
+f := new(big.Float)
+_, err := fmt.Sscan("1.19282e99", f)
+if err != nil {
+    log.Println("error scanning value:", err)
+} else {
+    fmt.Println(f)
+}
+

Output:

1.19282e+99
+

func (*Float) Set 1.5

func (z *Float) Set(x *Float) *Float

Set sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to the precision of x before setting z (and rounding will have no effect). Rounding is performed according to z's precision and rounding mode; and z's accuracy reports the result error relative to the exact (not rounded) result.

+

func (*Float) SetFloat64 1.5

func (z *Float) SetFloat64(x float64) *Float

SetFloat64 sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to 53 (and rounding will have no effect). SetFloat64 panics with ErrNaN if x is a NaN.

+

func (*Float) SetInf 1.5

func (z *Float) SetInf(signbit bool) *Float

SetInf sets z to the infinite Float -Inf if signbit is set, or +Inf if signbit is not set, and returns z. The precision of z is unchanged and the result is always Exact.

+

func (*Float) SetInt 1.5

func (z *Float) SetInt(x *Int) *Float

SetInt sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to the larger of x.BitLen() or 64 (and rounding will have no effect).

+

func (*Float) SetInt64 1.5

func (z *Float) SetInt64(x int64) *Float

SetInt64 sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to 64 (and rounding will have no effect).

+

func (*Float) SetMantExp 1.5

func (z *Float) SetMantExp(mant *Float, exp int) *Float

SetMantExp sets z to mant × 2**exp and returns z. The result z has the same precision and rounding mode as mant. SetMantExp is an inverse of Float.MantExp but does not require 0.5 <= |mant| < 1.0. Specifically, for a given x of type *Float, SetMantExp relates to Float.MantExp as follows:

+
mant := new(Float)
+new(Float).SetMantExp(mant, x.MantExp(mant)).Cmp(x) == 0
+

Special cases are:

+
z.SetMantExp(  ±0, exp) =   ±0
+z.SetMantExp(±Inf, exp) = ±Inf
+

z and mant may be the same in which case z's exponent is set to exp.

+

func (*Float) SetMode 1.5

func (z *Float) SetMode(mode RoundingMode) *Float

SetMode sets z's rounding mode to mode and returns an exact z. z remains unchanged otherwise. z.SetMode(z.Mode()) is a cheap way to set z's accuracy to Exact.

+

func (*Float) SetPrec 1.5

func (z *Float) SetPrec(prec uint) *Float

SetPrec sets z's precision to prec and returns the (possibly) rounded value of z. Rounding occurs according to z's rounding mode if the mantissa cannot be represented in prec bits without loss of precision. SetPrec(0) maps all finite values to ±0; infinite values remain unchanged. If prec > MaxPrec, it is set to MaxPrec.

+

func (*Float) SetRat 1.5

func (z *Float) SetRat(x *Rat) *Float

SetRat sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to the largest of a.BitLen(), b.BitLen(), or 64; with x = a/b.

+

func (*Float) SetString 1.5

func (z *Float) SetString(s string) (*Float, bool)

SetString sets z to the value of s and returns z and a boolean indicating success. s must be a floating-point number of the same format as accepted by Float.Parse, with base argument 0. The entire string (not just a prefix) must be valid for success. If the operation failed, the value of z is undefined but the returned value is nil.

Example +

Code:

f := new(big.Float)
+f.SetString("3.14159")
+fmt.Println(f)
+

Output:

3.14159
+

func (*Float) SetUint64 1.5

func (z *Float) SetUint64(x uint64) *Float

SetUint64 sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to 64 (and rounding will have no effect).

+

func (*Float) Sign 1.5

func (x *Float) Sign() int

Sign returns:

+
-1 if x <   0
+ 0 if x is ±0
++1 if x >   0
+

func (*Float) Signbit 1.5

func (x *Float) Signbit() bool

Signbit reports whether x is negative or negative zero.

+

func (*Float) Sqrt 1.10

func (z *Float) Sqrt(x *Float) *Float

Sqrt sets z to the rounded square root of x, and returns it.

+

If z's precision is 0, it is changed to x's precision before the operation. Rounding is performed according to z's precision and rounding mode, but z's accuracy is not computed. Specifically, the result of z.Acc() is undefined.

+

The function panics if z < 0. The value of z is undefined in that case.

+

func (*Float) String 1.5

func (x *Float) String() string

String formats x like x.Text('g', 10). (String must be called explicitly, Float.Format does not support %s verb.)

+

func (*Float) Sub 1.5

func (z *Float) Sub(x, y *Float) *Float

Sub sets z to the rounded difference x-y and returns z. Precision, rounding, and accuracy reporting are as for Float.Add. Sub panics with ErrNaN if x and y are infinities with equal signs. The value of z is undefined in that case.

+

func (*Float) Text 1.5

func (x *Float) Text(format byte, prec int) string

Text converts the floating-point number x to a string according to the given format and precision prec. The format is one of:

+
'e'	-d.dddde±dd, decimal exponent, at least two (possibly 0) exponent digits
+'E'	-d.ddddE±dd, decimal exponent, at least two (possibly 0) exponent digits
+'f'	-ddddd.dddd, no exponent
+'g'	like 'e' for large exponents, like 'f' otherwise
+'G'	like 'E' for large exponents, like 'f' otherwise
+'x'	-0xd.dddddp±dd, hexadecimal mantissa, decimal power of two exponent
+'p'	-0x.dddp±dd, hexadecimal mantissa, decimal power of two exponent (non-standard)
+'b'	-ddddddp±dd, decimal mantissa, decimal power of two exponent (non-standard)
+

For the power-of-two exponent formats, the mantissa is printed in normalized form:

+
'x'	hexadecimal mantissa in [1, 2), or 0
+'p'	hexadecimal mantissa in [½, 1), or 0
+'b'	decimal integer mantissa using x.Prec() bits, or 0
+

Note that the 'x' form is the one used by most other languages and libraries.

+

If format is a different character, Text returns a "%" followed by the unrecognized format character.

+

The precision prec controls the number of digits (excluding the exponent) printed by the 'e', 'E', 'f', 'g', 'G', and 'x' formats. For 'e', 'E', 'f', and 'x', it is the number of digits after the decimal point. For 'g' and 'G' it is the total number of digits. A negative precision selects the smallest number of decimal digits necessary to identify the value x uniquely using x.Prec() mantissa bits. The prec value is ignored for the 'b' and 'p' formats.

+

func (*Float) Uint64 1.5

func (x *Float) Uint64() (uint64, Accuracy)

Uint64 returns the unsigned integer resulting from truncating x towards zero. If 0 <= x <= math.MaxUint64, the result is Exact if x is an integer and Below otherwise. The result is (0, Above) for x < 0, and (math.MaxUint64, Below) for x > math.MaxUint64.

+

func (*Float) UnmarshalText 1.6

func (z *Float) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The result is rounded per the precision and rounding mode of z. If z's precision is 0, it is changed to 64 before rounding takes effect.

+

type Int

An Int represents a signed multi-precision integer. The zero value for an Int represents the value 0.

+

Operations always take pointer arguments (*Int) rather than Int values, and each unique Int value requires its own unique *Int pointer. To "copy" an Int value, an existing (or newly allocated) Int must be set to a new value using the Int.Set method; shallow copies of Ints are not supported and may lead to errors.

+

Note that methods may leak the Int's value through timing side-channels. Because of this and because of the scope and complexity of the implementation, Int is not well-suited to implement cryptographic operations. The standard library avoids exposing non-trivial Int methods to attacker-controlled inputs and the determination of whether a bug in math/big is considered a security vulnerability might depend on the impact on the standard library.

+
type Int struct {
+    // contains filtered or unexported fields
+}
+

func NewInt

func NewInt(x int64) *Int

NewInt allocates and returns a new Int set to x.

+

func (*Int) Abs

func (z *Int) Abs(x *Int) *Int

Abs sets z to |x| (the absolute value of x) and returns z.

+

func (*Int) Add

func (z *Int) Add(x, y *Int) *Int

Add sets z to the sum x+y and returns z.

+

func (*Int) And

func (z *Int) And(x, y *Int) *Int

And sets z = x & y and returns z.

+

func (*Int) AndNot

func (z *Int) AndNot(x, y *Int) *Int

AndNot sets z = x &^ y and returns z.

+

func (*Int) Append 1.6

func (x *Int) Append(buf []byte, base int) []byte

Append appends the string representation of x, as generated by x.Text(base), to buf and returns the extended buffer.

+

func (*Int) Binomial

func (z *Int) Binomial(n, k int64) *Int

Binomial sets z to the binomial coefficient C(n, k) and returns z.

+

func (*Int) Bit

func (x *Int) Bit(i int) uint

Bit returns the value of the i'th bit of x. That is, it returns (x>>i)&1. The bit index i must be >= 0.

+

func (*Int) BitLen

func (x *Int) BitLen() int

BitLen returns the length of the absolute value of x in bits. The bit length of 0 is 0.

+

func (*Int) Bits

func (x *Int) Bits() []Word

Bits provides raw (unchecked but fast) access to x by returning its absolute value as a little-endian Word slice. The result and x share the same underlying array. Bits is intended to support implementation of missing low-level Int functionality outside this package; it should be avoided otherwise.

+

func (*Int) Bytes

func (x *Int) Bytes() []byte

Bytes returns the absolute value of x as a big-endian byte slice.

+

To use a fixed length slice, or a preallocated one, use Int.FillBytes.

+

func (*Int) Cmp

func (x *Int) Cmp(y *Int) (r int)

Cmp compares x and y and returns:

+
-1 if x <  y
+ 0 if x == y
++1 if x >  y
+

func (*Int) CmpAbs 1.10

func (x *Int) CmpAbs(y *Int) int

CmpAbs compares the absolute values of x and y and returns:

+
-1 if |x| <  |y|
+ 0 if |x| == |y|
++1 if |x| >  |y|
+

func (*Int) Div

func (z *Int) Div(x, y *Int) *Int

Div sets z to the quotient x/y for y != 0 and returns z. If y == 0, a division-by-zero run-time panic occurs. Div implements Euclidean division (unlike Go); see Int.DivMod for more details.

+

func (*Int) DivMod

func (z *Int) DivMod(x, y, m *Int) (*Int, *Int)

DivMod sets z to the quotient x div y and m to the modulus x mod y and returns the pair (z, m) for y != 0. If y == 0, a division-by-zero run-time panic occurs.

+

DivMod implements Euclidean division and modulus (unlike Go):

+
q = x div y  such that
+m = x - y*q  with 0 <= m < |y|
+

(See Raymond T. Boute, “The Euclidean definition of the functions div and mod”. ACM Transactions on Programming Languages and Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992. ACM press.) See Int.QuoRem for T-division and modulus (like Go).

+

func (*Int) Exp

func (z *Int) Exp(x, y, m *Int) *Int

Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z. If m == nil or m == 0, z = x**y unless y <= 0 then z = 1. If m != 0, y < 0, and x and m are not relatively prime, z is unchanged and nil is returned.

+

Modular exponentiation of inputs of a particular size is not a cryptographically constant-time operation.

+

func (*Int) FillBytes 1.15

func (x *Int) FillBytes(buf []byte) []byte

FillBytes sets buf to the absolute value of x, storing it as a zero-extended big-endian byte slice, and returns buf.

+

If the absolute value of x doesn't fit in buf, FillBytes will panic.

+

func (*Int) Float64 1.21

func (x *Int) Float64() (float64, Accuracy)

Float64 returns the float64 value nearest x, and an indication of any rounding that occurred.

+

func (*Int) Format

func (x *Int) Format(s fmt.State, ch rune)

Format implements fmt.Formatter. It accepts the formats 'b' (binary), 'o' (octal with 0 prefix), 'O' (octal with 0o prefix), 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal). Also supported are the full suite of package fmt's format flags for integral types, including '+' and ' ' for sign control, '#' for leading zero in octal and for hexadecimal, a leading "0x" or "0X" for "%#x" and "%#X" respectively, specification of minimum digits precision, output field width, space or zero padding, and '-' for left or right justification.

+

func (*Int) GCD

func (z *Int) GCD(x, y, a, b *Int) *Int

GCD sets z to the greatest common divisor of a and b and returns z. If x or y are not nil, GCD sets their value such that z = a*x + b*y.

+

a and b may be positive, zero or negative. (Before Go 1.14 both had to be > 0.) Regardless of the signs of a and b, z is always >= 0.

+

If a == b == 0, GCD sets z = x = y = 0.

+

If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1.

+

If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0.

+

func (*Int) GobDecode

func (z *Int) GobDecode(buf []byte) error

GobDecode implements the encoding/gob.GobDecoder interface.

+

func (*Int) GobEncode

func (x *Int) GobEncode() ([]byte, error)

GobEncode implements the encoding/gob.GobEncoder interface.

+

func (*Int) Int64

func (x *Int) Int64() int64

Int64 returns the int64 representation of x. If x cannot be represented in an int64, the result is undefined.

+

func (*Int) IsInt64 1.9

func (x *Int) IsInt64() bool

IsInt64 reports whether x can be represented as an int64.

+

func (*Int) IsUint64 1.9

func (x *Int) IsUint64() bool

IsUint64 reports whether x can be represented as a uint64.

+

func (*Int) Lsh

func (z *Int) Lsh(x *Int, n uint) *Int

Lsh sets z = x << n and returns z.

+

func (*Int) MarshalJSON 1.1

func (x *Int) MarshalJSON() ([]byte, error)

MarshalJSON implements the encoding/json.Marshaler interface.

+

func (*Int) MarshalText 1.3

func (x *Int) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface.

+

func (*Int) Mod

func (z *Int) Mod(x, y *Int) *Int

Mod sets z to the modulus x%y for y != 0 and returns z. If y == 0, a division-by-zero run-time panic occurs. Mod implements Euclidean modulus (unlike Go); see Int.DivMod for more details.

+

func (*Int) ModInverse

func (z *Int) ModInverse(g, n *Int) *Int

ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ and returns z. If g and n are not relatively prime, g has no multiplicative inverse in the ring ℤ/nℤ. In this case, z is unchanged and the return value is nil. If n == 0, a division-by-zero run-time panic occurs.

+

func (*Int) ModSqrt 1.5

func (z *Int) ModSqrt(x, p *Int) *Int

ModSqrt sets z to a square root of x mod p if such a square root exists, and returns z. The modulus p must be an odd prime. If x is not a square mod p, ModSqrt leaves z unchanged and returns nil. This function panics if p is not an odd integer, its behavior is undefined if p is odd but not prime.

+

func (*Int) Mul

func (z *Int) Mul(x, y *Int) *Int

Mul sets z to the product x*y and returns z.

+

func (*Int) MulRange

func (z *Int) MulRange(a, b int64) *Int

MulRange sets z to the product of all integers in the range [a, b] inclusively and returns z. If a > b (empty range), the result is 1.

+

func (*Int) Neg

func (z *Int) Neg(x *Int) *Int

Neg sets z to -x and returns z.

+

func (*Int) Not

func (z *Int) Not(x *Int) *Int

Not sets z = ^x and returns z.

+

func (*Int) Or

func (z *Int) Or(x, y *Int) *Int

Or sets z = x | y and returns z.

+

func (*Int) ProbablyPrime

func (x *Int) ProbablyPrime(n int) bool

ProbablyPrime reports whether x is probably prime, applying the Miller-Rabin test with n pseudorandomly chosen bases as well as a Baillie-PSW test.

+

If x is prime, ProbablyPrime returns true. If x is chosen randomly and not prime, ProbablyPrime probably returns false. The probability of returning true for a randomly chosen non-prime is at most ¼ⁿ.

+

ProbablyPrime is 100% accurate for inputs less than 2⁶⁴. See Menezes et al., Handbook of Applied Cryptography, 1997, pp. 145-149, and FIPS 186-4 Appendix F for further discussion of the error probabilities.

+

ProbablyPrime is not suitable for judging primes that an adversary may have crafted to fool the test.

+

As of Go 1.8, ProbablyPrime(0) is allowed and applies only a Baillie-PSW test. Before Go 1.8, ProbablyPrime applied only the Miller-Rabin tests, and ProbablyPrime(0) panicked.

+

func (*Int) Quo

func (z *Int) Quo(x, y *Int) *Int

Quo sets z to the quotient x/y for y != 0 and returns z. If y == 0, a division-by-zero run-time panic occurs. Quo implements truncated division (like Go); see Int.QuoRem for more details.

+

func (*Int) QuoRem

func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int)

QuoRem sets z to the quotient x/y and r to the remainder x%y and returns the pair (z, r) for y != 0. If y == 0, a division-by-zero run-time panic occurs.

+

QuoRem implements T-division and modulus (like Go):

+
q = x/y      with the result truncated to zero
+r = x - y*q
+

(See Daan Leijen, “Division and Modulus for Computer Scientists”.) See DivMod for Euclidean division and modulus (unlike Go).

+

func (*Int) Rand

func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int

Rand sets z to a pseudo-random number in [0, n) and returns z.

+

As this uses the math/rand package, it must not be used for security-sensitive work. Use crypto/rand.Int instead.

+

func (*Int) Rem

func (z *Int) Rem(x, y *Int) *Int

Rem sets z to the remainder x%y for y != 0 and returns z. If y == 0, a division-by-zero run-time panic occurs. Rem implements truncated modulus (like Go); see Int.QuoRem for more details.

+

func (*Int) Rsh

func (z *Int) Rsh(x *Int, n uint) *Int

Rsh sets z = x >> n and returns z.

+

func (*Int) Scan

func (z *Int) Scan(s fmt.ScanState, ch rune) error

Scan is a support routine for fmt.Scanner; it sets z to the value of the scanned number. It accepts the formats 'b' (binary), 'o' (octal), 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal).

Example +

Code:

// The Scan function is rarely used directly;
+// the fmt package recognizes it as an implementation of fmt.Scanner.
+i := new(big.Int)
+_, err := fmt.Sscan("18446744073709551617", i)
+if err != nil {
+    log.Println("error scanning value:", err)
+} else {
+    fmt.Println(i)
+}
+

Output:

18446744073709551617
+

func (*Int) Set

func (z *Int) Set(x *Int) *Int

Set sets z to x and returns z.

+

func (*Int) SetBit

func (z *Int) SetBit(x *Int, i int, b uint) *Int

SetBit sets z to x, with x's i'th bit set to b (0 or 1). That is, if b is 1 SetBit sets z = x | (1 << i); if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1, SetBit will panic.

+

func (*Int) SetBits

func (z *Int) SetBits(abs []Word) *Int

SetBits provides raw (unchecked but fast) access to z by setting its value to abs, interpreted as a little-endian Word slice, and returning z. The result and abs share the same underlying array. SetBits is intended to support implementation of missing low-level Int functionality outside this package; it should be avoided otherwise.

+

func (*Int) SetBytes

func (z *Int) SetBytes(buf []byte) *Int

SetBytes interprets buf as the bytes of a big-endian unsigned integer, sets z to that value, and returns z.

+

func (*Int) SetInt64

func (z *Int) SetInt64(x int64) *Int

SetInt64 sets z to x and returns z.

+

func (*Int) SetString

func (z *Int) SetString(s string, base int) (*Int, bool)

SetString sets z to the value of s, interpreted in the given base, and returns z and a boolean indicating success. The entire string (not just a prefix) must be valid for success. If SetString fails, the value of z is undefined but the returned value is nil.

+

The base argument must be 0 or a value between 2 and MaxBase. For base 0, the number prefix determines the actual base: A prefix of “0b” or “0B” selects base 2, “0”, “0o” or “0O” selects base 8, and “0x” or “0X” selects base 16. Otherwise, the selected base is 10 and no prefix is accepted.

+

For bases <= 36, lower and upper case letters are considered the same: The letters 'a' to 'z' and 'A' to 'Z' represent digit values 10 to 35. For bases > 36, the upper case letters 'A' to 'Z' represent the digit values 36 to 61.

+

For base 0, an underscore character “_” may appear between a base prefix and an adjacent digit, and between successive digits; such underscores do not change the value of the number. Incorrect placement of underscores is reported as an error if there are no other errors. If base != 0, underscores are not recognized and act like any other character that is not a valid digit.

Example +

Code:

i := new(big.Int)
+i.SetString("644", 8) // octal
+fmt.Println(i)
+

Output:

420
+

func (*Int) SetUint64 1.1

func (z *Int) SetUint64(x uint64) *Int

SetUint64 sets z to x and returns z.

+

func (*Int) Sign

func (x *Int) Sign() int

Sign returns:

+
-1 if x <  0
+ 0 if x == 0
++1 if x >  0
+

func (*Int) Sqrt 1.8

func (z *Int) Sqrt(x *Int) *Int

Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z. It panics if x is negative.

+

func (*Int) String

func (x *Int) String() string

String returns the decimal representation of x as generated by x.Text(10).

+

func (*Int) Sub

func (z *Int) Sub(x, y *Int) *Int

Sub sets z to the difference x-y and returns z.

+

func (*Int) Text 1.6

func (x *Int) Text(base int) string

Text returns the string representation of x in the given base. Base must be between 2 and 62, inclusive. The result uses the lower-case letters 'a' to 'z' for digit values 10 to 35, and the upper-case letters 'A' to 'Z' for digit values 36 to 61. No prefix (such as "0x") is added to the string. If x is a nil pointer it returns "<nil>".

+

func (*Int) TrailingZeroBits 1.13

func (x *Int) TrailingZeroBits() uint

TrailingZeroBits returns the number of consecutive least significant zero bits of |x|.

+

func (*Int) Uint64 1.1

func (x *Int) Uint64() uint64

Uint64 returns the uint64 representation of x. If x cannot be represented in a uint64, the result is undefined.

+

func (*Int) UnmarshalJSON 1.1

func (z *Int) UnmarshalJSON(text []byte) error

UnmarshalJSON implements the encoding/json.Unmarshaler interface.

+

func (*Int) UnmarshalText 1.3

func (z *Int) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

+

func (*Int) Xor

func (z *Int) Xor(x, y *Int) *Int

Xor sets z = x ^ y and returns z.

+

type Rat

A Rat represents a quotient a/b of arbitrary precision. The zero value for a Rat represents the value 0.

+

Operations always take pointer arguments (*Rat) rather than Rat values, and each unique Rat value requires its own unique *Rat pointer. To "copy" a Rat value, an existing (or newly allocated) Rat must be set to a new value using the Rat.Set method; shallow copies of Rats are not supported and may lead to errors.

+
type Rat struct {
+    // contains filtered or unexported fields
+}
+

func NewRat

func NewRat(a, b int64) *Rat

NewRat creates a new Rat with numerator a and denominator b.

+

func (*Rat) Abs

func (z *Rat) Abs(x *Rat) *Rat

Abs sets z to |x| (the absolute value of x) and returns z.

+

func (*Rat) Add

func (z *Rat) Add(x, y *Rat) *Rat

Add sets z to the sum x+y and returns z.

+

func (*Rat) Cmp

func (x *Rat) Cmp(y *Rat) int

Cmp compares x and y and returns:

+
-1 if x <  y
+ 0 if x == y
++1 if x >  y
+

func (*Rat) Denom

func (x *Rat) Denom() *Int

Denom returns the denominator of x; it is always > 0. The result is a reference to x's denominator, unless x is an uninitialized (zero value) Rat, in which case the result is a new Int of value 1. (To initialize x, any operation that sets x will do, including x.Set(x).) If the result is a reference to x's denominator it may change if a new value is assigned to x, and vice versa.

+

func (*Rat) Float32 1.4

func (x *Rat) Float32() (f float32, exact bool)

Float32 returns the nearest float32 value for x and a bool indicating whether f represents x exactly. If the magnitude of x is too large to be represented by a float32, f is an infinity and exact is false. The sign of f always matches the sign of x, even if f == 0.

+

func (*Rat) Float64 1.1

func (x *Rat) Float64() (f float64, exact bool)

Float64 returns the nearest float64 value for x and a bool indicating whether f represents x exactly. If the magnitude of x is too large to be represented by a float64, f is an infinity and exact is false. The sign of f always matches the sign of x, even if f == 0.

+

func (*Rat) FloatPrec 1.22

func (x *Rat) FloatPrec() (n int, exact bool)

FloatPrec returns the number n of non-repeating digits immediately following the decimal point of the decimal representation of x. The boolean result indicates whether a decimal representation of x with that many fractional digits is exact or rounded.

+

Examples:

+
x      n    exact    decimal representation n fractional digits
+0      0    true     0
+1      0    true     1
+1/2    1    true     0.5
+1/3    0    false    0       (0.333... rounded)
+1/4    2    true     0.25
+1/6    1    false    0.2     (0.166... rounded)
+

func (*Rat) FloatString

func (x *Rat) FloatString(prec int) string

FloatString returns a string representation of x in decimal form with prec digits of precision after the radix point. The last digit is rounded to nearest, with halves rounded away from zero.

+

func (*Rat) GobDecode

func (z *Rat) GobDecode(buf []byte) error

GobDecode implements the encoding/gob.GobDecoder interface.

+

func (*Rat) GobEncode

func (x *Rat) GobEncode() ([]byte, error)

GobEncode implements the encoding/gob.GobEncoder interface.

+

func (*Rat) Inv

func (z *Rat) Inv(x *Rat) *Rat

Inv sets z to 1/x and returns z. If x == 0, Inv panics.

+

func (*Rat) IsInt

func (x *Rat) IsInt() bool

IsInt reports whether the denominator of x is 1.

+

func (*Rat) MarshalText 1.3

func (x *Rat) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface.

+

func (*Rat) Mul

func (z *Rat) Mul(x, y *Rat) *Rat

Mul sets z to the product x*y and returns z.

+

func (*Rat) Neg

func (z *Rat) Neg(x *Rat) *Rat

Neg sets z to -x and returns z.

+

func (*Rat) Num

func (x *Rat) Num() *Int

Num returns the numerator of x; it may be <= 0. The result is a reference to x's numerator; it may change if a new value is assigned to x, and vice versa. The sign of the numerator corresponds to the sign of x.

+

func (*Rat) Quo

func (z *Rat) Quo(x, y *Rat) *Rat

Quo sets z to the quotient x/y and returns z. If y == 0, Quo panics.

+

func (*Rat) RatString

func (x *Rat) RatString() string

RatString returns a string representation of x in the form "a/b" if b != 1, and in the form "a" if b == 1.

+

func (*Rat) Scan

func (z *Rat) Scan(s fmt.ScanState, ch rune) error

Scan is a support routine for fmt.Scanner. It accepts the formats 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent.

Example +

Code:

// The Scan function is rarely used directly;
+// the fmt package recognizes it as an implementation of fmt.Scanner.
+r := new(big.Rat)
+_, err := fmt.Sscan("1.5000", r)
+if err != nil {
+    log.Println("error scanning value:", err)
+} else {
+    fmt.Println(r)
+}
+

Output:

3/2
+

func (*Rat) Set

func (z *Rat) Set(x *Rat) *Rat

Set sets z to x (by making a copy of x) and returns z.

+

func (*Rat) SetFloat64 1.1

func (z *Rat) SetFloat64(f float64) *Rat

SetFloat64 sets z to exactly f and returns z. If f is not finite, SetFloat returns nil.

+

func (*Rat) SetFrac

func (z *Rat) SetFrac(a, b *Int) *Rat

SetFrac sets z to a/b and returns z. If b == 0, SetFrac panics.

+

func (*Rat) SetFrac64

func (z *Rat) SetFrac64(a, b int64) *Rat

SetFrac64 sets z to a/b and returns z. If b == 0, SetFrac64 panics.

+

func (*Rat) SetInt

func (z *Rat) SetInt(x *Int) *Rat

SetInt sets z to x (by making a copy of x) and returns z.

+

func (*Rat) SetInt64

func (z *Rat) SetInt64(x int64) *Rat

SetInt64 sets z to x and returns z.

+

func (*Rat) SetString

func (z *Rat) SetString(s string) (*Rat, bool)

SetString sets z to the value of s and returns z and a boolean indicating success. s can be given as a (possibly signed) fraction "a/b", or as a floating-point number optionally followed by an exponent. If a fraction is provided, both the dividend and the divisor may be a decimal integer or independently use a prefix of “0b”, “0” or “0o”, or “0x” (or their upper-case variants) to denote a binary, octal, or hexadecimal integer, respectively. The divisor may not be signed. If a floating-point number is provided, it may be in decimal form or use any of the same prefixes as above but for “0” to denote a non-decimal mantissa. A leading “0” is considered a decimal leading 0; it does not indicate octal representation in this case. An optional base-10 “e” or base-2 “p” (or their upper-case variants) exponent may be provided as well, except for hexadecimal floats which only accept an (optional) “p” exponent (because an “e” or “E” cannot be distinguished from a mantissa digit). If the exponent's absolute value is too large, the operation may fail. The entire string, not just a prefix, must be valid for success. If the operation failed, the value of z is undefined but the returned value is nil.

Example +

Code:

r := new(big.Rat)
+r.SetString("355/113")
+fmt.Println(r.FloatString(3))
+

Output:

3.142
+

func (*Rat) SetUint64 1.13

func (z *Rat) SetUint64(x uint64) *Rat

SetUint64 sets z to x and returns z.

+

func (*Rat) Sign

func (x *Rat) Sign() int

Sign returns:

+
-1 if x <  0
+ 0 if x == 0
++1 if x >  0
+

func (*Rat) String

func (x *Rat) String() string

String returns a string representation of x in the form "a/b" (even if b == 1).

+

func (*Rat) Sub

func (z *Rat) Sub(x, y *Rat) *Rat

Sub sets z to the difference x-y and returns z.

+

func (*Rat) UnmarshalText 1.3

func (z *Rat) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

+

type RoundingMode 1.5

RoundingMode determines how a Float value is rounded to the desired precision. Rounding may change the Float value; the rounding error is described by the Float's Accuracy.

+
type RoundingMode byte

These constants define supported rounding modes.

+
const (
+    ToNearestEven RoundingMode = iota // == IEEE 754-2008 roundTiesToEven
+    ToNearestAway                     // == IEEE 754-2008 roundTiesToAway
+    ToZero                            // == IEEE 754-2008 roundTowardZero
+    AwayFromZero                      // no IEEE 754-2008 equivalent
+    ToNegativeInf                     // == IEEE 754-2008 roundTowardNegative
+    ToPositiveInf                     // == IEEE 754-2008 roundTowardPositive
+)

Example +

Code:

operands := []float64{2.6, 2.5, 2.1, -2.1, -2.5, -2.6}
+
+fmt.Print("   x")
+for mode := big.ToNearestEven; mode <= big.ToPositiveInf; mode++ {
+    fmt.Printf("  %s", mode)
+}
+fmt.Println()
+
+for _, f64 := range operands {
+    fmt.Printf("%4g", f64)
+    for mode := big.ToNearestEven; mode <= big.ToPositiveInf; mode++ {
+        // sample operands above require 2 bits to represent mantissa
+        // set binary precision to 2 to round them to integer values
+        f := new(big.Float).SetPrec(2).SetMode(mode).SetFloat64(f64)
+        fmt.Printf("  %*g", len(mode.String()), f)
+    }
+    fmt.Println()
+}
+
+

Output:

   x  ToNearestEven  ToNearestAway  ToZero  AwayFromZero  ToNegativeInf  ToPositiveInf
+ 2.6              3              3       2             3              2              3
+ 2.5              2              3       2             3              2              3
+ 2.1              2              2       2             3              2              3
+-2.1             -2             -2      -2            -3             -3             -2
+-2.5             -2             -3      -2            -3             -3             -2
+-2.6             -3             -3      -2            -3             -3             -2
+

func (RoundingMode) String 1.5

func (i RoundingMode) String() string

type Word

A Word represents a single digit of a multi-precision unsigned integer.

+
type Word uint
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/math/big/ +

+
diff --git a/devdocs/go/math%2Fbits%2Findex.html b/devdocs/go/math%2Fbits%2Findex.html new file mode 100644 index 00000000..e0461437 --- /dev/null +++ b/devdocs/go/math%2Fbits%2Findex.html @@ -0,0 +1,377 @@ +

Package bits

Overview

Package bits implements bit counting and manipulation functions for the predeclared unsigned integer types.

+

Functions in this package may be implemented directly by the compiler, for better performance. For those functions the code in this package will not be used. Which functions are implemented by the compiler depends on the architecture and the Go release.

Index

Examples

Add32
Add64
Div32
Div64
LeadingZeros16
LeadingZeros32
LeadingZeros64
LeadingZeros8
Len16
Len32
Len64
Len8
Mul32
Mul64
OnesCount
OnesCount16
OnesCount32
OnesCount64
OnesCount8
Reverse16
Reverse32
Reverse64
Reverse8
ReverseBytes16
ReverseBytes32
ReverseBytes64
RotateLeft16
RotateLeft32
RotateLeft64
RotateLeft8
Sub32
Sub64
TrailingZeros16
TrailingZeros32
TrailingZeros64
TrailingZeros8

Package files

bits.go bits_errors.go bits_tables.go

Constants

UintSize is the size of a uint in bits.

+
const UintSize = uintSize

func Add 1.12

func Add(x, y, carry uint) (sum, carryOut uint)

Add returns the sum with carry of x, y and carry: sum = x + y + carry. The carry input must be 0 or 1; otherwise the behavior is undefined. The carryOut output is guaranteed to be 0 or 1.

+

This function's execution time does not depend on the inputs.

+

func Add32 1.12

func Add32(x, y, carry uint32) (sum, carryOut uint32)

Add32 returns the sum with carry of x, y and carry: sum = x + y + carry. The carry input must be 0 or 1; otherwise the behavior is undefined. The carryOut output is guaranteed to be 0 or 1.

+

This function's execution time does not depend on the inputs.

Example +

Code:

// First number is 33<<32 + 12
+n1 := []uint32{33, 12}
+// Second number is 21<<32 + 23
+n2 := []uint32{21, 23}
+// Add them together without producing carry.
+d1, carry := bits.Add32(n1[1], n2[1], 0)
+d0, _ := bits.Add32(n1[0], n2[0], carry)
+nsum := []uint32{d0, d1}
+fmt.Printf("%v + %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+
+// First number is 1<<32 + 2147483648
+n1 = []uint32{1, 0x80000000}
+// Second number is 1<<32 + 2147483648
+n2 = []uint32{1, 0x80000000}
+// Add them together producing carry.
+d1, carry = bits.Add32(n1[1], n2[1], 0)
+d0, _ = bits.Add32(n1[0], n2[0], carry)
+nsum = []uint32{d0, d1}
+fmt.Printf("%v + %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+

Output:

[33 12] + [21 23] = [54 35] (carry bit was 0)
+[1 2147483648] + [1 2147483648] = [3 0] (carry bit was 1)
+

func Add64 1.12

func Add64(x, y, carry uint64) (sum, carryOut uint64)

Add64 returns the sum with carry of x, y and carry: sum = x + y + carry. The carry input must be 0 or 1; otherwise the behavior is undefined. The carryOut output is guaranteed to be 0 or 1.

+

This function's execution time does not depend on the inputs.

Example +

Code:

// First number is 33<<64 + 12
+n1 := []uint64{33, 12}
+// Second number is 21<<64 + 23
+n2 := []uint64{21, 23}
+// Add them together without producing carry.
+d1, carry := bits.Add64(n1[1], n2[1], 0)
+d0, _ := bits.Add64(n1[0], n2[0], carry)
+nsum := []uint64{d0, d1}
+fmt.Printf("%v + %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+
+// First number is 1<<64 + 9223372036854775808
+n1 = []uint64{1, 0x8000000000000000}
+// Second number is 1<<64 + 9223372036854775808
+n2 = []uint64{1, 0x8000000000000000}
+// Add them together producing carry.
+d1, carry = bits.Add64(n1[1], n2[1], 0)
+d0, _ = bits.Add64(n1[0], n2[0], carry)
+nsum = []uint64{d0, d1}
+fmt.Printf("%v + %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+

Output:

[33 12] + [21 23] = [54 35] (carry bit was 0)
+[1 9223372036854775808] + [1 9223372036854775808] = [3 0] (carry bit was 1)
+

func Div 1.12

func Div(hi, lo, y uint) (quo, rem uint)

Div returns the quotient and remainder of (hi, lo) divided by y: quo = (hi, lo)/y, rem = (hi, lo)%y with the dividend bits' upper half in parameter hi and the lower half in parameter lo. Div panics for y == 0 (division by zero) or y <= hi (quotient overflow).

+

func Div32 1.12

func Div32(hi, lo, y uint32) (quo, rem uint32)

Div32 returns the quotient and remainder of (hi, lo) divided by y: quo = (hi, lo)/y, rem = (hi, lo)%y with the dividend bits' upper half in parameter hi and the lower half in parameter lo. Div32 panics for y == 0 (division by zero) or y <= hi (quotient overflow).

Example +

Code:

// First number is 0<<32 + 6
+n1 := []uint32{0, 6}
+// Second number is 0<<32 + 3
+n2 := []uint32{0, 3}
+// Divide them together.
+quo, rem := bits.Div32(n1[0], n1[1], n2[1])
+nsum := []uint32{quo, rem}
+fmt.Printf("[%v %v] / %v = %v\n", n1[0], n1[1], n2[1], nsum)
+
+// First number is 2<<32 + 2147483648
+n1 = []uint32{2, 0x80000000}
+// Second number is 0<<32 + 2147483648
+n2 = []uint32{0, 0x80000000}
+// Divide them together.
+quo, rem = bits.Div32(n1[0], n1[1], n2[1])
+nsum = []uint32{quo, rem}
+fmt.Printf("[%v %v] / %v = %v\n", n1[0], n1[1], n2[1], nsum)
+

Output:

[0 6] / 3 = [2 0]
+[2 2147483648] / 2147483648 = [5 0]
+

func Div64 1.12

func Div64(hi, lo, y uint64) (quo, rem uint64)

Div64 returns the quotient and remainder of (hi, lo) divided by y: quo = (hi, lo)/y, rem = (hi, lo)%y with the dividend bits' upper half in parameter hi and the lower half in parameter lo. Div64 panics for y == 0 (division by zero) or y <= hi (quotient overflow).

Example +

Code:

// First number is 0<<64 + 6
+n1 := []uint64{0, 6}
+// Second number is 0<<64 + 3
+n2 := []uint64{0, 3}
+// Divide them together.
+quo, rem := bits.Div64(n1[0], n1[1], n2[1])
+nsum := []uint64{quo, rem}
+fmt.Printf("[%v %v] / %v = %v\n", n1[0], n1[1], n2[1], nsum)
+
+// First number is 2<<64 + 9223372036854775808
+n1 = []uint64{2, 0x8000000000000000}
+// Second number is 0<<64 + 9223372036854775808
+n2 = []uint64{0, 0x8000000000000000}
+// Divide them together.
+quo, rem = bits.Div64(n1[0], n1[1], n2[1])
+nsum = []uint64{quo, rem}
+fmt.Printf("[%v %v] / %v = %v\n", n1[0], n1[1], n2[1], nsum)
+

Output:

[0 6] / 3 = [2 0]
+[2 9223372036854775808] / 9223372036854775808 = [5 0]
+

func LeadingZeros 1.9

func LeadingZeros(x uint) int

LeadingZeros returns the number of leading zero bits in x; the result is UintSize for x == 0.

+

func LeadingZeros16 1.9

func LeadingZeros16(x uint16) int

LeadingZeros16 returns the number of leading zero bits in x; the result is 16 for x == 0.

Example +

Code:

fmt.Printf("LeadingZeros16(%016b) = %d\n", 1, bits.LeadingZeros16(1))
+

Output:

LeadingZeros16(0000000000000001) = 15
+

func LeadingZeros32 1.9

func LeadingZeros32(x uint32) int

LeadingZeros32 returns the number of leading zero bits in x; the result is 32 for x == 0.

Example +

Code:

fmt.Printf("LeadingZeros32(%032b) = %d\n", 1, bits.LeadingZeros32(1))
+

Output:

LeadingZeros32(00000000000000000000000000000001) = 31
+

func LeadingZeros64 1.9

func LeadingZeros64(x uint64) int

LeadingZeros64 returns the number of leading zero bits in x; the result is 64 for x == 0.

Example +

Code:

fmt.Printf("LeadingZeros64(%064b) = %d\n", 1, bits.LeadingZeros64(1))
+

Output:

LeadingZeros64(0000000000000000000000000000000000000000000000000000000000000001) = 63
+

func LeadingZeros8 1.9

func LeadingZeros8(x uint8) int

LeadingZeros8 returns the number of leading zero bits in x; the result is 8 for x == 0.

Example +

Code:

fmt.Printf("LeadingZeros8(%08b) = %d\n", 1, bits.LeadingZeros8(1))
+

Output:

LeadingZeros8(00000001) = 7
+

func Len 1.9

func Len(x uint) int

Len returns the minimum number of bits required to represent x; the result is 0 for x == 0.

+

func Len16 1.9

func Len16(x uint16) (n int)

Len16 returns the minimum number of bits required to represent x; the result is 0 for x == 0.

Example +

Code:

fmt.Printf("Len16(%016b) = %d\n", 8, bits.Len16(8))
+

Output:

Len16(0000000000001000) = 4
+

func Len32 1.9

func Len32(x uint32) (n int)

Len32 returns the minimum number of bits required to represent x; the result is 0 for x == 0.

Example +

Code:

fmt.Printf("Len32(%032b) = %d\n", 8, bits.Len32(8))
+

Output:

Len32(00000000000000000000000000001000) = 4
+

func Len64 1.9

func Len64(x uint64) (n int)

Len64 returns the minimum number of bits required to represent x; the result is 0 for x == 0.

Example +

Code:

fmt.Printf("Len64(%064b) = %d\n", 8, bits.Len64(8))
+

Output:

Len64(0000000000000000000000000000000000000000000000000000000000001000) = 4
+

func Len8 1.9

func Len8(x uint8) int

Len8 returns the minimum number of bits required to represent x; the result is 0 for x == 0.

Example +

Code:

fmt.Printf("Len8(%08b) = %d\n", 8, bits.Len8(8))
+

Output:

Len8(00001000) = 4
+

func Mul 1.12

func Mul(x, y uint) (hi, lo uint)

Mul returns the full-width product of x and y: (hi, lo) = x * y with the product bits' upper half returned in hi and the lower half returned in lo.

+

This function's execution time does not depend on the inputs.

+

func Mul32 1.12

func Mul32(x, y uint32) (hi, lo uint32)

Mul32 returns the 64-bit product of x and y: (hi, lo) = x * y with the product bits' upper half returned in hi and the lower half returned in lo.

+

This function's execution time does not depend on the inputs.

Example +

Code:

// First number is 0<<32 + 12
+n1 := []uint32{0, 12}
+// Second number is 0<<32 + 12
+n2 := []uint32{0, 12}
+// Multiply them together without producing overflow.
+hi, lo := bits.Mul32(n1[1], n2[1])
+nsum := []uint32{hi, lo}
+fmt.Printf("%v * %v = %v\n", n1[1], n2[1], nsum)
+
+// First number is 0<<32 + 2147483648
+n1 = []uint32{0, 0x80000000}
+// Second number is 0<<32 + 2
+n2 = []uint32{0, 2}
+// Multiply them together producing overflow.
+hi, lo = bits.Mul32(n1[1], n2[1])
+nsum = []uint32{hi, lo}
+fmt.Printf("%v * %v = %v\n", n1[1], n2[1], nsum)
+

Output:

12 * 12 = [0 144]
+2147483648 * 2 = [1 0]
+

func Mul64 1.12

func Mul64(x, y uint64) (hi, lo uint64)

Mul64 returns the 128-bit product of x and y: (hi, lo) = x * y with the product bits' upper half returned in hi and the lower half returned in lo.

+

This function's execution time does not depend on the inputs.

Example +

Code:

// First number is 0<<64 + 12
+n1 := []uint64{0, 12}
+// Second number is 0<<64 + 12
+n2 := []uint64{0, 12}
+// Multiply them together without producing overflow.
+hi, lo := bits.Mul64(n1[1], n2[1])
+nsum := []uint64{hi, lo}
+fmt.Printf("%v * %v = %v\n", n1[1], n2[1], nsum)
+
+// First number is 0<<64 + 9223372036854775808
+n1 = []uint64{0, 0x8000000000000000}
+// Second number is 0<<64 + 2
+n2 = []uint64{0, 2}
+// Multiply them together producing overflow.
+hi, lo = bits.Mul64(n1[1], n2[1])
+nsum = []uint64{hi, lo}
+fmt.Printf("%v * %v = %v\n", n1[1], n2[1], nsum)
+

Output:

12 * 12 = [0 144]
+9223372036854775808 * 2 = [1 0]
+

func OnesCount 1.9

func OnesCount(x uint) int

OnesCount returns the number of one bits ("population count") in x.

Example +

Code:

fmt.Printf("OnesCount(%b) = %d\n", 14, bits.OnesCount(14))
+

Output:

OnesCount(1110) = 3
+

func OnesCount16 1.9

func OnesCount16(x uint16) int

OnesCount16 returns the number of one bits ("population count") in x.

Example +

Code:

fmt.Printf("OnesCount16(%016b) = %d\n", 14, bits.OnesCount16(14))
+

Output:

OnesCount16(0000000000001110) = 3
+

func OnesCount32 1.9

func OnesCount32(x uint32) int

OnesCount32 returns the number of one bits ("population count") in x.

Example +

Code:

fmt.Printf("OnesCount32(%032b) = %d\n", 14, bits.OnesCount32(14))
+

Output:

OnesCount32(00000000000000000000000000001110) = 3
+

func OnesCount64 1.9

func OnesCount64(x uint64) int

OnesCount64 returns the number of one bits ("population count") in x.

Example +

Code:

fmt.Printf("OnesCount64(%064b) = %d\n", 14, bits.OnesCount64(14))
+

Output:

OnesCount64(0000000000000000000000000000000000000000000000000000000000001110) = 3
+

func OnesCount8 1.9

func OnesCount8(x uint8) int

OnesCount8 returns the number of one bits ("population count") in x.

Example +

Code:

fmt.Printf("OnesCount8(%08b) = %d\n", 14, bits.OnesCount8(14))
+

Output:

OnesCount8(00001110) = 3
+

func Rem 1.14

func Rem(hi, lo, y uint) uint

Rem returns the remainder of (hi, lo) divided by y. Rem panics for y == 0 (division by zero) but, unlike Div, it doesn't panic on a quotient overflow.

+

func Rem32 1.14

func Rem32(hi, lo, y uint32) uint32

Rem32 returns the remainder of (hi, lo) divided by y. Rem32 panics for y == 0 (division by zero) but, unlike Div32, it doesn't panic on a quotient overflow.

+

func Rem64 1.14

func Rem64(hi, lo, y uint64) uint64

Rem64 returns the remainder of (hi, lo) divided by y. Rem64 panics for y == 0 (division by zero) but, unlike Div64, it doesn't panic on a quotient overflow.

+

func Reverse 1.9

func Reverse(x uint) uint

Reverse returns the value of x with its bits in reversed order.

+

func Reverse16 1.9

func Reverse16(x uint16) uint16

Reverse16 returns the value of x with its bits in reversed order.

Example +

Code:

fmt.Printf("%016b\n", 19)
+fmt.Printf("%016b\n", bits.Reverse16(19))
+

Output:

0000000000010011
+1100100000000000
+

func Reverse32 1.9

func Reverse32(x uint32) uint32

Reverse32 returns the value of x with its bits in reversed order.

Example +

Code:

fmt.Printf("%032b\n", 19)
+fmt.Printf("%032b\n", bits.Reverse32(19))
+

Output:

00000000000000000000000000010011
+11001000000000000000000000000000
+

func Reverse64 1.9

func Reverse64(x uint64) uint64

Reverse64 returns the value of x with its bits in reversed order.

Example +

Code:

fmt.Printf("%064b\n", 19)
+fmt.Printf("%064b\n", bits.Reverse64(19))
+

Output:

0000000000000000000000000000000000000000000000000000000000010011
+1100100000000000000000000000000000000000000000000000000000000000
+

func Reverse8 1.9

func Reverse8(x uint8) uint8

Reverse8 returns the value of x with its bits in reversed order.

Example +

Code:

fmt.Printf("%08b\n", 19)
+fmt.Printf("%08b\n", bits.Reverse8(19))
+

Output:

00010011
+11001000
+

func ReverseBytes 1.9

func ReverseBytes(x uint) uint

ReverseBytes returns the value of x with its bytes in reversed order.

+

This function's execution time does not depend on the inputs.

+

func ReverseBytes16 1.9

func ReverseBytes16(x uint16) uint16

ReverseBytes16 returns the value of x with its bytes in reversed order.

+

This function's execution time does not depend on the inputs.

Example +

Code:

fmt.Printf("%016b\n", 15)
+fmt.Printf("%016b\n", bits.ReverseBytes16(15))
+

Output:

0000000000001111
+0000111100000000
+

func ReverseBytes32 1.9

func ReverseBytes32(x uint32) uint32

ReverseBytes32 returns the value of x with its bytes in reversed order.

+

This function's execution time does not depend on the inputs.

Example +

Code:

fmt.Printf("%032b\n", 15)
+fmt.Printf("%032b\n", bits.ReverseBytes32(15))
+

Output:

00000000000000000000000000001111
+00001111000000000000000000000000
+

func ReverseBytes64 1.9

func ReverseBytes64(x uint64) uint64

ReverseBytes64 returns the value of x with its bytes in reversed order.

+

This function's execution time does not depend on the inputs.

Example +

Code:

fmt.Printf("%064b\n", 15)
+fmt.Printf("%064b\n", bits.ReverseBytes64(15))
+

Output:

0000000000000000000000000000000000000000000000000000000000001111
+0000111100000000000000000000000000000000000000000000000000000000
+

func RotateLeft 1.9

func RotateLeft(x uint, k int) uint

RotateLeft returns the value of x rotated left by (k mod UintSize) bits. To rotate x right by k bits, call RotateLeft(x, -k).

+

This function's execution time does not depend on the inputs.

+

func RotateLeft16 1.9

func RotateLeft16(x uint16, k int) uint16

RotateLeft16 returns the value of x rotated left by (k mod 16) bits. To rotate x right by k bits, call RotateLeft16(x, -k).

+

This function's execution time does not depend on the inputs.

Example +

Code:

fmt.Printf("%016b\n", 15)
+fmt.Printf("%016b\n", bits.RotateLeft16(15, 2))
+fmt.Printf("%016b\n", bits.RotateLeft16(15, -2))
+

Output:

0000000000001111
+0000000000111100
+1100000000000011
+

func RotateLeft32 1.9

func RotateLeft32(x uint32, k int) uint32

RotateLeft32 returns the value of x rotated left by (k mod 32) bits. To rotate x right by k bits, call RotateLeft32(x, -k).

+

This function's execution time does not depend on the inputs.

Example +

Code:

fmt.Printf("%032b\n", 15)
+fmt.Printf("%032b\n", bits.RotateLeft32(15, 2))
+fmt.Printf("%032b\n", bits.RotateLeft32(15, -2))
+

Output:

00000000000000000000000000001111
+00000000000000000000000000111100
+11000000000000000000000000000011
+

func RotateLeft64 1.9

func RotateLeft64(x uint64, k int) uint64

RotateLeft64 returns the value of x rotated left by (k mod 64) bits. To rotate x right by k bits, call RotateLeft64(x, -k).

+

This function's execution time does not depend on the inputs.

Example +

Code:

fmt.Printf("%064b\n", 15)
+fmt.Printf("%064b\n", bits.RotateLeft64(15, 2))
+fmt.Printf("%064b\n", bits.RotateLeft64(15, -2))
+

Output:

0000000000000000000000000000000000000000000000000000000000001111
+0000000000000000000000000000000000000000000000000000000000111100
+1100000000000000000000000000000000000000000000000000000000000011
+

func RotateLeft8 1.9

func RotateLeft8(x uint8, k int) uint8

RotateLeft8 returns the value of x rotated left by (k mod 8) bits. To rotate x right by k bits, call RotateLeft8(x, -k).

+

This function's execution time does not depend on the inputs.

Example +

Code:

fmt.Printf("%08b\n", 15)
+fmt.Printf("%08b\n", bits.RotateLeft8(15, 2))
+fmt.Printf("%08b\n", bits.RotateLeft8(15, -2))
+

Output:

00001111
+00111100
+11000011
+

func Sub 1.12

func Sub(x, y, borrow uint) (diff, borrowOut uint)

Sub returns the difference of x, y and borrow: diff = x - y - borrow. The borrow input must be 0 or 1; otherwise the behavior is undefined. The borrowOut output is guaranteed to be 0 or 1.

+

This function's execution time does not depend on the inputs.

+

func Sub32 1.12

func Sub32(x, y, borrow uint32) (diff, borrowOut uint32)

Sub32 returns the difference of x, y and borrow, diff = x - y - borrow. The borrow input must be 0 or 1; otherwise the behavior is undefined. The borrowOut output is guaranteed to be 0 or 1.

+

This function's execution time does not depend on the inputs.

Example +

Code:

// First number is 33<<32 + 23
+n1 := []uint32{33, 23}
+// Second number is 21<<32 + 12
+n2 := []uint32{21, 12}
+// Sub them together without producing carry.
+d1, carry := bits.Sub32(n1[1], n2[1], 0)
+d0, _ := bits.Sub32(n1[0], n2[0], carry)
+nsum := []uint32{d0, d1}
+fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+
+// First number is 3<<32 + 2147483647
+n1 = []uint32{3, 0x7fffffff}
+// Second number is 1<<32 + 2147483648
+n2 = []uint32{1, 0x80000000}
+// Sub them together producing carry.
+d1, carry = bits.Sub32(n1[1], n2[1], 0)
+d0, _ = bits.Sub32(n1[0], n2[0], carry)
+nsum = []uint32{d0, d1}
+fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+

Output:

[33 23] - [21 12] = [12 11] (carry bit was 0)
+[3 2147483647] - [1 2147483648] = [1 4294967295] (carry bit was 1)
+

func Sub64 1.12

func Sub64(x, y, borrow uint64) (diff, borrowOut uint64)

Sub64 returns the difference of x, y and borrow: diff = x - y - borrow. The borrow input must be 0 or 1; otherwise the behavior is undefined. The borrowOut output is guaranteed to be 0 or 1.

+

This function's execution time does not depend on the inputs.

Example +

Code:

// First number is 33<<64 + 23
+n1 := []uint64{33, 23}
+// Second number is 21<<64 + 12
+n2 := []uint64{21, 12}
+// Sub them together without producing carry.
+d1, carry := bits.Sub64(n1[1], n2[1], 0)
+d0, _ := bits.Sub64(n1[0], n2[0], carry)
+nsum := []uint64{d0, d1}
+fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+
+// First number is 3<<64 + 9223372036854775807
+n1 = []uint64{3, 0x7fffffffffffffff}
+// Second number is 1<<64 + 9223372036854775808
+n2 = []uint64{1, 0x8000000000000000}
+// Sub them together producing carry.
+d1, carry = bits.Sub64(n1[1], n2[1], 0)
+d0, _ = bits.Sub64(n1[0], n2[0], carry)
+nsum = []uint64{d0, d1}
+fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+

Output:

[33 23] - [21 12] = [12 11] (carry bit was 0)
+[3 9223372036854775807] - [1 9223372036854775808] = [1 18446744073709551615] (carry bit was 1)
+

func TrailingZeros 1.9

func TrailingZeros(x uint) int

TrailingZeros returns the number of trailing zero bits in x; the result is UintSize for x == 0.

+

func TrailingZeros16 1.9

func TrailingZeros16(x uint16) int

TrailingZeros16 returns the number of trailing zero bits in x; the result is 16 for x == 0.

Example +

Code:

fmt.Printf("TrailingZeros16(%016b) = %d\n", 14, bits.TrailingZeros16(14))
+

Output:

TrailingZeros16(0000000000001110) = 1
+

func TrailingZeros32 1.9

func TrailingZeros32(x uint32) int

TrailingZeros32 returns the number of trailing zero bits in x; the result is 32 for x == 0.

Example +

Code:

fmt.Printf("TrailingZeros32(%032b) = %d\n", 14, bits.TrailingZeros32(14))
+

Output:

TrailingZeros32(00000000000000000000000000001110) = 1
+

func TrailingZeros64 1.9

func TrailingZeros64(x uint64) int

TrailingZeros64 returns the number of trailing zero bits in x; the result is 64 for x == 0.

Example +

Code:

fmt.Printf("TrailingZeros64(%064b) = %d\n", 14, bits.TrailingZeros64(14))
+

Output:

TrailingZeros64(0000000000000000000000000000000000000000000000000000000000001110) = 1
+

func TrailingZeros8 1.9

func TrailingZeros8(x uint8) int

TrailingZeros8 returns the number of trailing zero bits in x; the result is 8 for x == 0.

Example +

Code:

fmt.Printf("TrailingZeros8(%08b) = %d\n", 14, bits.TrailingZeros8(14))
+

Output:

TrailingZeros8(00001110) = 1
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/math/bits/ +

+
diff --git a/devdocs/go/math%2Fcmplx%2Findex.html b/devdocs/go/math%2Fcmplx%2Findex.html new file mode 100644 index 00000000..8d64ef40 --- /dev/null +++ b/devdocs/go/math%2Fcmplx%2Findex.html @@ -0,0 +1,74 @@ +

Package cmplx

Overview

Package cmplx provides basic constants and mathematical functions for complex numbers. Special case handling conforms to the C99 standard Annex G IEC 60559-compatible complex arithmetic.

Index

Examples

Abs
Exp
Polar

Package files

abs.go asin.go conj.go exp.go isinf.go isnan.go log.go phase.go polar.go pow.go rect.go sin.go sqrt.go tan.go

func Abs

func Abs(x complex128) float64

Abs returns the absolute value (also called the modulus) of x.

Example +

Code:

fmt.Printf("%.1f", cmplx.Abs(3+4i))
+

Output:

5.0
+

func Acos

func Acos(x complex128) complex128

Acos returns the inverse cosine of x.

+

func Acosh

func Acosh(x complex128) complex128

Acosh returns the inverse hyperbolic cosine of x.

+

func Asin

func Asin(x complex128) complex128

Asin returns the inverse sine of x.

+

func Asinh

func Asinh(x complex128) complex128

Asinh returns the inverse hyperbolic sine of x.

+

func Atan

func Atan(x complex128) complex128

Atan returns the inverse tangent of x.

+

func Atanh

func Atanh(x complex128) complex128

Atanh returns the inverse hyperbolic tangent of x.

+

func Conj

func Conj(x complex128) complex128

Conj returns the complex conjugate of x.

+

func Cos

func Cos(x complex128) complex128

Cos returns the cosine of x.

+

func Cosh

func Cosh(x complex128) complex128

Cosh returns the hyperbolic cosine of x.

+

func Cot

func Cot(x complex128) complex128

Cot returns the cotangent of x.

+

func Exp

func Exp(x complex128) complex128

Exp returns e**x, the base-e exponential of x.

Example +

ExampleExp computes Euler's identity.

Code:

fmt.Printf("%.1f", cmplx.Exp(1i*math.Pi)+1)
+

Output:

(0.0+0.0i)
+

func Inf

func Inf() complex128

Inf returns a complex infinity, complex(+Inf, +Inf).

+

func IsInf

func IsInf(x complex128) bool

IsInf reports whether either real(x) or imag(x) is an infinity.

+

func IsNaN

func IsNaN(x complex128) bool

IsNaN reports whether either real(x) or imag(x) is NaN and neither is an infinity.

+

func Log

func Log(x complex128) complex128

Log returns the natural logarithm of x.

+

func Log10

func Log10(x complex128) complex128

Log10 returns the decimal logarithm of x.

+

func NaN

func NaN() complex128

NaN returns a complex “not-a-number” value.

+

func Phase

func Phase(x complex128) float64

Phase returns the phase (also called the argument) of x. The returned value is in the range [-Pi, Pi].

+

func Polar

func Polar(x complex128) (r, θ float64)

Polar returns the absolute value r and phase θ of x, such that x = r * e**θi. The phase is in the range [-Pi, Pi].

Example +

Code:

r, theta := cmplx.Polar(2i)
+fmt.Printf("r: %.1f, θ: %.1f*π", r, theta/math.Pi)
+

Output:

r: 2.0, θ: 0.5*π
+

func Pow

func Pow(x, y complex128) complex128

Pow returns x**y, the base-x exponential of y. For generalized compatibility with math.Pow:

+
Pow(0, ±0) returns 1+0i
+Pow(0, c) for real(c)<0 returns Inf+0i if imag(c) is zero, otherwise Inf+Inf i.
+

func Rect

func Rect(r, θ float64) complex128

Rect returns the complex number x with polar coordinates r, θ.

+

func Sin

func Sin(x complex128) complex128

Sin returns the sine of x.

+

func Sinh

func Sinh(x complex128) complex128

Sinh returns the hyperbolic sine of x.

+

func Sqrt

func Sqrt(x complex128) complex128

Sqrt returns the square root of x. The result r is chosen so that real(r) ≥ 0 and imag(r) has the same sign as imag(x).

+

func Tan

func Tan(x complex128) complex128

Tan returns the tangent of x.

+

func Tanh

func Tanh(x complex128) complex128

Tanh returns the hyperbolic tangent of x.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/math/cmplx/ +

+
diff --git a/devdocs/go/math%2Findex.html b/devdocs/go/math%2Findex.html new file mode 100644 index 00000000..158845f5 --- /dev/null +++ b/devdocs/go/math%2Findex.html @@ -0,0 +1,597 @@ +

Package math

Overview

Package math provides basic constants and mathematical functions.

+

This package does not guarantee bit-identical results across architectures.

Index

Examples

Abs
Acos
Acosh
Asin
Asinh
Atan
Atan2
Atanh
Cbrt
Ceil
Copysign
Cos
Cosh
Dim
Exp
Exp2
Expm1
Floor
Log
Log10
Log2
Mod
Modf
Pow
Pow10
Remainder
Round
RoundToEven
Sin
Sincos
Sinh
Sqrt
Tan
Tanh
Trunc

Package files

abs.go acosh.go asin.go asinh.go atan.go atan2.go atanh.go bits.go cbrt.go const.go copysign.go dim.go dim_asm.go erf.go erfinv.go exp.go exp2_noasm.go exp_amd64.go exp_asm.go expm1.go floor.go floor_asm.go fma.go frexp.go gamma.go hypot.go hypot_asm.go j0.go j1.go jn.go ldexp.go lgamma.go log.go log10.go log1p.go log_asm.go logb.go mod.go modf.go modf_noasm.go nextafter.go pow.go pow10.go remainder.go signbit.go sin.go sincos.go sinh.go sqrt.go stubs.go tan.go tanh.go trig_reduce.go unsafe.go

Constants

Mathematical constants.

+
const (
+    E   = 2.71828182845904523536028747135266249775724709369995957496696763 // https://oeis.org/A001113
+    Pi  = 3.14159265358979323846264338327950288419716939937510582097494459 // https://oeis.org/A000796
+    Phi = 1.61803398874989484820458683436563811772030917980576286213544862 // https://oeis.org/A001622
+
+    Sqrt2   = 1.41421356237309504880168872420969807856967187537694807317667974 // https://oeis.org/A002193
+    SqrtE   = 1.64872127070012814684865078781416357165377610071014801157507931 // https://oeis.org/A019774
+    SqrtPi  = 1.77245385090551602729816748334114518279754945612238712821380779 // https://oeis.org/A002161
+    SqrtPhi = 1.27201964951406896425242246173749149171560804184009624861664038 // https://oeis.org/A139339
+
+    Ln2    = 0.693147180559945309417232121458176568075500134360255254120680009 // https://oeis.org/A002162
+    Log2E  = 1 / Ln2
+    Ln10   = 2.30258509299404568401799145468436420760110148862877297603332790 // https://oeis.org/A002392
+    Log10E = 1 / Ln10
+)

Floating-point limit values. Max is the largest finite value representable by the type. SmallestNonzero is the smallest positive, non-zero value representable by the type.

+
const (
+    MaxFloat32             = 0x1p127 * (1 + (1 - 0x1p-23)) // 3.40282346638528859811704183484516925440e+38
+    SmallestNonzeroFloat32 = 0x1p-126 * 0x1p-23            // 1.401298464324817070923729583289916131280e-45
+
+    MaxFloat64             = 0x1p1023 * (1 + (1 - 0x1p-52)) // 1.79769313486231570814527423731704356798070e+308
+    SmallestNonzeroFloat64 = 0x1p-1022 * 0x1p-52            // 4.9406564584124654417656879286822137236505980e-324
+)

Integer limit values.

+
const (
+    MaxInt    = 1<<(intSize-1) - 1  // MaxInt32 or MaxInt64 depending on intSize.
+    MinInt    = -1 << (intSize - 1) // MinInt32 or MinInt64 depending on intSize.
+    MaxInt8   = 1<<7 - 1            // 127
+    MinInt8   = -1 << 7             // -128
+    MaxInt16  = 1<<15 - 1           // 32767
+    MinInt16  = -1 << 15            // -32768
+    MaxInt32  = 1<<31 - 1           // 2147483647
+    MinInt32  = -1 << 31            // -2147483648
+    MaxInt64  = 1<<63 - 1           // 9223372036854775807
+    MinInt64  = -1 << 63            // -9223372036854775808
+    MaxUint   = 1<<intSize - 1      // MaxUint32 or MaxUint64 depending on intSize.
+    MaxUint8  = 1<<8 - 1            // 255
+    MaxUint16 = 1<<16 - 1           // 65535
+    MaxUint32 = 1<<32 - 1           // 4294967295
+    MaxUint64 = 1<<64 - 1           // 18446744073709551615
+)

func Abs

func Abs(x float64) float64

Abs returns the absolute value of x.

+

Special cases are:

+
Abs(±Inf) = +Inf
+Abs(NaN) = NaN
+

Example +

Code:

x := math.Abs(-2)
+fmt.Printf("%.1f\n", x)
+
+y := math.Abs(2)
+fmt.Printf("%.1f\n", y)
+

Output:

2.0
+2.0
+

func Acos

func Acos(x float64) float64

Acos returns the arccosine, in radians, of x.

+

Special case is:

+
Acos(x) = NaN if x < -1 or x > 1
+

Example +

Code:

fmt.Printf("%.2f", math.Acos(1))
+

Output:

0.00
+

func Acosh

func Acosh(x float64) float64

Acosh returns the inverse hyperbolic cosine of x.

+

Special cases are:

+
Acosh(+Inf) = +Inf
+Acosh(x) = NaN if x < 1
+Acosh(NaN) = NaN
+

Example +

Code:

fmt.Printf("%.2f", math.Acosh(1))
+

Output:

0.00
+

func Asin

func Asin(x float64) float64

Asin returns the arcsine, in radians, of x.

+

Special cases are:

+
Asin(±0) = ±0
+Asin(x) = NaN if x < -1 or x > 1
+

Example +

Code:

fmt.Printf("%.2f", math.Asin(0))
+

Output:

0.00
+

func Asinh

func Asinh(x float64) float64

Asinh returns the inverse hyperbolic sine of x.

+

Special cases are:

+
Asinh(±0) = ±0
+Asinh(±Inf) = ±Inf
+Asinh(NaN) = NaN
+

Example +

Code:

fmt.Printf("%.2f", math.Asinh(0))
+

Output:

0.00
+

func Atan

func Atan(x float64) float64

Atan returns the arctangent, in radians, of x.

+

Special cases are:

+
Atan(±0) = ±0
+Atan(±Inf) = ±Pi/2
+

Example +

Code:

fmt.Printf("%.2f", math.Atan(0))
+

Output:

0.00
+

func Atan2

func Atan2(y, x float64) float64

Atan2 returns the arc tangent of y/x, using the signs of the two to determine the quadrant of the return value.

+

Special cases are (in order):

+
Atan2(y, NaN) = NaN
+Atan2(NaN, x) = NaN
+Atan2(+0, x>=0) = +0
+Atan2(-0, x>=0) = -0
+Atan2(+0, x<=-0) = +Pi
+Atan2(-0, x<=-0) = -Pi
+Atan2(y>0, 0) = +Pi/2
+Atan2(y<0, 0) = -Pi/2
+Atan2(+Inf, +Inf) = +Pi/4
+Atan2(-Inf, +Inf) = -Pi/4
+Atan2(+Inf, -Inf) = 3Pi/4
+Atan2(-Inf, -Inf) = -3Pi/4
+Atan2(y, +Inf) = 0
+Atan2(y>0, -Inf) = +Pi
+Atan2(y<0, -Inf) = -Pi
+Atan2(+Inf, x) = +Pi/2
+Atan2(-Inf, x) = -Pi/2
+

Example +

Code:

fmt.Printf("%.2f", math.Atan2(0, 0))
+

Output:

0.00
+

func Atanh

func Atanh(x float64) float64

Atanh returns the inverse hyperbolic tangent of x.

+

Special cases are:

+
Atanh(1) = +Inf
+Atanh(±0) = ±0
+Atanh(-1) = -Inf
+Atanh(x) = NaN if x < -1 or x > 1
+Atanh(NaN) = NaN
+

Example +

Code:

fmt.Printf("%.2f", math.Atanh(0))
+

Output:

0.00
+

func Cbrt

func Cbrt(x float64) float64

Cbrt returns the cube root of x.

+

Special cases are:

+
Cbrt(±0) = ±0
+Cbrt(±Inf) = ±Inf
+Cbrt(NaN) = NaN
+

Example +

Code:

fmt.Printf("%.2f\n", math.Cbrt(8))
+fmt.Printf("%.2f\n", math.Cbrt(27))
+

Output:

2.00
+3.00
+

func Ceil

func Ceil(x float64) float64

Ceil returns the least integer value greater than or equal to x.

+

Special cases are:

+
Ceil(±0) = ±0
+Ceil(±Inf) = ±Inf
+Ceil(NaN) = NaN
+

Example +

Code:

c := math.Ceil(1.49)
+fmt.Printf("%.1f", c)
+

Output:

2.0
+

func Copysign

func Copysign(f, sign float64) float64

Copysign returns a value with the magnitude of f and the sign of sign.

Example +

Code:

fmt.Printf("%.2f", math.Copysign(3.2, -1))
+

Output:

-3.20
+

func Cos

func Cos(x float64) float64

Cos returns the cosine of the radian argument x.

+

Special cases are:

+
Cos(±Inf) = NaN
+Cos(NaN) = NaN
+

Example +

Code:

fmt.Printf("%.2f", math.Cos(math.Pi/2))
+

Output:

0.00
+

func Cosh

func Cosh(x float64) float64

Cosh returns the hyperbolic cosine of x.

+

Special cases are:

+
Cosh(±0) = 1
+Cosh(±Inf) = +Inf
+Cosh(NaN) = NaN
+

Example +

Code:

fmt.Printf("%.2f", math.Cosh(0))
+

Output:

1.00
+

func Dim

func Dim(x, y float64) float64

Dim returns the maximum of x-y or 0.

+

Special cases are:

+
Dim(+Inf, +Inf) = NaN
+Dim(-Inf, -Inf) = NaN
+Dim(x, NaN) = Dim(NaN, x) = NaN
+

Example +

Code:

fmt.Printf("%.2f\n", math.Dim(4, -2))
+fmt.Printf("%.2f\n", math.Dim(-4, 2))
+

Output:

6.00
+0.00
+

func Erf

func Erf(x float64) float64

Erf returns the error function of x.

+

Special cases are:

+
Erf(+Inf) = 1
+Erf(-Inf) = -1
+Erf(NaN) = NaN
+

func Erfc

func Erfc(x float64) float64

Erfc returns the complementary error function of x.

+

Special cases are:

+
Erfc(+Inf) = 0
+Erfc(-Inf) = 2
+Erfc(NaN) = NaN
+

func Erfcinv 1.10

func Erfcinv(x float64) float64

Erfcinv returns the inverse of Erfc(x).

+

Special cases are:

+
Erfcinv(0) = +Inf
+Erfcinv(2) = -Inf
+Erfcinv(x) = NaN if x < 0 or x > 2
+Erfcinv(NaN) = NaN
+

func Erfinv 1.10

func Erfinv(x float64) float64

Erfinv returns the inverse error function of x.

+

Special cases are:

+
Erfinv(1) = +Inf
+Erfinv(-1) = -Inf
+Erfinv(x) = NaN if x < -1 or x > 1
+Erfinv(NaN) = NaN
+

func Exp

func Exp(x float64) float64

Exp returns e**x, the base-e exponential of x.

+

Special cases are:

+
Exp(+Inf) = +Inf
+Exp(NaN) = NaN
+

Very large values overflow to 0 or +Inf. Very small values underflow to 1.

Example +

Code:

fmt.Printf("%.2f\n", math.Exp(1))
+fmt.Printf("%.2f\n", math.Exp(2))
+fmt.Printf("%.2f\n", math.Exp(-1))
+

Output:

2.72
+7.39
+0.37
+

func Exp2

func Exp2(x float64) float64

Exp2 returns 2**x, the base-2 exponential of x.

+

Special cases are the same as Exp.

Example +

Code:

fmt.Printf("%.2f\n", math.Exp2(1))
+fmt.Printf("%.2f\n", math.Exp2(-3))
+

Output:

2.00
+0.12
+

func Expm1

func Expm1(x float64) float64

Expm1 returns e**x - 1, the base-e exponential of x minus 1. It is more accurate than Exp(x) - 1 when x is near zero.

+

Special cases are:

+
Expm1(+Inf) = +Inf
+Expm1(-Inf) = -1
+Expm1(NaN) = NaN
+

Very large values overflow to -1 or +Inf.

Example +

Code:

fmt.Printf("%.6f\n", math.Expm1(0.01))
+fmt.Printf("%.6f\n", math.Expm1(-1))
+

Output:

0.010050
+-0.632121
+

func FMA 1.14

func FMA(x, y, z float64) float64

FMA returns x * y + z, computed with only one rounding. (That is, FMA returns the fused multiply-add of x, y, and z.)

+

func Float32bits

func Float32bits(f float32) uint32

Float32bits returns the IEEE 754 binary representation of f, with the sign bit of f and the result in the same bit position. Float32bits(Float32frombits(x)) == x.

+

func Float32frombits

func Float32frombits(b uint32) float32

Float32frombits returns the floating-point number corresponding to the IEEE 754 binary representation b, with the sign bit of b and the result in the same bit position. Float32frombits(Float32bits(x)) == x.

+

func Float64bits

func Float64bits(f float64) uint64

Float64bits returns the IEEE 754 binary representation of f, with the sign bit of f and the result in the same bit position, and Float64bits(Float64frombits(x)) == x.

+

func Float64frombits

func Float64frombits(b uint64) float64

Float64frombits returns the floating-point number corresponding to the IEEE 754 binary representation b, with the sign bit of b and the result in the same bit position. Float64frombits(Float64bits(x)) == x.

+

func Floor

func Floor(x float64) float64

Floor returns the greatest integer value less than or equal to x.

+

Special cases are:

+
Floor(±0) = ±0
+Floor(±Inf) = ±Inf
+Floor(NaN) = NaN
+

Example +

Code:

c := math.Floor(1.51)
+fmt.Printf("%.1f", c)
+

Output:

1.0
+

func Frexp

func Frexp(f float64) (frac float64, exp int)

Frexp breaks f into a normalized fraction and an integral power of two. It returns frac and exp satisfying f == frac × 2**exp, with the absolute value of frac in the interval [½, 1).

+

Special cases are:

+
Frexp(±0) = ±0, 0
+Frexp(±Inf) = ±Inf, 0
+Frexp(NaN) = NaN, 0
+

func Gamma

func Gamma(x float64) float64

Gamma returns the Gamma function of x.

+

Special cases are:

+
Gamma(+Inf) = +Inf
+Gamma(+0) = +Inf
+Gamma(-0) = -Inf
+Gamma(x) = NaN for integer x < 0
+Gamma(-Inf) = NaN
+Gamma(NaN) = NaN
+

func Hypot

func Hypot(p, q float64) float64

Hypot returns Sqrt(p*p + q*q), taking care to avoid unnecessary overflow and underflow.

+

Special cases are:

+
Hypot(±Inf, q) = +Inf
+Hypot(p, ±Inf) = +Inf
+Hypot(NaN, q) = NaN
+Hypot(p, NaN) = NaN
+

func Ilogb

func Ilogb(x float64) int

Ilogb returns the binary exponent of x as an integer.

+

Special cases are:

+
Ilogb(±Inf) = MaxInt32
+Ilogb(0) = MinInt32
+Ilogb(NaN) = MaxInt32
+

func Inf

func Inf(sign int) float64

Inf returns positive infinity if sign >= 0, negative infinity if sign < 0.

+

func IsInf

func IsInf(f float64, sign int) bool

IsInf reports whether f is an infinity, according to sign. If sign > 0, IsInf reports whether f is positive infinity. If sign < 0, IsInf reports whether f is negative infinity. If sign == 0, IsInf reports whether f is either infinity.

+

func IsNaN

func IsNaN(f float64) (is bool)

IsNaN reports whether f is an IEEE 754 “not-a-number” value.

+

func J0

func J0(x float64) float64

J0 returns the order-zero Bessel function of the first kind.

+

Special cases are:

+
J0(±Inf) = 0
+J0(0) = 1
+J0(NaN) = NaN
+

func J1

func J1(x float64) float64

J1 returns the order-one Bessel function of the first kind.

+

Special cases are:

+
J1(±Inf) = 0
+J1(NaN) = NaN
+

func Jn

func Jn(n int, x float64) float64

Jn returns the order-n Bessel function of the first kind.

+

Special cases are:

+
Jn(n, ±Inf) = 0
+Jn(n, NaN) = NaN
+

func Ldexp

func Ldexp(frac float64, exp int) float64

Ldexp is the inverse of Frexp. It returns frac × 2**exp.

+

Special cases are:

+
Ldexp(±0, exp) = ±0
+Ldexp(±Inf, exp) = ±Inf
+Ldexp(NaN, exp) = NaN
+

func Lgamma

func Lgamma(x float64) (lgamma float64, sign int)

Lgamma returns the natural logarithm and sign (-1 or +1) of Gamma(x).

+

Special cases are:

+
Lgamma(+Inf) = +Inf
+Lgamma(0) = +Inf
+Lgamma(-integer) = +Inf
+Lgamma(-Inf) = -Inf
+Lgamma(NaN) = NaN
+

func Log

func Log(x float64) float64

Log returns the natural logarithm of x.

+

Special cases are:

+
Log(+Inf) = +Inf
+Log(0) = -Inf
+Log(x < 0) = NaN
+Log(NaN) = NaN
+

Example +

Code:

x := math.Log(1)
+fmt.Printf("%.1f\n", x)
+
+y := math.Log(2.7183)
+fmt.Printf("%.1f\n", y)
+

Output:

0.0
+1.0
+

func Log10

func Log10(x float64) float64

Log10 returns the decimal logarithm of x. The special cases are the same as for Log.

Example +

Code:

fmt.Printf("%.1f", math.Log10(100))
+

Output:

2.0
+

func Log1p

func Log1p(x float64) float64

Log1p returns the natural logarithm of 1 plus its argument x. It is more accurate than Log(1 + x) when x is near zero.

+

Special cases are:

+
Log1p(+Inf) = +Inf
+Log1p(±0) = ±0
+Log1p(-1) = -Inf
+Log1p(x < -1) = NaN
+Log1p(NaN) = NaN
+

func Log2

func Log2(x float64) float64

Log2 returns the binary logarithm of x. The special cases are the same as for Log.

Example +

Code:

fmt.Printf("%.1f", math.Log2(256))
+

Output:

8.0
+

func Logb

func Logb(x float64) float64

Logb returns the binary exponent of x.

+

Special cases are:

+
Logb(±Inf) = +Inf
+Logb(0) = -Inf
+Logb(NaN) = NaN
+

func Max

func Max(x, y float64) float64

Max returns the larger of x or y.

+

Special cases are:

+
Max(x, +Inf) = Max(+Inf, x) = +Inf
+Max(x, NaN) = Max(NaN, x) = NaN
+Max(+0, ±0) = Max(±0, +0) = +0
+Max(-0, -0) = -0
+

Note that this differs from the built-in function max when called with NaN and +Inf.

+

func Min

func Min(x, y float64) float64

Min returns the smaller of x or y.

+

Special cases are:

+
Min(x, -Inf) = Min(-Inf, x) = -Inf
+Min(x, NaN) = Min(NaN, x) = NaN
+Min(-0, ±0) = Min(±0, -0) = -0
+

Note that this differs from the built-in function min when called with NaN and -Inf.

+

func Mod

func Mod(x, y float64) float64

Mod returns the floating-point remainder of x/y. The magnitude of the result is less than y and its sign agrees with that of x.

+

Special cases are:

+
Mod(±Inf, y) = NaN
+Mod(NaN, y) = NaN
+Mod(x, 0) = NaN
+Mod(x, ±Inf) = x
+Mod(x, NaN) = NaN
+

Example +

Code:

c := math.Mod(7, 4)
+fmt.Printf("%.1f", c)
+

Output:

3.0
+

func Modf

func Modf(f float64) (int float64, frac float64)

Modf returns integer and fractional floating-point numbers that sum to f. Both values have the same sign as f.

+

Special cases are:

+
Modf(±Inf) = ±Inf, NaN
+Modf(NaN) = NaN, NaN
+

Example +

Code:

int, frac := math.Modf(3.14)
+fmt.Printf("%.2f, %.2f\n", int, frac)
+
+int, frac = math.Modf(-2.71)
+fmt.Printf("%.2f, %.2f\n", int, frac)
+

Output:

3.00, 0.14
+-2.00, -0.71
+

func NaN

func NaN() float64

NaN returns an IEEE 754 “not-a-number” value.

+

func Nextafter

func Nextafter(x, y float64) (r float64)

Nextafter returns the next representable float64 value after x towards y.

+

Special cases are:

+
Nextafter(x, x)   = x
+Nextafter(NaN, y) = NaN
+Nextafter(x, NaN) = NaN
+

func Nextafter32 1.4

func Nextafter32(x, y float32) (r float32)

Nextafter32 returns the next representable float32 value after x towards y.

+

Special cases are:

+
Nextafter32(x, x)   = x
+Nextafter32(NaN, y) = NaN
+Nextafter32(x, NaN) = NaN
+

func Pow

func Pow(x, y float64) float64

Pow returns x**y, the base-x exponential of y.

+

Special cases are (in order):

+
Pow(x, ±0) = 1 for any x
+Pow(1, y) = 1 for any y
+Pow(x, 1) = x for any x
+Pow(NaN, y) = NaN
+Pow(x, NaN) = NaN
+Pow(±0, y) = ±Inf for y an odd integer < 0
+Pow(±0, -Inf) = +Inf
+Pow(±0, +Inf) = +0
+Pow(±0, y) = +Inf for finite y < 0 and not an odd integer
+Pow(±0, y) = ±0 for y an odd integer > 0
+Pow(±0, y) = +0 for finite y > 0 and not an odd integer
+Pow(-1, ±Inf) = 1
+Pow(x, +Inf) = +Inf for |x| > 1
+Pow(x, -Inf) = +0 for |x| > 1
+Pow(x, +Inf) = +0 for |x| < 1
+Pow(x, -Inf) = +Inf for |x| < 1
+Pow(+Inf, y) = +Inf for y > 0
+Pow(+Inf, y) = +0 for y < 0
+Pow(-Inf, y) = Pow(-0, -y)
+Pow(x, y) = NaN for finite x < 0 and finite non-integer y
+

Example +

Code:

c := math.Pow(2, 3)
+fmt.Printf("%.1f", c)
+

Output:

8.0
+

func Pow10

func Pow10(n int) float64

Pow10 returns 10**n, the base-10 exponential of n.

+

Special cases are:

+
Pow10(n) =    0 for n < -323
+Pow10(n) = +Inf for n > 308
+

Example +

Code:

c := math.Pow10(2)
+fmt.Printf("%.1f", c)
+

Output:

100.0
+

func Remainder

func Remainder(x, y float64) float64

Remainder returns the IEEE 754 floating-point remainder of x/y.

+

Special cases are:

+
Remainder(±Inf, y) = NaN
+Remainder(NaN, y) = NaN
+Remainder(x, 0) = NaN
+Remainder(x, ±Inf) = x
+Remainder(x, NaN) = NaN
+

Example +

Code:

fmt.Printf("%.1f", math.Remainder(100, 30))
+

Output:

10.0
+

func Round 1.10

func Round(x float64) float64

Round returns the nearest integer, rounding half away from zero.

+

Special cases are:

+
Round(±0) = ±0
+Round(±Inf) = ±Inf
+Round(NaN) = NaN
+

Example +

Code:

p := math.Round(10.5)
+fmt.Printf("%.1f\n", p)
+
+n := math.Round(-10.5)
+fmt.Printf("%.1f\n", n)
+

Output:

11.0
+-11.0
+

func RoundToEven 1.10

func RoundToEven(x float64) float64

RoundToEven returns the nearest integer, rounding ties to even.

+

Special cases are:

+
RoundToEven(±0) = ±0
+RoundToEven(±Inf) = ±Inf
+RoundToEven(NaN) = NaN
+

Example +

Code:

u := math.RoundToEven(11.5)
+fmt.Printf("%.1f\n", u)
+
+d := math.RoundToEven(12.5)
+fmt.Printf("%.1f\n", d)
+

Output:

12.0
+12.0
+

func Signbit

func Signbit(x float64) bool

Signbit reports whether x is negative or negative zero.

+

func Sin

func Sin(x float64) float64

Sin returns the sine of the radian argument x.

+

Special cases are:

+
Sin(±0) = ±0
+Sin(±Inf) = NaN
+Sin(NaN) = NaN
+

Example +

Code:

fmt.Printf("%.2f", math.Sin(math.Pi))
+

Output:

0.00
+

func Sincos

func Sincos(x float64) (sin, cos float64)

Sincos returns Sin(x), Cos(x).

+

Special cases are:

+
Sincos(±0) = ±0, 1
+Sincos(±Inf) = NaN, NaN
+Sincos(NaN) = NaN, NaN
+

Example +

Code:

sin, cos := math.Sincos(0)
+fmt.Printf("%.2f, %.2f", sin, cos)
+

Output:

0.00, 1.00
+

func Sinh

func Sinh(x float64) float64

Sinh returns the hyperbolic sine of x.

+

Special cases are:

+
Sinh(±0) = ±0
+Sinh(±Inf) = ±Inf
+Sinh(NaN) = NaN
+

Example +

Code:

fmt.Printf("%.2f", math.Sinh(0))
+

Output:

0.00
+

func Sqrt

func Sqrt(x float64) float64

Sqrt returns the square root of x.

+

Special cases are:

+
Sqrt(+Inf) = +Inf
+Sqrt(±0) = ±0
+Sqrt(x < 0) = NaN
+Sqrt(NaN) = NaN
+

Example +

Code:

const (
+    a = 3
+    b = 4
+)
+c := math.Sqrt(a*a + b*b)
+fmt.Printf("%.1f", c)
+

Output:

5.0
+

func Tan

func Tan(x float64) float64

Tan returns the tangent of the radian argument x.

+

Special cases are:

+
Tan(±0) = ±0
+Tan(±Inf) = NaN
+Tan(NaN) = NaN
+

Example +

Code:

fmt.Printf("%.2f", math.Tan(0))
+

Output:

0.00
+

func Tanh

func Tanh(x float64) float64

Tanh returns the hyperbolic tangent of x.

+

Special cases are:

+
Tanh(±0) = ±0
+Tanh(±Inf) = ±1
+Tanh(NaN) = NaN
+

Example +

Code:

fmt.Printf("%.2f", math.Tanh(0))
+

Output:

0.00
+

func Trunc

func Trunc(x float64) float64

Trunc returns the integer value of x.

+

Special cases are:

+
Trunc(±0) = ±0
+Trunc(±Inf) = ±Inf
+Trunc(NaN) = NaN
+

Example +

Code:

fmt.Printf("%.2f\n", math.Trunc(math.Pi))
+fmt.Printf("%.2f\n", math.Trunc(-1.2345))
+

Output:

3.00
+-1.00
+

func Y0

func Y0(x float64) float64

Y0 returns the order-zero Bessel function of the second kind.

+

Special cases are:

+
Y0(+Inf) = 0
+Y0(0) = -Inf
+Y0(x < 0) = NaN
+Y0(NaN) = NaN
+

func Y1

func Y1(x float64) float64

Y1 returns the order-one Bessel function of the second kind.

+

Special cases are:

+
Y1(+Inf) = 0
+Y1(0) = -Inf
+Y1(x < 0) = NaN
+Y1(NaN) = NaN
+

func Yn

func Yn(n int, x float64) float64

Yn returns the order-n Bessel function of the second kind.

+

Special cases are:

+
Yn(n, +Inf) = 0
+Yn(n ≥ 0, 0) = -Inf
+Yn(n < 0, 0) = +Inf if n is odd, -Inf if n is even
+Yn(n, x < 0) = NaN
+Yn(n, NaN) = NaN
+

Subdirectories

Name Synopsis
..
big Package big implements arbitrary-precision arithmetic (big numbers).
bits Package bits implements bit counting and manipulation functions for the predeclared unsigned integer types.
cmplx Package cmplx provides basic constants and mathematical functions for complex numbers.
rand Package rand implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.
v2 Package rand implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/math/ +

+
diff --git a/devdocs/go/math%2Frand%2Findex.html b/devdocs/go/math%2Frand%2Findex.html new file mode 100644 index 00000000..17d714f2 --- /dev/null +++ b/devdocs/go/math%2Frand%2Findex.html @@ -0,0 +1,240 @@ +

Package rand

Overview

Package rand implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.

+

Random numbers are generated by a Source, usually wrapped in a Rand. Both types should be used by a single goroutine at a time: sharing among multiple goroutines requires some kind of synchronization.

+

Top-level functions, such as Float64 and Int, are safe for concurrent use by multiple goroutines.

+

This package's outputs might be easily predictable regardless of how it's seeded. For random numbers suitable for security-sensitive work, see the crypto/rand package.

Example +

Code:

+answers := []string{
+    "It is certain",
+    "It is decidedly so",
+    "Without a doubt",
+    "Yes definitely",
+    "You may rely on it",
+    "As I see it yes",
+    "Most likely",
+    "Outlook good",
+    "Yes",
+    "Signs point to yes",
+    "Reply hazy try again",
+    "Ask again later",
+    "Better not tell you now",
+    "Cannot predict now",
+    "Concentrate and ask again",
+    "Don't count on it",
+    "My reply is no",
+    "My sources say no",
+    "Outlook not so good",
+    "Very doubtful",
+}
+fmt.Println("Magic 8-Ball says:", answers[rand.Intn(len(answers))])
+

Example (Rand) +

This example shows the use of each of the methods on a *Rand. The use of the global functions is the same, without the receiver.

Code:

// Create and seed the generator.
+// Typically a non-fixed seed should be used, such as time.Now().UnixNano().
+// Using a fixed seed will produce the same output on every run.
+r := rand.New(rand.NewSource(99))
+
+// The tabwriter here helps us generate aligned output.
+w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
+defer w.Flush()
+show := func(name string, v1, v2, v3 any) {
+    fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3)
+}
+
+// Float32 and Float64 values are in [0, 1).
+show("Float32", r.Float32(), r.Float32(), r.Float32())
+show("Float64", r.Float64(), r.Float64(), r.Float64())
+
+// ExpFloat64 values have an average of 1 but decay exponentially.
+show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())
+
+// NormFloat64 values have an average of 0 and a standard deviation of 1.
+show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())
+
+// Int31, Int63, and Uint32 generate values of the given width.
+// The Int method (not shown) is like either Int31 or Int63
+// depending on the size of 'int'.
+show("Int31", r.Int31(), r.Int31(), r.Int31())
+show("Int63", r.Int63(), r.Int63(), r.Int63())
+show("Uint32", r.Uint32(), r.Uint32(), r.Uint32())
+
+// Intn, Int31n, and Int63n limit their output to be < n.
+// They do so more carefully than using r.Int()%n.
+show("Intn(10)", r.Intn(10), r.Intn(10), r.Intn(10))
+show("Int31n(10)", r.Int31n(10), r.Int31n(10), r.Int31n(10))
+show("Int63n(10)", r.Int63n(10), r.Int63n(10), r.Int63n(10))
+
+// Perm generates a random permutation of the numbers [0, n).
+show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
+

Output:

Float32     0.2635776           0.6358173           0.6718283
+Float64     0.628605430454327   0.4504798828572669  0.9562755949377957
+ExpFloat64  0.3362240648200941  1.4256072328483647  0.24354758816173044
+NormFloat64 0.17233959114940064 1.577014951434847   0.04259129641113857
+Int31       1501292890          1486668269          182840835
+Int63       3546343826724305832 5724354148158589552 5239846799706671610
+Uint32      2760229429          296659907           1922395059
+Intn(10)    1                   2                   5
+Int31n(10)  4                   7                   8
+Int63n(10)  7                   6                   3
+Perm        [1 4 2 3 0]         [4 2 1 3 0]         [1 2 4 0 3]
+

Index

Examples

Package
Intn
Perm
Shuffle
Shuffle (SlicesInUnison)
Package (Rand)

Package files

exp.go normal.go rand.go rng.go zipf.go

func ExpFloat64

func ExpFloat64() float64

ExpFloat64 returns an exponentially distributed float64 in the range (0, +[math.MaxFloat64]] with an exponential distribution whose rate parameter (lambda) is 1 and whose mean is 1/lambda (1) from the default Source. To produce a distribution with a different rate parameter, callers can adjust the output using:

+
sample = ExpFloat64() / desiredRateParameter
+

func Float32

func Float32() float32

Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0) from the default Source.

+

func Float64

func Float64() float64

Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0) from the default Source.

+

func Int

func Int() int

Int returns a non-negative pseudo-random int from the default Source.

+

func Int31

func Int31() int32

Int31 returns a non-negative pseudo-random 31-bit integer as an int32 from the default Source.

+

func Int31n

func Int31n(n int32) int32

Int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

+

func Int63

func Int63() int64

Int63 returns a non-negative pseudo-random 63-bit integer as an int64 from the default Source.

+

func Int63n

func Int63n(n int64) int64

Int63n returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

+

func Intn

func Intn(n int) int

Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

Example +

Code:

+fmt.Println(rand.Intn(100))
+fmt.Println(rand.Intn(100))
+fmt.Println(rand.Intn(100))
+

func NormFloat64

func NormFloat64() float64

NormFloat64 returns a normally distributed float64 in the range [-math.MaxFloat64, +[math.MaxFloat64]] with standard normal distribution (mean = 0, stddev = 1) from the default Source. To produce a different normal distribution, callers can adjust the output using:

+
sample = NormFloat64() * desiredStdDev + desiredMean
+

func Perm

func Perm(n int) []int

Perm returns, as a slice of n ints, a pseudo-random permutation of the integers in the half-open interval [0,n) from the default Source.

Example +

Code:

for _, value := range rand.Perm(3) {
+    fmt.Println(value)
+}
+
+

Output:

1
+2
+0
+

func Read 1.6

func Read(p []byte) (n int, err error)

Read generates len(p) random bytes from the default Source and writes them into p. It always returns len(p) and a nil error. Read, unlike the Rand.Read method, is safe for concurrent use.

+

Deprecated: For almost all use cases, crypto/rand.Read is more appropriate.

+

func Seed

func Seed(seed int64)

Seed uses the provided seed value to initialize the default Source to a deterministic state. Seed values that have the same remainder when divided by 2³¹-1 generate the same pseudo-random sequence. Seed, unlike the Rand.Seed method, is safe for concurrent use.

+

If Seed is not called, the generator is seeded randomly at program startup.

+

Prior to Go 1.20, the generator was seeded like Seed(1) at program startup. To force the old behavior, call Seed(1) at program startup. Alternately, set GODEBUG=randautoseed=0 in the environment before making any calls to functions in this package.

+

Deprecated: As of Go 1.20 there is no reason to call Seed with a random value. Programs that call Seed with a known value to get a specific sequence of results should use New(NewSource(seed)) to obtain a local random generator.

+

func Shuffle 1.10

func Shuffle(n int, swap func(i, j int))

Shuffle pseudo-randomizes the order of elements using the default Source. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.

Example +

Code:

+words := strings.Fields("ink runs from the corners of my mouth")
+rand.Shuffle(len(words), func(i, j int) {
+    words[i], words[j] = words[j], words[i]
+})
+fmt.Println(words)
+

Example (SlicesInUnison) +

Code:

+numbers := []byte("12345")
+letters := []byte("ABCDE")
+// Shuffle numbers, swapping corresponding entries in letters at the same time.
+rand.Shuffle(len(numbers), func(i, j int) {
+    numbers[i], numbers[j] = numbers[j], numbers[i]
+    letters[i], letters[j] = letters[j], letters[i]
+})
+for i := range numbers {
+    fmt.Printf("%c: %c\n", letters[i], numbers[i])
+}
+

func Uint32

func Uint32() uint32

Uint32 returns a pseudo-random 32-bit value as a uint32 from the default Source.

+

func Uint64 1.8

func Uint64() uint64

Uint64 returns a pseudo-random 64-bit value as a uint64 from the default Source.

+

type Rand

A Rand is a source of random numbers.

+
type Rand struct {
+    // contains filtered or unexported fields
+}
+

func New

func New(src Source) *Rand

New returns a new Rand that uses random values from src to generate other random values.

+

func (*Rand) ExpFloat64

func (r *Rand) ExpFloat64() float64

ExpFloat64 returns an exponentially distributed float64 in the range (0, +[math.MaxFloat64]] with an exponential distribution whose rate parameter (lambda) is 1 and whose mean is 1/lambda (1). To produce a distribution with a different rate parameter, callers can adjust the output using:

+
sample = ExpFloat64() / desiredRateParameter
+

func (*Rand) Float32

func (r *Rand) Float32() float32

Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0).

+

func (*Rand) Float64

func (r *Rand) Float64() float64

Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0).

+

func (*Rand) Int

func (r *Rand) Int() int

Int returns a non-negative pseudo-random int.

+

func (*Rand) Int31

func (r *Rand) Int31() int32

Int31 returns a non-negative pseudo-random 31-bit integer as an int32.

+

func (*Rand) Int31n

func (r *Rand) Int31n(n int32) int32

Int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

+

func (*Rand) Int63

func (r *Rand) Int63() int64

Int63 returns a non-negative pseudo-random 63-bit integer as an int64.

+

func (*Rand) Int63n

func (r *Rand) Int63n(n int64) int64

Int63n returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

+

func (*Rand) Intn

func (r *Rand) Intn(n int) int

Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

+

func (*Rand) NormFloat64

func (r *Rand) NormFloat64() float64

NormFloat64 returns a normally distributed float64 in the range -math.MaxFloat64 through +[math.MaxFloat64] inclusive, with standard normal distribution (mean = 0, stddev = 1). To produce a different normal distribution, callers can adjust the output using:

+
sample = NormFloat64() * desiredStdDev + desiredMean
+

func (*Rand) Perm

func (r *Rand) Perm(n int) []int

Perm returns, as a slice of n ints, a pseudo-random permutation of the integers in the half-open interval [0,n).

+

func (*Rand) Read 1.6

func (r *Rand) Read(p []byte) (n int, err error)

Read generates len(p) random bytes and writes them into p. It always returns len(p) and a nil error. Read should not be called concurrently with any other Rand method.

+

func (*Rand) Seed

func (r *Rand) Seed(seed int64)

Seed uses the provided seed value to initialize the generator to a deterministic state. Seed should not be called concurrently with any other Rand method.

+

func (*Rand) Shuffle 1.10

func (r *Rand) Shuffle(n int, swap func(i, j int))

Shuffle pseudo-randomizes the order of elements. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.

+

func (*Rand) Uint32

func (r *Rand) Uint32() uint32

Uint32 returns a pseudo-random 32-bit value as a uint32.

+

func (*Rand) Uint64 1.8

func (r *Rand) Uint64() uint64

Uint64 returns a pseudo-random 64-bit value as a uint64.

+

type Source

A Source represents a source of uniformly-distributed pseudo-random int64 values in the range [0, 1<<63).

+

A Source is not safe for concurrent use by multiple goroutines.

+
type Source interface {
+    Int63() int64
+    Seed(seed int64)
+}

func NewSource

func NewSource(seed int64) Source

NewSource returns a new pseudo-random Source seeded with the given value. Unlike the default Source used by top-level functions, this source is not safe for concurrent use by multiple goroutines. The returned Source implements Source64.

+

type Source64 1.8

A Source64 is a Source that can also generate uniformly-distributed pseudo-random uint64 values in the range [0, 1<<64) directly. If a Rand r's underlying Source s implements Source64, then r.Uint64 returns the result of one call to s.Uint64 instead of making two calls to s.Int63.

+
type Source64 interface {
+    Source
+    Uint64() uint64
+}

type Zipf

A Zipf generates Zipf distributed variates.

+
type Zipf struct {
+    // contains filtered or unexported fields
+}
+

func NewZipf

func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf

NewZipf returns a Zipf variate generator. The generator generates values k ∈ [0, imax] such that P(k) is proportional to (v + k) ** (-s). Requirements: s > 1 and v >= 1.

+

func (*Zipf) Uint64

func (z *Zipf) Uint64() uint64

Uint64 returns a value drawn from the Zipf distribution described by the Zipf object.

+

Subdirectories

Name Synopsis
..
v2 Package rand implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/math/rand/ +

+
diff --git a/devdocs/go/math%2Frand%2Fv2%2Findex.html b/devdocs/go/math%2Frand%2Fv2%2Findex.html new file mode 100644 index 00000000..79488bd9 --- /dev/null +++ b/devdocs/go/math%2Frand%2Fv2%2Findex.html @@ -0,0 +1,278 @@ +

Package rand

Overview

Package rand implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.

+

Random numbers are generated by a Source, usually wrapped in a Rand. Both types should be used by a single goroutine at a time: sharing among multiple goroutines requires some kind of synchronization.

+

Top-level functions, such as Float64 and Int, are safe for concurrent use by multiple goroutines.

+

This package's outputs might be easily predictable regardless of how it's seeded. For random numbers suitable for security-sensitive work, see the crypto/rand package.

Example +

Code:

+answers := []string{
+    "It is certain",
+    "It is decidedly so",
+    "Without a doubt",
+    "Yes definitely",
+    "You may rely on it",
+    "As I see it yes",
+    "Most likely",
+    "Outlook good",
+    "Yes",
+    "Signs point to yes",
+    "Reply hazy try again",
+    "Ask again later",
+    "Better not tell you now",
+    "Cannot predict now",
+    "Concentrate and ask again",
+    "Don't count on it",
+    "My reply is no",
+    "My sources say no",
+    "Outlook not so good",
+    "Very doubtful",
+}
+fmt.Println("Magic 8-Ball says:", answers[rand.IntN(len(answers))])
+

Example (Rand) +

This example shows the use of each of the methods on a *Rand. The use of the global functions is the same, without the receiver.

Code:

// Create and seed the generator.
+// Typically a non-fixed seed should be used, such as Uint64(), Uint64().
+// Using a fixed seed will produce the same output on every run.
+r := rand.New(rand.NewPCG(1, 2))
+
+// The tabwriter here helps us generate aligned output.
+w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
+defer w.Flush()
+show := func(name string, v1, v2, v3 any) {
+    fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3)
+}
+
+// Float32 and Float64 values are in [0, 1).
+show("Float32", r.Float32(), r.Float32(), r.Float32())
+show("Float64", r.Float64(), r.Float64(), r.Float64())
+
+// ExpFloat64 values have an average of 1 but decay exponentially.
+show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())
+
+// NormFloat64 values have an average of 0 and a standard deviation of 1.
+show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())
+
+// Int32, Int64, and Uint32 generate values of the given width.
+// The Int method (not shown) is like either Int32 or Int64
+// depending on the size of 'int'.
+show("Int32", r.Int32(), r.Int32(), r.Int32())
+show("Int64", r.Int64(), r.Int64(), r.Int64())
+show("Uint32", r.Uint32(), r.Uint32(), r.Uint32())
+
+// IntN, Int32N, and Int64N limit their output to be < n.
+// They do so more carefully than using r.Int()%n.
+show("IntN(10)", r.IntN(10), r.IntN(10), r.IntN(10))
+show("Int32N(10)", r.Int32N(10), r.Int32N(10), r.Int32N(10))
+show("Int64N(10)", r.Int64N(10), r.Int64N(10), r.Int64N(10))
+
+// Perm generates a random permutation of the numbers [0, n).
+show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
+

Output:

Float32     0.95955694          0.8076733            0.8135684
+Float64     0.4297927436037299  0.797802349388613    0.3883664855410056
+ExpFloat64  0.43463410545541104 0.5513632046504593   0.7426404617374481
+NormFloat64 -0.9303318111676635 -0.04750789419852852 0.22248301107582735
+Int32       2020777787          260808523            851126509
+Int64       5231057920893523323 4257872588489500903  158397175702351138
+Uint32      314478343           1418758728           208955345
+IntN(10)    6                   2                    0
+Int32N(10)  3                   7                    7
+Int64N(10)  8                   9                    4
+Perm        [0 3 1 4 2]         [4 1 2 0 3]          [4 3 2 0 1]
+

Index

Examples

Package
IntN
N
Perm
Shuffle
Shuffle (SlicesInUnison)
Package (Rand)

Package files

chacha8.go exp.go normal.go pcg.go rand.go zipf.go

func ExpFloat64 1.22

func ExpFloat64() float64

ExpFloat64 returns an exponentially distributed float64 in the range (0, +math.MaxFloat64] with an exponential distribution whose rate parameter (lambda) is 1 and whose mean is 1/lambda (1) from the default Source. To produce a distribution with a different rate parameter, callers can adjust the output using:

+
sample = ExpFloat64() / desiredRateParameter
+

func Float32 1.22

func Float32() float32

Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0) from the default Source.

+

func Float64 1.22

func Float64() float64

Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0) from the default Source.

+

func Int 1.22

func Int() int

Int returns a non-negative pseudo-random int from the default Source.

+

func Int32 1.22

func Int32() int32

Int32 returns a non-negative pseudo-random 31-bit integer as an int32 from the default Source.

+

func Int32N 1.22

func Int32N(n int32) int32

Int32N returns, as an int32, a pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

+

func Int64 1.22

func Int64() int64

Int64 returns a non-negative pseudo-random 63-bit integer as an int64 from the default Source.

+

func Int64N 1.22

func Int64N(n int64) int64

Int64N returns, as an int64, a pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

+

func IntN 1.22

func IntN(n int) int

IntN returns, as an int, a pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

Example +

Code:

+fmt.Println(rand.IntN(100))
+fmt.Println(rand.IntN(100))
+fmt.Println(rand.IntN(100))
+

func N

func N[Int intType](n Int) Int

N returns a pseudo-random number in the half-open interval [0,n) from the default Source. The type parameter Int can be any integer type. It panics if n <= 0.

Example +

Code:

+// Print an int64 in the half-open interval [0, 100).
+fmt.Println(rand.N(int64(100)))
+
+// Sleep for a random duration between 0 and 100 milliseconds.
+time.Sleep(rand.N(100 * time.Millisecond))
+

func NormFloat64 1.22

func NormFloat64() float64

NormFloat64 returns a normally distributed float64 in the range [-math.MaxFloat64, +math.MaxFloat64] with standard normal distribution (mean = 0, stddev = 1) from the default Source. To produce a different normal distribution, callers can adjust the output using:

+
sample = NormFloat64() * desiredStdDev + desiredMean
+

func Perm 1.22

func Perm(n int) []int

Perm returns, as a slice of n ints, a pseudo-random permutation of the integers in the half-open interval [0,n) from the default Source.

Example +

Code:

for _, value := range rand.Perm(3) {
+    fmt.Println(value)
+}
+
+

Output:

1
+2
+0
+

func Shuffle 1.22

func Shuffle(n int, swap func(i, j int))

Shuffle pseudo-randomizes the order of elements using the default Source. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.

Example +

Code:

+words := strings.Fields("ink runs from the corners of my mouth")
+rand.Shuffle(len(words), func(i, j int) {
+    words[i], words[j] = words[j], words[i]
+})
+fmt.Println(words)
+

Example (SlicesInUnison) +

Code:

+numbers := []byte("12345")
+letters := []byte("ABCDE")
+// Shuffle numbers, swapping corresponding entries in letters at the same time.
+rand.Shuffle(len(numbers), func(i, j int) {
+    numbers[i], numbers[j] = numbers[j], numbers[i]
+    letters[i], letters[j] = letters[j], letters[i]
+})
+for i := range numbers {
+    fmt.Printf("%c: %c\n", letters[i], numbers[i])
+}
+

func Uint32 1.22

func Uint32() uint32

Uint32 returns a pseudo-random 32-bit value as a uint32 from the default Source.

+

func Uint32N 1.22

func Uint32N(n uint32) uint32

Uint32N returns, as a uint32, a pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

+

func Uint64 1.22

func Uint64() uint64

Uint64 returns a pseudo-random 64-bit value as a uint64 from the default Source.

+

func Uint64N 1.22

func Uint64N(n uint64) uint64

Uint64N returns, as a uint64, a pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

+

func UintN 1.22

func UintN(n uint) uint

UintN returns, as a uint, a pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

+

type ChaCha8 1.22

A ChaCha8 is a ChaCha8-based cryptographically strong random number generator.

+
type ChaCha8 struct {
+    // contains filtered or unexported fields
+}
+

func NewChaCha8 1.22

func NewChaCha8(seed [32]byte) *ChaCha8

NewChaCha8 returns a new ChaCha8 seeded with the given seed.

+

func (*ChaCha8) MarshalBinary 1.22

func (c *ChaCha8) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

+

func (*ChaCha8) Seed 1.22

func (c *ChaCha8) Seed(seed [32]byte)

Seed resets the ChaCha8 to behave the same way as NewChaCha8(seed).

+

func (*ChaCha8) Uint64 1.22

func (c *ChaCha8) Uint64() uint64

Uint64 returns a uniformly distributed random uint64 value.

+

func (*ChaCha8) UnmarshalBinary 1.22

func (c *ChaCha8) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

+

type PCG 1.22

A PCG is a PCG generator with 128 bits of internal state. A zero PCG is equivalent to NewPCG(0, 0).

+
type PCG struct {
+    // contains filtered or unexported fields
+}
+

func NewPCG 1.22

func NewPCG(seed1, seed2 uint64) *PCG

NewPCG returns a new PCG seeded with the given values.

+

func (*PCG) MarshalBinary 1.22

func (p *PCG) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

+

func (*PCG) Seed 1.22

func (p *PCG) Seed(seed1, seed2 uint64)

Seed resets the PCG to behave the same way as NewPCG(seed1, seed2).

+

func (*PCG) Uint64 1.22

func (p *PCG) Uint64() uint64

Uint64 return a uniformly-distributed random uint64 value.

+

func (*PCG) UnmarshalBinary 1.22

func (p *PCG) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

+

type Rand 1.22

A Rand is a source of random numbers.

+
type Rand struct {
+    // contains filtered or unexported fields
+}
+

func New 1.22

func New(src Source) *Rand

New returns a new Rand that uses random values from src to generate other random values.

+

func (*Rand) ExpFloat64 1.22

func (r *Rand) ExpFloat64() float64

ExpFloat64 returns an exponentially distributed float64 in the range (0, +math.MaxFloat64] with an exponential distribution whose rate parameter (lambda) is 1 and whose mean is 1/lambda (1). To produce a distribution with a different rate parameter, callers can adjust the output using:

+
sample = ExpFloat64() / desiredRateParameter
+

func (*Rand) Float32 1.22

func (r *Rand) Float32() float32

Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0).

+

func (*Rand) Float64 1.22

func (r *Rand) Float64() float64

Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0).

+

func (*Rand) Int 1.22

func (r *Rand) Int() int

Int returns a non-negative pseudo-random int.

+

func (*Rand) Int32 1.22

func (r *Rand) Int32() int32

Int32 returns a non-negative pseudo-random 31-bit integer as an int32.

+

func (*Rand) Int32N 1.22

func (r *Rand) Int32N(n int32) int32

Int32N returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

+

func (*Rand) Int64 1.22

func (r *Rand) Int64() int64

Int64 returns a non-negative pseudo-random 63-bit integer as an int64.

+

func (*Rand) Int64N 1.22

func (r *Rand) Int64N(n int64) int64

Int64N returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

+

func (*Rand) IntN 1.22

func (r *Rand) IntN(n int) int

IntN returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

+

func (*Rand) NormFloat64 1.22

func (r *Rand) NormFloat64() float64

NormFloat64 returns a normally distributed float64 in the range -math.MaxFloat64 through +math.MaxFloat64 inclusive, with standard normal distribution (mean = 0, stddev = 1). To produce a different normal distribution, callers can adjust the output using:

+
sample = NormFloat64() * desiredStdDev + desiredMean
+

func (*Rand) Perm 1.22

func (r *Rand) Perm(n int) []int

Perm returns, as a slice of n ints, a pseudo-random permutation of the integers in the half-open interval [0,n).

+

func (*Rand) Shuffle 1.22

func (r *Rand) Shuffle(n int, swap func(i, j int))

Shuffle pseudo-randomizes the order of elements. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.

+

func (*Rand) Uint32 1.22

func (r *Rand) Uint32() uint32

Uint32 returns a pseudo-random 32-bit value as a uint32.

+

func (*Rand) Uint32N 1.22

func (r *Rand) Uint32N(n uint32) uint32

Uint32N returns, as a uint32, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n == 0.

+

func (*Rand) Uint64 1.22

func (r *Rand) Uint64() uint64

Uint64 returns a pseudo-random 64-bit value as a uint64.

+

func (*Rand) Uint64N 1.22

func (r *Rand) Uint64N(n uint64) uint64

Uint64N returns, as a uint64, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n == 0.

+

func (*Rand) UintN 1.22

func (r *Rand) UintN(n uint) uint

UintN returns, as a uint, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n == 0.

+

type Source 1.22

A Source is a source of uniformly-distributed pseudo-random uint64 values in the range [0, 1<<64).

+

A Source is not safe for concurrent use by multiple goroutines.

+
type Source interface {
+    Uint64() uint64
+}

type Zipf 1.22

A Zipf generates Zipf distributed variates.

+
type Zipf struct {
+    // contains filtered or unexported fields
+}
+

func NewZipf 1.22

func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf

NewZipf returns a Zipf variate generator. The generator generates values k ∈ [0, imax] such that P(k) is proportional to (v + k) ** (-s). Requirements: s > 1 and v >= 1.

+

func (*Zipf) Uint64 1.22

func (z *Zipf) Uint64() uint64

Uint64 returns a value drawn from the Zipf distribution described by the Zipf object.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/math/rand/v2/ +

+
diff --git a/devdocs/go/metadata b/devdocs/go/metadata new file mode 100644 index 00000000..b93cacdd --- /dev/null +++ b/devdocs/go/metadata @@ -0,0 +1,2 @@ +(1 (name . "Go") (slug . "go") (type . "go") (links (home . "https://golang.org/") (code . "https://go.googlesource.com/go")) (release . "1.22.0") (mtime . 1707337494) (db_size . 4222945) (attribution . "© Google, Inc.
+ Licensed under the Creative Commons Attribution License 3.0.")) \ No newline at end of file diff --git a/devdocs/go/mime%2Findex.html b/devdocs/go/mime%2Findex.html new file mode 100644 index 00000000..aa865152 --- /dev/null +++ b/devdocs/go/mime%2Findex.html @@ -0,0 +1,153 @@ +

Package mime

Overview

Package mime implements parts of the MIME spec.

Index

Examples

FormatMediaType
ParseMediaType
WordDecoder.Decode
WordDecoder.DecodeHeader
WordEncoder.Encode

Package files

encodedword.go grammar.go mediatype.go type.go type_unix.go

Constants

const (
+    // BEncoding represents Base64 encoding scheme as defined by RFC 2045.
+    BEncoding = WordEncoder('b')
+    // QEncoding represents the Q-encoding scheme as defined by RFC 2047.
+    QEncoding = WordEncoder('q')
+)

Variables

ErrInvalidMediaParameter is returned by ParseMediaType if the media type value was found but there was an error parsing the optional parameters

+
var ErrInvalidMediaParameter = errors.New("mime: invalid media parameter")

func AddExtensionType

func AddExtensionType(ext, typ string) error

AddExtensionType sets the MIME type associated with the extension ext to typ. The extension should begin with a leading dot, as in ".html".

+

func ExtensionsByType 1.5

func ExtensionsByType(typ string) ([]string, error)

ExtensionsByType returns the extensions known to be associated with the MIME type typ. The returned extensions will each begin with a leading dot, as in ".html". When typ has no associated extensions, ExtensionsByType returns an nil slice.

+

func FormatMediaType

func FormatMediaType(t string, param map[string]string) string

FormatMediaType serializes mediatype t and the parameters param as a media type conforming to RFC 2045 and RFC 2616. The type and parameter names are written in lower-case. When any of the arguments result in a standard violation then FormatMediaType returns the empty string.

Example +

Code:

mediatype := "text/html"
+params := map[string]string{
+    "charset": "utf-8",
+}
+
+result := mime.FormatMediaType(mediatype, params)
+
+fmt.Println("result:", result)
+

Output:

result: text/html; charset=utf-8
+

func ParseMediaType

func ParseMediaType(v string) (mediatype string, params map[string]string, err error)

ParseMediaType parses a media type value and any optional parameters, per RFC 1521. Media types are the values in Content-Type and Content-Disposition headers (RFC 2183). On success, ParseMediaType returns the media type converted to lowercase and trimmed of white space and a non-nil map. If there is an error parsing the optional parameter, the media type will be returned along with the error ErrInvalidMediaParameter. The returned map, params, maps from the lowercase attribute to the attribute value with its case preserved.

Example +

Code:

mediatype, params, err := mime.ParseMediaType("text/html; charset=utf-8")
+if err != nil {
+    panic(err)
+}
+
+fmt.Println("type:", mediatype)
+fmt.Println("charset:", params["charset"])
+

Output:

type: text/html
+charset: utf-8
+

func TypeByExtension

func TypeByExtension(ext string) string

TypeByExtension returns the MIME type associated with the file extension ext. The extension ext should begin with a leading dot, as in ".html". When ext has no associated type, TypeByExtension returns "".

+

Extensions are looked up first case-sensitively, then case-insensitively.

+

The built-in table is small but on unix it is augmented by the local system's MIME-info database or mime.types file(s) if available under one or more of these names:

+
/usr/local/share/mime/globs2
+/usr/share/mime/globs2
+/etc/mime.types
+/etc/apache2/mime.types
+/etc/apache/mime.types
+

On Windows, MIME types are extracted from the registry.

+

Text types have the charset parameter set to "utf-8" by default.

+

type WordDecoder 1.5

A WordDecoder decodes MIME headers containing RFC 2047 encoded-words.

+
type WordDecoder struct {
+    // CharsetReader, if non-nil, defines a function to generate
+    // charset-conversion readers, converting from the provided
+    // charset into UTF-8.
+    // Charsets are always lower-case. utf-8, iso-8859-1 and us-ascii charsets
+    // are handled by default.
+    // One of the CharsetReader's result values must be non-nil.
+    CharsetReader func(charset string, input io.Reader) (io.Reader, error)
+}
+

func (*WordDecoder) Decode 1.5

func (d *WordDecoder) Decode(word string) (string, error)

Decode decodes an RFC 2047 encoded-word.

Example +

Code:

dec := new(mime.WordDecoder)
+header, err := dec.Decode("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=")
+if err != nil {
+    panic(err)
+}
+fmt.Println(header)
+
+dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
+    switch charset {
+    case "x-case":
+        // Fake character set for example.
+        // Real use would integrate with packages such
+        // as code.google.com/p/go-charset
+        content, err := io.ReadAll(input)
+        if err != nil {
+            return nil, err
+        }
+        return bytes.NewReader(bytes.ToUpper(content)), nil
+    default:
+        return nil, fmt.Errorf("unhandled charset %q", charset)
+    }
+}
+header, err = dec.Decode("=?x-case?q?hello!?=")
+if err != nil {
+    panic(err)
+}
+fmt.Println(header)
+

Output:

¡Hola, señor!
+HELLO!
+

func (*WordDecoder) DecodeHeader 1.5

func (d *WordDecoder) DecodeHeader(header string) (string, error)

DecodeHeader decodes all encoded-words of the given string. It returns an error if and only if CharsetReader of d returns an error.

Example +

Code:

dec := new(mime.WordDecoder)
+header, err := dec.DecodeHeader("=?utf-8?q?=C3=89ric?= <eric@example.org>, =?utf-8?q?Ana=C3=AFs?= <anais@example.org>")
+if err != nil {
+    panic(err)
+}
+fmt.Println(header)
+
+header, err = dec.DecodeHeader("=?utf-8?q?=C2=A1Hola,?= =?utf-8?q?_se=C3=B1or!?=")
+if err != nil {
+    panic(err)
+}
+fmt.Println(header)
+
+dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
+    switch charset {
+    case "x-case":
+        // Fake character set for example.
+        // Real use would integrate with packages such
+        // as code.google.com/p/go-charset
+        content, err := io.ReadAll(input)
+        if err != nil {
+            return nil, err
+        }
+        return bytes.NewReader(bytes.ToUpper(content)), nil
+    default:
+        return nil, fmt.Errorf("unhandled charset %q", charset)
+    }
+}
+header, err = dec.DecodeHeader("=?x-case?q?hello_?= =?x-case?q?world!?=")
+if err != nil {
+    panic(err)
+}
+fmt.Println(header)
+

Output:

Éric <eric@example.org>, Anaïs <anais@example.org>
+¡Hola, señor!
+HELLO WORLD!
+

type WordEncoder 1.5

A WordEncoder is an RFC 2047 encoded-word encoder.

+
type WordEncoder byte

func (WordEncoder) Encode 1.5

func (e WordEncoder) Encode(charset, s string) string

Encode returns the encoded-word form of s. If s is ASCII without special characters, it is returned unchanged. The provided charset is the IANA charset name of s. It is case insensitive.

Example +

Code:

fmt.Println(mime.QEncoding.Encode("utf-8", "¡Hola, señor!"))
+fmt.Println(mime.QEncoding.Encode("utf-8", "Hello!"))
+fmt.Println(mime.BEncoding.Encode("UTF-8", "¡Hola, señor!"))
+fmt.Println(mime.QEncoding.Encode("ISO-8859-1", "Caf\xE9"))
+

Output:

=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=
+Hello!
+=?UTF-8?b?wqFIb2xhLCBzZcOxb3Ih?=
+=?ISO-8859-1?q?Caf=E9?=
+

Subdirectories

Name Synopsis
..
multipart Package multipart implements MIME multipart parsing, as defined in RFC 2046.
quotedprintable Package quotedprintable implements quoted-printable encoding as specified by RFC 2045.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/mime/ +

+
diff --git a/devdocs/go/mime%2Fmultipart%2Findex.html b/devdocs/go/mime%2Fmultipart%2Findex.html new file mode 100644 index 00000000..25e5e1fe --- /dev/null +++ b/devdocs/go/mime%2Fmultipart%2Findex.html @@ -0,0 +1,151 @@ +

Package multipart

Overview

Package multipart implements MIME multipart parsing, as defined in RFC 2046.

+

The implementation is sufficient for HTTP (RFC 2388) and the multipart bodies generated by popular browsers.

+

Limits

To protect against malicious inputs, this package sets limits on the size of the MIME data it processes.

+

Reader.NextPart and Reader.NextRawPart limit the number of headers in a part to 10000 and Reader.ReadForm limits the total number of headers in all FileHeaders to 10000. These limits may be adjusted with the GODEBUG=multipartmaxheaders=<values> setting.

+

Reader.ReadForm further limits the number of parts in a form to 1000. This limit may be adjusted with the GODEBUG=multipartmaxparts=<value> setting.

+

Copyright 2023 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

Index

Examples

NewReader

Package files

formdata.go multipart.go readmimeheader.go writer.go

Variables

ErrMessageTooLarge is returned by ReadForm if the message form data is too large to be processed.

+
var ErrMessageTooLarge = errors.New("multipart: message too large")

type File

File is an interface to access the file part of a multipart message. Its contents may be either stored in memory or on disk. If stored on disk, the File's underlying concrete type will be an *os.File.

+
type File interface {
+    io.Reader
+    io.ReaderAt
+    io.Seeker
+    io.Closer
+}

type FileHeader

A FileHeader describes a file part of a multipart request.

+
type FileHeader struct {
+    Filename string
+    Header   textproto.MIMEHeader
+    Size     int64 // Go 1.9
+    // contains filtered or unexported fields
+}
+

func (*FileHeader) Open

func (fh *FileHeader) Open() (File, error)

Open opens and returns the FileHeader's associated File.

+

type Form

Form is a parsed multipart form. Its File parts are stored either in memory or on disk, and are accessible via the *FileHeader's Open method. Its Value parts are stored as strings. Both are keyed by field name.

+
type Form struct {
+    Value map[string][]string
+    File  map[string][]*FileHeader
+}
+

func (*Form) RemoveAll

func (f *Form) RemoveAll() error

RemoveAll removes any temporary files associated with a Form.

+

type Part

A Part represents a single part in a multipart body.

+
type Part struct {
+    // The headers of the body, if any, with the keys canonicalized
+    // in the same fashion that the Go http.Request headers are.
+    // For example, "foo-bar" changes case to "Foo-Bar"
+    Header textproto.MIMEHeader
+    // contains filtered or unexported fields
+}
+

func (*Part) Close

func (p *Part) Close() error

func (*Part) FileName

func (p *Part) FileName() string

FileName returns the filename parameter of the Part's Content-Disposition header. If not empty, the filename is passed through filepath.Base (which is platform dependent) before being returned.

+

func (*Part) FormName

func (p *Part) FormName() string

FormName returns the name parameter if p has a Content-Disposition of type "form-data". Otherwise it returns the empty string.

+

func (*Part) Read

func (p *Part) Read(d []byte) (n int, err error)

Read reads the body of a part, after its headers and before the next part (if any) begins.

+

type Reader

Reader is an iterator over parts in a MIME multipart body. Reader's underlying parser consumes its input as needed. Seeking isn't supported.

+
type Reader struct {
+    // contains filtered or unexported fields
+}
+

func NewReader

func NewReader(r io.Reader, boundary string) *Reader

NewReader creates a new multipart Reader reading from r using the given MIME boundary.

+

The boundary is usually obtained from the "boundary" parameter of the message's "Content-Type" header. Use mime.ParseMediaType to parse such headers.

Example +

Code:

msg := &mail.Message{
+    Header: map[string][]string{
+        "Content-Type": {"multipart/mixed; boundary=foo"},
+    },
+    Body: strings.NewReader(
+        "--foo\r\nFoo: one\r\n\r\nA section\r\n" +
+            "--foo\r\nFoo: two\r\n\r\nAnd another\r\n" +
+            "--foo--\r\n"),
+}
+mediaType, params, err := mime.ParseMediaType(msg.Header.Get("Content-Type"))
+if err != nil {
+    log.Fatal(err)
+}
+if strings.HasPrefix(mediaType, "multipart/") {
+    mr := multipart.NewReader(msg.Body, params["boundary"])
+    for {
+        p, err := mr.NextPart()
+        if err == io.EOF {
+            return
+        }
+        if err != nil {
+            log.Fatal(err)
+        }
+        slurp, err := io.ReadAll(p)
+        if err != nil {
+            log.Fatal(err)
+        }
+        fmt.Printf("Part %q: %q\n", p.Header.Get("Foo"), slurp)
+    }
+}
+
+

Output:

Part "one": "A section"
+Part "two": "And another"
+

func (*Reader) NextPart

func (r *Reader) NextPart() (*Part, error)

NextPart returns the next part in the multipart or an error. When there are no more parts, the error io.EOF is returned.

+

As a special case, if the "Content-Transfer-Encoding" header has a value of "quoted-printable", that header is instead hidden and the body is transparently decoded during Read calls.

+

func (*Reader) NextRawPart 1.14

func (r *Reader) NextRawPart() (*Part, error)

NextRawPart returns the next part in the multipart or an error. When there are no more parts, the error io.EOF is returned.

+

Unlike NextPart, it does not have special handling for "Content-Transfer-Encoding: quoted-printable".

+

func (*Reader) ReadForm

func (r *Reader) ReadForm(maxMemory int64) (*Form, error)

ReadForm parses an entire multipart message whose parts have a Content-Disposition of "form-data". It stores up to maxMemory bytes + 10MB (reserved for non-file parts) in memory. File parts which can't be stored in memory will be stored on disk in temporary files. It returns ErrMessageTooLarge if all non-file parts can't be stored in memory.

+

type Writer

A Writer generates multipart messages.

+
type Writer struct {
+    // contains filtered or unexported fields
+}
+

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter returns a new multipart Writer with a random boundary, writing to w.

+

func (*Writer) Boundary

func (w *Writer) Boundary() string

Boundary returns the Writer's boundary.

+

func (*Writer) Close

func (w *Writer) Close() error

Close finishes the multipart message and writes the trailing boundary end line to the output.

+

func (*Writer) CreateFormField

func (w *Writer) CreateFormField(fieldname string) (io.Writer, error)

CreateFormField calls CreatePart with a header using the given field name.

+

func (*Writer) CreateFormFile

func (w *Writer) CreateFormFile(fieldname, filename string) (io.Writer, error)

CreateFormFile is a convenience wrapper around CreatePart. It creates a new form-data header with the provided field name and file name.

+

func (*Writer) CreatePart

func (w *Writer) CreatePart(header textproto.MIMEHeader) (io.Writer, error)

CreatePart creates a new multipart section with the provided header. The body of the part should be written to the returned Writer. After calling CreatePart, any previous part may no longer be written to.

+

func (*Writer) FormDataContentType

func (w *Writer) FormDataContentType() string

FormDataContentType returns the Content-Type for an HTTP multipart/form-data with this Writer's Boundary.

+

func (*Writer) SetBoundary 1.1

func (w *Writer) SetBoundary(boundary string) error

SetBoundary overrides the Writer's default randomly-generated boundary separator with an explicit value.

+

SetBoundary must be called before any parts are created, may only contain certain ASCII characters, and must be non-empty and at most 70 bytes long.

+

func (*Writer) WriteField

func (w *Writer) WriteField(fieldname, value string) error

WriteField calls CreateFormField and then writes the given value.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/mime/multipart/ +

+
diff --git a/devdocs/go/mime%2Fquotedprintable%2Findex.html b/devdocs/go/mime%2Fquotedprintable%2Findex.html new file mode 100644 index 00000000..9ca17762 --- /dev/null +++ b/devdocs/go/mime%2Fquotedprintable%2Findex.html @@ -0,0 +1,55 @@ +

Package quotedprintable

Overview

Package quotedprintable implements quoted-printable encoding as specified by RFC 2045.

Index

Examples

NewReader
NewWriter

Package files

reader.go writer.go

type Reader 1.5

Reader is a quoted-printable decoder.

+
type Reader struct {
+    // contains filtered or unexported fields
+}
+

func NewReader 1.5

func NewReader(r io.Reader) *Reader

NewReader returns a quoted-printable reader, decoding from r.

Example +

Code:

for _, s := range []string{
+    `=48=65=6C=6C=6F=2C=20=47=6F=70=68=65=72=73=21`,
+    `invalid escape: <b style="font-size: 200%">hello</b>`,
+    "Hello, Gophers! This symbol will be unescaped: =3D and this will be written in =\r\none line.",
+} {
+    b, err := io.ReadAll(quotedprintable.NewReader(strings.NewReader(s)))
+    fmt.Printf("%s %v\n", b, err)
+}
+

Output:

Hello, Gophers! <nil>
+invalid escape: <b style="font-size: 200%">hello</b> <nil>
+Hello, Gophers! This symbol will be unescaped: = and this will be written in one line. <nil>
+

func (*Reader) Read 1.5

func (r *Reader) Read(p []byte) (n int, err error)

Read reads and decodes quoted-printable data from the underlying reader.

+

type Writer 1.5

A Writer is a quoted-printable writer that implements io.WriteCloser.

+
type Writer struct {
+    // Binary mode treats the writer's input as pure binary and processes end of
+    // line bytes as binary data.
+    Binary bool
+    // contains filtered or unexported fields
+}
+

func NewWriter 1.5

func NewWriter(w io.Writer) *Writer

NewWriter returns a new Writer that writes to w.

Example +

Code:

w := quotedprintable.NewWriter(os.Stdout)
+w.Write([]byte("These symbols will be escaped: = \t"))
+w.Close()
+
+

Output:

These symbols will be escaped: =3D =09
+

func (*Writer) Close 1.5

func (w *Writer) Close() error

Close closes the Writer, flushing any unwritten data to the underlying io.Writer, but does not close the underlying io.Writer.

+

func (*Writer) Write 1.5

func (w *Writer) Write(p []byte) (n int, err error)

Write encodes p using quoted-printable encoding and writes it to the underlying io.Writer. It limits line length to 76 characters. The encoded bytes are not necessarily flushed until the Writer is closed.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/mime/quotedprintable/ +

+
diff --git a/devdocs/go/net%2Fhttp%2Fcgi%2Findex.html b/devdocs/go/net%2Fhttp%2Fcgi%2Findex.html new file mode 100644 index 00000000..c401bc1c --- /dev/null +++ b/devdocs/go/net%2Fhttp%2Fcgi%2Findex.html @@ -0,0 +1,48 @@ +

Package cgi

Overview

Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.

+

Note that using CGI means starting a new process to handle each request, which is typically less efficient than using a long-running server. This package is intended primarily for compatibility with existing systems.

Index

Package files

cgi_main.go child.go host.go

func Request

func Request() (*http.Request, error)

Request returns the HTTP request as represented in the current environment. This assumes the current program is being run by a web server in a CGI environment. The returned Request's Body is populated, if applicable.

+

func RequestFromMap

func RequestFromMap(params map[string]string) (*http.Request, error)

RequestFromMap creates an http.Request from CGI variables. The returned Request's Body field is not populated.

+

func Serve

func Serve(handler http.Handler) error

Serve executes the provided Handler on the currently active CGI request, if any. If there's no current CGI environment an error is returned. The provided handler may be nil to use http.DefaultServeMux.

+

type Handler

Handler runs an executable in a subprocess with a CGI environment.

+
type Handler struct {
+    Path string // path to the CGI executable
+    Root string // root URI prefix of handler or empty for "/"
+
+    // Dir specifies the CGI executable's working directory.
+    // If Dir is empty, the base directory of Path is used.
+    // If Path has no base directory, the current working
+    // directory is used.
+    Dir string
+
+    Env        []string    // extra environment variables to set, if any, as "key=value"
+    InheritEnv []string    // environment variables to inherit from host, as "key"
+    Logger     *log.Logger // optional log for errors or nil to use log.Print
+    Args       []string    // optional arguments to pass to child process
+    Stderr     io.Writer   // optional stderr for the child process; nil means os.Stderr; added in Go 1.7
+
+    // PathLocationHandler specifies the root http Handler that
+    // should handle internal redirects when the CGI process
+    // returns a Location header value starting with a "/", as
+    // specified in RFC 3875 § 6.3.2. This will likely be
+    // http.DefaultServeMux.
+    //
+    // If nil, a CGI response with a local URI path is instead sent
+    // back to the client and not redirected internally.
+    PathLocationHandler http.Handler
+}
+

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request)
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/http/cgi/ +

+
diff --git a/devdocs/go/net%2Fhttp%2Fcookiejar%2Findex.html b/devdocs/go/net%2Fhttp%2Fcookiejar%2Findex.html new file mode 100644 index 00000000..68b22eea --- /dev/null +++ b/devdocs/go/net%2Fhttp%2Fcookiejar%2Findex.html @@ -0,0 +1,106 @@ +

Package cookiejar

Overview

Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.

Index

Examples

New

Package files

jar.go punycode.go

type Jar 1.1

Jar implements the http.CookieJar interface from the net/http package.

+
type Jar struct {
+    // contains filtered or unexported fields
+}
+

func New 1.1

func New(o *Options) (*Jar, error)

New returns a new cookie jar. A nil *Options is equivalent to a zero Options.

Example +

Code:

// Start a server to give us cookies.
+ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+    if cookie, err := r.Cookie("Flavor"); err != nil {
+        http.SetCookie(w, &http.Cookie{Name: "Flavor", Value: "Chocolate Chip"})
+    } else {
+        cookie.Value = "Oatmeal Raisin"
+        http.SetCookie(w, cookie)
+    }
+}))
+defer ts.Close()
+
+u, err := url.Parse(ts.URL)
+if err != nil {
+    log.Fatal(err)
+}
+
+// All users of cookiejar should import "golang.org/x/net/publicsuffix"
+jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
+if err != nil {
+    log.Fatal(err)
+}
+
+client := &http.Client{
+    Jar: jar,
+}
+
+if _, err = client.Get(u.String()); err != nil {
+    log.Fatal(err)
+}
+
+fmt.Println("After 1st request:")
+for _, cookie := range jar.Cookies(u) {
+    fmt.Printf("  %s: %s\n", cookie.Name, cookie.Value)
+}
+
+if _, err = client.Get(u.String()); err != nil {
+    log.Fatal(err)
+}
+
+fmt.Println("After 2nd request:")
+for _, cookie := range jar.Cookies(u) {
+    fmt.Printf("  %s: %s\n", cookie.Name, cookie.Value)
+}
+

Output:

After 1st request:
+  Flavor: Chocolate Chip
+After 2nd request:
+  Flavor: Oatmeal Raisin
+

func (*Jar) Cookies 1.1

func (j *Jar) Cookies(u *url.URL) (cookies []*http.Cookie)

Cookies implements the Cookies method of the http.CookieJar interface.

+

It returns an empty slice if the URL's scheme is not HTTP or HTTPS.

+

func (*Jar) SetCookies 1.1

func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie)

SetCookies implements the SetCookies method of the http.CookieJar interface.

+

It does nothing if the URL's scheme is not HTTP or HTTPS.

+

type Options 1.1

Options are the options for creating a new Jar.

+
type Options struct {
+    // PublicSuffixList is the public suffix list that determines whether
+    // an HTTP server can set a cookie for a domain.
+    //
+    // A nil value is valid and may be useful for testing but it is not
+    // secure: it means that the HTTP server for foo.co.uk can set a cookie
+    // for bar.co.uk.
+    PublicSuffixList PublicSuffixList
+}
+

type PublicSuffixList 1.1

PublicSuffixList provides the public suffix of a domain. For example:

+

Implementations of PublicSuffixList must be safe for concurrent use by multiple goroutines.

+

An implementation that always returns "" is valid and may be useful for testing but it is not secure: it means that the HTTP server for foo.com can set a cookie for bar.com.

+

A public suffix list implementation is in the package golang.org/x/net/publicsuffix.

+
type PublicSuffixList interface {
+    // PublicSuffix returns the public suffix of domain.
+    //
+    // TODO: specify which of the caller and callee is responsible for IP
+    // addresses, for leading and trailing dots, for case sensitivity, and
+    // for IDN/Punycode.
+    PublicSuffix(domain string) string
+
+    // String returns a description of the source of this public suffix
+    // list. The description will typically contain something like a time
+    // stamp or version number.
+    String() string
+}
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/http/cookiejar/ +

+
diff --git a/devdocs/go/net%2Fhttp%2Ffcgi%2Findex.html b/devdocs/go/net%2Fhttp%2Ffcgi%2Findex.html new file mode 100644 index 00000000..521fefbb --- /dev/null +++ b/devdocs/go/net%2Fhttp%2Ffcgi%2Findex.html @@ -0,0 +1,19 @@ +

Package fcgi

Overview

Package fcgi implements the FastCGI protocol.

+

See https://fast-cgi.github.io/ for an unofficial mirror of the original documentation.

+

Currently only the responder role is supported.

Index

Package files

child.go fcgi.go

Variables

ErrConnClosed is returned by Read when a handler attempts to read the body of a request after the connection to the web server has been closed.

+
var ErrConnClosed = errors.New("fcgi: connection to web server closed")

ErrRequestAborted is returned by Read when a handler attempts to read the body of a request that has been aborted by the web server.

+
var ErrRequestAborted = errors.New("fcgi: request aborted by web server")

func ProcessEnv 1.9

func ProcessEnv(r *http.Request) map[string]string

ProcessEnv returns FastCGI environment variables associated with the request r for which no effort was made to be included in the request itself - the data is hidden in the request's context. As an example, if REMOTE_USER is set for a request, it will not be found anywhere in r, but it will be included in ProcessEnv's response (via r's context).

+

func Serve

func Serve(l net.Listener, handler http.Handler) error

Serve accepts incoming FastCGI connections on the listener l, creating a new goroutine for each. The goroutine reads requests and then calls handler to reply to them. If l is nil, Serve accepts connections from os.Stdin. If handler is nil, http.DefaultServeMux is used.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/http/fcgi/ +

+
diff --git a/devdocs/go/net%2Fhttp%2Fhttptest%2Findex.html b/devdocs/go/net%2Fhttp%2Fhttptest%2Findex.html new file mode 100644 index 00000000..46304728 --- /dev/null +++ b/devdocs/go/net%2Fhttp%2Fhttptest%2Findex.html @@ -0,0 +1,200 @@ +

Package httptest

Overview

Package httptest provides utilities for HTTP testing.

Index

Examples

NewTLSServer
ResponseRecorder
Server
Server (HTTP2)

Package files

httptest.go recorder.go server.go

Constants

DefaultRemoteAddr is the default remote address to return in RemoteAddr if an explicit DefaultRemoteAddr isn't set on ResponseRecorder.

+
const DefaultRemoteAddr = "1.2.3.4"

func NewRequest 1.7

func NewRequest(method, target string, body io.Reader) *http.Request

NewRequest returns a new incoming server Request, suitable for passing to an http.Handler for testing.

+

The target is the RFC 7230 "request-target": it may be either a path or an absolute URL. If target is an absolute URL, the host name from the URL is used. Otherwise, "example.com" is used.

+

The TLS field is set to a non-nil dummy value if target has scheme "https".

+

The Request.Proto is always HTTP/1.1.

+

An empty method means "GET".

+

The provided body may be nil. If the body is of type *bytes.Reader, *strings.Reader, or *bytes.Buffer, the Request.ContentLength is set.

+

NewRequest panics on error for ease of use in testing, where a panic is acceptable.

+

To generate a client HTTP request instead of a server request, see the NewRequest function in the net/http package.

+

type ResponseRecorder

ResponseRecorder is an implementation of http.ResponseWriter that records its mutations for later inspection in tests.

+
type ResponseRecorder struct {
+    // Code is the HTTP response code set by WriteHeader.
+    //
+    // Note that if a Handler never calls WriteHeader or Write,
+    // this might end up being 0, rather than the implicit
+    // http.StatusOK. To get the implicit value, use the Result
+    // method.
+    Code int
+
+    // HeaderMap contains the headers explicitly set by the Handler.
+    // It is an internal detail.
+    //
+    // Deprecated: HeaderMap exists for historical compatibility
+    // and should not be used. To access the headers returned by a handler,
+    // use the Response.Header map as returned by the Result method.
+    HeaderMap http.Header
+
+    // Body is the buffer to which the Handler's Write calls are sent.
+    // If nil, the Writes are silently discarded.
+    Body *bytes.Buffer
+
+    // Flushed is whether the Handler called Flush.
+    Flushed bool
+    // contains filtered or unexported fields
+}
+

Example +

Code:

handler := func(w http.ResponseWriter, r *http.Request) {
+    io.WriteString(w, "<html><body>Hello World!</body></html>")
+}
+
+req := httptest.NewRequest("GET", "http://example.com/foo", nil)
+w := httptest.NewRecorder()
+handler(w, req)
+
+resp := w.Result()
+body, _ := io.ReadAll(resp.Body)
+
+fmt.Println(resp.StatusCode)
+fmt.Println(resp.Header.Get("Content-Type"))
+fmt.Println(string(body))
+
+

Output:

200
+text/html; charset=utf-8
+<html><body>Hello World!</body></html>
+

func NewRecorder

func NewRecorder() *ResponseRecorder

NewRecorder returns an initialized ResponseRecorder.

+

func (*ResponseRecorder) Flush

func (rw *ResponseRecorder) Flush()

Flush implements http.Flusher. To test whether Flush was called, see rw.Flushed.

+

func (*ResponseRecorder) Header

func (rw *ResponseRecorder) Header() http.Header

Header implements http.ResponseWriter. It returns the response headers to mutate within a handler. To test the headers that were written after a handler completes, use the ResponseRecorder.Result method and see the returned Response value's Header.

+

func (*ResponseRecorder) Result 1.7

func (rw *ResponseRecorder) Result() *http.Response

Result returns the response generated by the handler.

+

The returned Response will have at least its StatusCode, Header, Body, and optionally Trailer populated. More fields may be populated in the future, so callers should not DeepEqual the result in tests.

+

The Response.Header is a snapshot of the headers at the time of the first write call, or at the time of this call, if the handler never did a write.

+

The Response.Body is guaranteed to be non-nil and Body.Read call is guaranteed to not return any error other than io.EOF.

+

Result must only be called after the handler has finished running.

+

func (*ResponseRecorder) Write

func (rw *ResponseRecorder) Write(buf []byte) (int, error)

Write implements http.ResponseWriter. The data in buf is written to rw.Body, if not nil.

+

func (*ResponseRecorder) WriteHeader

func (rw *ResponseRecorder) WriteHeader(code int)

WriteHeader implements http.ResponseWriter.

+

func (*ResponseRecorder) WriteString 1.6

func (rw *ResponseRecorder) WriteString(str string) (int, error)

WriteString implements io.StringWriter. The data in str is written to rw.Body, if not nil.

+

type Server

A Server is an HTTP server listening on a system-chosen port on the local loopback interface, for use in end-to-end HTTP tests.

+
type Server struct {
+    URL      string // base URL of form http://ipaddr:port with no trailing slash
+    Listener net.Listener
+
+    // EnableHTTP2 controls whether HTTP/2 is enabled
+    // on the server. It must be set between calling
+    // NewUnstartedServer and calling Server.StartTLS.
+    EnableHTTP2 bool // Go 1.14
+
+    // TLS is the optional TLS configuration, populated with a new config
+    // after TLS is started. If set on an unstarted server before StartTLS
+    // is called, existing fields are copied into the new config.
+    TLS *tls.Config
+
+    // Config may be changed after calling NewUnstartedServer and
+    // before Start or StartTLS.
+    Config *http.Server
+    // contains filtered or unexported fields
+}
+

Example +

Code:

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+    fmt.Fprintln(w, "Hello, client")
+}))
+defer ts.Close()
+
+res, err := http.Get(ts.URL)
+if err != nil {
+    log.Fatal(err)
+}
+greeting, err := io.ReadAll(res.Body)
+res.Body.Close()
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%s", greeting)
+

Output:

Hello, client
+

Example (HTTP2) +

Code:

ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+    fmt.Fprintf(w, "Hello, %s", r.Proto)
+}))
+ts.EnableHTTP2 = true
+ts.StartTLS()
+defer ts.Close()
+
+res, err := ts.Client().Get(ts.URL)
+if err != nil {
+    log.Fatal(err)
+}
+greeting, err := io.ReadAll(res.Body)
+res.Body.Close()
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%s", greeting)
+
+

Output:

Hello, HTTP/2.0
+

func NewServer

func NewServer(handler http.Handler) *Server

NewServer starts and returns a new Server. The caller should call Close when finished, to shut it down.

+

func NewTLSServer

func NewTLSServer(handler http.Handler) *Server

NewTLSServer starts and returns a new Server using TLS. The caller should call Close when finished, to shut it down.

Example +

Code:

ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+    fmt.Fprintln(w, "Hello, client")
+}))
+defer ts.Close()
+
+client := ts.Client()
+res, err := client.Get(ts.URL)
+if err != nil {
+    log.Fatal(err)
+}
+
+greeting, err := io.ReadAll(res.Body)
+res.Body.Close()
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%s", greeting)
+

Output:

Hello, client
+

func NewUnstartedServer

func NewUnstartedServer(handler http.Handler) *Server

NewUnstartedServer returns a new Server but doesn't start it.

+

After changing its configuration, the caller should call Start or StartTLS.

+

The caller should call Close when finished, to shut it down.

+

func (*Server) Certificate 1.9

func (s *Server) Certificate() *x509.Certificate

Certificate returns the certificate used by the server, or nil if the server doesn't use TLS.

+

func (*Server) Client 1.9

func (s *Server) Client() *http.Client

Client returns an HTTP client configured for making requests to the server. It is configured to trust the server's TLS test certificate and will close its idle connections on Server.Close.

+

func (*Server) Close

func (s *Server) Close()

Close shuts down the server and blocks until all outstanding requests on this server have completed.

+

func (*Server) CloseClientConnections

func (s *Server) CloseClientConnections()

CloseClientConnections closes any open HTTP connections to the test Server.

+

func (*Server) Start

func (s *Server) Start()

Start starts a server from NewUnstartedServer.

+

func (*Server) StartTLS

func (s *Server) StartTLS()

StartTLS starts TLS on a server from NewUnstartedServer.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/http/httptest/ +

+
diff --git a/devdocs/go/net%2Fhttp%2Fhttptrace%2Findex.html b/devdocs/go/net%2Fhttp%2Fhttptrace%2Findex.html new file mode 100644 index 00000000..f81e7f0c --- /dev/null +++ b/devdocs/go/net%2Fhttp%2Fhttptrace%2Findex.html @@ -0,0 +1,167 @@ +

Package httptrace

Overview

Package httptrace provides mechanisms to trace the events within HTTP client requests.

Example +

Code:

+req, _ := http.NewRequest("GET", "http://example.com", nil)
+trace := &httptrace.ClientTrace{
+    GotConn: func(connInfo httptrace.GotConnInfo) {
+        fmt.Printf("Got Conn: %+v\n", connInfo)
+    },
+    DNSDone: func(dnsInfo httptrace.DNSDoneInfo) {
+        fmt.Printf("DNS Info: %+v\n", dnsInfo)
+    },
+}
+req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
+_, err := http.DefaultTransport.RoundTrip(req)
+if err != nil {
+    log.Fatal(err)
+}
+

Index

Examples

Package

Package files

trace.go

func WithClientTrace 1.7

func WithClientTrace(ctx context.Context, trace *ClientTrace) context.Context

WithClientTrace returns a new context based on the provided parent ctx. HTTP client requests made with the returned context will use the provided trace hooks, in addition to any previous hooks registered with ctx. Any hooks defined in the provided trace will be called first.

+

type ClientTrace 1.7

ClientTrace is a set of hooks to run at various stages of an outgoing HTTP request. Any particular hook may be nil. Functions may be called concurrently from different goroutines and some may be called after the request has completed or failed.

+

ClientTrace currently traces a single HTTP request & response during a single round trip and has no hooks that span a series of redirected requests.

+

See https://blog.golang.org/http-tracing for more.

+
type ClientTrace struct {
+    // GetConn is called before a connection is created or
+    // retrieved from an idle pool. The hostPort is the
+    // "host:port" of the target or proxy. GetConn is called even
+    // if there's already an idle cached connection available.
+    GetConn func(hostPort string)
+
+    // GotConn is called after a successful connection is
+    // obtained. There is no hook for failure to obtain a
+    // connection; instead, use the error from
+    // Transport.RoundTrip.
+    GotConn func(GotConnInfo)
+
+    // PutIdleConn is called when the connection is returned to
+    // the idle pool. If err is nil, the connection was
+    // successfully returned to the idle pool. If err is non-nil,
+    // it describes why not. PutIdleConn is not called if
+    // connection reuse is disabled via Transport.DisableKeepAlives.
+    // PutIdleConn is called before the caller's Response.Body.Close
+    // call returns.
+    // For HTTP/2, this hook is not currently used.
+    PutIdleConn func(err error)
+
+    // GotFirstResponseByte is called when the first byte of the response
+    // headers is available.
+    GotFirstResponseByte func()
+
+    // Got100Continue is called if the server replies with a "100
+    // Continue" response.
+    Got100Continue func()
+
+    // Got1xxResponse is called for each 1xx informational response header
+    // returned before the final non-1xx response. Got1xxResponse is called
+    // for "100 Continue" responses, even if Got100Continue is also defined.
+    // If it returns an error, the client request is aborted with that error value.
+    Got1xxResponse func(code int, header textproto.MIMEHeader) error // Go 1.11
+
+    // DNSStart is called when a DNS lookup begins.
+    DNSStart func(DNSStartInfo)
+
+    // DNSDone is called when a DNS lookup ends.
+    DNSDone func(DNSDoneInfo)
+
+    // ConnectStart is called when a new connection's Dial begins.
+    // If net.Dialer.DualStack (IPv6 "Happy Eyeballs") support is
+    // enabled, this may be called multiple times.
+    ConnectStart func(network, addr string)
+
+    // ConnectDone is called when a new connection's Dial
+    // completes. The provided err indicates whether the
+    // connection completed successfully.
+    // If net.Dialer.DualStack ("Happy Eyeballs") support is
+    // enabled, this may be called multiple times.
+    ConnectDone func(network, addr string, err error)
+
+    // TLSHandshakeStart is called when the TLS handshake is started. When
+    // connecting to an HTTPS site via an HTTP proxy, the handshake happens
+    // after the CONNECT request is processed by the proxy.
+    TLSHandshakeStart func() // Go 1.8
+
+    // TLSHandshakeDone is called after the TLS handshake with either the
+    // successful handshake's connection state, or a non-nil error on handshake
+    // failure.
+    TLSHandshakeDone func(tls.ConnectionState, error) // Go 1.8
+
+    // WroteHeaderField is called after the Transport has written
+    // each request header. At the time of this call the values
+    // might be buffered and not yet written to the network.
+    WroteHeaderField func(key string, value []string) // Go 1.11
+
+    // WroteHeaders is called after the Transport has written
+    // all request headers.
+    WroteHeaders func()
+
+    // Wait100Continue is called if the Request specified
+    // "Expect: 100-continue" and the Transport has written the
+    // request headers but is waiting for "100 Continue" from the
+    // server before writing the request body.
+    Wait100Continue func()
+
+    // WroteRequest is called with the result of writing the
+    // request and any body. It may be called multiple times
+    // in the case of retried requests.
+    WroteRequest func(WroteRequestInfo)
+}
+

func ContextClientTrace 1.7

func ContextClientTrace(ctx context.Context) *ClientTrace

ContextClientTrace returns the ClientTrace associated with the provided context. If none, it returns nil.

+

type DNSDoneInfo 1.7

DNSDoneInfo contains information about the results of a DNS lookup.

+
type DNSDoneInfo struct {
+    // Addrs are the IPv4 and/or IPv6 addresses found in the DNS
+    // lookup. The contents of the slice should not be mutated.
+    Addrs []net.IPAddr
+
+    // Err is any error that occurred during the DNS lookup.
+    Err error
+
+    // Coalesced is whether the Addrs were shared with another
+    // caller who was doing the same DNS lookup concurrently.
+    Coalesced bool
+}
+

type DNSStartInfo 1.7

DNSStartInfo contains information about a DNS request.

+
type DNSStartInfo struct {
+    Host string
+}
+

type GotConnInfo 1.7

GotConnInfo is the argument to the [ClientTrace.GotConn] function and contains information about the obtained connection.

+
type GotConnInfo struct {
+    // Conn is the connection that was obtained. It is owned by
+    // the http.Transport and should not be read, written or
+    // closed by users of ClientTrace.
+    Conn net.Conn
+
+    // Reused is whether this connection has been previously
+    // used for another HTTP request.
+    Reused bool
+
+    // WasIdle is whether this connection was obtained from an
+    // idle pool.
+    WasIdle bool
+
+    // IdleTime reports how long the connection was previously
+    // idle, if WasIdle is true.
+    IdleTime time.Duration
+}
+

type WroteRequestInfo 1.7

WroteRequestInfo contains information provided to the WroteRequest hook.

+
type WroteRequestInfo struct {
+    // Err is any error encountered while writing the Request.
+    Err error
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/http/httptrace/ +

+
diff --git a/devdocs/go/net%2Fhttp%2Fhttputil%2Findex.html b/devdocs/go/net%2Fhttp%2Fhttputil%2Findex.html new file mode 100644 index 00000000..8b319ab3 --- /dev/null +++ b/devdocs/go/net%2Fhttp%2Fhttputil%2Findex.html @@ -0,0 +1,341 @@ +

Package httputil

Overview

Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package.

Index

Examples

DumpRequest
DumpRequestOut
DumpResponse
ReverseProxy

Package files

dump.go httputil.go persist.go reverseproxy.go

Variables

var (
+    // Deprecated: No longer used.
+    ErrPersistEOF = &http.ProtocolError{ErrorString: "persistent connection closed"}
+
+    // Deprecated: No longer used.
+    ErrClosed = &http.ProtocolError{ErrorString: "connection closed by user"}
+
+    // Deprecated: No longer used.
+    ErrPipeline = &http.ProtocolError{ErrorString: "pipeline error"}
+)

ErrLineTooLong is returned when reading malformed chunked data with lines that are too long.

+
var ErrLineTooLong = internal.ErrLineTooLong

func DumpRequest

func DumpRequest(req *http.Request, body bool) ([]byte, error)

DumpRequest returns the given request in its HTTP/1.x wire representation. It should only be used by servers to debug client requests. The returned representation is an approximation only; some details of the initial request are lost while parsing it into an http.Request. In particular, the order and case of header field names are lost. The order of values in multi-valued headers is kept intact. HTTP/2 requests are dumped in HTTP/1.x form, not in their original binary representations.

+

If body is true, DumpRequest also returns the body. To do so, it consumes req.Body and then replaces it with a new io.ReadCloser that yields the same bytes. If DumpRequest returns an error, the state of req is undefined.

+

The documentation for http.Request.Write details which fields of req are included in the dump.

Example +

Code:

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+    dump, err := httputil.DumpRequest(r, true)
+    if err != nil {
+        http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
+        return
+    }
+
+    fmt.Fprintf(w, "%q", dump)
+}))
+defer ts.Close()
+
+const body = "Go is a general-purpose language designed with systems programming in mind."
+req, err := http.NewRequest("POST", ts.URL, strings.NewReader(body))
+if err != nil {
+    log.Fatal(err)
+}
+req.Host = "www.example.org"
+resp, err := http.DefaultClient.Do(req)
+if err != nil {
+    log.Fatal(err)
+}
+defer resp.Body.Close()
+
+b, err := io.ReadAll(resp.Body)
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%s", b)
+
+

Output:

"POST / HTTP/1.1\r\nHost: www.example.org\r\nAccept-Encoding: gzip\r\nContent-Length: 75\r\nUser-Agent: Go-http-client/1.1\r\n\r\nGo is a general-purpose language designed with systems programming in mind."
+

func DumpRequestOut

func DumpRequestOut(req *http.Request, body bool) ([]byte, error)

DumpRequestOut is like DumpRequest but for outgoing client requests. It includes any headers that the standard http.Transport adds, such as User-Agent.

Example +

Code:

const body = "Go is a general-purpose language designed with systems programming in mind."
+req, err := http.NewRequest("PUT", "http://www.example.org", strings.NewReader(body))
+if err != nil {
+    log.Fatal(err)
+}
+
+dump, err := httputil.DumpRequestOut(req, true)
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%q", dump)
+
+

Output:

"PUT / HTTP/1.1\r\nHost: www.example.org\r\nUser-Agent: Go-http-client/1.1\r\nContent-Length: 75\r\nAccept-Encoding: gzip\r\n\r\nGo is a general-purpose language designed with systems programming in mind."
+

func DumpResponse

func DumpResponse(resp *http.Response, body bool) ([]byte, error)

DumpResponse is like DumpRequest but dumps a response.

Example +

Code:

const body = "Go is a general-purpose language designed with systems programming in mind."
+ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+    w.Header().Set("Date", "Wed, 19 Jul 1972 19:00:00 GMT")
+    fmt.Fprintln(w, body)
+}))
+defer ts.Close()
+
+resp, err := http.Get(ts.URL)
+if err != nil {
+    log.Fatal(err)
+}
+defer resp.Body.Close()
+
+dump, err := httputil.DumpResponse(resp, true)
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%q", dump)
+
+

Output:

"HTTP/1.1 200 OK\r\nContent-Length: 76\r\nContent-Type: text/plain; charset=utf-8\r\nDate: Wed, 19 Jul 1972 19:00:00 GMT\r\n\r\nGo is a general-purpose language designed with systems programming in mind.\n"
+

func NewChunkedReader

func NewChunkedReader(r io.Reader) io.Reader

NewChunkedReader returns a new chunkedReader that translates the data read from r out of HTTP "chunked" format before returning it. The chunkedReader returns io.EOF when the final 0-length chunk is read.

+

NewChunkedReader is not needed by normal applications. The http package automatically decodes chunking when reading response bodies.

+

func NewChunkedWriter

func NewChunkedWriter(w io.Writer) io.WriteCloser

NewChunkedWriter returns a new chunkedWriter that translates writes into HTTP "chunked" format before writing them to w. Closing the returned chunkedWriter sends the final 0-length chunk that marks the end of the stream but does not send the final CRLF that appears after trailers; trailers and the last CRLF must be written separately.

+

NewChunkedWriter is not needed by normal applications. The http package adds chunking automatically if handlers don't set a Content-Length header. Using NewChunkedWriter inside a handler would result in double chunking or chunking with a Content-Length length, both of which are wrong.

+

type BufferPool 1.6

A BufferPool is an interface for getting and returning temporary byte slices for use by io.CopyBuffer.

+
type BufferPool interface {
+    Get() []byte
+    Put([]byte)
+}

type ClientConn

ClientConn is an artifact of Go's early HTTP implementation. It is low-level, old, and unused by Go's current HTTP stack. We should have deleted it before Go 1.

+

Deprecated: Use Client or Transport in package net/http instead.

+
type ClientConn struct {
+    // contains filtered or unexported fields
+}
+

func NewClientConn

func NewClientConn(c net.Conn, r *bufio.Reader) *ClientConn

NewClientConn is an artifact of Go's early HTTP implementation. It is low-level, old, and unused by Go's current HTTP stack. We should have deleted it before Go 1.

+

Deprecated: Use the Client or Transport in package net/http instead.

+

func NewProxyClientConn

func NewProxyClientConn(c net.Conn, r *bufio.Reader) *ClientConn

NewProxyClientConn is an artifact of Go's early HTTP implementation. It is low-level, old, and unused by Go's current HTTP stack. We should have deleted it before Go 1.

+

Deprecated: Use the Client or Transport in package net/http instead.

+

func (*ClientConn) Close

func (cc *ClientConn) Close() error

Close calls ClientConn.Hijack and then also closes the underlying connection.

+

func (*ClientConn) Do

func (cc *ClientConn) Do(req *http.Request) (*http.Response, error)

Do is convenience method that writes a request and reads a response.

+

func (*ClientConn) Hijack

func (cc *ClientConn) Hijack() (c net.Conn, r *bufio.Reader)

Hijack detaches the ClientConn and returns the underlying connection as well as the read-side bufio which may have some left over data. Hijack may be called before the user or Read have signaled the end of the keep-alive logic. The user should not call Hijack while ClientConn.Read or ClientConn.Write is in progress.

+

func (*ClientConn) Pending

func (cc *ClientConn) Pending() int

Pending returns the number of unanswered requests that have been sent on the connection.

+

func (*ClientConn) Read

func (cc *ClientConn) Read(req *http.Request) (resp *http.Response, err error)

Read reads the next response from the wire. A valid response might be returned together with an ErrPersistEOF, which means that the remote requested that this be the last request serviced. Read can be called concurrently with ClientConn.Write, but not with another Read.

+

func (*ClientConn) Write

func (cc *ClientConn) Write(req *http.Request) error

Write writes a request. An ErrPersistEOF error is returned if the connection has been closed in an HTTP keep-alive sense. If req.Close equals true, the keep-alive connection is logically closed after this request and the opposing server is informed. An ErrUnexpectedEOF indicates the remote closed the underlying TCP connection, which is usually considered as graceful close.

+

type ProxyRequest 1.20

A ProxyRequest contains a request to be rewritten by a ReverseProxy.

+
type ProxyRequest struct {
+    // In is the request received by the proxy.
+    // The Rewrite function must not modify In.
+    In *http.Request
+
+    // Out is the request which will be sent by the proxy.
+    // The Rewrite function may modify or replace this request.
+    // Hop-by-hop headers are removed from this request
+    // before Rewrite is called.
+    Out *http.Request
+}
+

func (*ProxyRequest) SetURL 1.20

func (r *ProxyRequest) SetURL(target *url.URL)

SetURL routes the outbound request to the scheme, host, and base path provided in target. If the target's path is "/base" and the incoming request was for "/dir", the target request will be for "/base/dir".

+

SetURL rewrites the outbound Host header to match the target's host. To preserve the inbound request's Host header (the default behavior of NewSingleHostReverseProxy):

+
rewriteFunc := func(r *httputil.ProxyRequest) {
+	r.SetURL(url)
+	r.Out.Host = r.In.Host
+}
+

func (*ProxyRequest) SetXForwarded 1.20

func (r *ProxyRequest) SetXForwarded()

SetXForwarded sets the X-Forwarded-For, X-Forwarded-Host, and X-Forwarded-Proto headers of the outbound request.

+

If the outbound request contains an existing X-Forwarded-For header, SetXForwarded appends the client IP address to it. To append to the inbound request's X-Forwarded-For header (the default behavior of ReverseProxy when using a Director function), copy the header from the inbound request before calling SetXForwarded:

+
rewriteFunc := func(r *httputil.ProxyRequest) {
+	r.Out.Header["X-Forwarded-For"] = r.In.Header["X-Forwarded-For"]
+	r.SetXForwarded()
+}
+

type ReverseProxy

ReverseProxy is an HTTP Handler that takes an incoming request and sends it to another server, proxying the response back to the client.

+

1xx responses are forwarded to the client if the underlying transport supports ClientTrace.Got1xxResponse.

+
type ReverseProxy struct {
+    // Rewrite must be a function which modifies
+    // the request into a new request to be sent
+    // using Transport. Its response is then copied
+    // back to the original client unmodified.
+    // Rewrite must not access the provided ProxyRequest
+    // or its contents after returning.
+    //
+    // The Forwarded, X-Forwarded, X-Forwarded-Host,
+    // and X-Forwarded-Proto headers are removed from the
+    // outbound request before Rewrite is called. See also
+    // the ProxyRequest.SetXForwarded method.
+    //
+    // Unparsable query parameters are removed from the
+    // outbound request before Rewrite is called.
+    // The Rewrite function may copy the inbound URL's
+    // RawQuery to the outbound URL to preserve the original
+    // parameter string. Note that this can lead to security
+    // issues if the proxy's interpretation of query parameters
+    // does not match that of the downstream server.
+    //
+    // At most one of Rewrite or Director may be set.
+    Rewrite func(*ProxyRequest) // Go 1.20
+
+    // Director is a function which modifies
+    // the request into a new request to be sent
+    // using Transport. Its response is then copied
+    // back to the original client unmodified.
+    // Director must not access the provided Request
+    // after returning.
+    //
+    // By default, the X-Forwarded-For header is set to the
+    // value of the client IP address. If an X-Forwarded-For
+    // header already exists, the client IP is appended to the
+    // existing values. As a special case, if the header
+    // exists in the Request.Header map but has a nil value
+    // (such as when set by the Director func), the X-Forwarded-For
+    // header is not modified.
+    //
+    // To prevent IP spoofing, be sure to delete any pre-existing
+    // X-Forwarded-For header coming from the client or
+    // an untrusted proxy.
+    //
+    // Hop-by-hop headers are removed from the request after
+    // Director returns, which can remove headers added by
+    // Director. Use a Rewrite function instead to ensure
+    // modifications to the request are preserved.
+    //
+    // Unparsable query parameters are removed from the outbound
+    // request if Request.Form is set after Director returns.
+    //
+    // At most one of Rewrite or Director may be set.
+    Director func(*http.Request)
+
+    // The transport used to perform proxy requests.
+    // If nil, http.DefaultTransport is used.
+    Transport http.RoundTripper
+
+    // FlushInterval specifies the flush interval
+    // to flush to the client while copying the
+    // response body.
+    // If zero, no periodic flushing is done.
+    // A negative value means to flush immediately
+    // after each write to the client.
+    // The FlushInterval is ignored when ReverseProxy
+    // recognizes a response as a streaming response, or
+    // if its ContentLength is -1; for such responses, writes
+    // are flushed to the client immediately.
+    FlushInterval time.Duration
+
+    // ErrorLog specifies an optional logger for errors
+    // that occur when attempting to proxy the request.
+    // If nil, logging is done via the log package's standard logger.
+    ErrorLog *log.Logger // Go 1.4
+
+    // BufferPool optionally specifies a buffer pool to
+    // get byte slices for use by io.CopyBuffer when
+    // copying HTTP response bodies.
+    BufferPool BufferPool // Go 1.6
+
+    // ModifyResponse is an optional function that modifies the
+    // Response from the backend. It is called if the backend
+    // returns a response at all, with any HTTP status code.
+    // If the backend is unreachable, the optional ErrorHandler is
+    // called without any call to ModifyResponse.
+    //
+    // If ModifyResponse returns an error, ErrorHandler is called
+    // with its error value. If ErrorHandler is nil, its default
+    // implementation is used.
+    ModifyResponse func(*http.Response) error // Go 1.8
+
+    // ErrorHandler is an optional function that handles errors
+    // reaching the backend or errors from ModifyResponse.
+    //
+    // If nil, the default is to log the provided error and return
+    // a 502 Status Bad Gateway response.
+    ErrorHandler func(http.ResponseWriter, *http.Request, error) // Go 1.11
+}
+

Example +

Code:

backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+    fmt.Fprintln(w, "this call was relayed by the reverse proxy")
+}))
+defer backendServer.Close()
+
+rpURL, err := url.Parse(backendServer.URL)
+if err != nil {
+    log.Fatal(err)
+}
+frontendProxy := httptest.NewServer(&httputil.ReverseProxy{
+    Rewrite: func(r *httputil.ProxyRequest) {
+        r.SetXForwarded()
+        r.SetURL(rpURL)
+    },
+})
+defer frontendProxy.Close()
+
+resp, err := http.Get(frontendProxy.URL)
+if err != nil {
+    log.Fatal(err)
+}
+
+b, err := io.ReadAll(resp.Body)
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%s", b)
+
+

Output:

this call was relayed by the reverse proxy
+

func NewSingleHostReverseProxy

func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy

NewSingleHostReverseProxy returns a new ReverseProxy that routes URLs to the scheme, host, and base path provided in target. If the target's path is "/base" and the incoming request was for "/dir", the target request will be for /base/dir.

+

NewSingleHostReverseProxy does not rewrite the Host header.

+

To customize the ReverseProxy behavior beyond what NewSingleHostReverseProxy provides, use ReverseProxy directly with a Rewrite function. The ProxyRequest SetURL method may be used to route the outbound request. (Note that SetURL, unlike NewSingleHostReverseProxy, rewrites the Host header of the outbound request by default.)

+
proxy := &ReverseProxy{
+	Rewrite: func(r *ProxyRequest) {
+		r.SetURL(target)
+		r.Out.Host = r.In.Host // if desired
+	},
+}
+

func (*ReverseProxy) ServeHTTP

func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request)

type ServerConn

ServerConn is an artifact of Go's early HTTP implementation. It is low-level, old, and unused by Go's current HTTP stack. We should have deleted it before Go 1.

+

Deprecated: Use the Server in package net/http instead.

+
type ServerConn struct {
+    // contains filtered or unexported fields
+}
+

func NewServerConn

func NewServerConn(c net.Conn, r *bufio.Reader) *ServerConn

NewServerConn is an artifact of Go's early HTTP implementation. It is low-level, old, and unused by Go's current HTTP stack. We should have deleted it before Go 1.

+

Deprecated: Use the Server in package net/http instead.

+

func (*ServerConn) Close

func (sc *ServerConn) Close() error

Close calls ServerConn.Hijack and then also closes the underlying connection.

+

func (*ServerConn) Hijack

func (sc *ServerConn) Hijack() (net.Conn, *bufio.Reader)

Hijack detaches the ServerConn and returns the underlying connection as well as the read-side bufio which may have some left over data. Hijack may be called before Read has signaled the end of the keep-alive logic. The user should not call Hijack while ServerConn.Read or ServerConn.Write is in progress.

+

func (*ServerConn) Pending

func (sc *ServerConn) Pending() int

Pending returns the number of unanswered requests that have been received on the connection.

+

func (*ServerConn) Read

func (sc *ServerConn) Read() (*http.Request, error)

Read returns the next request on the wire. An ErrPersistEOF is returned if it is gracefully determined that there are no more requests (e.g. after the first request on an HTTP/1.0 connection, or after a Connection:close on a HTTP/1.1 connection).

+

func (*ServerConn) Write

func (sc *ServerConn) Write(req *http.Request, resp *http.Response) error

Write writes resp in response to req. To close the connection gracefully, set the Response.Close field to true. Write should be considered operational until it returns an error, regardless of any errors returned on the ServerConn.Read side.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/http/httputil/ +

+
diff --git a/devdocs/go/net%2Fhttp%2Findex.html b/devdocs/go/net%2Fhttp%2Findex.html new file mode 100644 index 00000000..c5ca9625 --- /dev/null +++ b/devdocs/go/net%2Fhttp%2Findex.html @@ -0,0 +1,2003 @@ +

Package http

Overview

Package http provides HTTP client and server implementations.

+

Get, Head, Post, and PostForm make HTTP (or HTTPS) requests:

+
resp, err := http.Get("http://example.com/")
+...
+resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
+...
+resp, err := http.PostForm("http://example.com/form",
+	url.Values{"key": {"Value"}, "id": {"123"}})
+

The caller must close the response body when finished with it:

+
resp, err := http.Get("http://example.com/")
+if err != nil {
+	// handle error
+}
+defer resp.Body.Close()
+body, err := io.ReadAll(resp.Body)
+// ...
+

Clients and Transports

For control over HTTP client headers, redirect policy, and other settings, create a Client:

+
client := &http.Client{
+	CheckRedirect: redirectPolicyFunc,
+}
+
+resp, err := client.Get("http://example.com")
+// ...
+
+req, err := http.NewRequest("GET", "http://example.com", nil)
+// ...
+req.Header.Add("If-None-Match", `W/"wyzzy"`)
+resp, err := client.Do(req)
+// ...
+

For control over proxies, TLS configuration, keep-alives, compression, and other settings, create a Transport:

+
tr := &http.Transport{
+	MaxIdleConns:       10,
+	IdleConnTimeout:    30 * time.Second,
+	DisableCompression: true,
+}
+client := &http.Client{Transport: tr}
+resp, err := client.Get("https://example.com")
+

Clients and Transports are safe for concurrent use by multiple goroutines and for efficiency should only be created once and re-used.

+

Servers

ListenAndServe starts an HTTP server with a given address and handler. The handler is usually nil, which means to use DefaultServeMux. Handle and HandleFunc add handlers to DefaultServeMux:

+
http.Handle("/foo", fooHandler)
+
+http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
+	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
+})
+
+log.Fatal(http.ListenAndServe(":8080", nil))
+

More control over the server's behavior is available by creating a custom Server:

+
s := &http.Server{
+	Addr:           ":8080",
+	Handler:        myHandler,
+	ReadTimeout:    10 * time.Second,
+	WriteTimeout:   10 * time.Second,
+	MaxHeaderBytes: 1 << 20,
+}
+log.Fatal(s.ListenAndServe())
+

HTTP/2

Starting with Go 1.6, the http package has transparent support for the HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 can do so by setting [Transport.TLSNextProto] (for clients) or [Server.TLSNextProto] (for servers) to a non-nil, empty map. Alternatively, the following GODEBUG settings are currently supported:

+
GODEBUG=http2client=0  # disable HTTP/2 client support
+GODEBUG=http2server=0  # disable HTTP/2 server support
+GODEBUG=http2debug=1   # enable verbose HTTP/2 debug logs
+GODEBUG=http2debug=2   # ... even more verbose, with frame dumps
+

Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug

+

The http package's Transport and Server both automatically enable HTTP/2 support for simple configurations. To enable HTTP/2 for more complex configurations, to use lower-level HTTP/2 features, or to use a newer version of Go's http2 package, import "golang.org/x/net/http2" directly and use its ConfigureTransport and/or ConfigureServer functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 package takes precedence over the net/http package's built-in HTTP/2 support.

Index

Examples

FileServer
FileServer (DotFileHiding)
FileServer (StripPrefix)
Get
Handle
HandleFunc
Hijacker
ListenAndServe
ListenAndServeTLS
NotFoundHandler
ResponseWriter (Trailers)
ServeMux.Handle
Server.Shutdown
StripPrefix

Package files

client.go clone.go cookie.go doc.go filetransport.go fs.go h2_bundle.go h2_error.go header.go http.go jar.go mapping.go method.go pattern.go request.go response.go responsecontroller.go roundtrip.go routing_index.go routing_tree.go servemux121.go server.go sniff.go socks_bundle.go status.go transfer.go transport.go transport_default_other.go

Constants

Common HTTP methods.

+

Unless otherwise noted, these are defined in RFC 7231 section 4.3.

+
const (
+    MethodGet     = "GET"
+    MethodHead    = "HEAD"
+    MethodPost    = "POST"
+    MethodPut     = "PUT"
+    MethodPatch   = "PATCH" // RFC 5789
+    MethodDelete  = "DELETE"
+    MethodConnect = "CONNECT"
+    MethodOptions = "OPTIONS"
+    MethodTrace   = "TRACE"
+)

HTTP status codes as registered with IANA. See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

+
const (
+    StatusContinue           = 100 // RFC 9110, 15.2.1
+    StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2
+    StatusProcessing         = 102 // RFC 2518, 10.1
+    StatusEarlyHints         = 103 // RFC 8297
+
+    StatusOK                   = 200 // RFC 9110, 15.3.1
+    StatusCreated              = 201 // RFC 9110, 15.3.2
+    StatusAccepted             = 202 // RFC 9110, 15.3.3
+    StatusNonAuthoritativeInfo = 203 // RFC 9110, 15.3.4
+    StatusNoContent            = 204 // RFC 9110, 15.3.5
+    StatusResetContent         = 205 // RFC 9110, 15.3.6
+    StatusPartialContent       = 206 // RFC 9110, 15.3.7
+    StatusMultiStatus          = 207 // RFC 4918, 11.1
+    StatusAlreadyReported      = 208 // RFC 5842, 7.1
+    StatusIMUsed               = 226 // RFC 3229, 10.4.1
+
+    StatusMultipleChoices  = 300 // RFC 9110, 15.4.1
+    StatusMovedPermanently = 301 // RFC 9110, 15.4.2
+    StatusFound            = 302 // RFC 9110, 15.4.3
+    StatusSeeOther         = 303 // RFC 9110, 15.4.4
+    StatusNotModified      = 304 // RFC 9110, 15.4.5
+    StatusUseProxy         = 305 // RFC 9110, 15.4.6
+
+    StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8
+    StatusPermanentRedirect = 308 // RFC 9110, 15.4.9
+
+    StatusBadRequest                   = 400 // RFC 9110, 15.5.1
+    StatusUnauthorized                 = 401 // RFC 9110, 15.5.2
+    StatusPaymentRequired              = 402 // RFC 9110, 15.5.3
+    StatusForbidden                    = 403 // RFC 9110, 15.5.4
+    StatusNotFound                     = 404 // RFC 9110, 15.5.5
+    StatusMethodNotAllowed             = 405 // RFC 9110, 15.5.6
+    StatusNotAcceptable                = 406 // RFC 9110, 15.5.7
+    StatusProxyAuthRequired            = 407 // RFC 9110, 15.5.8
+    StatusRequestTimeout               = 408 // RFC 9110, 15.5.9
+    StatusConflict                     = 409 // RFC 9110, 15.5.10
+    StatusGone                         = 410 // RFC 9110, 15.5.11
+    StatusLengthRequired               = 411 // RFC 9110, 15.5.12
+    StatusPreconditionFailed           = 412 // RFC 9110, 15.5.13
+    StatusRequestEntityTooLarge        = 413 // RFC 9110, 15.5.14
+    StatusRequestURITooLong            = 414 // RFC 9110, 15.5.15
+    StatusUnsupportedMediaType         = 415 // RFC 9110, 15.5.16
+    StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17
+    StatusExpectationFailed            = 417 // RFC 9110, 15.5.18
+    StatusTeapot                       = 418 // RFC 9110, 15.5.19 (Unused)
+    StatusMisdirectedRequest           = 421 // RFC 9110, 15.5.20
+    StatusUnprocessableEntity          = 422 // RFC 9110, 15.5.21
+    StatusLocked                       = 423 // RFC 4918, 11.3
+    StatusFailedDependency             = 424 // RFC 4918, 11.4
+    StatusTooEarly                     = 425 // RFC 8470, 5.2.
+    StatusUpgradeRequired              = 426 // RFC 9110, 15.5.22
+    StatusPreconditionRequired         = 428 // RFC 6585, 3
+    StatusTooManyRequests              = 429 // RFC 6585, 4
+    StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
+    StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3
+
+    StatusInternalServerError           = 500 // RFC 9110, 15.6.1
+    StatusNotImplemented                = 501 // RFC 9110, 15.6.2
+    StatusBadGateway                    = 502 // RFC 9110, 15.6.3
+    StatusServiceUnavailable            = 503 // RFC 9110, 15.6.4
+    StatusGatewayTimeout                = 504 // RFC 9110, 15.6.5
+    StatusHTTPVersionNotSupported       = 505 // RFC 9110, 15.6.6
+    StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
+    StatusInsufficientStorage           = 507 // RFC 4918, 11.5
+    StatusLoopDetected                  = 508 // RFC 5842, 7.2
+    StatusNotExtended                   = 510 // RFC 2774, 7
+    StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
+)

DefaultMaxHeaderBytes is the maximum permitted size of the headers in an HTTP request. This can be overridden by setting [Server.MaxHeaderBytes].

+
const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
+

DefaultMaxIdleConnsPerHost is the default value of Transport's MaxIdleConnsPerHost.

+
const DefaultMaxIdleConnsPerHost = 2

TimeFormat is the time format to use when generating times in HTTP headers. It is like time.RFC1123 but hard-codes GMT as the time zone. The time being formatted must be in UTC for Format to generate the correct format.

+

For parsing this time format, see ParseTime.

+
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

TrailerPrefix is a magic prefix for [ResponseWriter.Header] map keys that, if present, signals that the map entry is actually for the response trailers, and not the response headers. The prefix is stripped after the ServeHTTP call finishes and the values are sent in the trailers.

+

This mechanism is intended only for trailers that are not known prior to the headers being written. If the set of trailers is fixed or known before the header is written, the normal Go trailers mechanism is preferred:

+
https://pkg.go.dev/net/http#ResponseWriter
+https://pkg.go.dev/net/http#example-ResponseWriter-Trailers
+
const TrailerPrefix = "Trailer:"

Variables

var (
+    // ErrNotSupported indicates that a feature is not supported.
+    //
+    // It is returned by ResponseController methods to indicate that
+    // the handler does not support the method, and by the Push method
+    // of Pusher implementations to indicate that HTTP/2 Push support
+    // is not available.
+    ErrNotSupported = &ProtocolError{"feature not supported"}
+
+    // Deprecated: ErrUnexpectedTrailer is no longer returned by
+    // anything in the net/http package. Callers should not
+    // compare errors against this variable.
+    ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"}
+
+    // ErrMissingBoundary is returned by Request.MultipartReader when the
+    // request's Content-Type does not include a "boundary" parameter.
+    ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"}
+
+    // ErrNotMultipart is returned by Request.MultipartReader when the
+    // request's Content-Type is not multipart/form-data.
+    ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"}
+
+    // Deprecated: ErrHeaderTooLong is no longer returned by
+    // anything in the net/http package. Callers should not
+    // compare errors against this variable.
+    ErrHeaderTooLong = &ProtocolError{"header too long"}
+
+    // Deprecated: ErrShortBody is no longer returned by
+    // anything in the net/http package. Callers should not
+    // compare errors against this variable.
+    ErrShortBody = &ProtocolError{"entity body too short"}
+
+    // Deprecated: ErrMissingContentLength is no longer returned by
+    // anything in the net/http package. Callers should not
+    // compare errors against this variable.
+    ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"}
+)

Errors used by the HTTP server.

+
var (
+    // ErrBodyNotAllowed is returned by ResponseWriter.Write calls
+    // when the HTTP method or response code does not permit a
+    // body.
+    ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
+
+    // ErrHijacked is returned by ResponseWriter.Write calls when
+    // the underlying connection has been hijacked using the
+    // Hijacker interface. A zero-byte write on a hijacked
+    // connection will return ErrHijacked without any other side
+    // effects.
+    ErrHijacked = errors.New("http: connection has been hijacked")
+
+    // ErrContentLength is returned by ResponseWriter.Write calls
+    // when a Handler set a Content-Length response header with a
+    // declared size and then attempted to write more bytes than
+    // declared.
+    ErrContentLength = errors.New("http: wrote more than the declared Content-Length")
+
+    // Deprecated: ErrWriteAfterFlush is no longer returned by
+    // anything in the net/http package. Callers should not
+    // compare errors against this variable.
+    ErrWriteAfterFlush = errors.New("unused")
+)
var (
+    // ServerContextKey is a context key. It can be used in HTTP
+    // handlers with Context.Value to access the server that
+    // started the handler. The associated value will be of
+    // type *Server.
+    ServerContextKey = &contextKey{"http-server"}
+
+    // LocalAddrContextKey is a context key. It can be used in
+    // HTTP handlers with Context.Value to access the local
+    // address the connection arrived on.
+    // The associated value will be of type net.Addr.
+    LocalAddrContextKey = &contextKey{"local-addr"}
+)

DefaultClient is the default Client and is used by Get, Head, and Post.

+
var DefaultClient = &Client{}

DefaultServeMux is the default ServeMux used by Serve.

+
var DefaultServeMux = &defaultServeMux

ErrAbortHandler is a sentinel panic value to abort a handler. While any panic from ServeHTTP aborts the response to the client, panicking with ErrAbortHandler also suppresses logging of a stack trace to the server's error log.

+
var ErrAbortHandler = errors.New("net/http: abort Handler")

ErrBodyReadAfterClose is returned when reading a Request or Response Body after the body has been closed. This typically happens when the body is read after an HTTP Handler calls WriteHeader or Write on its ResponseWriter.

+
var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")

ErrHandlerTimeout is returned on ResponseWriter Write calls in handlers which have timed out.

+
var ErrHandlerTimeout = errors.New("http: Handler timeout")

ErrLineTooLong is returned when reading request or response bodies with malformed chunked encoding.

+
var ErrLineTooLong = internal.ErrLineTooLong

ErrMissingFile is returned by FormFile when the provided file field name is either not present in the request or not a file field.

+
var ErrMissingFile = errors.New("http: no such file")

ErrNoCookie is returned by Request's Cookie method when a cookie is not found.

+
var ErrNoCookie = errors.New("http: named cookie not present")

ErrNoLocation is returned by the Response.Location method when no Location header is present.

+
var ErrNoLocation = errors.New("http: no Location header in response")

ErrSchemeMismatch is returned when a server returns an HTTP response to an HTTPS client.

+
var ErrSchemeMismatch = errors.New("http: server gave HTTP response to HTTPS client")

ErrServerClosed is returned by the Server.Serve, ServeTLS, ListenAndServe, and ListenAndServeTLS methods after a call to Server.Shutdown or Server.Close.

+
var ErrServerClosed = errors.New("http: Server closed")

ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol.

+
var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")

ErrUseLastResponse can be returned by Client.CheckRedirect hooks to control how redirects are processed. If returned, the next request is not sent and the most recent response is returned with its body unclosed.

+
var ErrUseLastResponse = errors.New("net/http: use last response")

NoBody is an io.ReadCloser with no bytes. Read always returns EOF and Close always returns nil. It can be used in an outgoing client request to explicitly signal that a request has zero bytes. An alternative, however, is to simply set [Request.Body] to nil.

+
var NoBody = noBody{}

func CanonicalHeaderKey

func CanonicalHeaderKey(s string) string

CanonicalHeaderKey returns the canonical format of the header key s. The canonicalization converts the first letter and any letter following a hyphen to upper case; the rest are converted to lowercase. For example, the canonical key for "accept-encoding" is "Accept-Encoding". If s contains a space or invalid header field bytes, it is returned without modifications.

+

func DetectContentType

func DetectContentType(data []byte) string

DetectContentType implements the algorithm described at https://mimesniff.spec.whatwg.org/ to determine the Content-Type of the given data. It considers at most the first 512 bytes of data. DetectContentType always returns a valid MIME type: if it cannot determine a more specific one, it returns "application/octet-stream".

+

func Error

func Error(w ResponseWriter, error string, code int)

Error replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be plain text.

+

func Handle

func Handle(pattern string, handler Handler)

Handle registers the handler for the given pattern in DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

Example +

Code:

package http_test
+
+import (
+    "fmt"
+    "log"
+    "net/http"
+    "sync"
+)
+
+type countHandler struct {
+    mu sync.Mutex // guards n
+    n  int
+}
+
+func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+    h.mu.Lock()
+    defer h.mu.Unlock()
+    h.n++
+    fmt.Fprintf(w, "count is %d\n", h.n)
+}
+
+func ExampleHandle() {
+    http.Handle("/count", new(countHandler))
+    log.Fatal(http.ListenAndServe(":8080", nil))
+}
+

func HandleFunc

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc registers the handler function for the given pattern in DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

Example +

Code:

+h1 := func(w http.ResponseWriter, _ *http.Request) {
+    io.WriteString(w, "Hello from a HandleFunc #1!\n")
+}
+h2 := func(w http.ResponseWriter, _ *http.Request) {
+    io.WriteString(w, "Hello from a HandleFunc #2!\n")
+}
+
+http.HandleFunc("/", h1)
+http.HandleFunc("/endpoint", h2)
+
+log.Fatal(http.ListenAndServe(":8080", nil))
+

func ListenAndServe

func ListenAndServe(addr string, handler Handler) error

ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.

+

The handler is typically nil, in which case DefaultServeMux is used.

+

ListenAndServe always returns a non-nil error.

Example +

Code:

+// Hello world, the web server
+
+helloHandler := func(w http.ResponseWriter, req *http.Request) {
+    io.WriteString(w, "Hello, world!\n")
+}
+
+http.HandleFunc("/hello", helloHandler)
+log.Fatal(http.ListenAndServe(":8080", nil))
+

func ListenAndServeTLS

func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error

ListenAndServeTLS acts identically to ListenAndServe, except that it expects HTTPS connections. Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

Example +

Code:

+http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
+    io.WriteString(w, "Hello, TLS!\n")
+})
+
+// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
+log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/")
+err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
+log.Fatal(err)
+

func MaxBytesReader

func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser

MaxBytesReader is similar to io.LimitReader but is intended for limiting the size of incoming request bodies. In contrast to io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a non-nil error of type *MaxBytesError for a Read beyond the limit, and closes the underlying reader when its Close method is called.

+

MaxBytesReader prevents clients from accidentally or maliciously sending a large request and wasting server resources. If possible, it tells the ResponseWriter to close the connection after the limit has been reached.

+

func NotFound

func NotFound(w ResponseWriter, r *Request)

NotFound replies to the request with an HTTP 404 not found error.

+

func ParseHTTPVersion

func ParseHTTPVersion(vers string) (major, minor int, ok bool)

ParseHTTPVersion parses an HTTP version string according to RFC 7230, section 2.6. "HTTP/1.0" returns (1, 0, true). Note that strings without a minor version, such as "HTTP/2", are not valid.

+

func ParseTime 1.1

func ParseTime(text string) (t time.Time, err error)

ParseTime parses a time header (such as the Date: header), trying each of the three formats allowed by HTTP/1.1: TimeFormat, time.RFC850, and time.ANSIC.

+

func ProxyFromEnvironment

func ProxyFromEnvironment(req *Request) (*url.URL, error)

ProxyFromEnvironment returns the URL of the proxy to use for a given request, as indicated by the environment variables HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions thereof). Requests use the proxy from the environment variable matching their scheme, unless excluded by NO_PROXY.

+

The environment values may be either a complete URL or a "host[:port]", in which case the "http" scheme is assumed. The schemes "http", "https", and "socks5" are supported. An error is returned if the value is a different form.

+

A nil URL and nil error are returned if no proxy is defined in the environment, or a proxy should not be used for the given request, as defined by NO_PROXY.

+

As a special case, if req.URL.Host is "localhost" (with or without a port number), then a nil URL and nil error will be returned.

+

func ProxyURL

func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)

ProxyURL returns a proxy function (for use in a Transport) that always returns the same URL.

+

func Redirect

func Redirect(w ResponseWriter, r *Request, url string, code int)

Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

+

The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.

+

If the Content-Type header has not been set, Redirect sets it to "text/html; charset=utf-8" and writes a small HTML body. Setting the Content-Type header to any value, including nil, disables that behavior.

+

func Serve

func Serve(l net.Listener, handler Handler) error

Serve accepts incoming HTTP connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.

+

The handler is typically nil, in which case DefaultServeMux is used.

+

HTTP/2 support is only enabled if the Listener returns *tls.Conn connections and they were configured with "h2" in the TLS Config.NextProtos.

+

Serve always returns a non-nil error.

+

func ServeContent

func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)

ServeContent replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests.

+

If the response's Content-Type header is not set, ServeContent first tries to deduce the type from name's file extension and, if that fails, falls back to reading the first block of the content and passing it to DetectContentType. The name is otherwise unused; in particular it can be empty and is never sent in the response.

+

If modtime is not the zero time or Unix epoch, ServeContent includes it in a Last-Modified header in the response. If the request includes an If-Modified-Since header, ServeContent uses modtime to decide whether the content needs to be sent at all.

+

The content's Seek method must work: ServeContent uses a seek to the end of the content to determine its size.

+

If the caller has set w's ETag header formatted per RFC 7232, section 2.3, ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.

+

Note that *os.File implements the io.ReadSeeker interface.

+

func ServeFile

func ServeFile(w ResponseWriter, r *Request, name string)

ServeFile replies to the request with the contents of the named file or directory.

+

If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories. If the provided name is constructed from user input, it should be sanitized before calling ServeFile.

+

As a precaution, ServeFile will reject requests where r.URL.Path contains a ".." path element; this protects against callers who might unsafely use filepath.Join on r.URL.Path without sanitizing it and then use that filepath.Join result as the name argument.

+

As another special case, ServeFile redirects any request where r.URL.Path ends in "/index.html" to the same path, without the final "index.html". To avoid such redirects either modify the path or use ServeContent.

+

Outside of those two special cases, ServeFile does not use r.URL.Path for selecting the file or directory to serve; only the file or directory provided in the name argument is used.

+

func ServeFileFS 1.22

func ServeFileFS(w ResponseWriter, r *Request, fsys fs.FS, name string)

ServeFileFS replies to the request with the contents of the named file or directory from the file system fsys.

+

If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories. If the provided name is constructed from user input, it should be sanitized before calling ServeFile.

+

As a precaution, ServeFile will reject requests where r.URL.Path contains a ".." path element; this protects against callers who might unsafely use filepath.Join on r.URL.Path without sanitizing it and then use that filepath.Join result as the name argument.

+

As another special case, ServeFile redirects any request where r.URL.Path ends in "/index.html" to the same path, without the final "index.html". To avoid such redirects either modify the path or use ServeContent.

+

Outside of those two special cases, ServeFile does not use r.URL.Path for selecting the file or directory to serve; only the file or directory provided in the name argument is used.

+

func ServeTLS 1.9

func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error

ServeTLS accepts incoming HTTPS connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.

+

The handler is typically nil, in which case DefaultServeMux is used.

+

Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

+

ServeTLS always returns a non-nil error.

+

func SetCookie

func SetCookie(w ResponseWriter, cookie *Cookie)

SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

+

func StatusText

func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

+

type Client

A Client is an HTTP client. Its zero value (DefaultClient) is a usable client that uses DefaultTransport.

+

The [Client.Transport] typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.

+

A Client is higher-level than a RoundTripper (such as Transport) and additionally handles HTTP details such as cookies and redirects.

+

When following redirects, the Client will forward all headers set on the initial Request except:

+
type Client struct {
+    // Transport specifies the mechanism by which individual
+    // HTTP requests are made.
+    // If nil, DefaultTransport is used.
+    Transport RoundTripper
+
+    // CheckRedirect specifies the policy for handling redirects.
+    // If CheckRedirect is not nil, the client calls it before
+    // following an HTTP redirect. The arguments req and via are
+    // the upcoming request and the requests made already, oldest
+    // first. If CheckRedirect returns an error, the Client's Get
+    // method returns both the previous Response (with its Body
+    // closed) and CheckRedirect's error (wrapped in a url.Error)
+    // instead of issuing the Request req.
+    // As a special case, if CheckRedirect returns ErrUseLastResponse,
+    // then the most recent response is returned with its body
+    // unclosed, along with a nil error.
+    //
+    // If CheckRedirect is nil, the Client uses its default policy,
+    // which is to stop after 10 consecutive requests.
+    CheckRedirect func(req *Request, via []*Request) error
+
+    // Jar specifies the cookie jar.
+    //
+    // The Jar is used to insert relevant cookies into every
+    // outbound Request and is updated with the cookie values
+    // of every inbound Response. The Jar is consulted for every
+    // redirect that the Client follows.
+    //
+    // If Jar is nil, cookies are only sent if they are explicitly
+    // set on the Request.
+    Jar CookieJar
+
+    // Timeout specifies a time limit for requests made by this
+    // Client. The timeout includes connection time, any
+    // redirects, and reading the response body. The timer remains
+    // running after Get, Head, Post, or Do return and will
+    // interrupt reading of the Response.Body.
+    //
+    // A Timeout of zero means no timeout.
+    //
+    // The Client cancels requests to the underlying Transport
+    // as if the Request's Context ended.
+    //
+    // For compatibility, the Client will also use the deprecated
+    // CancelRequest method on Transport if found. New
+    // RoundTripper implementations should use the Request's Context
+    // for cancellation instead of implementing CancelRequest.
+    Timeout time.Duration // Go 1.3
+}
+

func (*Client) CloseIdleConnections 1.12

func (c *Client) CloseIdleConnections()

CloseIdleConnections closes any connections on its Transport which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.

+

If [Client.Transport] does not have a Client.CloseIdleConnections method then this method does nothing.

+

func (*Client) Do

func (c *Client) Do(req *Request) (*Response, error)

Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.

+

An error is returned if caused by client policy (such as CheckRedirect), or failure to speak HTTP (such as a network connectivity problem). A non-2xx status code doesn't cause an error.

+

If the returned error is nil, the Response will contain a non-nil Body which the user is expected to close. If the Body is not both read to EOF and closed, the Client's underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection to the server for a subsequent "keep-alive" request.

+

The request Body, if non-nil, will be closed by the underlying Transport, even on errors. The Body may be closed asynchronously after Do returns.

+

On error, any Response can be ignored. A non-nil Response with a non-nil error only occurs when CheckRedirect fails, and even then the returned [Response.Body] is already closed.

+

Generally Get, Post, or PostForm will be used instead of Do.

+

If the server replies with a redirect, the Client first uses the CheckRedirect function to determine whether the redirect should be followed. If permitted, a 301, 302, or 303 redirect causes subsequent requests to use HTTP method GET (or HEAD if the original request was HEAD), with no body. A 307 or 308 redirect preserves the original HTTP method and body, provided that the [Request.GetBody] function is defined. The NewRequest function automatically sets GetBody for common standard library body types.

+

Any returned error will be of type *url.Error. The url.Error value's Timeout method will report true if the request timed out.

+

func (*Client) Get

func (c *Client) Get(url string) (resp *Response, err error)

Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect after calling the [Client.CheckRedirect] function:

+
301 (Moved Permanently)
+302 (Found)
+303 (See Other)
+307 (Temporary Redirect)
+308 (Permanent Redirect)
+

An error is returned if the [Client.CheckRedirect] function fails or if there was an HTTP protocol error. A non-2xx response doesn't cause an error. Any returned error will be of type *url.Error. The url.Error value's Timeout method will report true if the request timed out.

+

When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.

+

To make a request with custom headers, use NewRequest and Client.Do.

+

To make a request with a specified context.Context, use NewRequestWithContext and Client.Do.

+

func (*Client) Head

func (c *Client) Head(url string) (resp *Response, err error)

Head issues a HEAD to the specified URL. If the response is one of the following redirect codes, Head follows the redirect after calling the [Client.CheckRedirect] function:

+
301 (Moved Permanently)
+302 (Found)
+303 (See Other)
+307 (Temporary Redirect)
+308 (Permanent Redirect)
+

To make a request with a specified context.Context, use NewRequestWithContext and Client.Do.

+

func (*Client) Post

func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)

Post issues a POST to the specified URL.

+

Caller should close resp.Body when done reading from it.

+

If the provided body is an io.Closer, it is closed after the request.

+

To set custom headers, use NewRequest and Client.Do.

+

To make a request with a specified context.Context, use NewRequestWithContext and Client.Do.

+

See the Client.Do method documentation for details on how redirects are handled.

+

func (*Client) PostForm

func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)

PostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body.

+

The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use NewRequest and Client.Do.

+

When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.

+

See the Client.Do method documentation for details on how redirects are handled.

+

To make a request with a specified context.Context, use NewRequestWithContext and Client.Do.

+

type CloseNotifier 1.1

The CloseNotifier interface is implemented by ResponseWriters which allow detecting when the underlying connection has gone away.

+

This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready.

+

Deprecated: the CloseNotifier interface predates Go's context package. New code should use Request.Context instead.

+
type CloseNotifier interface {
+    // CloseNotify returns a channel that receives at most a
+    // single value (true) when the client connection has gone
+    // away.
+    //
+    // CloseNotify may wait to notify until Request.Body has been
+    // fully read.
+    //
+    // After the Handler has returned, there is no guarantee
+    // that the channel receives a value.
+    //
+    // If the protocol is HTTP/1.1 and CloseNotify is called while
+    // processing an idempotent request (such a GET) while
+    // HTTP/1.1 pipelining is in use, the arrival of a subsequent
+    // pipelined request may cause a value to be sent on the
+    // returned channel. In practice HTTP/1.1 pipelining is not
+    // enabled in browsers and not seen often in the wild. If this
+    // is a problem, use HTTP/2 or only use CloseNotify on methods
+    // such as POST.
+    CloseNotify() <-chan bool
+}

type ConnState 1.3

A ConnState represents the state of a client connection to a server. It's used by the optional [Server.ConnState] hook.

+
type ConnState int
const (
+    // StateNew represents a new connection that is expected to
+    // send a request immediately. Connections begin at this
+    // state and then transition to either StateActive or
+    // StateClosed.
+    StateNew ConnState = iota
+
+    // StateActive represents a connection that has read 1 or more
+    // bytes of a request. The Server.ConnState hook for
+    // StateActive fires before the request has entered a handler
+    // and doesn't fire again until the request has been
+    // handled. After the request is handled, the state
+    // transitions to StateClosed, StateHijacked, or StateIdle.
+    // For HTTP/2, StateActive fires on the transition from zero
+    // to one active request, and only transitions away once all
+    // active requests are complete. That means that ConnState
+    // cannot be used to do per-request work; ConnState only notes
+    // the overall state of the connection.
+    StateActive
+
+    // StateIdle represents a connection that has finished
+    // handling a request and is in the keep-alive state, waiting
+    // for a new request. Connections transition from StateIdle
+    // to either StateActive or StateClosed.
+    StateIdle
+
+    // StateHijacked represents a hijacked connection.
+    // This is a terminal state. It does not transition to StateClosed.
+    StateHijacked
+
+    // StateClosed represents a closed connection.
+    // This is a terminal state. Hijacked connections do not
+    // transition to StateClosed.
+    StateClosed
+)

func (ConnState) String 1.3

func (c ConnState) String() string

A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an HTTP response or the Cookie header of an HTTP request.

+

See https://tools.ietf.org/html/rfc6265 for details.

+
type Cookie struct {
+    Name  string
+    Value string
+
+    Path       string    // optional
+    Domain     string    // optional
+    Expires    time.Time // optional
+    RawExpires string    // for reading cookies only
+
+    // MaxAge=0 means no 'Max-Age' attribute specified.
+    // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
+    // MaxAge>0 means Max-Age attribute present and given in seconds
+    MaxAge   int
+    Secure   bool
+    HttpOnly bool
+    SameSite SameSite // Go 1.11
+    Raw      string
+    Unparsed []string // Raw text of unparsed attribute-value pairs
+}
+

func (*Cookie) String

func (c *Cookie) String() string

String returns the serialization of the cookie for use in a Cookie header (if only Name and Value are set) or a Set-Cookie response header (if other fields are set). If c is nil or c.Name is invalid, the empty string is returned.

+

func (*Cookie) Valid 1.18

func (c *Cookie) Valid() error

Valid reports whether the cookie is valid.

+

type CookieJar

A CookieJar manages storage and use of cookies in HTTP requests.

+

Implementations of CookieJar must be safe for concurrent use by multiple goroutines.

+

The net/http/cookiejar package provides a CookieJar implementation.

+
type CookieJar interface {
+    // SetCookies handles the receipt of the cookies in a reply for the
+    // given URL.  It may or may not choose to save the cookies, depending
+    // on the jar's policy and implementation.
+    SetCookies(u *url.URL, cookies []*Cookie)
+
+    // Cookies returns the cookies to send in a request for the given URL.
+    // It is up to the implementation to honor the standard cookie use
+    // restrictions such as in RFC 6265.
+    Cookies(u *url.URL) []*Cookie
+}

type Dir

A Dir implements FileSystem using the native file system restricted to a specific directory tree.

+

While the [FileSystem.Open] method takes '/'-separated paths, a Dir's string value is a filename on the native file system, not a URL, so it is separated by filepath.Separator, which isn't necessarily '/'.

+

Note that Dir could expose sensitive files and directories. Dir will follow symlinks pointing out of the directory tree, which can be especially dangerous if serving from a directory in which users are able to create arbitrary symlinks. Dir will also allow access to files and directories starting with a period, which could expose sensitive directories like .git or sensitive files like .htpasswd. To exclude files with a leading period, remove the files/directories from the server or create a custom FileSystem implementation.

+

An empty Dir is treated as ".".

+
type Dir string

func (Dir) Open

func (d Dir) Open(name string) (File, error)

Open implements FileSystem using os.Open, opening files for reading rooted and relative to the directory d.

+

type File

A File is returned by a FileSystem's Open method and can be served by the FileServer implementation.

+

The methods should behave the same as those on an *os.File.

+
type File interface {
+    io.Closer
+    io.Reader
+    io.Seeker
+    Readdir(count int) ([]fs.FileInfo, error)
+    Stat() (fs.FileInfo, error)
+}

type FileSystem

A FileSystem implements access to a collection of named files. The elements in a file path are separated by slash ('/', U+002F) characters, regardless of host operating system convention. See the FileServer function to convert a FileSystem to a Handler.

+

This interface predates the fs.FS interface, which can be used instead: the FS adapter function converts an fs.FS to a FileSystem.

+
type FileSystem interface {
+    Open(name string) (File, error)
+}

func FS 1.16

func FS(fsys fs.FS) FileSystem

FS converts fsys to a FileSystem implementation, for use with FileServer and NewFileTransport. The files provided by fsys must implement io.Seeker.

+

type Flusher

The Flusher interface is implemented by ResponseWriters that allow an HTTP handler to flush buffered data to the client.

+

The default HTTP/1.x and HTTP/2 ResponseWriter implementations support Flusher, but ResponseWriter wrappers may not. Handlers should always test for this ability at runtime.

+

Note that even for ResponseWriters that support Flush, if the client is connected through an HTTP proxy, the buffered data may not reach the client until the response completes.

+
type Flusher interface {
+    // Flush sends any buffered data to the client.
+    Flush()
+}

type Handler

A Handler responds to an HTTP request.

+

[Handler.ServeHTTP] should write reply headers and data to the ResponseWriter and then return. Returning signals that the request is finished; it is not valid to use the ResponseWriter or read from the [Request.Body] after or concurrently with the completion of the ServeHTTP call.

+

Depending on the HTTP client software, HTTP protocol version, and any intermediaries between the client and the Go server, it may not be possible to read from the [Request.Body] after writing to the ResponseWriter. Cautious handlers should read the [Request.Body] first, and then reply.

+

Except for reading the body, handlers should not modify the provided Request.

+

If ServeHTTP panics, the server (the caller of ServeHTTP) assumes that the effect of the panic was isolated to the active request. It recovers the panic, logs a stack trace to the server error log, and either closes the network connection or sends an HTTP/2 RST_STREAM, depending on the HTTP protocol. To abort a handler so the client sees an interrupted response but the server doesn't log an error, panic with the value ErrAbortHandler.

+
type Handler interface {
+    ServeHTTP(ResponseWriter, *Request)
+}

func AllowQuerySemicolons 1.17

func AllowQuerySemicolons(h Handler) Handler

AllowQuerySemicolons returns a handler that serves requests by converting any unescaped semicolons in the URL query to ampersands, and invoking the handler h.

+

This restores the pre-Go 1.17 behavior of splitting query parameters on both semicolons and ampersands. (See golang.org/issue/25192). Note that this behavior doesn't match that of many proxies, and the mismatch can lead to security issues.

+

AllowQuerySemicolons should be invoked before Request.ParseForm is called.

+

func FileServer

func FileServer(root FileSystem) Handler

FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.

+

As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html".

+

To use the operating system's file system implementation, use http.Dir:

+
http.Handle("/", http.FileServer(http.Dir("/tmp")))
+

To use an fs.FS implementation, use http.FileServerFS instead.

Example +

Code:

+// Simple static webserver:
+log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
+

Example (DotFileHiding) +

Code:

package http_test
+
+import (
+    "io/fs"
+    "log"
+    "net/http"
+    "strings"
+)
+
+// containsDotFile reports whether name contains a path element starting with a period.
+// The name is assumed to be a delimited by forward slashes, as guaranteed
+// by the http.FileSystem interface.
+func containsDotFile(name string) bool {
+    parts := strings.Split(name, "/")
+    for _, part := range parts {
+        if strings.HasPrefix(part, ".") {
+            return true
+        }
+    }
+    return false
+}
+
+// dotFileHidingFile is the http.File use in dotFileHidingFileSystem.
+// It is used to wrap the Readdir method of http.File so that we can
+// remove files and directories that start with a period from its output.
+type dotFileHidingFile struct {
+    http.File
+}
+
+// Readdir is a wrapper around the Readdir method of the embedded File
+// that filters out all files that start with a period in their name.
+func (f dotFileHidingFile) Readdir(n int) (fis []fs.FileInfo, err error) {
+    files, err := f.File.Readdir(n)
+    for _, file := range files { // Filters out the dot files
+        if !strings.HasPrefix(file.Name(), ".") {
+            fis = append(fis, file)
+        }
+    }
+    return
+}
+
+// dotFileHidingFileSystem is an http.FileSystem that hides
+// hidden "dot files" from being served.
+type dotFileHidingFileSystem struct {
+    http.FileSystem
+}
+
+// Open is a wrapper around the Open method of the embedded FileSystem
+// that serves a 403 permission error when name has a file or directory
+// with whose name starts with a period in its path.
+func (fsys dotFileHidingFileSystem) Open(name string) (http.File, error) {
+    if containsDotFile(name) { // If dot file, return 403 response
+        return nil, fs.ErrPermission
+    }
+
+    file, err := fsys.FileSystem.Open(name)
+    if err != nil {
+        return nil, err
+    }
+    return dotFileHidingFile{file}, err
+}
+
+func ExampleFileServer_dotFileHiding() {
+    fsys := dotFileHidingFileSystem{http.Dir(".")}
+    http.Handle("/", http.FileServer(fsys))
+    log.Fatal(http.ListenAndServe(":8080", nil))
+}
+

Example (StripPrefix) +

Code:

+// To serve a directory on disk (/tmp) under an alternate URL
+// path (/tmpfiles/), use StripPrefix to modify the request
+// URL's path before the FileServer sees it:
+http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
+

func FileServerFS 1.22

func FileServerFS(root fs.FS) Handler

FileServerFS returns a handler that serves HTTP requests with the contents of the file system fsys.

+

As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html".

+
http.Handle("/", http.FileServerFS(fsys))
+

func MaxBytesHandler 1.18

func MaxBytesHandler(h Handler, n int64) Handler

MaxBytesHandler returns a Handler that runs h with its ResponseWriter and [Request.Body] wrapped by a MaxBytesReader.

+

func NotFoundHandler

func NotFoundHandler() Handler

NotFoundHandler returns a simple request handler that replies to each request with a “404 page not found” reply.

Example +

Code:

+mux := http.NewServeMux()
+
+// Create sample handler to returns 404
+mux.Handle("/resources", http.NotFoundHandler())
+
+// Create sample handler that returns 200
+mux.Handle("/resources/people/", newPeopleHandler())
+
+log.Fatal(http.ListenAndServe(":8080", mux))
+

func RedirectHandler

func RedirectHandler(url string, code int) Handler

RedirectHandler returns a request handler that redirects each request it receives to the given url using the given status code.

+

The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.

+

func StripPrefix

func StripPrefix(prefix string, h Handler) Handler

StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path (and RawPath if set) and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error. The prefix must match exactly: if the prefix in the request contains escaped characters the reply is also an HTTP 404 not found error.

Example +

Code:

+// To serve a directory on disk (/tmp) under an alternate URL
+// path (/tmpfiles/), use StripPrefix to modify the request
+// URL's path before the FileServer sees it:
+http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
+

func TimeoutHandler

func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler

TimeoutHandler returns a Handler that runs h with the given time limit.

+

The new Handler calls h.ServeHTTP to handle each request, but if a call runs for longer than its time limit, the handler responds with a 503 Service Unavailable error and the given message in its body. (If msg is empty, a suitable default message will be sent.) After such a timeout, writes by h to its ResponseWriter will return ErrHandlerTimeout.

+

TimeoutHandler supports the Pusher interface but does not support the Hijacker or Flusher interfaces.

+

type HandlerFunc

The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

+
type HandlerFunc func(ResponseWriter, *Request)

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)

ServeHTTP calls f(w, r).

+

A Header represents the key-value pairs in an HTTP header.

+

The keys should be in canonical form, as returned by CanonicalHeaderKey.

+
type Header map[string][]string

func (Header) Add

func (h Header) Add(key, value string)

Add adds the key, value pair to the header. It appends to any existing values associated with key. The key is case insensitive; it is canonicalized by CanonicalHeaderKey.

+

func (Header) Clone 1.13

func (h Header) Clone() Header

Clone returns a copy of h or nil if h is nil.

+

func (Header) Del

func (h Header) Del(key string)

Del deletes the values associated with key. The key is case insensitive; it is canonicalized by CanonicalHeaderKey.

+

func (Header) Get

func (h Header) Get(key string) string

Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. Get assumes that all keys are stored in canonical form. To use non-canonical keys, access the map directly.

+

func (Header) Set

func (h Header) Set(key, value string)

Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey. To use non-canonical keys, assign to the map directly.

+

func (Header) Values 1.14

func (h Header) Values(key string) []string

Values returns all values associated with the given key. It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. To use non-canonical keys, access the map directly. The returned slice is not a copy.

+

func (Header) Write

func (h Header) Write(w io.Writer) error

Write writes a header in wire format.

+

func (Header) WriteSubset

func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error

WriteSubset writes a header in wire format. If exclude is not nil, keys where exclude[key] == true are not written. Keys are not canonicalized before checking the exclude map.

+

type Hijacker

The Hijacker interface is implemented by ResponseWriters that allow an HTTP handler to take over the connection.

+

The default ResponseWriter for HTTP/1.x connections supports Hijacker, but HTTP/2 connections intentionally do not. ResponseWriter wrappers may also not support Hijacker. Handlers should always test for this ability at runtime.

+
type Hijacker interface {
+    // Hijack lets the caller take over the connection.
+    // After a call to Hijack the HTTP server library
+    // will not do anything else with the connection.
+    //
+    // It becomes the caller's responsibility to manage
+    // and close the connection.
+    //
+    // The returned net.Conn may have read or write deadlines
+    // already set, depending on the configuration of the
+    // Server. It is the caller's responsibility to set
+    // or clear those deadlines as needed.
+    //
+    // The returned bufio.Reader may contain unprocessed buffered
+    // data from the client.
+    //
+    // After a call to Hijack, the original Request.Body must not
+    // be used. The original Request's Context remains valid and
+    // is not canceled until the Request's ServeHTTP method
+    // returns.
+    Hijack() (net.Conn, *bufio.ReadWriter, error)
+}

Example +

Code:

+http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
+    hj, ok := w.(http.Hijacker)
+    if !ok {
+        http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
+        return
+    }
+    conn, bufrw, err := hj.Hijack()
+    if err != nil {
+        http.Error(w, err.Error(), http.StatusInternalServerError)
+        return
+    }
+    // Don't forget to close the connection:
+    defer conn.Close()
+    bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
+    bufrw.Flush()
+    s, err := bufrw.ReadString('\n')
+    if err != nil {
+        log.Printf("error reading string: %v", err)
+        return
+    }
+    fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
+    bufrw.Flush()
+})
+

type MaxBytesError 1.19

MaxBytesError is returned by MaxBytesReader when its read limit is exceeded.

+
type MaxBytesError struct {
+    Limit int64
+}
+

func (*MaxBytesError) Error 1.19

func (e *MaxBytesError) Error() string

type ProtocolError

ProtocolError represents an HTTP protocol error.

+

Deprecated: Not all errors in the http package related to protocol errors are of type ProtocolError.

+
type ProtocolError struct {
+    ErrorString string
+}
+

func (*ProtocolError) Error

func (pe *ProtocolError) Error() string

func (*ProtocolError) Is 1.21

func (pe *ProtocolError) Is(err error) bool

Is lets http.ErrNotSupported match errors.ErrUnsupported.

+

type PushOptions 1.8

PushOptions describes options for [Pusher.Push].

+
type PushOptions struct {
+    // Method specifies the HTTP method for the promised request.
+    // If set, it must be "GET" or "HEAD". Empty means "GET".
+    Method string
+
+    // Header specifies additional promised request headers. This cannot
+    // include HTTP/2 pseudo header fields like ":path" and ":scheme",
+    // which will be added automatically.
+    Header Header
+}
+

type Pusher 1.8

Pusher is the interface implemented by ResponseWriters that support HTTP/2 server push. For more background, see https://tools.ietf.org/html/rfc7540#section-8.2.

+
type Pusher interface {
+    // Push initiates an HTTP/2 server push. This constructs a synthetic
+    // request using the given target and options, serializes that request
+    // into a PUSH_PROMISE frame, then dispatches that request using the
+    // server's request handler. If opts is nil, default options are used.
+    //
+    // The target must either be an absolute path (like "/path") or an absolute
+    // URL that contains a valid host and the same scheme as the parent request.
+    // If the target is a path, it will inherit the scheme and host of the
+    // parent request.
+    //
+    // The HTTP/2 spec disallows recursive pushes and cross-authority pushes.
+    // Push may or may not detect these invalid pushes; however, invalid
+    // pushes will be detected and canceled by conforming clients.
+    //
+    // Handlers that wish to push URL X should call Push before sending any
+    // data that may trigger a request for URL X. This avoids a race where the
+    // client issues requests for X before receiving the PUSH_PROMISE for X.
+    //
+    // Push will run in a separate goroutine making the order of arrival
+    // non-deterministic. Any required synchronization needs to be implemented
+    // by the caller.
+    //
+    // Push returns ErrNotSupported if the client has disabled push or if push
+    // is not supported on the underlying connection.
+    Push(target string, opts *PushOptions) error
+}

type Request

A Request represents an HTTP request received by a server or to be sent by a client.

+

The field semantics differ slightly between client and server usage. In addition to the notes on the fields below, see the documentation for Request.Write and RoundTripper.

+
type Request struct {
+    // Method specifies the HTTP method (GET, POST, PUT, etc.).
+    // For client requests, an empty string means GET.
+    Method string
+
+    // URL specifies either the URI being requested (for server
+    // requests) or the URL to access (for client requests).
+    //
+    // For server requests, the URL is parsed from the URI
+    // supplied on the Request-Line as stored in RequestURI.  For
+    // most requests, fields other than Path and RawQuery will be
+    // empty. (See RFC 7230, Section 5.3)
+    //
+    // For client requests, the URL's Host specifies the server to
+    // connect to, while the Request's Host field optionally
+    // specifies the Host header value to send in the HTTP
+    // request.
+    URL *url.URL
+
+    // The protocol version for incoming server requests.
+    //
+    // For client requests, these fields are ignored. The HTTP
+    // client code always uses either HTTP/1.1 or HTTP/2.
+    // See the docs on Transport for details.
+    Proto      string // "HTTP/1.0"
+    ProtoMajor int    // 1
+    ProtoMinor int    // 0
+
+    // Header contains the request header fields either received
+    // by the server or to be sent by the client.
+    //
+    // If a server received a request with header lines,
+    //
+    //	Host: example.com
+    //	accept-encoding: gzip, deflate
+    //	Accept-Language: en-us
+    //	fOO: Bar
+    //	foo: two
+    //
+    // then
+    //
+    //	Header = map[string][]string{
+    //		"Accept-Encoding": {"gzip, deflate"},
+    //		"Accept-Language": {"en-us"},
+    //		"Foo": {"Bar", "two"},
+    //	}
+    //
+    // For incoming requests, the Host header is promoted to the
+    // Request.Host field and removed from the Header map.
+    //
+    // HTTP defines that header names are case-insensitive. The
+    // request parser implements this by using CanonicalHeaderKey,
+    // making the first character and any characters following a
+    // hyphen uppercase and the rest lowercase.
+    //
+    // For client requests, certain headers such as Content-Length
+    // and Connection are automatically written when needed and
+    // values in Header may be ignored. See the documentation
+    // for the Request.Write method.
+    Header Header
+
+    // Body is the request's body.
+    //
+    // For client requests, a nil body means the request has no
+    // body, such as a GET request. The HTTP Client's Transport
+    // is responsible for calling the Close method.
+    //
+    // For server requests, the Request Body is always non-nil
+    // but will return EOF immediately when no body is present.
+    // The Server will close the request body. The ServeHTTP
+    // Handler does not need to.
+    //
+    // Body must allow Read to be called concurrently with Close.
+    // In particular, calling Close should unblock a Read waiting
+    // for input.
+    Body io.ReadCloser
+
+    // GetBody defines an optional func to return a new copy of
+    // Body. It is used for client requests when a redirect requires
+    // reading the body more than once. Use of GetBody still
+    // requires setting Body.
+    //
+    // For server requests, it is unused.
+    GetBody func() (io.ReadCloser, error) // Go 1.8
+
+    // ContentLength records the length of the associated content.
+    // The value -1 indicates that the length is unknown.
+    // Values >= 0 indicate that the given number of bytes may
+    // be read from Body.
+    //
+    // For client requests, a value of 0 with a non-nil Body is
+    // also treated as unknown.
+    ContentLength int64
+
+    // TransferEncoding lists the transfer encodings from outermost to
+    // innermost. An empty list denotes the "identity" encoding.
+    // TransferEncoding can usually be ignored; chunked encoding is
+    // automatically added and removed as necessary when sending and
+    // receiving requests.
+    TransferEncoding []string
+
+    // Close indicates whether to close the connection after
+    // replying to this request (for servers) or after sending this
+    // request and reading its response (for clients).
+    //
+    // For server requests, the HTTP server handles this automatically
+    // and this field is not needed by Handlers.
+    //
+    // For client requests, setting this field prevents re-use of
+    // TCP connections between requests to the same hosts, as if
+    // Transport.DisableKeepAlives were set.
+    Close bool
+
+    // For server requests, Host specifies the host on which the
+    // URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this
+    // is either the value of the "Host" header or the host name
+    // given in the URL itself. For HTTP/2, it is the value of the
+    // ":authority" pseudo-header field.
+    // It may be of the form "host:port". For international domain
+    // names, Host may be in Punycode or Unicode form. Use
+    // golang.org/x/net/idna to convert it to either format if
+    // needed.
+    // To prevent DNS rebinding attacks, server Handlers should
+    // validate that the Host header has a value for which the
+    // Handler considers itself authoritative. The included
+    // ServeMux supports patterns registered to particular host
+    // names and thus protects its registered Handlers.
+    //
+    // For client requests, Host optionally overrides the Host
+    // header to send. If empty, the Request.Write method uses
+    // the value of URL.Host. Host may contain an international
+    // domain name.
+    Host string
+
+    // Form contains the parsed form data, including both the URL
+    // field's query parameters and the PATCH, POST, or PUT form data.
+    // This field is only available after ParseForm is called.
+    // The HTTP client ignores Form and uses Body instead.
+    Form url.Values
+
+    // PostForm contains the parsed form data from PATCH, POST
+    // or PUT body parameters.
+    //
+    // This field is only available after ParseForm is called.
+    // The HTTP client ignores PostForm and uses Body instead.
+    PostForm url.Values // Go 1.1
+
+    // MultipartForm is the parsed multipart form, including file uploads.
+    // This field is only available after ParseMultipartForm is called.
+    // The HTTP client ignores MultipartForm and uses Body instead.
+    MultipartForm *multipart.Form
+
+    // Trailer specifies additional headers that are sent after the request
+    // body.
+    //
+    // For server requests, the Trailer map initially contains only the
+    // trailer keys, with nil values. (The client declares which trailers it
+    // will later send.)  While the handler is reading from Body, it must
+    // not reference Trailer. After reading from Body returns EOF, Trailer
+    // can be read again and will contain non-nil values, if they were sent
+    // by the client.
+    //
+    // For client requests, Trailer must be initialized to a map containing
+    // the trailer keys to later send. The values may be nil or their final
+    // values. The ContentLength must be 0 or -1, to send a chunked request.
+    // After the HTTP request is sent the map values can be updated while
+    // the request body is read. Once the body returns EOF, the caller must
+    // not mutate Trailer.
+    //
+    // Few HTTP clients, servers, or proxies support HTTP trailers.
+    Trailer Header
+
+    // RemoteAddr allows HTTP servers and other software to record
+    // the network address that sent the request, usually for
+    // logging. This field is not filled in by ReadRequest and
+    // has no defined format. The HTTP server in this package
+    // sets RemoteAddr to an "IP:port" address before invoking a
+    // handler.
+    // This field is ignored by the HTTP client.
+    RemoteAddr string
+
+    // RequestURI is the unmodified request-target of the
+    // Request-Line (RFC 7230, Section 3.1.1) as sent by the client
+    // to a server. Usually the URL field should be used instead.
+    // It is an error to set this field in an HTTP client request.
+    RequestURI string
+
+    // TLS allows HTTP servers and other software to record
+    // information about the TLS connection on which the request
+    // was received. This field is not filled in by ReadRequest.
+    // The HTTP server in this package sets the field for
+    // TLS-enabled connections before invoking a handler;
+    // otherwise it leaves the field nil.
+    // This field is ignored by the HTTP client.
+    TLS *tls.ConnectionState
+
+    // Cancel is an optional channel whose closure indicates that the client
+    // request should be regarded as canceled. Not all implementations of
+    // RoundTripper may support Cancel.
+    //
+    // For server requests, this field is not applicable.
+    //
+    // Deprecated: Set the Request's context with NewRequestWithContext
+    // instead. If a Request's Cancel field and context are both
+    // set, it is undefined whether Cancel is respected.
+    Cancel <-chan struct{} // Go 1.5
+
+    // Response is the redirect response which caused this request
+    // to be created. This field is only populated during client
+    // redirects.
+    Response *Response // Go 1.7
+    // contains filtered or unexported fields
+}
+

func NewRequest

func NewRequest(method, url string, body io.Reader) (*Request, error)

NewRequest wraps NewRequestWithContext using context.Background.

+

func NewRequestWithContext 1.13

func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)

NewRequestWithContext returns a new Request given a method, URL, and optional body.

+

If the provided body is also an io.Closer, the returned [Request.Body] is set to body and will be closed (possibly asynchronously) by the Client methods Do, Post, and PostForm, and Transport.RoundTrip.

+

NewRequestWithContext returns a Request suitable for use with Client.Do or Transport.RoundTrip. To create a request for use with testing a Server Handler, either use the NewRequest function in the net/http/httptest package, use ReadRequest, or manually update the Request fields. For an outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body. See the Request type's documentation for the difference between inbound and outbound request fields.

+

If body is of type *bytes.Buffer, *bytes.Reader, or *strings.Reader, the returned request's ContentLength is set to its exact value (instead of -1), GetBody is populated (so 307 and 308 redirects can replay the body), and Body is set to NoBody if the ContentLength is 0.

+

func ReadRequest

func ReadRequest(b *bufio.Reader) (*Request, error)

ReadRequest reads and parses an incoming request from b.

+

ReadRequest is a low-level function and should only be used for specialized applications; most code should use the Server to read requests and handle them via the Handler interface. ReadRequest only supports HTTP/1.x requests. For HTTP/2, use golang.org/x/net/http2.

+

func (*Request) AddCookie

func (r *Request) AddCookie(c *Cookie)

AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, AddCookie does not attach more than one Cookie header field. That means all cookies, if any, are written into the same line, separated by semicolon. AddCookie only sanitizes c's name and value, and does not sanitize a Cookie header already present in the request.

+

func (*Request) BasicAuth 1.4

func (r *Request) BasicAuth() (username, password string, ok bool)

BasicAuth returns the username and password provided in the request's Authorization header, if the request uses HTTP Basic Authentication. See RFC 2617, Section 2.

+

func (*Request) Clone 1.13

func (r *Request) Clone(ctx context.Context) *Request

Clone returns a deep copy of r with its context changed to ctx. The provided ctx must be non-nil.

+

For an outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body.

+

func (*Request) Context 1.7

func (r *Request) Context() context.Context

Context returns the request's context. To change the context, use Request.Clone or Request.WithContext.

+

The returned context is always non-nil; it defaults to the background context.

+

For outgoing client requests, the context controls cancellation.

+

For incoming server requests, the context is canceled when the client's connection closes, the request is canceled (with HTTP/2), or when the ServeHTTP method returns.

+

func (*Request) Cookie

func (r *Request) Cookie(name string) (*Cookie, error)

Cookie returns the named cookie provided in the request or ErrNoCookie if not found. If multiple cookies match the given name, only one cookie will be returned.

+

func (*Request) Cookies

func (r *Request) Cookies() []*Cookie

Cookies parses and returns the HTTP cookies sent with the request.

+

func (*Request) FormFile

func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile returns the first file for the provided form key. FormFile calls Request.ParseMultipartForm and Request.ParseForm if necessary.

+

func (*Request) FormValue

func (r *Request) FormValue(key string) string

FormValue returns the first value for the named component of the query. The precedence order:

+
  1. application/x-www-form-urlencoded form body (POST, PUT, PATCH only)
  2. +
  3. query parameters (always)
  4. +
  5. multipart/form-data form body (always)
  6. +

FormValue calls Request.ParseMultipartForm and Request.ParseForm if necessary and ignores any errors returned by these functions. If key is not present, FormValue returns the empty string. To access multiple values of the same key, call ParseForm and then inspect [Request.Form] directly.

+

func (*Request) MultipartReader

func (r *Request) MultipartReader() (*multipart.Reader, error)

MultipartReader returns a MIME multipart reader if this is a multipart/form-data or a multipart/mixed POST request, else returns nil and an error. Use this function instead of Request.ParseMultipartForm to process the request body as a stream.

+

func (*Request) ParseForm

func (r *Request) ParseForm() error

ParseForm populates r.Form and r.PostForm.

+

For all requests, ParseForm parses the raw query from the URL and updates r.Form.

+

For POST, PUT, and PATCH requests, it also reads the request body, parses it as a form and puts the results into both r.PostForm and r.Form. Request body parameters take precedence over URL query string values in r.Form.

+

If the request Body's size has not already been limited by MaxBytesReader, the size is capped at 10MB.

+

For other HTTP methods, or when the Content-Type is not application/x-www-form-urlencoded, the request Body is not read, and r.PostForm is initialized to a non-nil, empty value.

+

Request.ParseMultipartForm calls ParseForm automatically. ParseForm is idempotent.

+

func (*Request) ParseMultipartForm

func (r *Request) ParseMultipartForm(maxMemory int64) error

ParseMultipartForm parses a request body as multipart/form-data. The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files. ParseMultipartForm calls Request.ParseForm if necessary. If ParseForm returns an error, ParseMultipartForm returns it but also continues parsing the request body. After one call to ParseMultipartForm, subsequent calls have no effect.

+

func (*Request) PathValue 1.22

func (r *Request) PathValue(name string) string

PathValue returns the value for the named path wildcard in the ServeMux pattern that matched the request. It returns the empty string if the request was not matched against a pattern or there is no such wildcard in the pattern.

+

func (*Request) PostFormValue 1.1

func (r *Request) PostFormValue(key string) string

PostFormValue returns the first value for the named component of the POST, PUT, or PATCH request body. URL query parameters are ignored. PostFormValue calls Request.ParseMultipartForm and Request.ParseForm if necessary and ignores any errors returned by these functions. If key is not present, PostFormValue returns the empty string.

+

func (*Request) ProtoAtLeast

func (r *Request) ProtoAtLeast(major, minor int) bool

ProtoAtLeast reports whether the HTTP protocol used in the request is at least major.minor.

+

func (*Request) Referer

func (r *Request) Referer() string

Referer returns the referring URL, if sent in the request.

+

Referer is misspelled as in the request itself, a mistake from the earliest days of HTTP. This value can also be fetched from the Header map as Header["Referer"]; the benefit of making it available as a method is that the compiler can diagnose programs that use the alternate (correct English) spelling req.Referrer() but cannot diagnose programs that use Header["Referrer"].

+

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string)

SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.

+

With HTTP Basic Authentication the provided username and password are not encrypted. It should generally only be used in an HTTPS request.

+

The username may not contain a colon. Some protocols may impose additional requirements on pre-escaping the username and password. For instance, when used with OAuth2, both arguments must be URL encoded first with url.QueryEscape.

+

func (*Request) SetPathValue 1.22

func (r *Request) SetPathValue(name, value string)

SetPathValue sets name to value, so that subsequent calls to r.PathValue(name) return value.

+

func (*Request) UserAgent

func (r *Request) UserAgent() string

UserAgent returns the client's User-Agent, if sent in the request.

+

func (*Request) WithContext 1.7

func (r *Request) WithContext(ctx context.Context) *Request

WithContext returns a shallow copy of r with its context changed to ctx. The provided ctx must be non-nil.

+

For outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body.

+

To create a new request with a context, use NewRequestWithContext. To make a deep copy of a request with a new context, use Request.Clone.

+

func (*Request) Write

func (r *Request) Write(w io.Writer) error

Write writes an HTTP/1.1 request, which is the header and body, in wire format. This method consults the following fields of the request:

+
Host
+URL
+Method (defaults to "GET")
+Header
+ContentLength
+TransferEncoding
+Body
+

If Body is present, Content-Length is <= 0 and [Request.TransferEncoding] hasn't been set to "identity", Write adds "Transfer-Encoding: chunked" to the header. Body is closed after it is sent.

+

func (*Request) WriteProxy

func (r *Request) WriteProxy(w io.Writer) error

WriteProxy is like Request.Write but writes the request in the form expected by an HTTP proxy. In particular, Request.WriteProxy writes the initial Request-URI line of the request with an absolute URI, per section 5.3 of RFC 7230, including the scheme and host. In either case, WriteProxy also writes a Host header, using either r.Host or r.URL.Host.

+

type Response

Response represents the response from an HTTP request.

+

The Client and Transport return Responses from servers once the response headers have been received. The response body is streamed on demand as the Body field is read.

+
type Response struct {
+    Status     string // e.g. "200 OK"
+    StatusCode int    // e.g. 200
+    Proto      string // e.g. "HTTP/1.0"
+    ProtoMajor int    // e.g. 1
+    ProtoMinor int    // e.g. 0
+
+    // Header maps header keys to values. If the response had multiple
+    // headers with the same key, they may be concatenated, with comma
+    // delimiters.  (RFC 7230, section 3.2.2 requires that multiple headers
+    // be semantically equivalent to a comma-delimited sequence.) When
+    // Header values are duplicated by other fields in this struct (e.g.,
+    // ContentLength, TransferEncoding, Trailer), the field values are
+    // authoritative.
+    //
+    // Keys in the map are canonicalized (see CanonicalHeaderKey).
+    Header Header
+
+    // Body represents the response body.
+    //
+    // The response body is streamed on demand as the Body field
+    // is read. If the network connection fails or the server
+    // terminates the response, Body.Read calls return an error.
+    //
+    // The http Client and Transport guarantee that Body is always
+    // non-nil, even on responses without a body or responses with
+    // a zero-length body. It is the caller's responsibility to
+    // close Body. The default HTTP client's Transport may not
+    // reuse HTTP/1.x "keep-alive" TCP connections if the Body is
+    // not read to completion and closed.
+    //
+    // The Body is automatically dechunked if the server replied
+    // with a "chunked" Transfer-Encoding.
+    //
+    // As of Go 1.12, the Body will also implement io.Writer
+    // on a successful "101 Switching Protocols" response,
+    // as used by WebSockets and HTTP/2's "h2c" mode.
+    Body io.ReadCloser
+
+    // ContentLength records the length of the associated content. The
+    // value -1 indicates that the length is unknown. Unless Request.Method
+    // is "HEAD", values >= 0 indicate that the given number of bytes may
+    // be read from Body.
+    ContentLength int64
+
+    // Contains transfer encodings from outer-most to inner-most. Value is
+    // nil, means that "identity" encoding is used.
+    TransferEncoding []string
+
+    // Close records whether the header directed that the connection be
+    // closed after reading Body. The value is advice for clients: neither
+    // ReadResponse nor Response.Write ever closes a connection.
+    Close bool
+
+    // Uncompressed reports whether the response was sent compressed but
+    // was decompressed by the http package. When true, reading from
+    // Body yields the uncompressed content instead of the compressed
+    // content actually set from the server, ContentLength is set to -1,
+    // and the "Content-Length" and "Content-Encoding" fields are deleted
+    // from the responseHeader. To get the original response from
+    // the server, set Transport.DisableCompression to true.
+    Uncompressed bool // Go 1.7
+
+    // Trailer maps trailer keys to values in the same
+    // format as Header.
+    //
+    // The Trailer initially contains only nil values, one for
+    // each key specified in the server's "Trailer" header
+    // value. Those values are not added to Header.
+    //
+    // Trailer must not be accessed concurrently with Read calls
+    // on the Body.
+    //
+    // After Body.Read has returned io.EOF, Trailer will contain
+    // any trailer values sent by the server.
+    Trailer Header
+
+    // Request is the request that was sent to obtain this Response.
+    // Request's Body is nil (having already been consumed).
+    // This is only populated for Client requests.
+    Request *Request
+
+    // TLS contains information about the TLS connection on which the
+    // response was received. It is nil for unencrypted responses.
+    // The pointer is shared between responses and should not be
+    // modified.
+    TLS *tls.ConnectionState // Go 1.3
+}
+

func Get

func Get(url string) (resp *Response, err error)

Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect, up to a maximum of 10 redirects:

+
301 (Moved Permanently)
+302 (Found)
+303 (See Other)
+307 (Temporary Redirect)
+308 (Permanent Redirect)
+

An error is returned if there were too many redirects or if there was an HTTP protocol error. A non-2xx response doesn't cause an error. Any returned error will be of type *url.Error. The url.Error value's Timeout method will report true if the request timed out.

+

When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.

+

Get is a wrapper around DefaultClient.Get.

+

To make a request with custom headers, use NewRequest and DefaultClient.Do.

+

To make a request with a specified context.Context, use NewRequestWithContext and DefaultClient.Do.

Example +

Code:

+res, err := http.Get("http://www.google.com/robots.txt")
+if err != nil {
+    log.Fatal(err)
+}
+body, err := io.ReadAll(res.Body)
+res.Body.Close()
+if res.StatusCode > 299 {
+    log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body)
+}
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%s", body)
+
func Head(url string) (resp *Response, err error)

Head issues a HEAD to the specified URL. If the response is one of the following redirect codes, Head follows the redirect, up to a maximum of 10 redirects:

+
301 (Moved Permanently)
+302 (Found)
+303 (See Other)
+307 (Temporary Redirect)
+308 (Permanent Redirect)
+

Head is a wrapper around DefaultClient.Head.

+

To make a request with a specified context.Context, use NewRequestWithContext and DefaultClient.Do.

+

func Post

func Post(url, contentType string, body io.Reader) (resp *Response, err error)

Post issues a POST to the specified URL.

+

Caller should close resp.Body when done reading from it.

+

If the provided body is an io.Closer, it is closed after the request.

+

Post is a wrapper around DefaultClient.Post.

+

To set custom headers, use NewRequest and DefaultClient.Do.

+

See the Client.Do method documentation for details on how redirects are handled.

+

To make a request with a specified context.Context, use NewRequestWithContext and DefaultClient.Do.

+

func PostForm

func PostForm(url string, data url.Values) (resp *Response, err error)

PostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body.

+

The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use NewRequest and DefaultClient.Do.

+

When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.

+

PostForm is a wrapper around DefaultClient.PostForm.

+

See the Client.Do method documentation for details on how redirects are handled.

+

To make a request with a specified context.Context, use NewRequestWithContext and DefaultClient.Do.

+

func ReadResponse

func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)

ReadResponse reads and returns an HTTP response from r. The req parameter optionally specifies the Request that corresponds to this Response. If nil, a GET request is assumed. Clients must call resp.Body.Close when finished reading resp.Body. After that call, clients can inspect resp.Trailer to find key/value pairs included in the response trailer.

+

func (*Response) Cookies

func (r *Response) Cookies() []*Cookie

Cookies parses and returns the cookies set in the Set-Cookie headers.

+

func (*Response) Location

func (r *Response) Location() (*url.URL, error)

Location returns the URL of the response's "Location" header, if present. Relative redirects are resolved relative to [Response.Request]. ErrNoLocation is returned if no Location header is present.

+

func (*Response) ProtoAtLeast

func (r *Response) ProtoAtLeast(major, minor int) bool

ProtoAtLeast reports whether the HTTP protocol used in the response is at least major.minor.

+

func (*Response) Write

func (r *Response) Write(w io.Writer) error

Write writes r to w in the HTTP/1.x server response format, including the status line, headers, body, and optional trailer.

+

This method consults the following fields of the response r:

+
StatusCode
+ProtoMajor
+ProtoMinor
+Request.Method
+TransferEncoding
+Trailer
+Body
+ContentLength
+Header, values for non-canonical keys will have unpredictable behavior
+

The Response Body is closed after it is sent.

+

type ResponseController 1.20

A ResponseController is used by an HTTP handler to control the response.

+

A ResponseController may not be used after the [Handler.ServeHTTP] method has returned.

+
type ResponseController struct {
+    // contains filtered or unexported fields
+}
+

func NewResponseController 1.20

func NewResponseController(rw ResponseWriter) *ResponseController

NewResponseController creates a ResponseController for a request.

+

The ResponseWriter should be the original value passed to the [Handler.ServeHTTP] method, or have an Unwrap method returning the original ResponseWriter.

+

If the ResponseWriter implements any of the following methods, the ResponseController will call them as appropriate:

+
Flush()
+FlushError() error // alternative Flush returning an error
+Hijack() (net.Conn, *bufio.ReadWriter, error)
+SetReadDeadline(deadline time.Time) error
+SetWriteDeadline(deadline time.Time) error
+EnableFullDuplex() error
+

If the ResponseWriter does not support a method, ResponseController returns an error matching ErrNotSupported.

+

func (*ResponseController) EnableFullDuplex 1.21

func (c *ResponseController) EnableFullDuplex() error

EnableFullDuplex indicates that the request handler will interleave reads from [Request.Body] with writes to the ResponseWriter.

+

For HTTP/1 requests, the Go HTTP server by default consumes any unread portion of the request body before beginning to write the response, preventing handlers from concurrently reading from the request and writing the response. Calling EnableFullDuplex disables this behavior and permits handlers to continue to read from the request while concurrently writing the response.

+

For HTTP/2 requests, the Go HTTP server always permits concurrent reads and responses.

+

func (*ResponseController) Flush 1.20

func (c *ResponseController) Flush() error

Flush flushes buffered data to the client.

+

func (*ResponseController) Hijack 1.20

func (c *ResponseController) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack lets the caller take over the connection. See the Hijacker interface for details.

+

func (*ResponseController) SetReadDeadline 1.20

func (c *ResponseController) SetReadDeadline(deadline time.Time) error

SetReadDeadline sets the deadline for reading the entire request, including the body. Reads from the request body after the deadline has been exceeded will return an error. A zero value means no deadline.

+

Setting the read deadline after it has been exceeded will not extend it.

+

func (*ResponseController) SetWriteDeadline 1.20

func (c *ResponseController) SetWriteDeadline(deadline time.Time) error

SetWriteDeadline sets the deadline for writing the response. Writes to the response body after the deadline has been exceeded will not block, but may succeed if the data has been buffered. A zero value means no deadline.

+

Setting the write deadline after it has been exceeded will not extend it.

+

type ResponseWriter

A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.

+

A ResponseWriter may not be used after [Handler.ServeHTTP] has returned.

+
type ResponseWriter interface {
+    // Header returns the header map that will be sent by
+    // [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which
+    // [Handler] implementations can set HTTP trailers.
+    //
+    // Changing the header map after a call to [ResponseWriter.WriteHeader] (or
+    // [ResponseWriter.Write]) has no effect unless the HTTP status code was of the
+    // 1xx class or the modified headers are trailers.
+    //
+    // There are two ways to set Trailers. The preferred way is to
+    // predeclare in the headers which trailers you will later
+    // send by setting the "Trailer" header to the names of the
+    // trailer keys which will come later. In this case, those
+    // keys of the Header map are treated as if they were
+    // trailers. See the example. The second way, for trailer
+    // keys not known to the [Handler] until after the first [ResponseWriter.Write],
+    // is to prefix the [Header] map keys with the [TrailerPrefix]
+    // constant value.
+    //
+    // To suppress automatic response headers (such as "Date"), set
+    // their value to nil.
+    Header() Header
+
+    // Write writes the data to the connection as part of an HTTP reply.
+    //
+    // If [ResponseWriter.WriteHeader] has not yet been called, Write calls
+    // WriteHeader(http.StatusOK) before writing the data. If the Header
+    // does not contain a Content-Type line, Write adds a Content-Type set
+    // to the result of passing the initial 512 bytes of written data to
+    // [DetectContentType]. Additionally, if the total size of all written
+    // data is under a few KB and there are no Flush calls, the
+    // Content-Length header is added automatically.
+    //
+    // Depending on the HTTP protocol version and the client, calling
+    // Write or WriteHeader may prevent future reads on the
+    // Request.Body. For HTTP/1.x requests, handlers should read any
+    // needed request body data before writing the response. Once the
+    // headers have been flushed (due to either an explicit Flusher.Flush
+    // call or writing enough data to trigger a flush), the request body
+    // may be unavailable. For HTTP/2 requests, the Go HTTP server permits
+    // handlers to continue to read the request body while concurrently
+    // writing the response. However, such behavior may not be supported
+    // by all HTTP/2 clients. Handlers should read before writing if
+    // possible to maximize compatibility.
+    Write([]byte) (int, error)
+
+    // WriteHeader sends an HTTP response header with the provided
+    // status code.
+    //
+    // If WriteHeader is not called explicitly, the first call to Write
+    // will trigger an implicit WriteHeader(http.StatusOK).
+    // Thus explicit calls to WriteHeader are mainly used to
+    // send error codes or 1xx informational responses.
+    //
+    // The provided code must be a valid HTTP 1xx-5xx status code.
+    // Any number of 1xx headers may be written, followed by at most
+    // one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx
+    // headers may be buffered. Use the Flusher interface to send
+    // buffered data. The header map is cleared when 2xx-5xx headers are
+    // sent, but not with 1xx headers.
+    //
+    // The server will automatically send a 100 (Continue) header
+    // on the first read from the request body if the request has
+    // an "Expect: 100-continue" header.
+    WriteHeader(statusCode int)
+}

Example (Trailers) +

HTTP Trailers are a set of key/value pairs like headers that come after the HTTP response, instead of before.

Code:

+mux := http.NewServeMux()
+mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
+    // Before any call to WriteHeader or Write, declare
+    // the trailers you will set during the HTTP
+    // response. These three headers are actually sent in
+    // the trailer.
+    w.Header().Set("Trailer", "AtEnd1, AtEnd2")
+    w.Header().Add("Trailer", "AtEnd3")
+
+    w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
+    w.WriteHeader(http.StatusOK)
+
+    w.Header().Set("AtEnd1", "value 1")
+    io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
+    w.Header().Set("AtEnd2", "value 2")
+    w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.
+})
+

type RoundTripper

RoundTripper is an interface representing the ability to execute a single HTTP transaction, obtaining the Response for a given Request.

+

A RoundTripper must be safe for concurrent use by multiple goroutines.

+
type RoundTripper interface {
+    // RoundTrip executes a single HTTP transaction, returning
+    // a Response for the provided Request.
+    //
+    // RoundTrip should not attempt to interpret the response. In
+    // particular, RoundTrip must return err == nil if it obtained
+    // a response, regardless of the response's HTTP status code.
+    // A non-nil err should be reserved for failure to obtain a
+    // response. Similarly, RoundTrip should not attempt to
+    // handle higher-level protocol details such as redirects,
+    // authentication, or cookies.
+    //
+    // RoundTrip should not modify the request, except for
+    // consuming and closing the Request's Body. RoundTrip may
+    // read fields of the request in a separate goroutine. Callers
+    // should not mutate or reuse the request until the Response's
+    // Body has been closed.
+    //
+    // RoundTrip must always close the body, including on errors,
+    // but depending on the implementation may do so in a separate
+    // goroutine even after RoundTrip returns. This means that
+    // callers wanting to reuse the body for subsequent requests
+    // must arrange to wait for the Close call before doing so.
+    //
+    // The Request's URL and Header fields must be initialized.
+    RoundTrip(*Request) (*Response, error)
+}

DefaultTransport is the default implementation of Transport and is used by DefaultClient. It establishes network connections as needed and caches them for reuse by subsequent calls. It uses HTTP proxies as directed by the environment variables HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions thereof).

+
var DefaultTransport RoundTripper = &Transport{
+    Proxy: ProxyFromEnvironment,
+    DialContext: defaultTransportDialContext(&net.Dialer{
+        Timeout:   30 * time.Second,
+        KeepAlive: 30 * time.Second,
+    }),
+    ForceAttemptHTTP2:     true,
+    MaxIdleConns:          100,
+    IdleConnTimeout:       90 * time.Second,
+    TLSHandshakeTimeout:   10 * time.Second,
+    ExpectContinueTimeout: 1 * time.Second,
+}

func NewFileTransport

func NewFileTransport(fs FileSystem) RoundTripper

NewFileTransport returns a new RoundTripper, serving the provided FileSystem. The returned RoundTripper ignores the URL host in its incoming requests, as well as most other properties of the request.

+

The typical use case for NewFileTransport is to register the "file" protocol with a Transport, as in:

+
t := &http.Transport{}
+t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
+c := &http.Client{Transport: t}
+res, err := c.Get("file:///etc/passwd")
+...
+

func NewFileTransportFS 1.22

func NewFileTransportFS(fsys fs.FS) RoundTripper

NewFileTransportFS returns a new RoundTripper, serving the provided file system fsys. The returned RoundTripper ignores the URL host in its incoming requests, as well as most other properties of the request.

+

The typical use case for NewFileTransportFS is to register the "file" protocol with a Transport, as in:

+
fsys := os.DirFS("/")
+t := &http.Transport{}
+t.RegisterProtocol("file", http.NewFileTransportFS(fsys))
+c := &http.Client{Transport: t}
+res, err := c.Get("file:///etc/passwd")
+...
+

type SameSite 1.11

SameSite allows a server to define a cookie attribute making it impossible for the browser to send this cookie along with cross-site requests. The main goal is to mitigate the risk of cross-origin information leakage, and provide some protection against cross-site request forgery attacks.

+

See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.

+
type SameSite int
const (
+    SameSiteDefaultMode SameSite = iota + 1
+    SameSiteLaxMode
+    SameSiteStrictMode
+    SameSiteNoneMode
+)

type ServeMux

ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.

+

Patterns

Patterns can match the method, host and path of a request. Some examples:

+

In general, a pattern looks like

+
[METHOD ][HOST]/[PATH]
+

All three parts are optional; "/" is a valid pattern. If METHOD is present, it must be followed by a single space.

+

Literal (that is, non-wildcard) parts of a pattern match the corresponding parts of a request case-sensitively.

+

A pattern with no method matches every method. A pattern with the method GET matches both GET and HEAD requests. Otherwise, the method must match exactly.

+

A pattern with no host matches every host. A pattern with a host matches URLs on that host only.

+

A path can include wildcard segments of the form {NAME} or {NAME...}. For example, "/b/{bucket}/o/{objectname...}". The wildcard name must be a valid Go identifier. Wildcards must be full path segments: they must be preceded by a slash and followed by either a slash or the end of the string. For example, "/b_{bucket}" is not a valid pattern.

+

Normally a wildcard matches only a single path segment, ending at the next literal slash (not %2F) in the request URL. But if the "..." is present, then the wildcard matches the remainder of the URL path, including slashes. (Therefore it is invalid for a "..." wildcard to appear anywhere but at the end of a pattern.) The match for a wildcard can be obtained by calling Request.PathValue with the wildcard's name. A trailing slash in a path acts as an anonymous "..." wildcard.

+

The special wildcard {$} matches only the end of the URL. For example, the pattern "/{$}" matches only the path "/", whereas the pattern "/" matches every path.

+

For matching, both pattern paths and incoming request paths are unescaped segment by segment. So, for example, the path "/a%2Fb/100%25" is treated as having two segments, "a/b" and "100%". The pattern "/a%2fb/" matches it, but the pattern "/a/b/" does not.

+

Precedence

If two or more patterns match a request, then the most specific pattern takes precedence. A pattern P1 is more specific than P2 if P1 matches a strict subset of P2’s requests; that is, if P2 matches all the requests of P1 and more. If neither is more specific, then the patterns conflict. There is one exception to this rule, for backwards compatibility: if two patterns would otherwise conflict and one has a host while the other does not, then the pattern with the host takes precedence. If a pattern passed ServeMux.Handle or ServeMux.HandleFunc conflicts with another pattern that is already registered, those functions panic.

+

As an example of the general rule, "/images/thumbnails/" is more specific than "/images/", so both can be registered. The former matches paths beginning with "/images/thumbnails/" and the latter will match any other path in the "/images/" subtree.

+

As another example, consider the patterns "GET /" and "/index.html": both match a GET request for "/index.html", but the former pattern matches all other GET and HEAD requests, while the latter matches any request for "/index.html" that uses a different method. The patterns conflict.

+

Trailing-slash redirection

Consider a ServeMux with a handler for a subtree, registered using a trailing slash or "..." wildcard. If the ServeMux receives a request for the subtree root without a trailing slash, it redirects the request by adding the trailing slash. This behavior can be overridden with a separate registration for the path without the trailing slash or "..." wildcard. For example, registering "/images/" causes ServeMux to redirect a request for "/images" to "/images/", unless "/images" has been registered separately.

+

Request sanitizing

ServeMux also takes care of sanitizing the URL request path and the Host header, stripping the port number and redirecting any request containing . or .. segments or repeated slashes to an equivalent, cleaner URL.

+

Compatibility

The pattern syntax and matching behavior of ServeMux changed significantly in Go 1.22. To restore the old behavior, set the GODEBUG environment variable to "httpmuxgo121=1". This setting is read once, at program startup; changes during execution will be ignored.

+

The backwards-incompatible changes include:

+
type ServeMux struct {
+    // contains filtered or unexported fields
+}
+

func NewServeMux

func NewServeMux() *ServeMux

NewServeMux allocates and returns a new ServeMux.

+

func (*ServeMux) Handle

func (mux *ServeMux) Handle(pattern string, handler Handler)

Handle registers the handler for the given pattern. If the given pattern conflicts, with one that is already registered, Handle panics.

Example +

Code:

+mux := http.NewServeMux()
+mux.Handle("/api/", apiHandler{})
+mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
+    // The "/" pattern matches everything, so we need to check
+    // that we're at the root here.
+    if req.URL.Path != "/" {
+        http.NotFound(w, req)
+        return
+    }
+    fmt.Fprintf(w, "Welcome to the home page!")
+})
+

func (*ServeMux) HandleFunc

func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc registers the handler function for the given pattern. If the given pattern conflicts, with one that is already registered, HandleFunc panics.

+

func (*ServeMux) Handler 1.1

func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)

Handler returns the handler to use for the given request, consulting r.Method, r.Host, and r.URL.Path. It always returns a non-nil handler. If the path is not in its canonical form, the handler will be an internally-generated handler that redirects to the canonical path. If the host contains a port, it is ignored when matching handlers.

+

The path and host are used unchanged for CONNECT requests.

+

Handler also returns the registered pattern that matches the request or, in the case of internally-generated redirects, the path that will match after following the redirect.

+

If there is no registered handler that applies to the request, Handler returns a “page not found” handler and an empty pattern.

+

func (*ServeMux) ServeHTTP

func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)

ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL.

+

type Server

A Server defines parameters for running an HTTP server. The zero value for Server is a valid configuration.

+
type Server struct {
+    // Addr optionally specifies the TCP address for the server to listen on,
+    // in the form "host:port". If empty, ":http" (port 80) is used.
+    // The service names are defined in RFC 6335 and assigned by IANA.
+    // See net.Dial for details of the address format.
+    Addr string
+
+    Handler Handler // handler to invoke, http.DefaultServeMux if nil
+
+    // DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
+    // otherwise responds with 200 OK and Content-Length: 0.
+    DisableGeneralOptionsHandler bool // Go 1.20
+
+    // TLSConfig optionally provides a TLS configuration for use
+    // by ServeTLS and ListenAndServeTLS. Note that this value is
+    // cloned by ServeTLS and ListenAndServeTLS, so it's not
+    // possible to modify the configuration with methods like
+    // tls.Config.SetSessionTicketKeys. To use
+    // SetSessionTicketKeys, use Server.Serve with a TLS Listener
+    // instead.
+    TLSConfig *tls.Config
+
+    // ReadTimeout is the maximum duration for reading the entire
+    // request, including the body. A zero or negative value means
+    // there will be no timeout.
+    //
+    // Because ReadTimeout does not let Handlers make per-request
+    // decisions on each request body's acceptable deadline or
+    // upload rate, most users will prefer to use
+    // ReadHeaderTimeout. It is valid to use them both.
+    ReadTimeout time.Duration
+
+    // ReadHeaderTimeout is the amount of time allowed to read
+    // request headers. The connection's read deadline is reset
+    // after reading the headers and the Handler can decide what
+    // is considered too slow for the body. If ReadHeaderTimeout
+    // is zero, the value of ReadTimeout is used. If both are
+    // zero, there is no timeout.
+    ReadHeaderTimeout time.Duration // Go 1.8
+
+    // WriteTimeout is the maximum duration before timing out
+    // writes of the response. It is reset whenever a new
+    // request's header is read. Like ReadTimeout, it does not
+    // let Handlers make decisions on a per-request basis.
+    // A zero or negative value means there will be no timeout.
+    WriteTimeout time.Duration
+
+    // IdleTimeout is the maximum amount of time to wait for the
+    // next request when keep-alives are enabled. If IdleTimeout
+    // is zero, the value of ReadTimeout is used. If both are
+    // zero, there is no timeout.
+    IdleTimeout time.Duration // Go 1.8
+
+    // MaxHeaderBytes controls the maximum number of bytes the
+    // server will read parsing the request header's keys and
+    // values, including the request line. It does not limit the
+    // size of the request body.
+    // If zero, DefaultMaxHeaderBytes is used.
+    MaxHeaderBytes int
+
+    // TLSNextProto optionally specifies a function to take over
+    // ownership of the provided TLS connection when an ALPN
+    // protocol upgrade has occurred. The map key is the protocol
+    // name negotiated. The Handler argument should be used to
+    // handle HTTP requests and will initialize the Request's TLS
+    // and RemoteAddr if not already set. The connection is
+    // automatically closed when the function returns.
+    // If TLSNextProto is not nil, HTTP/2 support is not enabled
+    // automatically.
+    TLSNextProto map[string]func(*Server, *tls.Conn, Handler) // Go 1.1
+
+    // ConnState specifies an optional callback function that is
+    // called when a client connection changes state. See the
+    // ConnState type and associated constants for details.
+    ConnState func(net.Conn, ConnState) // Go 1.3
+
+    // ErrorLog specifies an optional logger for errors accepting
+    // connections, unexpected behavior from handlers, and
+    // underlying FileSystem errors.
+    // If nil, logging is done via the log package's standard logger.
+    ErrorLog *log.Logger // Go 1.3
+
+    // BaseContext optionally specifies a function that returns
+    // the base context for incoming requests on this server.
+    // The provided Listener is the specific Listener that's
+    // about to start accepting requests.
+    // If BaseContext is nil, the default is context.Background().
+    // If non-nil, it must return a non-nil context.
+    BaseContext func(net.Listener) context.Context // Go 1.13
+
+    // ConnContext optionally specifies a function that modifies
+    // the context used for a new connection c. The provided ctx
+    // is derived from the base context and has a ServerContextKey
+    // value.
+    ConnContext func(ctx context.Context, c net.Conn) context.Context // Go 1.13
+    // contains filtered or unexported fields
+}
+

func (*Server) Close 1.8

func (srv *Server) Close() error

Close immediately closes all active net.Listeners and any connections in state StateNew, StateActive, or StateIdle. For a graceful shutdown, use Server.Shutdown.

+

Close does not attempt to close (and does not even know about) any hijacked connections, such as WebSockets.

+

Close returns any error returned from closing the Server's underlying Listener(s).

+

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() error

ListenAndServe listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.

+

If srv.Addr is blank, ":http" is used.

+

ListenAndServe always returns a non-nil error. After Server.Shutdown or Server.Close, the returned error is ErrServerClosed.

+

func (*Server) ListenAndServeTLS

func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error

ListenAndServeTLS listens on the TCP network address srv.Addr and then calls ServeTLS to handle requests on incoming TLS connections. Accepted connections are configured to enable TCP keep-alives.

+

Filenames containing a certificate and matching private key for the server must be provided if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

+

If srv.Addr is blank, ":https" is used.

+

ListenAndServeTLS always returns a non-nil error. After Server.Shutdown or Server.Close, the returned error is ErrServerClosed.

+

func (*Server) RegisterOnShutdown 1.9

func (srv *Server) RegisterOnShutdown(f func())

RegisterOnShutdown registers a function to call on Server.Shutdown. This can be used to gracefully shutdown connections that have undergone ALPN protocol upgrade or that have been hijacked. This function should start protocol-specific graceful shutdown, but should not wait for shutdown to complete.

+

func (*Server) Serve

func (srv *Server) Serve(l net.Listener) error

Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call srv.Handler to reply to them.

+

HTTP/2 support is only enabled if the Listener returns *tls.Conn connections and they were configured with "h2" in the TLS Config.NextProtos.

+

Serve always returns a non-nil error and closes l. After Server.Shutdown or Server.Close, the returned error is ErrServerClosed.

+

func (*Server) ServeTLS 1.9

func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error

ServeTLS accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines perform TLS setup and then read requests, calling srv.Handler to reply to them.

+

Files containing a certificate and matching private key for the server must be provided if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

+

ServeTLS always returns a non-nil error. After Server.Shutdown or Server.Close, the returned error is ErrServerClosed.

+

func (*Server) SetKeepAlivesEnabled 1.3

func (srv *Server) SetKeepAlivesEnabled(v bool)

SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. By default, keep-alives are always enabled. Only very resource-constrained environments or servers in the process of shutting down should disable them.

+

func (*Server) Shutdown 1.8

func (srv *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener(s).

+

When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return ErrServerClosed. Make sure the program doesn't exit and waits instead for Shutdown to return.

+

Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets. The caller of Shutdown should separately notify such long-lived connections of shutdown and wait for them to close, if desired. See Server.RegisterOnShutdown for a way to register shutdown notification functions.

+

Once Shutdown has been called on a server, it may not be reused; future calls to methods such as Serve will return ErrServerClosed.

Example +

Code:

+var srv http.Server
+
+idleConnsClosed := make(chan struct{})
+go func() {
+    sigint := make(chan os.Signal, 1)
+    signal.Notify(sigint, os.Interrupt)
+    <-sigint
+
+    // We received an interrupt signal, shut down.
+    if err := srv.Shutdown(context.Background()); err != nil {
+        // Error from closing listeners, or context timeout:
+        log.Printf("HTTP server Shutdown: %v", err)
+    }
+    close(idleConnsClosed)
+}()
+
+if err := srv.ListenAndServe(); err != http.ErrServerClosed {
+    // Error starting or closing listener:
+    log.Fatalf("HTTP server ListenAndServe: %v", err)
+}
+
+<-idleConnsClosed
+

type Transport

Transport is an implementation of RoundTripper that supports HTTP, HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).

+

By default, Transport caches connections for future re-use. This may leave many open connections when accessing many hosts. This behavior can be managed using Transport.CloseIdleConnections method and the [Transport.MaxIdleConnsPerHost] and [Transport.DisableKeepAlives] fields.

+

Transports should be reused instead of created as needed. Transports are safe for concurrent use by multiple goroutines.

+

A Transport is a low-level primitive for making HTTP and HTTPS requests. For high-level functionality, such as cookies and redirects, see Client.

+

Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2 for HTTPS URLs, depending on whether the server supports HTTP/2, and how the Transport is configured. The DefaultTransport supports HTTP/2. To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2 and call ConfigureTransport. See the package docs for more about HTTP/2.

+

Responses with status codes in the 1xx range are either handled automatically (100 expect-continue) or ignored. The one exception is HTTP status code 101 (Switching Protocols), which is considered a terminal status and returned by Transport.RoundTrip. To see the ignored 1xx responses, use the httptrace trace package's ClientTrace.Got1xxResponse.

+

Transport only retries a request upon encountering a network error if the connection has been already been used successfully and if the request is idempotent and either has no body or has its [Request.GetBody] defined. HTTP requests are considered idempotent if they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or if their Header map contains an "Idempotency-Key" or "X-Idempotency-Key" entry. If the idempotency key value is a zero-length slice, the request is treated as idempotent but the header is not sent on the wire.

+
type Transport struct {
+
+    // Proxy specifies a function to return a proxy for a given
+    // Request. If the function returns a non-nil error, the
+    // request is aborted with the provided error.
+    //
+    // The proxy type is determined by the URL scheme. "http",
+    // "https", and "socks5" are supported. If the scheme is empty,
+    // "http" is assumed.
+    //
+    // If the proxy URL contains a userinfo subcomponent,
+    // the proxy request will pass the username and password
+    // in a Proxy-Authorization header.
+    //
+    // If Proxy is nil or returns a nil *URL, no proxy is used.
+    Proxy func(*Request) (*url.URL, error)
+
+    // OnProxyConnectResponse is called when the Transport gets an HTTP response from
+    // a proxy for a CONNECT request. It's called before the check for a 200 OK response.
+    // If it returns an error, the request fails with that error.
+    OnProxyConnectResponse func(ctx context.Context, proxyURL *url.URL, connectReq *Request, connectRes *Response) error // Go 1.20
+
+    // DialContext specifies the dial function for creating unencrypted TCP connections.
+    // If DialContext is nil (and the deprecated Dial below is also nil),
+    // then the transport dials using package net.
+    //
+    // DialContext runs concurrently with calls to RoundTrip.
+    // A RoundTrip call that initiates a dial may end up using
+    // a connection dialed previously when the earlier connection
+    // becomes idle before the later DialContext completes.
+    DialContext func(ctx context.Context, network, addr string) (net.Conn, error) // Go 1.7
+
+    // Dial specifies the dial function for creating unencrypted TCP connections.
+    //
+    // Dial runs concurrently with calls to RoundTrip.
+    // A RoundTrip call that initiates a dial may end up using
+    // a connection dialed previously when the earlier connection
+    // becomes idle before the later Dial completes.
+    //
+    // Deprecated: Use DialContext instead, which allows the transport
+    // to cancel dials as soon as they are no longer needed.
+    // If both are set, DialContext takes priority.
+    Dial func(network, addr string) (net.Conn, error)
+
+    // DialTLSContext specifies an optional dial function for creating
+    // TLS connections for non-proxied HTTPS requests.
+    //
+    // If DialTLSContext is nil (and the deprecated DialTLS below is also nil),
+    // DialContext and TLSClientConfig are used.
+    //
+    // If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS
+    // requests and the TLSClientConfig and TLSHandshakeTimeout
+    // are ignored. The returned net.Conn is assumed to already be
+    // past the TLS handshake.
+    DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error) // Go 1.14
+
+    // DialTLS specifies an optional dial function for creating
+    // TLS connections for non-proxied HTTPS requests.
+    //
+    // Deprecated: Use DialTLSContext instead, which allows the transport
+    // to cancel dials as soon as they are no longer needed.
+    // If both are set, DialTLSContext takes priority.
+    DialTLS func(network, addr string) (net.Conn, error) // Go 1.4
+
+    // TLSClientConfig specifies the TLS configuration to use with
+    // tls.Client.
+    // If nil, the default configuration is used.
+    // If non-nil, HTTP/2 support may not be enabled by default.
+    TLSClientConfig *tls.Config
+
+    // TLSHandshakeTimeout specifies the maximum amount of time to
+    // wait for a TLS handshake. Zero means no timeout.
+    TLSHandshakeTimeout time.Duration // Go 1.3
+
+    // DisableKeepAlives, if true, disables HTTP keep-alives and
+    // will only use the connection to the server for a single
+    // HTTP request.
+    //
+    // This is unrelated to the similarly named TCP keep-alives.
+    DisableKeepAlives bool
+
+    // DisableCompression, if true, prevents the Transport from
+    // requesting compression with an "Accept-Encoding: gzip"
+    // request header when the Request contains no existing
+    // Accept-Encoding value. If the Transport requests gzip on
+    // its own and gets a gzipped response, it's transparently
+    // decoded in the Response.Body. However, if the user
+    // explicitly requested gzip it is not automatically
+    // uncompressed.
+    DisableCompression bool
+
+    // MaxIdleConns controls the maximum number of idle (keep-alive)
+    // connections across all hosts. Zero means no limit.
+    MaxIdleConns int // Go 1.7
+
+    // MaxIdleConnsPerHost, if non-zero, controls the maximum idle
+    // (keep-alive) connections to keep per-host. If zero,
+    // DefaultMaxIdleConnsPerHost is used.
+    MaxIdleConnsPerHost int
+
+    // MaxConnsPerHost optionally limits the total number of
+    // connections per host, including connections in the dialing,
+    // active, and idle states. On limit violation, dials will block.
+    //
+    // Zero means no limit.
+    MaxConnsPerHost int // Go 1.11
+
+    // IdleConnTimeout is the maximum amount of time an idle
+    // (keep-alive) connection will remain idle before closing
+    // itself.
+    // Zero means no limit.
+    IdleConnTimeout time.Duration // Go 1.7
+
+    // ResponseHeaderTimeout, if non-zero, specifies the amount of
+    // time to wait for a server's response headers after fully
+    // writing the request (including its body, if any). This
+    // time does not include the time to read the response body.
+    ResponseHeaderTimeout time.Duration // Go 1.1
+
+    // ExpectContinueTimeout, if non-zero, specifies the amount of
+    // time to wait for a server's first response headers after fully
+    // writing the request headers if the request has an
+    // "Expect: 100-continue" header. Zero means no timeout and
+    // causes the body to be sent immediately, without
+    // waiting for the server to approve.
+    // This time does not include the time to send the request header.
+    ExpectContinueTimeout time.Duration // Go 1.6
+
+    // TLSNextProto specifies how the Transport switches to an
+    // alternate protocol (such as HTTP/2) after a TLS ALPN
+    // protocol negotiation. If Transport dials a TLS connection
+    // with a non-empty protocol name and TLSNextProto contains a
+    // map entry for that key (such as "h2"), then the func is
+    // called with the request's authority (such as "example.com"
+    // or "example.com:1234") and the TLS connection. The function
+    // must return a RoundTripper that then handles the request.
+    // If TLSNextProto is not nil, HTTP/2 support is not enabled
+    // automatically.
+    TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper // Go 1.6
+
+    // ProxyConnectHeader optionally specifies headers to send to
+    // proxies during CONNECT requests.
+    // To set the header dynamically, see GetProxyConnectHeader.
+    ProxyConnectHeader Header // Go 1.8
+
+    // GetProxyConnectHeader optionally specifies a func to return
+    // headers to send to proxyURL during a CONNECT request to the
+    // ip:port target.
+    // If it returns an error, the Transport's RoundTrip fails with
+    // that error. It can return (nil, nil) to not add headers.
+    // If GetProxyConnectHeader is non-nil, ProxyConnectHeader is
+    // ignored.
+    GetProxyConnectHeader func(ctx context.Context, proxyURL *url.URL, target string) (Header, error) // Go 1.16
+
+    // MaxResponseHeaderBytes specifies a limit on how many
+    // response bytes are allowed in the server's response
+    // header.
+    //
+    // Zero means to use a default limit.
+    MaxResponseHeaderBytes int64 // Go 1.7
+
+    // WriteBufferSize specifies the size of the write buffer used
+    // when writing to the transport.
+    // If zero, a default (currently 4KB) is used.
+    WriteBufferSize int // Go 1.13
+
+    // ReadBufferSize specifies the size of the read buffer used
+    // when reading from the transport.
+    // If zero, a default (currently 4KB) is used.
+    ReadBufferSize int // Go 1.13
+
+    // ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero
+    // Dial, DialTLS, or DialContext func or TLSClientConfig is provided.
+    // By default, use of any those fields conservatively disables HTTP/2.
+    // To use a custom dialer or TLS config and still attempt HTTP/2
+    // upgrades, set this to true.
+    ForceAttemptHTTP2 bool // Go 1.13
+    // contains filtered or unexported fields
+}
+

func (*Transport) CancelRequest 1.1

func (t *Transport) CancelRequest(req *Request)

CancelRequest cancels an in-flight request by closing its connection. CancelRequest should only be called after Transport.RoundTrip has returned.

+

Deprecated: Use Request.WithContext to create a request with a cancelable context instead. CancelRequest cannot cancel HTTP/2 requests.

+

func (*Transport) Clone 1.13

func (t *Transport) Clone() *Transport

Clone returns a deep copy of t's exported fields.

+

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.

+

func (*Transport) RegisterProtocol

func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)

RegisterProtocol registers a new protocol with scheme. The Transport will pass requests using the given scheme to rt. It is rt's responsibility to simulate HTTP request semantics.

+

RegisterProtocol can be used by other packages to provide implementations of protocol schemes like "ftp" or "file".

+

If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will handle the Transport.RoundTrip itself for that one request, as if the protocol were not registered.

+

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *Request) (*Response, error)

RoundTrip implements the RoundTripper interface.

+

For higher-level HTTP client support (such as handling of cookies and redirects), see Get, Post, and the Client type.

+

Like the RoundTripper interface, the error types returned by RoundTrip are unspecified.

+

Subdirectories

Name Synopsis
..
cgi Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.
cookiejar Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
fcgi Package fcgi implements the FastCGI protocol.
httptest Package httptest provides utilities for HTTP testing.
httptrace Package httptrace provides mechanisms to trace the events within HTTP client requests.
httputil Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package.
pprof Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/http/ +

+
diff --git a/devdocs/go/net%2Fhttp%2Finternal%2Findex.html b/devdocs/go/net%2Fhttp%2Finternal%2Findex.html new file mode 100644 index 00000000..9903dd5b --- /dev/null +++ b/devdocs/go/net%2Fhttp%2Finternal%2Findex.html @@ -0,0 +1,24 @@ +

Package internal

Overview

Package internal contains HTTP internals shared by net/http and net/http/httputil.

Index

Package files

chunked.go

Variables

var ErrLineTooLong = errors.New("header line too long")

func NewChunkedReader

func NewChunkedReader(r io.Reader) io.Reader

NewChunkedReader returns a new chunkedReader that translates the data read from r out of HTTP "chunked" format before returning it. The chunkedReader returns io.EOF when the final 0-length chunk is read.

+

NewChunkedReader is not needed by normal applications. The http package automatically decodes chunking when reading response bodies.

+

func NewChunkedWriter

func NewChunkedWriter(w io.Writer) io.WriteCloser

NewChunkedWriter returns a new chunkedWriter that translates writes into HTTP "chunked" format before writing them to w. Closing the returned chunkedWriter sends the final 0-length chunk that marks the end of the stream but does not send the final CRLF that appears after trailers; trailers and the last CRLF must be written separately.

+

NewChunkedWriter is not needed by normal applications. The http package adds chunking automatically if handlers don't set a Content-Length header. Using newChunkedWriter inside a handler would result in double chunking or chunking with a Content-Length length, both of which are wrong.

+

type FlushAfterChunkWriter

FlushAfterChunkWriter signals from the caller of NewChunkedWriter that each chunk should be followed by a flush. It is used by the net/http.Transport code to keep the buffering behavior for headers and trailers, but flush out chunks aggressively in the middle for request bodies which may be generated slowly. See Issue 6574.

+
type FlushAfterChunkWriter struct {
+    *bufio.Writer
+}
+

Subdirectories

Name Synopsis
..
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/http/internal/ +

+
diff --git a/devdocs/go/net%2Fhttp%2Fpprof%2Findex.html b/devdocs/go/net%2Fhttp%2Fpprof%2Findex.html new file mode 100644 index 00000000..552a61c3 --- /dev/null +++ b/devdocs/go/net%2Fhttp%2Fpprof%2Findex.html @@ -0,0 +1,48 @@ +

Package pprof

Overview

Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.

+

The package is typically only imported for the side effect of registering its HTTP handlers. The handled paths all begin with /debug/pprof/.

+

To use pprof, link this package into your program:

+
import _ "net/http/pprof"
+

If your application is not already running an http server, you need to start one. Add "net/http" and "log" to your imports and the following code to your main function:

+
go func() {
+	log.Println(http.ListenAndServe("localhost:6060", nil))
+}()
+

By default, all the profiles listed in runtime/pprof.Profile are available (via Handler), in addition to the Cmdline, Profile, Symbol, and Trace profiles defined in this package. If you are not using DefaultServeMux, you will have to register handlers with the mux you are using.

+

Parameters

Parameters can be passed via GET query params:

+

Usage examples

Use the pprof tool to look at the heap profile:

+
go tool pprof http://localhost:6060/debug/pprof/heap
+

Or to look at a 30-second CPU profile:

+
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
+

Or to look at the goroutine blocking profile, after calling runtime.SetBlockProfileRate in your program:

+
go tool pprof http://localhost:6060/debug/pprof/block
+

Or to look at the holders of contended mutexes, after calling runtime.SetMutexProfileFraction in your program:

+
go tool pprof http://localhost:6060/debug/pprof/mutex
+

The package also exports a handler that serves execution trace data for the "go tool trace" command. To collect a 5-second execution trace:

+
curl -o trace.out http://localhost:6060/debug/pprof/trace?seconds=5
+go tool trace trace.out
+

To view all available profiles, open http://localhost:6060/debug/pprof/ in your browser.

+

For a study of the facility in action, visit https://blog.golang.org/2011/06/profiling-go-programs.html.

Index

Package files

pprof.go

func Cmdline

func Cmdline(w http.ResponseWriter, r *http.Request)

Cmdline responds with the running program's command line, with arguments separated by NUL bytes. The package initialization registers it as /debug/pprof/cmdline.

+

func Handler

func Handler(name string) http.Handler

Handler returns an HTTP handler that serves the named profile. Available profiles can be found in runtime/pprof.Profile.

+

func Index

func Index(w http.ResponseWriter, r *http.Request)

Index responds with the pprof-formatted profile named by the request. For example, "/debug/pprof/heap" serves the "heap" profile. Index responds to a request for "/debug/pprof/" with an HTML page listing the available profiles.

+

func Profile

func Profile(w http.ResponseWriter, r *http.Request)

Profile responds with the pprof-formatted cpu profile. Profiling lasts for duration specified in seconds GET parameter, or for 30 seconds if not specified. The package initialization registers it as /debug/pprof/profile.

+

func Symbol

func Symbol(w http.ResponseWriter, r *http.Request)

Symbol looks up the program counters listed in the request, responding with a table mapping program counters to function names. The package initialization registers it as /debug/pprof/symbol.

+

func Trace 1.5

func Trace(w http.ResponseWriter, r *http.Request)

Trace responds with the execution trace in binary form. Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified. The package initialization registers it as /debug/pprof/trace.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/http/pprof/ +

+
diff --git a/devdocs/go/net%2Findex.html b/devdocs/go/net%2Findex.html new file mode 100644 index 00000000..3ef06794 --- /dev/null +++ b/devdocs/go/net%2Findex.html @@ -0,0 +1,1610 @@ +

Package net

Overview

Package net provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.

+

Although the package provides access to low-level networking primitives, most clients will need only the basic interface provided by the Dial, Listen, and Accept functions and the associated Conn and Listener interfaces. The crypto/tls package uses the same interfaces and similar Dial and Listen functions.

+

The Dial function connects to a server:

+
conn, err := net.Dial("tcp", "golang.org:80")
+if err != nil {
+	// handle error
+}
+fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
+status, err := bufio.NewReader(conn).ReadString('\n')
+// ...
+

The Listen function creates servers:

+
ln, err := net.Listen("tcp", ":8080")
+if err != nil {
+	// handle error
+}
+for {
+	conn, err := ln.Accept()
+	if err != nil {
+		// handle error
+	}
+	go handleConnection(conn)
+}
+

Name Resolution

The method for resolving domain names, whether indirectly with functions like Dial or directly with functions like LookupHost and LookupAddr, varies by operating system.

+

On Unix systems, the resolver has two options for resolving names. It can use a pure Go resolver that sends DNS requests directly to the servers listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C library routines such as getaddrinfo and getnameinfo.

+

By default the pure Go resolver is used, because a blocked DNS request consumes only a goroutine, while a blocked C call consumes an operating system thread. When cgo is available, the cgo-based resolver is used instead under a variety of conditions: on systems that do not let programs make direct DNS requests (OS X), when the LOCALDOMAIN environment variable is present (even if empty), when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, when the ASR_CONFIG environment variable is non-empty (OpenBSD only), when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the Go resolver does not implement, and when the name being looked up ends in .local or is an mDNS name.

+

The resolver decision can be overridden by setting the netdns value of the GODEBUG environment variable (see package runtime) to go or cgo, as in:

+
export GODEBUG=netdns=go    # force pure Go resolver
+export GODEBUG=netdns=cgo   # force native resolver (cgo, win32)
+

The decision can also be forced while building the Go source tree by setting the netgo or netcgo build tag.

+

A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver to print debugging information about its decisions. To force a particular resolver while also printing debugging information, join the two settings by a plus sign, as in GODEBUG=netdns=go+1.

+

On macOS, if Go code that uses the net package is built with -buildmode=c-archive, linking the resulting archive into a C program requires passing -lresolv when linking the C code.

+

On Plan 9, the resolver always accesses /net/cs and /net/dns.

+

On Windows, in Go 1.18.x and earlier, the resolver always used C library functions, such as GetAddrInfo and DnsQuery.

Index

Examples

CIDRMask
Dialer
Dialer (Unix)
IP.DefaultMask
IP.Equal
IP.IsGlobalUnicast
IP.IsInterfaceLocalMulticast
IP.IsLinkLocalMulticast
IP.IsLinkLocalUnicast
IP.IsLoopback
IP.IsMulticast
IP.IsPrivate
IP.IsUnspecified
IP.Mask
IP.String
IP.To16
IP (To4)
IPv4
IPv4Mask
Listener
ParseCIDR
ParseIP
UDPConn.WriteTo

Package files

addrselect.go cgo_linux.go cgo_resnew.go cgo_socknew.go cgo_unix.go cgo_unix_cgo.go cgo_unix_cgo_res.go conf.go dial.go dnsclient.go dnsclient_unix.go dnsconfig.go dnsconfig_unix.go error_posix.go error_unix.go fd_posix.go fd_unix.go file.go file_unix.go hook.go hook_unix.go hosts.go interface.go interface_linux.go ip.go iprawsock.go iprawsock_posix.go ipsock.go ipsock_posix.go lookup.go lookup_unix.go mac.go mptcpsock_linux.go net.go netcgo_off.go netgo_off.go nss.go parse.go pipe.go port.go port_unix.go rawconn.go rlimit_unix.go sendfile_linux.go sock_cloexec.go sock_linux.go sock_posix.go sockaddr_posix.go sockopt_linux.go sockopt_posix.go sockoptip_linux.go sockoptip_posix.go splice_linux.go tcpsock.go tcpsock_posix.go tcpsockopt_posix.go tcpsockopt_unix.go udpsock.go udpsock_posix.go unixsock.go unixsock_posix.go unixsock_readmsg_cmsg_cloexec.go writev_unix.go

Constants

IP address lengths (bytes).

+
const (
+    IPv4len = 4
+    IPv6len = 16
+)

Variables

Well-known IPv4 addresses

+
var (
+    IPv4bcast     = IPv4(255, 255, 255, 255) // limited broadcast
+    IPv4allsys    = IPv4(224, 0, 0, 1)       // all systems
+    IPv4allrouter = IPv4(224, 0, 0, 2)       // all routers
+    IPv4zero      = IPv4(0, 0, 0, 0)         // all zeros
+)

Well-known IPv6 addresses

+
var (
+    IPv6zero                   = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+    IPv6unspecified            = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+    IPv6loopback               = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
+    IPv6interfacelocalallnodes = IP{0xff, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
+    IPv6linklocalallnodes      = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
+    IPv6linklocalallrouters    = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02}
+)

DefaultResolver is the resolver used by the package-level Lookup functions and by Dialers without a specified Resolver.

+
var DefaultResolver = &Resolver{}

ErrClosed is the error returned by an I/O call on a network connection that has already been closed, or that is closed by another goroutine before the I/O is completed. This may be wrapped in another error, and should normally be tested using errors.Is(err, net.ErrClosed).

+
var ErrClosed error = errClosed

Various errors contained in OpError.

+
var (
+    ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection")
+)

func JoinHostPort

func JoinHostPort(host, port string) string

JoinHostPort combines host and port into a network address of the form "host:port". If host contains a colon, as found in literal IPv6 addresses, then JoinHostPort returns "[host]:port".

+

See func Dial for a description of the host and port parameters.

+

func LookupAddr

func LookupAddr(addr string) (names []string, err error)

LookupAddr performs a reverse lookup for the given address, returning a list of names mapping to that address.

+

The returned names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

+

When using the host C library resolver, at most one result will be returned. To bypass the host resolver, use a custom Resolver.

+

LookupAddr uses context.Background internally; to specify the context, use Resolver.LookupAddr.

+

func LookupCNAME

func LookupCNAME(host string) (cname string, err error)

LookupCNAME returns the canonical name for the given host. Callers that do not care about the canonical name can call LookupHost or LookupIP directly; both take care of resolving the canonical name as part of the lookup.

+

A canonical name is the final name after following zero or more CNAME records. LookupCNAME does not return an error if host does not contain DNS "CNAME" records, as long as host resolves to address records.

+

The returned canonical name is validated to be a properly formatted presentation-format domain name.

+

LookupCNAME uses context.Background internally; to specify the context, use Resolver.LookupCNAME.

+

func LookupHost

func LookupHost(host string) (addrs []string, err error)

LookupHost looks up the given host using the local resolver. It returns a slice of that host's addresses.

+

LookupHost uses context.Background internally; to specify the context, use Resolver.LookupHost.

+

func LookupPort

func LookupPort(network, service string) (port int, err error)

LookupPort looks up the port for the given network and service.

+

LookupPort uses context.Background internally; to specify the context, use Resolver.LookupPort.

+

func LookupTXT

func LookupTXT(name string) ([]string, error)

LookupTXT returns the DNS TXT records for the given domain name.

+

LookupTXT uses context.Background internally; to specify the context, use Resolver.LookupTXT.

+

func ParseCIDR

func ParseCIDR(s string) (IP, *IPNet, error)

ParseCIDR parses s as a CIDR notation IP address and prefix length, like "192.0.2.0/24" or "2001:db8::/32", as defined in RFC 4632 and RFC 4291.

+

It returns the IP address and the network implied by the IP and prefix length. For example, ParseCIDR("192.0.2.1/24") returns the IP address 192.0.2.1 and the network 192.0.2.0/24.

Example +

Code:

ipv4Addr, ipv4Net, err := net.ParseCIDR("192.0.2.1/24")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(ipv4Addr)
+fmt.Println(ipv4Net)
+
+ipv6Addr, ipv6Net, err := net.ParseCIDR("2001:db8:a0b:12f0::1/32")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(ipv6Addr)
+fmt.Println(ipv6Net)
+
+

Output:

192.0.2.1
+192.0.2.0/24
+2001:db8:a0b:12f0::1
+2001:db8::/32
+

func Pipe

func Pipe() (Conn, Conn)

Pipe creates a synchronous, in-memory, full duplex network connection; both ends implement the Conn interface. Reads on one end are matched with writes on the other, copying data directly between the two; there is no internal buffering.

+

func SplitHostPort

func SplitHostPort(hostport string) (host, port string, err error)

SplitHostPort splits a network address of the form "host:port", "host%zone:port", "[host]:port" or "[host%zone]:port" into host or host%zone and port.

+

A literal IPv6 address in hostport must be enclosed in square brackets, as in "[::1]:80", "[::1%lo0]:80".

+

See func Dial for a description of the hostport parameter, and host and port results.

+

type Addr

Addr represents a network end point address.

+

The two methods [Addr.Network] and [Addr.String] conventionally return strings that can be passed as the arguments to Dial, but the exact form and meaning of the strings is up to the implementation.

+
type Addr interface {
+    Network() string // name of the network (for example, "tcp", "udp")
+    String() string  // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80")
+}

func InterfaceAddrs

func InterfaceAddrs() ([]Addr, error)

InterfaceAddrs returns a list of the system's unicast interface addresses.

+

The returned list does not identify the associated interface; use Interfaces and Interface.Addrs for more detail.

+

type AddrError

type AddrError struct {
+    Err  string
+    Addr string
+}
+

func (*AddrError) Error

func (e *AddrError) Error() string

func (*AddrError) Temporary

func (e *AddrError) Temporary() bool

func (*AddrError) Timeout

func (e *AddrError) Timeout() bool

type Buffers 1.8

Buffers contains zero or more runs of bytes to write.

+

On certain machines, for certain types of connections, this is optimized into an OS-specific batch write operation (such as "writev").

+
type Buffers [][]byte

func (*Buffers) Read 1.8

func (v *Buffers) Read(p []byte) (n int, err error)

Read from the buffers.

+

Read implements io.Reader for Buffers.

+

Read modifies the slice v as well as v[i] for 0 <= i < len(v), but does not modify v[i][j] for any i, j.

+

func (*Buffers) WriteTo 1.8

func (v *Buffers) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes contents of the buffers to w.

+

WriteTo implements io.WriterTo for Buffers.

+

WriteTo modifies the slice v as well as v[i] for 0 <= i < len(v), but does not modify v[i][j] for any i, j.

+

type Conn

Conn is a generic stream-oriented network connection.

+

Multiple goroutines may invoke methods on a Conn simultaneously.

+
type Conn interface {
+    // Read reads data from the connection.
+    // Read can be made to time out and return an error after a fixed
+    // time limit; see SetDeadline and SetReadDeadline.
+    Read(b []byte) (n int, err error)
+
+    // Write writes data to the connection.
+    // Write can be made to time out and return an error after a fixed
+    // time limit; see SetDeadline and SetWriteDeadline.
+    Write(b []byte) (n int, err error)
+
+    // Close closes the connection.
+    // Any blocked Read or Write operations will be unblocked and return errors.
+    Close() error
+
+    // LocalAddr returns the local network address, if known.
+    LocalAddr() Addr
+
+    // RemoteAddr returns the remote network address, if known.
+    RemoteAddr() Addr
+
+    // SetDeadline sets the read and write deadlines associated
+    // with the connection. It is equivalent to calling both
+    // SetReadDeadline and SetWriteDeadline.
+    //
+    // A deadline is an absolute time after which I/O operations
+    // fail instead of blocking. The deadline applies to all future
+    // and pending I/O, not just the immediately following call to
+    // Read or Write. After a deadline has been exceeded, the
+    // connection can be refreshed by setting a deadline in the future.
+    //
+    // If the deadline is exceeded a call to Read or Write or to other
+    // I/O methods will return an error that wraps os.ErrDeadlineExceeded.
+    // This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
+    // The error's Timeout method will return true, but note that there
+    // are other possible errors for which the Timeout method will
+    // return true even if the deadline has not been exceeded.
+    //
+    // An idle timeout can be implemented by repeatedly extending
+    // the deadline after successful Read or Write calls.
+    //
+    // A zero value for t means I/O operations will not time out.
+    SetDeadline(t time.Time) error
+
+    // SetReadDeadline sets the deadline for future Read calls
+    // and any currently-blocked Read call.
+    // A zero value for t means Read will not time out.
+    SetReadDeadline(t time.Time) error
+
+    // SetWriteDeadline sets the deadline for future Write calls
+    // and any currently-blocked Write call.
+    // Even if write times out, it may return n > 0, indicating that
+    // some of the data was successfully written.
+    // A zero value for t means Write will not time out.
+    SetWriteDeadline(t time.Time) error
+}

func Dial

func Dial(network, address string) (Conn, error)

Dial connects to the address on the named network.

+

Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4" (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and "unixpacket".

+

For TCP and UDP networks, the address has the form "host:port". The host must be a literal IP address, or a host name that can be resolved to IP addresses. The port must be a literal port number or a service name. If the host is a literal IPv6 address it must be enclosed in square brackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80". The zone specifies the scope of the literal IPv6 address as defined in RFC 4007. The functions JoinHostPort and SplitHostPort manipulate a pair of host and port in this form. When using TCP, and the host resolves to multiple IP addresses, Dial will try each IP address in order until one succeeds.

+

Examples:

+
Dial("tcp", "golang.org:http")
+Dial("tcp", "192.0.2.1:http")
+Dial("tcp", "198.51.100.1:80")
+Dial("udp", "[2001:db8::1]:domain")
+Dial("udp", "[fe80::1%lo0]:53")
+Dial("tcp", ":80")
+

For IP networks, the network must be "ip", "ip4" or "ip6" followed by a colon and a literal protocol number or a protocol name, and the address has the form "host". The host must be a literal IP address or a literal IPv6 address with zone. It depends on each operating system how the operating system behaves with a non-well known protocol number such as "0" or "255".

+

Examples:

+
Dial("ip4:1", "192.0.2.1")
+Dial("ip6:ipv6-icmp", "2001:db8::1")
+Dial("ip6:58", "fe80::1%lo0")
+

For TCP, UDP and IP networks, if the host is empty or a literal unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for TCP and UDP, "", "0.0.0.0" or "::" for IP, the local system is assumed.

+

For Unix networks, the address must be a file system path.

+

func DialTimeout

func DialTimeout(network, address string, timeout time.Duration) (Conn, error)

DialTimeout acts like Dial but takes a timeout.

+

The timeout includes name resolution, if required. When using TCP, and the host in the address parameter resolves to multiple IP addresses, the timeout is spread over each consecutive dial, such that each is given an appropriate fraction of the time to connect.

+

See func Dial for a description of the network and address parameters.

+

func FileConn

func FileConn(f *os.File) (c Conn, err error)

FileConn returns a copy of the network connection corresponding to the open file f. It is the caller's responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.

+

type DNSConfigError

DNSConfigError represents an error reading the machine's DNS configuration. (No longer used; kept for compatibility.)

+
type DNSConfigError struct {
+    Err error
+}
+

func (*DNSConfigError) Error

func (e *DNSConfigError) Error() string

func (*DNSConfigError) Temporary

func (e *DNSConfigError) Temporary() bool

func (*DNSConfigError) Timeout

func (e *DNSConfigError) Timeout() bool

func (*DNSConfigError) Unwrap 1.13

func (e *DNSConfigError) Unwrap() error

type DNSError

DNSError represents a DNS lookup error.

+
type DNSError struct {
+    Err         string // description of the error
+    Name        string // name looked for
+    Server      string // server used
+    IsTimeout   bool   // if true, timed out; not all timeouts set this
+    IsTemporary bool   // if true, error is temporary; not all errors set this; added in Go 1.6
+
+    // IsNotFound is set to true when the requested name does not
+    // contain any records of the requested type (data not found),
+    // or the name itself was not found (NXDOMAIN).
+    IsNotFound bool // Go 1.13
+}
+

func (*DNSError) Error

func (e *DNSError) Error() string

func (*DNSError) Temporary

func (e *DNSError) Temporary() bool

Temporary reports whether the DNS error is known to be temporary. This is not always known; a DNS lookup may fail due to a temporary error and return a DNSError for which Temporary returns false.

+

func (*DNSError) Timeout

func (e *DNSError) Timeout() bool

Timeout reports whether the DNS lookup is known to have timed out. This is not always known; a DNS lookup may fail due to a timeout and return a DNSError for which Timeout returns false.

+

type Dialer 1.1

A Dialer contains options for connecting to an address.

+

The zero value for each field is equivalent to dialing without that option. Dialing with the zero value of Dialer is therefore equivalent to just calling the Dial function.

+

It is safe to call Dialer's methods concurrently.

+
type Dialer struct {
+    // Timeout is the maximum amount of time a dial will wait for
+    // a connect to complete. If Deadline is also set, it may fail
+    // earlier.
+    //
+    // The default is no timeout.
+    //
+    // When using TCP and dialing a host name with multiple IP
+    // addresses, the timeout may be divided between them.
+    //
+    // With or without a timeout, the operating system may impose
+    // its own earlier timeout. For instance, TCP timeouts are
+    // often around 3 minutes.
+    Timeout time.Duration
+
+    // Deadline is the absolute point in time after which dials
+    // will fail. If Timeout is set, it may fail earlier.
+    // Zero means no deadline, or dependent on the operating system
+    // as with the Timeout option.
+    Deadline time.Time
+
+    // LocalAddr is the local address to use when dialing an
+    // address. The address must be of a compatible type for the
+    // network being dialed.
+    // If nil, a local address is automatically chosen.
+    LocalAddr Addr
+
+    // DualStack previously enabled RFC 6555 Fast Fallback
+    // support, also known as "Happy Eyeballs", in which IPv4 is
+    // tried soon if IPv6 appears to be misconfigured and
+    // hanging.
+    //
+    // Deprecated: Fast Fallback is enabled by default. To
+    // disable, set FallbackDelay to a negative value.
+    DualStack bool // Go 1.2
+
+    // FallbackDelay specifies the length of time to wait before
+    // spawning a RFC 6555 Fast Fallback connection. That is, this
+    // is the amount of time to wait for IPv6 to succeed before
+    // assuming that IPv6 is misconfigured and falling back to
+    // IPv4.
+    //
+    // If zero, a default delay of 300ms is used.
+    // A negative value disables Fast Fallback support.
+    FallbackDelay time.Duration // Go 1.5
+
+    // KeepAlive specifies the interval between keep-alive
+    // probes for an active network connection.
+    // If zero, keep-alive probes are sent with a default value
+    // (currently 15 seconds), if supported by the protocol and operating
+    // system. Network protocols or operating systems that do
+    // not support keep-alives ignore this field.
+    // If negative, keep-alive probes are disabled.
+    KeepAlive time.Duration // Go 1.3
+
+    // Resolver optionally specifies an alternate resolver to use.
+    Resolver *Resolver // Go 1.8
+
+    // Cancel is an optional channel whose closure indicates that
+    // the dial should be canceled. Not all types of dials support
+    // cancellation.
+    //
+    // Deprecated: Use DialContext instead.
+    Cancel <-chan struct{} // Go 1.6
+
+    // If Control is not nil, it is called after creating the network
+    // connection but before actually dialing.
+    //
+    // Network and address parameters passed to Control function are not
+    // necessarily the ones passed to Dial. For example, passing "tcp" to Dial
+    // will cause the Control function to be called with "tcp4" or "tcp6".
+    //
+    // Control is ignored if ControlContext is not nil.
+    Control func(network, address string, c syscall.RawConn) error // Go 1.11
+
+    // If ControlContext is not nil, it is called after creating the network
+    // connection but before actually dialing.
+    //
+    // Network and address parameters passed to ControlContext function are not
+    // necessarily the ones passed to Dial. For example, passing "tcp" to Dial
+    // will cause the ControlContext function to be called with "tcp4" or "tcp6".
+    //
+    // If ControlContext is not nil, Control is ignored.
+    ControlContext func(ctx context.Context, network, address string, c syscall.RawConn) error // Go 1.20
+    // contains filtered or unexported fields
+}
+

Example +

Code:

+var d net.Dialer
+ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+defer cancel()
+
+conn, err := d.DialContext(ctx, "tcp", "localhost:12345")
+if err != nil {
+    log.Fatalf("Failed to dial: %v", err)
+}
+defer conn.Close()
+
+if _, err := conn.Write([]byte("Hello, World!")); err != nil {
+    log.Fatal(err)
+}
+

Example (Unix) +

Code:

+// DialUnix does not take a context.Context parameter. This example shows
+// how to dial a Unix socket with a Context. Note that the Context only
+// applies to the dial operation; it does not apply to the connection once
+// it has been established.
+var d net.Dialer
+ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+defer cancel()
+
+d.LocalAddr = nil // if you have a local addr, add it here
+raddr := net.UnixAddr{Name: "/path/to/unix.sock", Net: "unix"}
+conn, err := d.DialContext(ctx, "unix", raddr.String())
+if err != nil {
+    log.Fatalf("Failed to dial: %v", err)
+}
+defer conn.Close()
+if _, err := conn.Write([]byte("Hello, socket!")); err != nil {
+    log.Fatal(err)
+}
+

func (*Dialer) Dial 1.1

func (d *Dialer) Dial(network, address string) (Conn, error)

Dial connects to the address on the named network.

+

See func Dial for a description of the network and address parameters.

+

Dial uses context.Background internally; to specify the context, use Dialer.DialContext.

+

func (*Dialer) DialContext 1.7

func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn, error)

DialContext connects to the address on the named network using the provided context.

+

The provided Context must be non-nil. If the context expires before the connection is complete, an error is returned. Once successfully connected, any expiration of the context will not affect the connection.

+

When using TCP, and the host in the address parameter resolves to multiple network addresses, any dial timeout (from d.Timeout or ctx) is spread over each consecutive dial, such that each is given an appropriate fraction of the time to connect. For example, if a host has 4 IP addresses and the timeout is 1 minute, the connect to each single address will be given 15 seconds to complete before trying the next one.

+

See func Dial for a description of the network and address parameters.

+

func (*Dialer) MultipathTCP 1.21

func (d *Dialer) MultipathTCP() bool

MultipathTCP reports whether MPTCP will be used.

+

This method doesn't check if MPTCP is supported by the operating system or not.

+

func (*Dialer) SetMultipathTCP 1.21

func (d *Dialer) SetMultipathTCP(use bool)

SetMultipathTCP directs the Dial methods to use, or not use, MPTCP, if supported by the operating system. This method overrides the system default and the GODEBUG=multipathtcp=... setting if any.

+

If MPTCP is not available on the host or not supported by the server, the Dial methods will fall back to TCP.

+

type Error

An Error represents a network error.

+
type Error interface {
+    error
+    Timeout() bool // Is the error a timeout?
+
+    // Deprecated: Temporary errors are not well-defined.
+    // Most "temporary" errors are timeouts, and the few exceptions are surprising.
+    // Do not use this method.
+    Temporary() bool
+}

type Flags

type Flags uint
const (
+    FlagUp           Flags = 1 << iota // interface is administratively up
+    FlagBroadcast                      // interface supports broadcast access capability
+    FlagLoopback                       // interface is a loopback interface
+    FlagPointToPoint                   // interface belongs to a point-to-point link
+    FlagMulticast                      // interface supports multicast access capability
+    FlagRunning                        // interface is in running state
+)

func (Flags) String

func (f Flags) String() string

type HardwareAddr

A HardwareAddr represents a physical hardware address.

+
type HardwareAddr []byte

func ParseMAC

func ParseMAC(s string) (hw HardwareAddr, err error)

ParseMAC parses s as an IEEE 802 MAC-48, EUI-48, EUI-64, or a 20-octet IP over InfiniBand link-layer address using one of the following formats:

+
00:00:5e:00:53:01
+02:00:5e:10:00:00:00:01
+00:00:00:00:fe:80:00:00:00:00:00:00:02:00:5e:10:00:00:00:01
+00-00-5e-00-53-01
+02-00-5e-10-00-00-00-01
+00-00-00-00-fe-80-00-00-00-00-00-00-02-00-5e-10-00-00-00-01
+0000.5e00.5301
+0200.5e10.0000.0001
+0000.0000.fe80.0000.0000.0000.0200.5e10.0000.0001
+

func (HardwareAddr) String

func (a HardwareAddr) String() string

type IP

An IP is a single IP address, a slice of bytes. Functions in this package accept either 4-byte (IPv4) or 16-byte (IPv6) slices as input.

+

Note that in this documentation, referring to an IP address as an IPv4 address or an IPv6 address is a semantic property of the address, not just the length of the byte slice: a 16-byte slice can still be an IPv4 address.

+
type IP []byte

Example (To4) +

Code:

ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+ipv4 := net.IPv4(10, 255, 0, 0)
+
+fmt.Println(ipv6.To4())
+fmt.Println(ipv4.To4())
+
+

Output:

<nil>
+10.255.0.0
+

func IPv4

func IPv4(a, b, c, d byte) IP

IPv4 returns the IP address (in 16-byte form) of the IPv4 address a.b.c.d.

Example +

Code:

fmt.Println(net.IPv4(8, 8, 8, 8))
+
+

Output:

8.8.8.8
+

func LookupIP

func LookupIP(host string) ([]IP, error)

LookupIP looks up host using the local resolver. It returns a slice of that host's IPv4 and IPv6 addresses.

+

func ParseIP

func ParseIP(s string) IP

ParseIP parses s as an IP address, returning the result. The string s can be in IPv4 dotted decimal ("192.0.2.1"), IPv6 ("2001:db8::68"), or IPv4-mapped IPv6 ("::ffff:192.0.2.1") form. If s is not a valid textual representation of an IP address, ParseIP returns nil.

Example +

Code:

fmt.Println(net.ParseIP("192.0.2.1"))
+fmt.Println(net.ParseIP("2001:db8::68"))
+fmt.Println(net.ParseIP("192.0.2"))
+
+

Output:

192.0.2.1
+2001:db8::68
+<nil>
+

func (IP) DefaultMask

func (ip IP) DefaultMask() IPMask

DefaultMask returns the default IP mask for the IP address ip. Only IPv4 addresses have default masks; DefaultMask returns nil if ip is not a valid IPv4 address.

Example +

Code:

ip := net.ParseIP("192.0.2.1")
+fmt.Println(ip.DefaultMask())
+
+

Output:

ffffff00
+

func (IP) Equal

func (ip IP) Equal(x IP) bool

Equal reports whether ip and x are the same IP address. An IPv4 address and that same address in IPv6 form are considered to be equal.

Example +

Code:

ipv4DNS := net.ParseIP("8.8.8.8")
+ipv4Lo := net.ParseIP("127.0.0.1")
+ipv6DNS := net.ParseIP("0:0:0:0:0:FFFF:0808:0808")
+
+fmt.Println(ipv4DNS.Equal(ipv4DNS))
+fmt.Println(ipv4DNS.Equal(ipv4Lo))
+fmt.Println(ipv4DNS.Equal(ipv6DNS))
+
+

Output:

true
+false
+true
+

func (IP) IsGlobalUnicast

func (ip IP) IsGlobalUnicast() bool

IsGlobalUnicast reports whether ip is a global unicast address.

+

The identification of global unicast addresses uses address type identification as defined in RFC 1122, RFC 4632 and RFC 4291 with the exception of IPv4 directed broadcast addresses. It returns true even if ip is in IPv4 private address space or local IPv6 unicast address space.

Example +

Code:

ipv6Global := net.ParseIP("2000::")
+ipv6UniqLocal := net.ParseIP("2000::")
+ipv6Multi := net.ParseIP("FF00::")
+
+ipv4Private := net.ParseIP("10.255.0.0")
+ipv4Public := net.ParseIP("8.8.8.8")
+ipv4Broadcast := net.ParseIP("255.255.255.255")
+
+fmt.Println(ipv6Global.IsGlobalUnicast())
+fmt.Println(ipv6UniqLocal.IsGlobalUnicast())
+fmt.Println(ipv6Multi.IsGlobalUnicast())
+
+fmt.Println(ipv4Private.IsGlobalUnicast())
+fmt.Println(ipv4Public.IsGlobalUnicast())
+fmt.Println(ipv4Broadcast.IsGlobalUnicast())
+
+

Output:

true
+true
+false
+true
+true
+false
+

func (IP) IsInterfaceLocalMulticast

func (ip IP) IsInterfaceLocalMulticast() bool

IsInterfaceLocalMulticast reports whether ip is an interface-local multicast address.

Example +

Code:

ipv6InterfaceLocalMulti := net.ParseIP("ff01::1")
+ipv6Global := net.ParseIP("2000::")
+ipv4 := net.ParseIP("255.0.0.0")
+
+fmt.Println(ipv6InterfaceLocalMulti.IsInterfaceLocalMulticast())
+fmt.Println(ipv6Global.IsInterfaceLocalMulticast())
+fmt.Println(ipv4.IsInterfaceLocalMulticast())
+
+

Output:

true
+false
+false
+

func (IP) IsLinkLocalMulticast

func (ip IP) IsLinkLocalMulticast() bool

IsLinkLocalMulticast reports whether ip is a link-local multicast address.

Example +

Code:

ipv6LinkLocalMulti := net.ParseIP("ff02::2")
+ipv6LinkLocalUni := net.ParseIP("fe80::")
+ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")
+ipv4LinkLocalUni := net.ParseIP("169.254.0.0")
+
+fmt.Println(ipv6LinkLocalMulti.IsLinkLocalMulticast())
+fmt.Println(ipv6LinkLocalUni.IsLinkLocalMulticast())
+fmt.Println(ipv4LinkLocalMulti.IsLinkLocalMulticast())
+fmt.Println(ipv4LinkLocalUni.IsLinkLocalMulticast())
+
+

Output:

true
+false
+true
+false
+

func (IP) IsLinkLocalUnicast

func (ip IP) IsLinkLocalUnicast() bool

IsLinkLocalUnicast reports whether ip is a link-local unicast address.

Example +

Code:

ipv6LinkLocalUni := net.ParseIP("fe80::")
+ipv6Global := net.ParseIP("2000::")
+ipv4LinkLocalUni := net.ParseIP("169.254.0.0")
+ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")
+
+fmt.Println(ipv6LinkLocalUni.IsLinkLocalUnicast())
+fmt.Println(ipv6Global.IsLinkLocalUnicast())
+fmt.Println(ipv4LinkLocalUni.IsLinkLocalUnicast())
+fmt.Println(ipv4LinkLocalMulti.IsLinkLocalUnicast())
+
+

Output:

true
+false
+true
+false
+

func (IP) IsLoopback

func (ip IP) IsLoopback() bool

IsLoopback reports whether ip is a loopback address.

Example +

Code:

ipv6Lo := net.ParseIP("::1")
+ipv6 := net.ParseIP("ff02::1")
+ipv4Lo := net.ParseIP("127.0.0.0")
+ipv4 := net.ParseIP("128.0.0.0")
+
+fmt.Println(ipv6Lo.IsLoopback())
+fmt.Println(ipv6.IsLoopback())
+fmt.Println(ipv4Lo.IsLoopback())
+fmt.Println(ipv4.IsLoopback())
+
+

Output:

true
+false
+true
+false
+

func (IP) IsMulticast

func (ip IP) IsMulticast() bool

IsMulticast reports whether ip is a multicast address.

Example +

Code:

ipv6Multi := net.ParseIP("FF00::")
+ipv6LinkLocalMulti := net.ParseIP("ff02::1")
+ipv6Lo := net.ParseIP("::1")
+ipv4Multi := net.ParseIP("239.0.0.0")
+ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")
+ipv4Lo := net.ParseIP("127.0.0.0")
+
+fmt.Println(ipv6Multi.IsMulticast())
+fmt.Println(ipv6LinkLocalMulti.IsMulticast())
+fmt.Println(ipv6Lo.IsMulticast())
+fmt.Println(ipv4Multi.IsMulticast())
+fmt.Println(ipv4LinkLocalMulti.IsMulticast())
+fmt.Println(ipv4Lo.IsMulticast())
+
+

Output:

true
+true
+false
+true
+true
+false
+

func (IP) IsPrivate 1.17

func (ip IP) IsPrivate() bool

IsPrivate reports whether ip is a private address, according to RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses).

Example +

Code:

ipv6Private := net.ParseIP("fc00::")
+ipv6Public := net.ParseIP("fe00::")
+ipv4Private := net.ParseIP("10.255.0.0")
+ipv4Public := net.ParseIP("11.0.0.0")
+
+fmt.Println(ipv6Private.IsPrivate())
+fmt.Println(ipv6Public.IsPrivate())
+fmt.Println(ipv4Private.IsPrivate())
+fmt.Println(ipv4Public.IsPrivate())
+
+

Output:

true
+false
+true
+false
+

func (IP) IsUnspecified

func (ip IP) IsUnspecified() bool

IsUnspecified reports whether ip is an unspecified address, either the IPv4 address "0.0.0.0" or the IPv6 address "::".

Example +

Code:

ipv6Unspecified := net.ParseIP("::")
+ipv6Specified := net.ParseIP("fe00::")
+ipv4Unspecified := net.ParseIP("0.0.0.0")
+ipv4Specified := net.ParseIP("8.8.8.8")
+
+fmt.Println(ipv6Unspecified.IsUnspecified())
+fmt.Println(ipv6Specified.IsUnspecified())
+fmt.Println(ipv4Unspecified.IsUnspecified())
+fmt.Println(ipv4Specified.IsUnspecified())
+
+

Output:

true
+false
+true
+false
+

func (IP) MarshalText 1.2

func (ip IP) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The encoding is the same as returned by IP.String, with one exception: When len(ip) is zero, it returns an empty slice.

+

func (IP) Mask

func (ip IP) Mask(mask IPMask) IP

Mask returns the result of masking the IP address ip with mask.

Example +

Code:

ipv4Addr := net.ParseIP("192.0.2.1")
+// This mask corresponds to a /24 subnet for IPv4.
+ipv4Mask := net.CIDRMask(24, 32)
+fmt.Println(ipv4Addr.Mask(ipv4Mask))
+
+ipv6Addr := net.ParseIP("2001:db8:a0b:12f0::1")
+// This mask corresponds to a /32 subnet for IPv6.
+ipv6Mask := net.CIDRMask(32, 128)
+fmt.Println(ipv6Addr.Mask(ipv6Mask))
+
+

Output:

192.0.2.0
+2001:db8::
+

func (IP) String

func (ip IP) String() string

String returns the string form of the IP address ip. It returns one of 4 forms:

+

Example +

Code:

ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+ipv4 := net.IPv4(10, 255, 0, 0)
+
+fmt.Println(ipv6.String())
+fmt.Println(ipv4.String())
+
+

Output:

fc00::
+10.255.0.0
+

func (IP) To16

func (ip IP) To16() IP

To16 converts the IP address ip to a 16-byte representation. If ip is not an IP address (it is the wrong length), To16 returns nil.

Example +

Code:

ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+ipv4 := net.IPv4(10, 255, 0, 0)
+
+fmt.Println(ipv6.To16())
+fmt.Println(ipv4.To16())
+
+

Output:

fc00::
+10.255.0.0
+

func (IP) To4

func (ip IP) To4() IP

To4 converts the IPv4 address ip to a 4-byte representation. If ip is not an IPv4 address, To4 returns nil.

+

func (*IP) UnmarshalText 1.2

func (ip *IP) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The IP address is expected in a form accepted by ParseIP.

+

type IPAddr

IPAddr represents the address of an IP end point.

+
type IPAddr struct {
+    IP   IP
+    Zone string // IPv6 scoped addressing zone; added in Go 1.1
+}
+

func ResolveIPAddr

func ResolveIPAddr(network, address string) (*IPAddr, error)

ResolveIPAddr returns an address of IP end point.

+

The network must be an IP network name.

+

If the host in the address parameter is not a literal IP address, ResolveIPAddr resolves the address to an address of IP end point. Otherwise, it parses the address as a literal IP address. The address parameter can use a host name, but this is not recommended, because it will return at most one of the host name's IP addresses.

+

See func Dial for a description of the network and address parameters.

+

func (*IPAddr) Network

func (a *IPAddr) Network() string

Network returns the address's network name, "ip".

+

func (*IPAddr) String

func (a *IPAddr) String() string

type IPConn

IPConn is the implementation of the Conn and PacketConn interfaces for IP network connections.

+
type IPConn struct {
+    // contains filtered or unexported fields
+}
+

func DialIP

func DialIP(network string, laddr, raddr *IPAddr) (*IPConn, error)

DialIP acts like Dial for IP networks.

+

The network must be an IP network name; see func Dial for details.

+

If laddr is nil, a local address is automatically chosen. If the IP field of raddr is nil or an unspecified IP address, the local system is assumed.

+

func ListenIP

func ListenIP(network string, laddr *IPAddr) (*IPConn, error)

ListenIP acts like ListenPacket for IP networks.

+

The network must be an IP network name; see func Dial for details.

+

If the IP field of laddr is nil or an unspecified IP address, ListenIP listens on all available IP addresses of the local system except multicast IP addresses.

+

func (*IPConn) Close

func (c *IPConn) Close() error

Close closes the connection.

+

func (*IPConn) File

func (c *IPConn) File() (f *os.File, err error)

File returns a copy of the underlying os.File. It is the caller's responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.

+

The returned os.File's file descriptor is different from the connection's. Attempting to change properties of the original using this duplicate may or may not have the desired effect.

+

func (*IPConn) LocalAddr

func (c *IPConn) LocalAddr() Addr

LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.

+

func (*IPConn) Read

func (c *IPConn) Read(b []byte) (int, error)

Read implements the Conn Read method.

+

func (*IPConn) ReadFrom

func (c *IPConn) ReadFrom(b []byte) (int, Addr, error)

ReadFrom implements the PacketConn ReadFrom method.

+

func (*IPConn) ReadFromIP

func (c *IPConn) ReadFromIP(b []byte) (int, *IPAddr, error)

ReadFromIP acts like ReadFrom but returns an IPAddr.

+

func (*IPConn) ReadMsgIP 1.1

func (c *IPConn) ReadMsgIP(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error)

ReadMsgIP reads a message from c, copying the payload into b and the associated out-of-band data into oob. It returns the number of bytes copied into b, the number of bytes copied into oob, the flags that were set on the message and the source address of the message.

+

The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

+

func (*IPConn) RemoteAddr

func (c *IPConn) RemoteAddr() Addr

RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.

+

func (*IPConn) SetDeadline

func (c *IPConn) SetDeadline(t time.Time) error

SetDeadline implements the Conn SetDeadline method.

+

func (*IPConn) SetReadBuffer

func (c *IPConn) SetReadBuffer(bytes int) error

SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

+

func (*IPConn) SetReadDeadline

func (c *IPConn) SetReadDeadline(t time.Time) error

SetReadDeadline implements the Conn SetReadDeadline method.

+

func (*IPConn) SetWriteBuffer

func (c *IPConn) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

+

func (*IPConn) SetWriteDeadline

func (c *IPConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements the Conn SetWriteDeadline method.

+

func (*IPConn) SyscallConn 1.9

func (c *IPConn) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

+

func (*IPConn) Write

func (c *IPConn) Write(b []byte) (int, error)

Write implements the Conn Write method.

+

func (*IPConn) WriteMsgIP 1.1

func (c *IPConn) WriteMsgIP(b, oob []byte, addr *IPAddr) (n, oobn int, err error)

WriteMsgIP writes a message to addr via c, copying the payload from b and the associated out-of-band data from oob. It returns the number of payload and out-of-band bytes written.

+

The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

+

func (*IPConn) WriteTo

func (c *IPConn) WriteTo(b []byte, addr Addr) (int, error)

WriteTo implements the PacketConn WriteTo method.

+

func (*IPConn) WriteToIP

func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (int, error)

WriteToIP acts like IPConn.WriteTo but takes an IPAddr.

+

type IPMask

An IPMask is a bitmask that can be used to manipulate IP addresses for IP addressing and routing.

+

See type IPNet and func ParseCIDR for details.

+
type IPMask []byte

func CIDRMask

func CIDRMask(ones, bits int) IPMask

CIDRMask returns an IPMask consisting of 'ones' 1 bits followed by 0s up to a total length of 'bits' bits. For a mask of this form, CIDRMask is the inverse of IPMask.Size.

Example +

Code:

// This mask corresponds to a /31 subnet for IPv4.
+fmt.Println(net.CIDRMask(31, 32))
+
+// This mask corresponds to a /64 subnet for IPv6.
+fmt.Println(net.CIDRMask(64, 128))
+
+

Output:

fffffffe
+ffffffffffffffff0000000000000000
+

func IPv4Mask

func IPv4Mask(a, b, c, d byte) IPMask

IPv4Mask returns the IP mask (in 4-byte form) of the IPv4 mask a.b.c.d.

Example +

Code:

fmt.Println(net.IPv4Mask(255, 255, 255, 0))
+
+

Output:

ffffff00
+

func (IPMask) Size

func (m IPMask) Size() (ones, bits int)

Size returns the number of leading ones and total bits in the mask. If the mask is not in the canonical form--ones followed by zeros--then Size returns 0, 0.

+

func (IPMask) String

func (m IPMask) String() string

String returns the hexadecimal form of m, with no punctuation.

+

type IPNet

An IPNet represents an IP network.

+
type IPNet struct {
+    IP   IP     // network number
+    Mask IPMask // network mask
+}
+

func (*IPNet) Contains

func (n *IPNet) Contains(ip IP) bool

Contains reports whether the network includes ip.

+

func (*IPNet) Network

func (n *IPNet) Network() string

Network returns the address's network name, "ip+net".

+

func (*IPNet) String

func (n *IPNet) String() string

String returns the CIDR notation of n like "192.0.2.0/24" or "2001:db8::/48" as defined in RFC 4632 and RFC 4291. If the mask is not in the canonical form, it returns the string which consists of an IP address, followed by a slash character and a mask expressed as hexadecimal form with no punctuation like "198.51.100.0/c000ff00".

+

type Interface

Interface represents a mapping between network interface name and index. It also represents network interface facility information.

+
type Interface struct {
+    Index        int          // positive integer that starts at one, zero is never used
+    MTU          int          // maximum transmission unit
+    Name         string       // e.g., "en0", "lo0", "eth0.100"
+    HardwareAddr HardwareAddr // IEEE MAC-48, EUI-48 and EUI-64 form
+    Flags        Flags        // e.g., FlagUp, FlagLoopback, FlagMulticast
+}
+

func InterfaceByIndex

func InterfaceByIndex(index int) (*Interface, error)

InterfaceByIndex returns the interface specified by index.

+

On Solaris, it returns one of the logical network interfaces sharing the logical data link; for more precision use InterfaceByName.

+

func InterfaceByName

func InterfaceByName(name string) (*Interface, error)

InterfaceByName returns the interface specified by name.

+

func Interfaces

func Interfaces() ([]Interface, error)

Interfaces returns a list of the system's network interfaces.

+

func (*Interface) Addrs

func (ifi *Interface) Addrs() ([]Addr, error)

Addrs returns a list of unicast interface addresses for a specific interface.

+

func (*Interface) MulticastAddrs

func (ifi *Interface) MulticastAddrs() ([]Addr, error)

MulticastAddrs returns a list of multicast, joined group addresses for a specific interface.

+

type InvalidAddrError

type InvalidAddrError string

func (InvalidAddrError) Error

func (e InvalidAddrError) Error() string

func (InvalidAddrError) Temporary

func (e InvalidAddrError) Temporary() bool

func (InvalidAddrError) Timeout

func (e InvalidAddrError) Timeout() bool

type ListenConfig 1.11

ListenConfig contains options for listening to an address.

+
type ListenConfig struct {
+    // If Control is not nil, it is called after creating the network
+    // connection but before binding it to the operating system.
+    //
+    // Network and address parameters passed to Control method are not
+    // necessarily the ones passed to Listen. For example, passing "tcp" to
+    // Listen will cause the Control function to be called with "tcp4" or "tcp6".
+    Control func(network, address string, c syscall.RawConn) error
+
+    // KeepAlive specifies the keep-alive period for network
+    // connections accepted by this listener.
+    // If zero, keep-alives are enabled if supported by the protocol
+    // and operating system. Network protocols or operating systems
+    // that do not support keep-alives ignore this field.
+    // If negative, keep-alives are disabled.
+    KeepAlive time.Duration // Go 1.13
+    // contains filtered or unexported fields
+}
+

func (*ListenConfig) Listen 1.11

func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error)

Listen announces on the local network address.

+

See func Listen for a description of the network and address parameters.

+

func (*ListenConfig) ListenPacket 1.11

func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error)

ListenPacket announces on the local network address.

+

See func ListenPacket for a description of the network and address parameters.

+

func (*ListenConfig) MultipathTCP 1.21

func (lc *ListenConfig) MultipathTCP() bool

MultipathTCP reports whether MPTCP will be used.

+

This method doesn't check if MPTCP is supported by the operating system or not.

+

func (*ListenConfig) SetMultipathTCP 1.21

func (lc *ListenConfig) SetMultipathTCP(use bool)

SetMultipathTCP directs the Listen method to use, or not use, MPTCP, if supported by the operating system. This method overrides the system default and the GODEBUG=multipathtcp=... setting if any.

+

If MPTCP is not available on the host or not supported by the client, the Listen method will fall back to TCP.

+

type Listener

A Listener is a generic network listener for stream-oriented protocols.

+

Multiple goroutines may invoke methods on a Listener simultaneously.

+
type Listener interface {
+    // Accept waits for and returns the next connection to the listener.
+    Accept() (Conn, error)
+
+    // Close closes the listener.
+    // Any blocked Accept operations will be unblocked and return errors.
+    Close() error
+
+    // Addr returns the listener's network address.
+    Addr() Addr
+}

Example +

Code:

+// Listen on TCP port 2000 on all available unicast and
+// anycast IP addresses of the local system.
+l, err := net.Listen("tcp", ":2000")
+if err != nil {
+    log.Fatal(err)
+}
+defer l.Close()
+for {
+    // Wait for a connection.
+    conn, err := l.Accept()
+    if err != nil {
+        log.Fatal(err)
+    }
+    // Handle the connection in a new goroutine.
+    // The loop then returns to accepting, so that
+    // multiple connections may be served concurrently.
+    go func(c net.Conn) {
+        // Echo all incoming data.
+        io.Copy(c, c)
+        // Shut down the connection.
+        c.Close()
+    }(conn)
+}
+

func FileListener

func FileListener(f *os.File) (ln Listener, err error)

FileListener returns a copy of the network listener corresponding to the open file f. It is the caller's responsibility to close ln when finished. Closing ln does not affect f, and closing f does not affect ln.

+

func Listen

func Listen(network, address string) (Listener, error)

Listen announces on the local network address.

+

The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket".

+

For TCP networks, if the host in the address parameter is empty or a literal unspecified IP address, Listen listens on all available unicast and anycast IP addresses of the local system. To only use IPv4, use network "tcp4". The address can use a host name, but this is not recommended, because it will create a listener for at most one of the host's IP addresses. If the port in the address parameter is empty or "0", as in "127.0.0.1:" or "[::1]:0", a port number is automatically chosen. The Addr method of Listener can be used to discover the chosen port.

+

See func Dial for a description of the network and address parameters.

+

Listen uses context.Background internally; to specify the context, use ListenConfig.Listen.

+

type MX

An MX represents a single DNS MX record.

+
type MX struct {
+    Host string
+    Pref uint16
+}
+

func LookupMX

func LookupMX(name string) ([]*MX, error)

LookupMX returns the DNS MX records for the given domain name sorted by preference.

+

The returned mail server names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

+

LookupMX uses context.Background internally; to specify the context, use Resolver.LookupMX.

+

type NS 1.1

An NS represents a single DNS NS record.

+
type NS struct {
+    Host string
+}
+

func LookupNS 1.1

func LookupNS(name string) ([]*NS, error)

LookupNS returns the DNS NS records for the given domain name.

+

The returned name server names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

+

LookupNS uses context.Background internally; to specify the context, use Resolver.LookupNS.

+

type OpError

OpError is the error type usually returned by functions in the net package. It describes the operation, network type, and address of an error.

+
type OpError struct {
+    // Op is the operation which caused the error, such as
+    // "read" or "write".
+    Op string
+
+    // Net is the network type on which this error occurred,
+    // such as "tcp" or "udp6".
+    Net string
+
+    // For operations involving a remote network connection, like
+    // Dial, Read, or Write, Source is the corresponding local
+    // network address.
+    Source Addr // Go 1.5
+
+    // Addr is the network address for which this error occurred.
+    // For local operations, like Listen or SetDeadline, Addr is
+    // the address of the local endpoint being manipulated.
+    // For operations involving a remote network connection, like
+    // Dial, Read, or Write, Addr is the remote address of that
+    // connection.
+    Addr Addr
+
+    // Err is the error that occurred during the operation.
+    // The Error method panics if the error is nil.
+    Err error
+}
+

func (*OpError) Error

func (e *OpError) Error() string

func (*OpError) Temporary

func (e *OpError) Temporary() bool

func (*OpError) Timeout

func (e *OpError) Timeout() bool

func (*OpError) Unwrap 1.13

func (e *OpError) Unwrap() error

type PacketConn

PacketConn is a generic packet-oriented network connection.

+

Multiple goroutines may invoke methods on a PacketConn simultaneously.

+
type PacketConn interface {
+    // ReadFrom reads a packet from the connection,
+    // copying the payload into p. It returns the number of
+    // bytes copied into p and the return address that
+    // was on the packet.
+    // It returns the number of bytes read (0 <= n <= len(p))
+    // and any error encountered. Callers should always process
+    // the n > 0 bytes returned before considering the error err.
+    // ReadFrom can be made to time out and return an error after a
+    // fixed time limit; see SetDeadline and SetReadDeadline.
+    ReadFrom(p []byte) (n int, addr Addr, err error)
+
+    // WriteTo writes a packet with payload p to addr.
+    // WriteTo can be made to time out and return an Error after a
+    // fixed time limit; see SetDeadline and SetWriteDeadline.
+    // On packet-oriented connections, write timeouts are rare.
+    WriteTo(p []byte, addr Addr) (n int, err error)
+
+    // Close closes the connection.
+    // Any blocked ReadFrom or WriteTo operations will be unblocked and return errors.
+    Close() error
+
+    // LocalAddr returns the local network address, if known.
+    LocalAddr() Addr
+
+    // SetDeadline sets the read and write deadlines associated
+    // with the connection. It is equivalent to calling both
+    // SetReadDeadline and SetWriteDeadline.
+    //
+    // A deadline is an absolute time after which I/O operations
+    // fail instead of blocking. The deadline applies to all future
+    // and pending I/O, not just the immediately following call to
+    // Read or Write. After a deadline has been exceeded, the
+    // connection can be refreshed by setting a deadline in the future.
+    //
+    // If the deadline is exceeded a call to Read or Write or to other
+    // I/O methods will return an error that wraps os.ErrDeadlineExceeded.
+    // This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
+    // The error's Timeout method will return true, but note that there
+    // are other possible errors for which the Timeout method will
+    // return true even if the deadline has not been exceeded.
+    //
+    // An idle timeout can be implemented by repeatedly extending
+    // the deadline after successful ReadFrom or WriteTo calls.
+    //
+    // A zero value for t means I/O operations will not time out.
+    SetDeadline(t time.Time) error
+
+    // SetReadDeadline sets the deadline for future ReadFrom calls
+    // and any currently-blocked ReadFrom call.
+    // A zero value for t means ReadFrom will not time out.
+    SetReadDeadline(t time.Time) error
+
+    // SetWriteDeadline sets the deadline for future WriteTo calls
+    // and any currently-blocked WriteTo call.
+    // Even if write times out, it may return n > 0, indicating that
+    // some of the data was successfully written.
+    // A zero value for t means WriteTo will not time out.
+    SetWriteDeadline(t time.Time) error
+}

func FilePacketConn

func FilePacketConn(f *os.File) (c PacketConn, err error)

FilePacketConn returns a copy of the packet network connection corresponding to the open file f. It is the caller's responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.

+

func ListenPacket

func ListenPacket(network, address string) (PacketConn, error)

ListenPacket announces on the local network address.

+

The network must be "udp", "udp4", "udp6", "unixgram", or an IP transport. The IP transports are "ip", "ip4", or "ip6" followed by a colon and a literal protocol number or a protocol name, as in "ip:1" or "ip:icmp".

+

For UDP and IP networks, if the host in the address parameter is empty or a literal unspecified IP address, ListenPacket listens on all available IP addresses of the local system except multicast IP addresses. To only use IPv4, use network "udp4" or "ip4:proto". The address can use a host name, but this is not recommended, because it will create a listener for at most one of the host's IP addresses. If the port in the address parameter is empty or "0", as in "127.0.0.1:" or "[::1]:0", a port number is automatically chosen. The LocalAddr method of PacketConn can be used to discover the chosen port.

+

See func Dial for a description of the network and address parameters.

+

ListenPacket uses context.Background internally; to specify the context, use ListenConfig.ListenPacket.

+

type ParseError

A ParseError is the error type of literal network address parsers.

+
type ParseError struct {
+    // Type is the type of string that was expected, such as
+    // "IP address", "CIDR address".
+    Type string
+
+    // Text is the malformed text string.
+    Text string
+}
+

func (*ParseError) Error

func (e *ParseError) Error() string

func (*ParseError) Temporary 1.17

func (e *ParseError) Temporary() bool

func (*ParseError) Timeout 1.17

func (e *ParseError) Timeout() bool

type Resolver 1.8

A Resolver looks up names and numbers.

+

A nil *Resolver is equivalent to a zero Resolver.

+
type Resolver struct {
+    // PreferGo controls whether Go's built-in DNS resolver is preferred
+    // on platforms where it's available. It is equivalent to setting
+    // GODEBUG=netdns=go, but scoped to just this resolver.
+    PreferGo bool
+
+    // StrictErrors controls the behavior of temporary errors
+    // (including timeout, socket errors, and SERVFAIL) when using
+    // Go's built-in resolver. For a query composed of multiple
+    // sub-queries (such as an A+AAAA address lookup, or walking the
+    // DNS search list), this option causes such errors to abort the
+    // whole query instead of returning a partial result. This is
+    // not enabled by default because it may affect compatibility
+    // with resolvers that process AAAA queries incorrectly.
+    StrictErrors bool // Go 1.9
+
+    // Dial optionally specifies an alternate dialer for use by
+    // Go's built-in DNS resolver to make TCP and UDP connections
+    // to DNS services. The host in the address parameter will
+    // always be a literal IP address and not a host name, and the
+    // port in the address parameter will be a literal port number
+    // and not a service name.
+    // If the Conn returned is also a PacketConn, sent and received DNS
+    // messages must adhere to RFC 1035 section 4.2.1, "UDP usage".
+    // Otherwise, DNS messages transmitted over Conn must adhere
+    // to RFC 7766 section 5, "Transport Protocol Selection".
+    // If nil, the default dialer is used.
+    Dial func(ctx context.Context, network, address string) (Conn, error) // Go 1.9
+    // contains filtered or unexported fields
+}
+

func (*Resolver) LookupAddr 1.8

func (r *Resolver) LookupAddr(ctx context.Context, addr string) ([]string, error)

LookupAddr performs a reverse lookup for the given address, returning a list of names mapping to that address.

+

The returned names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

+

func (*Resolver) LookupCNAME 1.8

func (r *Resolver) LookupCNAME(ctx context.Context, host string) (string, error)

LookupCNAME returns the canonical name for the given host. Callers that do not care about the canonical name can call LookupHost or LookupIP directly; both take care of resolving the canonical name as part of the lookup.

+

A canonical name is the final name after following zero or more CNAME records. LookupCNAME does not return an error if host does not contain DNS "CNAME" records, as long as host resolves to address records.

+

The returned canonical name is validated to be a properly formatted presentation-format domain name.

+

func (*Resolver) LookupHost 1.8

func (r *Resolver) LookupHost(ctx context.Context, host string) (addrs []string, err error)

LookupHost looks up the given host using the local resolver. It returns a slice of that host's addresses.

+

func (*Resolver) LookupIP 1.15

func (r *Resolver) LookupIP(ctx context.Context, network, host string) ([]IP, error)

LookupIP looks up host for the given network using the local resolver. It returns a slice of that host's IP addresses of the type specified by network. network must be one of "ip", "ip4" or "ip6".

+

func (*Resolver) LookupIPAddr 1.8

func (r *Resolver) LookupIPAddr(ctx context.Context, host string) ([]IPAddr, error)

LookupIPAddr looks up host using the local resolver. It returns a slice of that host's IPv4 and IPv6 addresses.

+

func (*Resolver) LookupMX 1.8

func (r *Resolver) LookupMX(ctx context.Context, name string) ([]*MX, error)

LookupMX returns the DNS MX records for the given domain name sorted by preference.

+

The returned mail server names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

+

func (*Resolver) LookupNS 1.8

func (r *Resolver) LookupNS(ctx context.Context, name string) ([]*NS, error)

LookupNS returns the DNS NS records for the given domain name.

+

The returned name server names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

+

func (*Resolver) LookupNetIP 1.18

func (r *Resolver) LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)

LookupNetIP looks up host using the local resolver. It returns a slice of that host's IP addresses of the type specified by network. The network must be one of "ip", "ip4" or "ip6".

+

func (*Resolver) LookupPort 1.8

func (r *Resolver) LookupPort(ctx context.Context, network, service string) (port int, err error)

LookupPort looks up the port for the given network and service.

+

The network must be one of "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6" or "ip".

+

func (*Resolver) LookupSRV 1.8

func (r *Resolver) LookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error)

LookupSRV tries to resolve an SRV query of the given service, protocol, and domain name. The proto is "tcp" or "udp". The returned records are sorted by priority and randomized by weight within a priority.

+

LookupSRV constructs the DNS name to look up following RFC 2782. That is, it looks up _service._proto.name. To accommodate services publishing SRV records under non-standard names, if both service and proto are empty strings, LookupSRV looks up name directly.

+

The returned service names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

+

func (*Resolver) LookupTXT 1.8

func (r *Resolver) LookupTXT(ctx context.Context, name string) ([]string, error)

LookupTXT returns the DNS TXT records for the given domain name.

+

type SRV

An SRV represents a single DNS SRV record.

+
type SRV struct {
+    Target   string
+    Port     uint16
+    Priority uint16
+    Weight   uint16
+}
+

func LookupSRV

func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error)

LookupSRV tries to resolve an SRV query of the given service, protocol, and domain name. The proto is "tcp" or "udp". The returned records are sorted by priority and randomized by weight within a priority.

+

LookupSRV constructs the DNS name to look up following RFC 2782. That is, it looks up _service._proto.name. To accommodate services publishing SRV records under non-standard names, if both service and proto are empty strings, LookupSRV looks up name directly.

+

The returned service names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

+

type TCPAddr

TCPAddr represents the address of a TCP end point.

+
type TCPAddr struct {
+    IP   IP
+    Port int
+    Zone string // IPv6 scoped addressing zone; added in Go 1.1
+}
+

func ResolveTCPAddr

func ResolveTCPAddr(network, address string) (*TCPAddr, error)

ResolveTCPAddr returns an address of TCP end point.

+

The network must be a TCP network name.

+

If the host in the address parameter is not a literal IP address or the port is not a literal port number, ResolveTCPAddr resolves the address to an address of TCP end point. Otherwise, it parses the address as a pair of literal IP address and port number. The address parameter can use a host name, but this is not recommended, because it will return at most one of the host name's IP addresses.

+

See func Dial for a description of the network and address parameters.

+

func TCPAddrFromAddrPort 1.18

func TCPAddrFromAddrPort(addr netip.AddrPort) *TCPAddr

TCPAddrFromAddrPort returns addr as a TCPAddr. If addr.IsValid() is false, then the returned TCPAddr will contain a nil IP field, indicating an address family-agnostic unspecified address.

+

func (*TCPAddr) AddrPort 1.18

func (a *TCPAddr) AddrPort() netip.AddrPort

AddrPort returns the TCPAddr a as a netip.AddrPort.

+

If a.Port does not fit in a uint16, it's silently truncated.

+

If a is nil, a zero value is returned.

+

func (*TCPAddr) Network

func (a *TCPAddr) Network() string

Network returns the address's network name, "tcp".

+

func (*TCPAddr) String

func (a *TCPAddr) String() string

type TCPConn

TCPConn is an implementation of the Conn interface for TCP network connections.

+
type TCPConn struct {
+    // contains filtered or unexported fields
+}
+

func DialTCP

func DialTCP(network string, laddr, raddr *TCPAddr) (*TCPConn, error)

DialTCP acts like Dial for TCP networks.

+

The network must be a TCP network name; see func Dial for details.

+

If laddr is nil, a local address is automatically chosen. If the IP field of raddr is nil or an unspecified IP address, the local system is assumed.

+

func (*TCPConn) Close

func (c *TCPConn) Close() error

Close closes the connection.

+

func (*TCPConn) CloseRead

func (c *TCPConn) CloseRead() error

CloseRead shuts down the reading side of the TCP connection. Most callers should just use Close.

+

func (*TCPConn) CloseWrite

func (c *TCPConn) CloseWrite() error

CloseWrite shuts down the writing side of the TCP connection. Most callers should just use Close.

+

func (*TCPConn) File

func (c *TCPConn) File() (f *os.File, err error)

File returns a copy of the underlying os.File. It is the caller's responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.

+

The returned os.File's file descriptor is different from the connection's. Attempting to change properties of the original using this duplicate may or may not have the desired effect.

+

func (*TCPConn) LocalAddr

func (c *TCPConn) LocalAddr() Addr

LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.

+

func (*TCPConn) MultipathTCP 1.21

func (c *TCPConn) MultipathTCP() (bool, error)

MultipathTCP reports whether the ongoing connection is using MPTCP.

+

If Multipath TCP is not supported by the host, by the other peer or intentionally / accidentally filtered out by a device in between, a fallback to TCP will be done. This method does its best to check if MPTCP is still being used or not.

+

On Linux, more conditions are verified on kernels >= v5.16, improving the results.

+

func (*TCPConn) Read

func (c *TCPConn) Read(b []byte) (int, error)

Read implements the Conn Read method.

+

func (*TCPConn) ReadFrom

func (c *TCPConn) ReadFrom(r io.Reader) (int64, error)

ReadFrom implements the io.ReaderFrom ReadFrom method.

+

func (*TCPConn) RemoteAddr

func (c *TCPConn) RemoteAddr() Addr

RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.

+

func (*TCPConn) SetDeadline

func (c *TCPConn) SetDeadline(t time.Time) error

SetDeadline implements the Conn SetDeadline method.

+

func (*TCPConn) SetKeepAlive

func (c *TCPConn) SetKeepAlive(keepalive bool) error

SetKeepAlive sets whether the operating system should send keep-alive messages on the connection.

+

func (*TCPConn) SetKeepAlivePeriod 1.2

func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error

SetKeepAlivePeriod sets period between keep-alives.

+

func (*TCPConn) SetLinger

func (c *TCPConn) SetLinger(sec int) error

SetLinger sets the behavior of Close on a connection which still has data waiting to be sent or to be acknowledged.

+

If sec < 0 (the default), the operating system finishes sending the data in the background.

+

If sec == 0, the operating system discards any unsent or unacknowledged data.

+

If sec > 0, the data is sent in the background as with sec < 0. On some operating systems including Linux, this may cause Close to block until all data has been sent or discarded. On some operating systems after sec seconds have elapsed any remaining unsent data may be discarded.

+

func (*TCPConn) SetNoDelay

func (c *TCPConn) SetNoDelay(noDelay bool) error

SetNoDelay controls whether the operating system should delay packet transmission in hopes of sending fewer packets (Nagle's algorithm). The default is true (no delay), meaning that data is sent as soon as possible after a Write.

+

func (*TCPConn) SetReadBuffer

func (c *TCPConn) SetReadBuffer(bytes int) error

SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

+

func (*TCPConn) SetReadDeadline

func (c *TCPConn) SetReadDeadline(t time.Time) error

SetReadDeadline implements the Conn SetReadDeadline method.

+

func (*TCPConn) SetWriteBuffer

func (c *TCPConn) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

+

func (*TCPConn) SetWriteDeadline

func (c *TCPConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements the Conn SetWriteDeadline method.

+

func (*TCPConn) SyscallConn 1.9

func (c *TCPConn) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

+

func (*TCPConn) Write

func (c *TCPConn) Write(b []byte) (int, error)

Write implements the Conn Write method.

+

func (*TCPConn) WriteTo 1.22

func (c *TCPConn) WriteTo(w io.Writer) (int64, error)

WriteTo implements the io.WriterTo WriteTo method.

+

type TCPListener

TCPListener is a TCP network listener. Clients should typically use variables of type Listener instead of assuming TCP.

+
type TCPListener struct {
+    // contains filtered or unexported fields
+}
+

func ListenTCP

func ListenTCP(network string, laddr *TCPAddr) (*TCPListener, error)

ListenTCP acts like Listen for TCP networks.

+

The network must be a TCP network name; see func Dial for details.

+

If the IP field of laddr is nil or an unspecified IP address, ListenTCP listens on all available unicast and anycast IP addresses of the local system. If the Port field of laddr is 0, a port number is automatically chosen.

+

func (*TCPListener) Accept

func (l *TCPListener) Accept() (Conn, error)

Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn.

+

func (*TCPListener) AcceptTCP

func (l *TCPListener) AcceptTCP() (*TCPConn, error)

AcceptTCP accepts the next incoming call and returns the new connection.

+

func (*TCPListener) Addr

func (l *TCPListener) Addr() Addr

Addr returns the listener's network address, a *TCPAddr. The Addr returned is shared by all invocations of Addr, so do not modify it.

+

func (*TCPListener) Close

func (l *TCPListener) Close() error

Close stops listening on the TCP address. Already Accepted connections are not closed.

+

func (*TCPListener) File

func (l *TCPListener) File() (f *os.File, err error)

File returns a copy of the underlying os.File. It is the caller's responsibility to close f when finished. Closing l does not affect f, and closing f does not affect l.

+

The returned os.File's file descriptor is different from the connection's. Attempting to change properties of the original using this duplicate may or may not have the desired effect.

+

func (*TCPListener) SetDeadline

func (l *TCPListener) SetDeadline(t time.Time) error

SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.

+

func (*TCPListener) SyscallConn 1.10

func (l *TCPListener) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

+

The returned RawConn only supports calling Control. Read and Write return an error.

+

type UDPAddr

UDPAddr represents the address of a UDP end point.

+
type UDPAddr struct {
+    IP   IP
+    Port int
+    Zone string // IPv6 scoped addressing zone; added in Go 1.1
+}
+

func ResolveUDPAddr

func ResolveUDPAddr(network, address string) (*UDPAddr, error)

ResolveUDPAddr returns an address of UDP end point.

+

The network must be a UDP network name.

+

If the host in the address parameter is not a literal IP address or the port is not a literal port number, ResolveUDPAddr resolves the address to an address of UDP end point. Otherwise, it parses the address as a pair of literal IP address and port number. The address parameter can use a host name, but this is not recommended, because it will return at most one of the host name's IP addresses.

+

See func Dial for a description of the network and address parameters.

+

func UDPAddrFromAddrPort 1.18

func UDPAddrFromAddrPort(addr netip.AddrPort) *UDPAddr

UDPAddrFromAddrPort returns addr as a UDPAddr. If addr.IsValid() is false, then the returned UDPAddr will contain a nil IP field, indicating an address family-agnostic unspecified address.

+

func (*UDPAddr) AddrPort 1.18

func (a *UDPAddr) AddrPort() netip.AddrPort

AddrPort returns the UDPAddr a as a netip.AddrPort.

+

If a.Port does not fit in a uint16, it's silently truncated.

+

If a is nil, a zero value is returned.

+

func (*UDPAddr) Network

func (a *UDPAddr) Network() string

Network returns the address's network name, "udp".

+

func (*UDPAddr) String

func (a *UDPAddr) String() string

type UDPConn

UDPConn is the implementation of the Conn and PacketConn interfaces for UDP network connections.

+
type UDPConn struct {
+    // contains filtered or unexported fields
+}
+

func DialUDP

func DialUDP(network string, laddr, raddr *UDPAddr) (*UDPConn, error)

DialUDP acts like Dial for UDP networks.

+

The network must be a UDP network name; see func Dial for details.

+

If laddr is nil, a local address is automatically chosen. If the IP field of raddr is nil or an unspecified IP address, the local system is assumed.

+

func ListenMulticastUDP

func ListenMulticastUDP(network string, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error)

ListenMulticastUDP acts like ListenPacket for UDP networks but takes a group address on a specific network interface.

+

The network must be a UDP network name; see func Dial for details.

+

ListenMulticastUDP listens on all available IP addresses of the local system including the group, multicast IP address. If ifi is nil, ListenMulticastUDP uses the system-assigned multicast interface, although this is not recommended because the assignment depends on platforms and sometimes it might require routing configuration. If the Port field of gaddr is 0, a port number is automatically chosen.

+

ListenMulticastUDP is just for convenience of simple, small applications. There are golang.org/x/net/ipv4 and golang.org/x/net/ipv6 packages for general purpose uses.

+

Note that ListenMulticastUDP will set the IP_MULTICAST_LOOP socket option to 0 under IPPROTO_IP, to disable loopback of multicast packets.

+

func ListenUDP

func ListenUDP(network string, laddr *UDPAddr) (*UDPConn, error)

ListenUDP acts like ListenPacket for UDP networks.

+

The network must be a UDP network name; see func Dial for details.

+

If the IP field of laddr is nil or an unspecified IP address, ListenUDP listens on all available IP addresses of the local system except multicast IP addresses. If the Port field of laddr is 0, a port number is automatically chosen.

+

func (*UDPConn) Close

func (c *UDPConn) Close() error

Close closes the connection.

+

func (*UDPConn) File

func (c *UDPConn) File() (f *os.File, err error)

File returns a copy of the underlying os.File. It is the caller's responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.

+

The returned os.File's file descriptor is different from the connection's. Attempting to change properties of the original using this duplicate may or may not have the desired effect.

+

func (*UDPConn) LocalAddr

func (c *UDPConn) LocalAddr() Addr

LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.

+

func (*UDPConn) Read

func (c *UDPConn) Read(b []byte) (int, error)

Read implements the Conn Read method.

+

func (*UDPConn) ReadFrom

func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error)

ReadFrom implements the PacketConn ReadFrom method.

+

func (*UDPConn) ReadFromUDP

func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error)

ReadFromUDP acts like ReadFrom but returns a UDPAddr.

+

func (*UDPConn) ReadFromUDPAddrPort 1.18

func (c *UDPConn) ReadFromUDPAddrPort(b []byte) (n int, addr netip.AddrPort, err error)

ReadFromUDPAddrPort acts like ReadFrom but returns a netip.AddrPort.

+

If c is bound to an unspecified address, the returned netip.AddrPort's address might be an IPv4-mapped IPv6 address. Use netip.Addr.Unmap to get the address without the IPv6 prefix.

+

func (*UDPConn) ReadMsgUDP 1.1

func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)

ReadMsgUDP reads a message from c, copying the payload into b and the associated out-of-band data into oob. It returns the number of bytes copied into b, the number of bytes copied into oob, the flags that were set on the message and the source address of the message.

+

The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

+

func (*UDPConn) ReadMsgUDPAddrPort 1.18

func (c *UDPConn) ReadMsgUDPAddrPort(b, oob []byte) (n, oobn, flags int, addr netip.AddrPort, err error)

ReadMsgUDPAddrPort is like ReadMsgUDP but returns an netip.AddrPort instead of a UDPAddr.

+

func (*UDPConn) RemoteAddr

func (c *UDPConn) RemoteAddr() Addr

RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.

+

func (*UDPConn) SetDeadline

func (c *UDPConn) SetDeadline(t time.Time) error

SetDeadline implements the Conn SetDeadline method.

+

func (*UDPConn) SetReadBuffer

func (c *UDPConn) SetReadBuffer(bytes int) error

SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

+

func (*UDPConn) SetReadDeadline

func (c *UDPConn) SetReadDeadline(t time.Time) error

SetReadDeadline implements the Conn SetReadDeadline method.

+

func (*UDPConn) SetWriteBuffer

func (c *UDPConn) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

+

func (*UDPConn) SetWriteDeadline

func (c *UDPConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements the Conn SetWriteDeadline method.

+

func (*UDPConn) SyscallConn 1.9

func (c *UDPConn) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

+

func (*UDPConn) Write

func (c *UDPConn) Write(b []byte) (int, error)

Write implements the Conn Write method.

+

func (*UDPConn) WriteMsgUDP 1.1

func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobn int, err error)

WriteMsgUDP writes a message to addr via c if c isn't connected, or to c's remote address if c is connected (in which case addr must be nil). The payload is copied from b and the associated out-of-band data is copied from oob. It returns the number of payload and out-of-band bytes written.

+

The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

+

func (*UDPConn) WriteMsgUDPAddrPort 1.18

func (c *UDPConn) WriteMsgUDPAddrPort(b, oob []byte, addr netip.AddrPort) (n, oobn int, err error)

WriteMsgUDPAddrPort is like WriteMsgUDP but takes a netip.AddrPort instead of a UDPAddr.

+

func (*UDPConn) WriteTo

func (c *UDPConn) WriteTo(b []byte, addr Addr) (int, error)

WriteTo implements the PacketConn WriteTo method.

Example +

Code:

+// Unlike Dial, ListenPacket creates a connection without any
+// association with peers.
+conn, err := net.ListenPacket("udp", ":0")
+if err != nil {
+    log.Fatal(err)
+}
+defer conn.Close()
+
+dst, err := net.ResolveUDPAddr("udp", "192.0.2.1:2000")
+if err != nil {
+    log.Fatal(err)
+}
+
+// The connection can write data to the desired address.
+_, err = conn.WriteTo([]byte("data"), dst)
+if err != nil {
+    log.Fatal(err)
+}
+

func (*UDPConn) WriteToUDP

func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (int, error)

WriteToUDP acts like WriteTo but takes a UDPAddr.

+

func (*UDPConn) WriteToUDPAddrPort 1.18

func (c *UDPConn) WriteToUDPAddrPort(b []byte, addr netip.AddrPort) (int, error)

WriteToUDPAddrPort acts like WriteTo but takes a netip.AddrPort.

+

type UnixAddr

UnixAddr represents the address of a Unix domain socket end point.

+
type UnixAddr struct {
+    Name string
+    Net  string
+}
+

func ResolveUnixAddr

func ResolveUnixAddr(network, address string) (*UnixAddr, error)

ResolveUnixAddr returns an address of Unix domain socket end point.

+

The network must be a Unix network name.

+

See func Dial for a description of the network and address parameters.

+

func (*UnixAddr) Network

func (a *UnixAddr) Network() string

Network returns the address's network name, "unix", "unixgram" or "unixpacket".

+

func (*UnixAddr) String

func (a *UnixAddr) String() string

type UnixConn

UnixConn is an implementation of the Conn interface for connections to Unix domain sockets.

+
type UnixConn struct {
+    // contains filtered or unexported fields
+}
+

func DialUnix

func DialUnix(network string, laddr, raddr *UnixAddr) (*UnixConn, error)

DialUnix acts like Dial for Unix networks.

+

The network must be a Unix network name; see func Dial for details.

+

If laddr is non-nil, it is used as the local address for the connection.

+

func ListenUnixgram

func ListenUnixgram(network string, laddr *UnixAddr) (*UnixConn, error)

ListenUnixgram acts like ListenPacket for Unix networks.

+

The network must be "unixgram".

+

func (*UnixConn) Close

func (c *UnixConn) Close() error

Close closes the connection.

+

func (*UnixConn) CloseRead 1.1

func (c *UnixConn) CloseRead() error

CloseRead shuts down the reading side of the Unix domain connection. Most callers should just use Close.

+

func (*UnixConn) CloseWrite 1.1

func (c *UnixConn) CloseWrite() error

CloseWrite shuts down the writing side of the Unix domain connection. Most callers should just use Close.

+

func (*UnixConn) File

func (c *UnixConn) File() (f *os.File, err error)

File returns a copy of the underlying os.File. It is the caller's responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.

+

The returned os.File's file descriptor is different from the connection's. Attempting to change properties of the original using this duplicate may or may not have the desired effect.

+

func (*UnixConn) LocalAddr

func (c *UnixConn) LocalAddr() Addr

LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.

+

func (*UnixConn) Read

func (c *UnixConn) Read(b []byte) (int, error)

Read implements the Conn Read method.

+

func (*UnixConn) ReadFrom

func (c *UnixConn) ReadFrom(b []byte) (int, Addr, error)

ReadFrom implements the PacketConn ReadFrom method.

+

func (*UnixConn) ReadFromUnix

func (c *UnixConn) ReadFromUnix(b []byte) (int, *UnixAddr, error)

ReadFromUnix acts like UnixConn.ReadFrom but returns a UnixAddr.

+

func (*UnixConn) ReadMsgUnix

func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error)

ReadMsgUnix reads a message from c, copying the payload into b and the associated out-of-band data into oob. It returns the number of bytes copied into b, the number of bytes copied into oob, the flags that were set on the message and the source address of the message.

+

Note that if len(b) == 0 and len(oob) > 0, this function will still read (and discard) 1 byte from the connection.

+

func (*UnixConn) RemoteAddr

func (c *UnixConn) RemoteAddr() Addr

RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.

+

func (*UnixConn) SetDeadline

func (c *UnixConn) SetDeadline(t time.Time) error

SetDeadline implements the Conn SetDeadline method.

+

func (*UnixConn) SetReadBuffer

func (c *UnixConn) SetReadBuffer(bytes int) error

SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

+

func (*UnixConn) SetReadDeadline

func (c *UnixConn) SetReadDeadline(t time.Time) error

SetReadDeadline implements the Conn SetReadDeadline method.

+

func (*UnixConn) SetWriteBuffer

func (c *UnixConn) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

+

func (*UnixConn) SetWriteDeadline

func (c *UnixConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements the Conn SetWriteDeadline method.

+

func (*UnixConn) SyscallConn 1.9

func (c *UnixConn) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

+

func (*UnixConn) Write

func (c *UnixConn) Write(b []byte) (int, error)

Write implements the Conn Write method.

+

func (*UnixConn) WriteMsgUnix

func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err error)

WriteMsgUnix writes a message to addr via c, copying the payload from b and the associated out-of-band data from oob. It returns the number of payload and out-of-band bytes written.

+

Note that if len(b) == 0 and len(oob) > 0, this function will still write 1 byte to the connection.

+

func (*UnixConn) WriteTo

func (c *UnixConn) WriteTo(b []byte, addr Addr) (int, error)

WriteTo implements the PacketConn WriteTo method.

+

func (*UnixConn) WriteToUnix

func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (int, error)

WriteToUnix acts like UnixConn.WriteTo but takes a UnixAddr.

+

type UnixListener

UnixListener is a Unix domain socket listener. Clients should typically use variables of type Listener instead of assuming Unix domain sockets.

+
type UnixListener struct {
+    // contains filtered or unexported fields
+}
+

func ListenUnix

func ListenUnix(network string, laddr *UnixAddr) (*UnixListener, error)

ListenUnix acts like Listen for Unix networks.

+

The network must be "unix" or "unixpacket".

+

func (*UnixListener) Accept

func (l *UnixListener) Accept() (Conn, error)

Accept implements the Accept method in the Listener interface. Returned connections will be of type *UnixConn.

+

func (*UnixListener) AcceptUnix

func (l *UnixListener) AcceptUnix() (*UnixConn, error)

AcceptUnix accepts the next incoming call and returns the new connection.

+

func (*UnixListener) Addr

func (l *UnixListener) Addr() Addr

Addr returns the listener's network address. The Addr returned is shared by all invocations of Addr, so do not modify it.

+

func (*UnixListener) Close

func (l *UnixListener) Close() error

Close stops listening on the Unix address. Already accepted connections are not closed.

+

func (*UnixListener) File

func (l *UnixListener) File() (f *os.File, err error)

File returns a copy of the underlying os.File. It is the caller's responsibility to close f when finished. Closing l does not affect f, and closing f does not affect l.

+

The returned os.File's file descriptor is different from the connection's. Attempting to change properties of the original using this duplicate may or may not have the desired effect.

+

func (*UnixListener) SetDeadline

func (l *UnixListener) SetDeadline(t time.Time) error

SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.

+

func (*UnixListener) SetUnlinkOnClose 1.8

func (l *UnixListener) SetUnlinkOnClose(unlink bool)

SetUnlinkOnClose sets whether the underlying socket file should be removed from the file system when the listener is closed.

+

The default behavior is to unlink the socket file only when package net created it. That is, when the listener and the underlying socket file were created by a call to Listen or ListenUnix, then by default closing the listener will remove the socket file. but if the listener was created by a call to FileListener to use an already existing socket file, then by default closing the listener will not remove the socket file.

+

func (*UnixListener) SyscallConn 1.10

func (l *UnixListener) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

+

The returned RawConn only supports calling Control. Read and Write return an error.

+

type UnknownNetworkError

type UnknownNetworkError string

func (UnknownNetworkError) Error

func (e UnknownNetworkError) Error() string

func (UnknownNetworkError) Temporary

func (e UnknownNetworkError) Temporary() bool

func (UnknownNetworkError) Timeout

func (e UnknownNetworkError) Timeout() bool

Bugs

Subdirectories

Name Synopsis
..
http Package http provides HTTP client and server implementations.
cgi Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.
cookiejar Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
fcgi Package fcgi implements the FastCGI protocol.
httptest Package httptest provides utilities for HTTP testing.
httptrace Package httptrace provides mechanisms to trace the events within HTTP client requests.
httputil Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package.
pprof Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
mail Package mail implements parsing of mail messages.
netip Package netip defines an IP address type that's a small value type.
rpc Package rpc provides access to the exported methods of an object across a network or other I/O connection.
jsonrpc Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package.
smtp Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
textproto Package textproto implements generic support for text-based request/response protocols in the style of HTTP, NNTP, and SMTP.
url Package url parses URLs and implements query escaping.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/ +

+
diff --git a/devdocs/go/net%2Fmail%2Findex.html b/devdocs/go/net%2Fmail%2Findex.html new file mode 100644 index 00000000..dced07f0 --- /dev/null +++ b/devdocs/go/net%2Fmail%2Findex.html @@ -0,0 +1,121 @@ +

Package mail

Overview

Package mail implements parsing of mail messages.

+

For the most part, this package follows the syntax as specified by RFC 5322 and extended by RFC 6532. Notable divergences:

+

Index

Examples

ParseAddress
ParseAddressList
ReadMessage

Package files

message.go

Variables

var ErrHeaderNotPresent = errors.New("mail: header not in message")

func ParseDate 1.8

func ParseDate(date string) (time.Time, error)

ParseDate parses an RFC 5322 date string.

+

type Address

Address represents a single mail address. An address such as "Barry Gibbs <bg@example.com>" is represented as Address{Name: "Barry Gibbs", Address: "bg@example.com"}.

+
type Address struct {
+    Name    string // Proper name; may be empty.
+    Address string // user@domain
+}
+

func ParseAddress 1.1

func ParseAddress(address string) (*Address, error)

ParseAddress parses a single RFC 5322 address, e.g. "Barry Gibbs <bg@example.com>"

Example +

Code:

e, err := mail.ParseAddress("Alice <alice@example.com>")
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Println(e.Name, e.Address)
+
+

Output:

Alice alice@example.com
+

func ParseAddressList 1.1

func ParseAddressList(list string) ([]*Address, error)

ParseAddressList parses the given string as a list of addresses.

Example +

Code:

const list = "Alice <alice@example.com>, Bob <bob@example.com>, Eve <eve@example.com>"
+emails, err := mail.ParseAddressList(list)
+if err != nil {
+    log.Fatal(err)
+}
+
+for _, v := range emails {
+    fmt.Println(v.Name, v.Address)
+}
+
+

Output:

Alice alice@example.com
+Bob bob@example.com
+Eve eve@example.com
+

func (*Address) String

func (a *Address) String() string

String formats the address as a valid RFC 5322 address. If the address's name contains non-ASCII characters the name will be rendered according to RFC 2047.

+

type AddressParser 1.5

An AddressParser is an RFC 5322 address parser.

+
type AddressParser struct {
+    // WordDecoder optionally specifies a decoder for RFC 2047 encoded-words.
+    WordDecoder *mime.WordDecoder
+}
+

func (*AddressParser) Parse 1.5

func (p *AddressParser) Parse(address string) (*Address, error)

Parse parses a single RFC 5322 address of the form "Gogh Fir <gf@example.com>" or "foo@example.com".

+

func (*AddressParser) ParseList 1.5

func (p *AddressParser) ParseList(list string) ([]*Address, error)

ParseList parses the given string as a list of comma-separated addresses of the form "Gogh Fir <gf@example.com>" or "foo@example.com".

+

A Header represents the key-value pairs in a mail message header.

+
type Header map[string][]string

func (Header) AddressList

func (h Header) AddressList(key string) ([]*Address, error)

AddressList parses the named header field as a list of addresses.

+

func (Header) Date

func (h Header) Date() (time.Time, error)

Date parses the Date header field.

+

func (Header) Get

func (h Header) Get(key string) string

Get gets the first value associated with the given key. It is case insensitive; CanonicalMIMEHeaderKey is used to canonicalize the provided key. If there are no values associated with the key, Get returns "". To access multiple values of a key, or to use non-canonical keys, access the map directly.

+

type Message

A Message represents a parsed mail message.

+
type Message struct {
+    Header Header
+    Body   io.Reader
+}
+

func ReadMessage

func ReadMessage(r io.Reader) (msg *Message, err error)

ReadMessage reads a message from r. The headers are parsed, and the body of the message will be available for reading from msg.Body.

Example +

Code:

msg := `Date: Mon, 23 Jun 2015 11:40:36 -0400
+From: Gopher <from@example.com>
+To: Another Gopher <to@example.com>
+Subject: Gophers at Gophercon
+
+Message body
+`
+
+r := strings.NewReader(msg)
+m, err := mail.ReadMessage(r)
+if err != nil {
+    log.Fatal(err)
+}
+
+header := m.Header
+fmt.Println("Date:", header.Get("Date"))
+fmt.Println("From:", header.Get("From"))
+fmt.Println("To:", header.Get("To"))
+fmt.Println("Subject:", header.Get("Subject"))
+
+body, err := io.ReadAll(m.Body)
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%s", body)
+
+

Output:

Date: Mon, 23 Jun 2015 11:40:36 -0400
+From: Gopher <from@example.com>
+To: Another Gopher <to@example.com>
+Subject: Gophers at Gophercon
+Message body
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/mail/ +

+
diff --git a/devdocs/go/net%2Fnetip%2Findex.html b/devdocs/go/net%2Fnetip%2Findex.html new file mode 100644 index 00000000..0c7a4bb9 --- /dev/null +++ b/devdocs/go/net%2Fnetip%2Findex.html @@ -0,0 +1,260 @@ +

Package netip

Overview

Package netip defines an IP address type that's a small value type. Building on that Addr type, the package also defines AddrPort (an IP address and a port) and Prefix (an IP address and a bit length prefix).

+

Compared to the net.IP type, Addr type takes less memory, is immutable, and is comparable (supports == and being a map key).

Index

Package files

leaf_alts.go netip.go uint128.go

type Addr 1.18

Addr represents an IPv4 or IPv6 address (with or without a scoped addressing zone), similar to net.IP or net.IPAddr.

+

Unlike net.IP or net.IPAddr, Addr is a comparable value type (it supports == and can be a map key) and is immutable.

+

The zero Addr is not a valid IP address. Addr{} is distinct from both 0.0.0.0 and ::.

+
type Addr struct {
+    // contains filtered or unexported fields
+}
+

func AddrFrom16 1.18

func AddrFrom16(addr [16]byte) Addr

AddrFrom16 returns the IPv6 address given by the bytes in addr. An IPv4-mapped IPv6 address is left as an IPv6 address. (Use Unmap to convert them if needed.)

+

func AddrFrom4 1.18

func AddrFrom4(addr [4]byte) Addr

AddrFrom4 returns the address of the IPv4 address given by the bytes in addr.

+

func AddrFromSlice 1.18

func AddrFromSlice(slice []byte) (ip Addr, ok bool)

AddrFromSlice parses the 4- or 16-byte byte slice as an IPv4 or IPv6 address. Note that a net.IP can be passed directly as the []byte argument. If slice's length is not 4 or 16, AddrFromSlice returns Addr{}, false.

+

func IPv4Unspecified 1.18

func IPv4Unspecified() Addr

IPv4Unspecified returns the IPv4 unspecified address "0.0.0.0".

+

func IPv6LinkLocalAllNodes 1.18

func IPv6LinkLocalAllNodes() Addr

IPv6LinkLocalAllNodes returns the IPv6 link-local all nodes multicast address ff02::1.

+

func IPv6LinkLocalAllRouters 1.20

func IPv6LinkLocalAllRouters() Addr

IPv6LinkLocalAllRouters returns the IPv6 link-local all routers multicast address ff02::2.

+

func IPv6Loopback 1.20

func IPv6Loopback() Addr

IPv6Loopback returns the IPv6 loopback address ::1.

+

func IPv6Unspecified 1.18

func IPv6Unspecified() Addr

IPv6Unspecified returns the IPv6 unspecified address "::".

+

func MustParseAddr 1.18

func MustParseAddr(s string) Addr

MustParseAddr calls ParseAddr(s) and panics on error. It is intended for use in tests with hard-coded strings.

+

func ParseAddr 1.18

func ParseAddr(s string) (Addr, error)

ParseAddr parses s as an IP address, returning the result. The string s can be in dotted decimal ("192.0.2.1"), IPv6 ("2001:db8::68"), or IPv6 with a scoped addressing zone ("fe80::1cc0:3e8c:119f:c2e1%ens18").

+

func (Addr) AppendTo 1.18

func (ip Addr) AppendTo(b []byte) []byte

AppendTo appends a text encoding of ip, as generated by Addr.MarshalText, to b and returns the extended buffer.

+

func (Addr) As16 1.18

func (ip Addr) As16() (a16 [16]byte)

As16 returns the IP address in its 16-byte representation. IPv4 addresses are returned as IPv4-mapped IPv6 addresses. IPv6 addresses with zones are returned without their zone (use the Addr.Zone method to get it). The ip zero value returns all zeroes.

+

func (Addr) As4 1.18

func (ip Addr) As4() (a4 [4]byte)

As4 returns an IPv4 or IPv4-in-IPv6 address in its 4-byte representation. If ip is the zero Addr or an IPv6 address, As4 panics. Note that 0.0.0.0 is not the zero Addr.

+

func (Addr) AsSlice 1.18

func (ip Addr) AsSlice() []byte

AsSlice returns an IPv4 or IPv6 address in its respective 4-byte or 16-byte representation.

+

func (Addr) BitLen 1.18

func (ip Addr) BitLen() int

BitLen returns the number of bits in the IP address: 128 for IPv6, 32 for IPv4, and 0 for the zero Addr.

+

Note that IPv4-mapped IPv6 addresses are considered IPv6 addresses and therefore have bit length 128.

+

func (Addr) Compare 1.18

func (ip Addr) Compare(ip2 Addr) int

Compare returns an integer comparing two IPs. The result will be 0 if ip == ip2, -1 if ip < ip2, and +1 if ip > ip2. The definition of "less than" is the same as the Addr.Less method.

+

func (Addr) Is4 1.18

func (ip Addr) Is4() bool

Is4 reports whether ip is an IPv4 address.

+

It returns false for IPv4-mapped IPv6 addresses. See Addr.Unmap.

+

func (Addr) Is4In6 1.18

func (ip Addr) Is4In6() bool

Is4In6 reports whether ip is an IPv4-mapped IPv6 address.

+

func (Addr) Is6 1.18

func (ip Addr) Is6() bool

Is6 reports whether ip is an IPv6 address, including IPv4-mapped IPv6 addresses.

+

func (Addr) IsGlobalUnicast 1.18

func (ip Addr) IsGlobalUnicast() bool

IsGlobalUnicast reports whether ip is a global unicast address.

+

It returns true for IPv6 addresses which fall outside of the current IANA-allocated 2000::/3 global unicast space, with the exception of the link-local address space. It also returns true even if ip is in the IPv4 private address space or IPv6 unique local address space. It returns false for the zero Addr.

+

For reference, see RFC 1122, RFC 4291, and RFC 4632.

+

func (Addr) IsInterfaceLocalMulticast 1.18

func (ip Addr) IsInterfaceLocalMulticast() bool

IsInterfaceLocalMulticast reports whether ip is an IPv6 interface-local multicast address.

+

func (Addr) IsLinkLocalMulticast 1.18

func (ip Addr) IsLinkLocalMulticast() bool

IsLinkLocalMulticast reports whether ip is a link-local multicast address.

+

func (Addr) IsLinkLocalUnicast 1.18

func (ip Addr) IsLinkLocalUnicast() bool

IsLinkLocalUnicast reports whether ip is a link-local unicast address.

+

func (Addr) IsLoopback 1.18

func (ip Addr) IsLoopback() bool

IsLoopback reports whether ip is a loopback address.

+

func (Addr) IsMulticast 1.18

func (ip Addr) IsMulticast() bool

IsMulticast reports whether ip is a multicast address.

+

func (Addr) IsPrivate 1.18

func (ip Addr) IsPrivate() bool

IsPrivate reports whether ip is a private address, according to RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses). That is, it reports whether ip is in 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, or fc00::/7. This is the same as net.IP.IsPrivate.

+

func (Addr) IsUnspecified 1.18

func (ip Addr) IsUnspecified() bool

IsUnspecified reports whether ip is an unspecified address, either the IPv4 address "0.0.0.0" or the IPv6 address "::".

+

Note that the zero Addr is not an unspecified address.

+

func (Addr) IsValid 1.18

func (ip Addr) IsValid() bool

IsValid reports whether the Addr is an initialized address (not the zero Addr).

+

Note that "0.0.0.0" and "::" are both valid values.

+

func (Addr) Less 1.18

func (ip Addr) Less(ip2 Addr) bool

Less reports whether ip sorts before ip2. IP addresses sort first by length, then their address. IPv6 addresses with zones sort just after the same address without a zone.

+

func (Addr) MarshalBinary 1.18

func (ip Addr) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface. It returns a zero-length slice for the zero Addr, the 4-byte form for an IPv4 address, and the 16-byte form with zone appended for an IPv6 address.

+

func (Addr) MarshalText 1.18

func (ip Addr) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface, The encoding is the same as returned by Addr.String, with one exception: If ip is the zero Addr, the encoding is the empty string.

+

func (Addr) Next 1.18

func (ip Addr) Next() Addr

Next returns the address following ip. If there is none, it returns the zero Addr.

+

func (Addr) Prefix 1.18

func (ip Addr) Prefix(b int) (Prefix, error)

Prefix keeps only the top b bits of IP, producing a Prefix of the specified length. If ip is a zero Addr, Prefix always returns a zero Prefix and a nil error. Otherwise, if bits is less than zero or greater than ip.BitLen(), Prefix returns an error.

+

func (Addr) Prev 1.18

func (ip Addr) Prev() Addr

Prev returns the IP before ip. If there is none, it returns the IP zero value.

+

func (Addr) String 1.18

func (ip Addr) String() string

String returns the string form of the IP address ip. It returns one of 5 forms:

+

Note that unlike package net's IP.String method, IPv4-mapped IPv6 addresses format with a "::ffff:" prefix before the dotted quad.

+

func (Addr) StringExpanded 1.18

func (ip Addr) StringExpanded() string

StringExpanded is like Addr.String but IPv6 addresses are expanded with leading zeroes and no "::" compression. For example, "2001:db8::1" becomes "2001:0db8:0000:0000:0000:0000:0000:0001".

+

func (Addr) Unmap 1.18

func (ip Addr) Unmap() Addr

Unmap returns ip with any IPv4-mapped IPv6 address prefix removed.

+

That is, if ip is an IPv6 address wrapping an IPv4 address, it returns the wrapped IPv4 address. Otherwise it returns ip unmodified.

+

func (*Addr) UnmarshalBinary 1.18

func (ip *Addr) UnmarshalBinary(b []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. It expects data in the form generated by MarshalBinary.

+

func (*Addr) UnmarshalText 1.18

func (ip *Addr) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The IP address is expected in a form accepted by ParseAddr.

+

If text is empty, UnmarshalText sets *ip to the zero Addr and returns no error.

+

func (Addr) WithZone 1.18

func (ip Addr) WithZone(zone string) Addr

WithZone returns an IP that's the same as ip but with the provided zone. If zone is empty, the zone is removed. If ip is an IPv4 address, WithZone is a no-op and returns ip unchanged.

+

func (Addr) Zone 1.18

func (ip Addr) Zone() string

Zone returns ip's IPv6 scoped addressing zone, if any.

+

type AddrPort 1.18

AddrPort is an IP and a port number.

+
type AddrPort struct {
+    // contains filtered or unexported fields
+}
+

func AddrPortFrom 1.18

func AddrPortFrom(ip Addr, port uint16) AddrPort

AddrPortFrom returns an AddrPort with the provided IP and port. It does not allocate.

+

func MustParseAddrPort 1.18

func MustParseAddrPort(s string) AddrPort

MustParseAddrPort calls ParseAddrPort(s) and panics on error. It is intended for use in tests with hard-coded strings.

+

func ParseAddrPort 1.18

func ParseAddrPort(s string) (AddrPort, error)

ParseAddrPort parses s as an AddrPort.

+

It doesn't do any name resolution: both the address and the port must be numeric.

+

func (AddrPort) Addr 1.18

func (p AddrPort) Addr() Addr

Addr returns p's IP address.

+

func (AddrPort) AppendTo 1.18

func (p AddrPort) AppendTo(b []byte) []byte

AppendTo appends a text encoding of p, as generated by AddrPort.MarshalText, to b and returns the extended buffer.

+

func (AddrPort) Compare 1.22

func (p AddrPort) Compare(p2 AddrPort) int

Compare returns an integer comparing two AddrPorts. The result will be 0 if p == p2, -1 if p < p2, and +1 if p > p2. AddrPorts sort first by IP address, then port.

+

func (AddrPort) IsValid 1.18

func (p AddrPort) IsValid() bool

IsValid reports whether p.Addr() is valid. All ports are valid, including zero.

+

func (AddrPort) MarshalBinary 1.18

func (p AddrPort) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface. It returns Addr.MarshalBinary with an additional two bytes appended containing the port in little-endian.

+

func (AddrPort) MarshalText 1.18

func (p AddrPort) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The encoding is the same as returned by AddrPort.String, with one exception: if p.Addr() is the zero Addr, the encoding is the empty string.

+

func (AddrPort) Port 1.18

func (p AddrPort) Port() uint16

Port returns p's port.

+

func (AddrPort) String 1.18

func (p AddrPort) String() string

func (*AddrPort) UnmarshalBinary 1.18

func (p *AddrPort) UnmarshalBinary(b []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. It expects data in the form generated by AddrPort.MarshalBinary.

+

func (*AddrPort) UnmarshalText 1.18

func (p *AddrPort) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The AddrPort is expected in a form generated by AddrPort.MarshalText or accepted by ParseAddrPort.

+

type Prefix 1.18

Prefix is an IP address prefix (CIDR) representing an IP network.

+

The first Prefix.Bits() of Addr() are specified. The remaining bits match any address. The range of Bits() is [0,32] for IPv4 or [0,128] for IPv6.

+
type Prefix struct {
+    // contains filtered or unexported fields
+}
+

func MustParsePrefix 1.18

func MustParsePrefix(s string) Prefix

MustParsePrefix calls ParsePrefix(s) and panics on error. It is intended for use in tests with hard-coded strings.

+

func ParsePrefix 1.18

func ParsePrefix(s string) (Prefix, error)

ParsePrefix parses s as an IP address prefix. The string can be in the form "192.168.1.0/24" or "2001:db8::/32", the CIDR notation defined in RFC 4632 and RFC 4291. IPv6 zones are not permitted in prefixes, and an error will be returned if a zone is present.

+

Note that masked address bits are not zeroed. Use Masked for that.

+

func PrefixFrom 1.18

func PrefixFrom(ip Addr, bits int) Prefix

PrefixFrom returns a Prefix with the provided IP address and bit prefix length.

+

It does not allocate. Unlike Addr.Prefix, PrefixFrom does not mask off the host bits of ip.

+

If bits is less than zero or greater than ip.BitLen, Prefix.Bits will return an invalid value -1.

+

func (Prefix) Addr 1.18

func (p Prefix) Addr() Addr

Addr returns p's IP address.

+

func (Prefix) AppendTo 1.18

func (p Prefix) AppendTo(b []byte) []byte

AppendTo appends a text encoding of p, as generated by Prefix.MarshalText, to b and returns the extended buffer.

+

func (Prefix) Bits 1.18

func (p Prefix) Bits() int

Bits returns p's prefix length.

+

It reports -1 if invalid.

+

func (Prefix) Contains 1.18

func (p Prefix) Contains(ip Addr) bool

Contains reports whether the network p includes ip.

+

An IPv4 address will not match an IPv6 prefix. An IPv4-mapped IPv6 address will not match an IPv4 prefix. A zero-value IP will not match any prefix. If ip has an IPv6 zone, Contains returns false, because Prefixes strip zones.

+

func (Prefix) IsSingleIP 1.18

func (p Prefix) IsSingleIP() bool

IsSingleIP reports whether p contains exactly one IP.

+

func (Prefix) IsValid 1.18

func (p Prefix) IsValid() bool

IsValid reports whether p.Bits() has a valid range for p.Addr(). If p.Addr() is the zero Addr, IsValid returns false. Note that if p is the zero Prefix, then p.IsValid() == false.

+

func (Prefix) MarshalBinary 1.18

func (p Prefix) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface. It returns Addr.MarshalBinary with an additional byte appended containing the prefix bits.

+

func (Prefix) MarshalText 1.18

func (p Prefix) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface, The encoding is the same as returned by Prefix.String, with one exception: If p is the zero value, the encoding is the empty string.

+

func (Prefix) Masked 1.18

func (p Prefix) Masked() Prefix

Masked returns p in its canonical form, with all but the high p.Bits() bits of p.Addr() masked off.

+

If p is zero or otherwise invalid, Masked returns the zero Prefix.

+

func (Prefix) Overlaps 1.18

func (p Prefix) Overlaps(o Prefix) bool

Overlaps reports whether p and o contain any IP addresses in common.

+

If p and o are of different address families or either have a zero IP, it reports false. Like the Contains method, a prefix with an IPv4-mapped IPv6 address is still treated as an IPv6 mask.

+

func (Prefix) String 1.18

func (p Prefix) String() string

String returns the CIDR notation of p: "<ip>/<bits>".

+

func (*Prefix) UnmarshalBinary 1.18

func (p *Prefix) UnmarshalBinary(b []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. It expects data in the form generated by Prefix.MarshalBinary.

+

func (*Prefix) UnmarshalText 1.18

func (p *Prefix) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The IP address is expected in a form accepted by ParsePrefix or generated by Prefix.MarshalText.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/netip/ +

+
diff --git a/devdocs/go/net%2Frpc%2Findex.html b/devdocs/go/net%2Frpc%2Findex.html new file mode 100644 index 00000000..b70617b5 --- /dev/null +++ b/devdocs/go/net%2Frpc%2Findex.html @@ -0,0 +1,218 @@ +

Package rpc

Overview

Package rpc provides access to the exported methods of an object across a network or other I/O connection. A server registers an object, making it visible as a service with the name of the type of the object. After registration, exported methods of the object will be accessible remotely. A server may register multiple objects (services) of different types but it is an error to register multiple objects of the same type.

+

Only methods that satisfy these criteria will be made available for remote access; other methods will be ignored:

+

In effect, the method must look schematically like

+
func (t *T) MethodName(argType T1, replyType *T2) error
+

where T1 and T2 can be marshaled by encoding/gob. These requirements apply even if a different codec is used. (In the future, these requirements may soften for custom codecs.)

+

The method's first argument represents the arguments provided by the caller; the second argument represents the result parameters to be returned to the caller. The method's return value, if non-nil, is passed back as a string that the client sees as if created by errors.New. If an error is returned, the reply parameter will not be sent back to the client.

+

The server may handle requests on a single connection by calling ServeConn. More typically it will create a network listener and call Accept or, for an HTTP listener, HandleHTTP and http.Serve.

+

A client wishing to use the service establishes a connection and then invokes NewClient on the connection. The convenience function Dial (DialHTTP) performs both steps for a raw network connection (an HTTP connection). The resulting Client object has two methods, Call and Go, that specify the service and method to call, a pointer containing the arguments, and a pointer to receive the result parameters.

+

The Call method waits for the remote call to complete while the Go method launches the call asynchronously and signals completion using the Call structure's Done channel.

+

Unless an explicit codec is set up, package encoding/gob is used to transport the data.

+

Here is a simple example. A server wishes to export an object of type Arith:

+
package server
+
+import "errors"
+
+type Args struct {
+	A, B int
+}
+
+type Quotient struct {
+	Quo, Rem int
+}
+
+type Arith int
+
+func (t *Arith) Multiply(args *Args, reply *int) error {
+	*reply = args.A * args.B
+	return nil
+}
+
+func (t *Arith) Divide(args *Args, quo *Quotient) error {
+	if args.B == 0 {
+		return errors.New("divide by zero")
+	}
+	quo.Quo = args.A / args.B
+	quo.Rem = args.A % args.B
+	return nil
+}
+

The server calls (for HTTP service):

+
arith := new(Arith)
+rpc.Register(arith)
+rpc.HandleHTTP()
+l, err := net.Listen("tcp", ":1234")
+if err != nil {
+	log.Fatal("listen error:", err)
+}
+go http.Serve(l, nil)
+

At this point, clients can see a service "Arith" with methods "Arith.Multiply" and "Arith.Divide". To invoke one, a client first dials the server:

+
client, err := rpc.DialHTTP("tcp", serverAddress + ":1234")
+if err != nil {
+	log.Fatal("dialing:", err)
+}
+

Then it can make a remote call:

+
// Synchronous call
+args := &server.Args{7,8}
+var reply int
+err = client.Call("Arith.Multiply", args, &reply)
+if err != nil {
+	log.Fatal("arith error:", err)
+}
+fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply)
+

or

+
// Asynchronous call
+quotient := new(Quotient)
+divCall := client.Go("Arith.Divide", args, quotient, nil)
+replyCall := <-divCall.Done	// will be equal to divCall
+// check errors, print, etc.
+

A server implementation will often provide a simple, type-safe wrapper for the client.

+

The net/rpc package is frozen and is not accepting new features.

Index

Package files

client.go debug.go server.go

Constants

const (
+    // Defaults used by HandleHTTP
+    DefaultRPCPath   = "/_goRPC_"
+    DefaultDebugPath = "/debug/rpc"
+)

Variables

DefaultServer is the default instance of *Server.

+
var DefaultServer = NewServer()
var ErrShutdown = errors.New("connection is shut down")

func Accept

func Accept(lis net.Listener)

Accept accepts connections on the listener and serves requests to DefaultServer for each incoming connection. Accept blocks; the caller typically invokes it in a go statement.

+

func HandleHTTP

func HandleHTTP()

HandleHTTP registers an HTTP handler for RPC messages to DefaultServer on DefaultRPCPath and a debugging handler on DefaultDebugPath. It is still necessary to invoke http.Serve(), typically in a go statement.

+

func Register

func Register(rcvr any) error

Register publishes the receiver's methods in the DefaultServer.

+

func RegisterName

func RegisterName(name string, rcvr any) error

RegisterName is like Register but uses the provided name for the type instead of the receiver's concrete type.

+

func ServeCodec

func ServeCodec(codec ServerCodec)

ServeCodec is like ServeConn but uses the specified codec to decode requests and encode responses.

+

func ServeConn

func ServeConn(conn io.ReadWriteCloser)

ServeConn runs the DefaultServer on a single connection. ServeConn blocks, serving the connection until the client hangs up. The caller typically invokes ServeConn in a go statement. ServeConn uses the gob wire format (see package gob) on the connection. To use an alternate codec, use ServeCodec. See NewClient's comment for information about concurrent access.

+

func ServeRequest

func ServeRequest(codec ServerCodec) error

ServeRequest is like ServeCodec but synchronously serves a single request. It does not close the codec upon completion.

+

type Call

Call represents an active RPC.

+
type Call struct {
+    ServiceMethod string     // The name of the service and method to call.
+    Args          any        // The argument to the function (*struct).
+    Reply         any        // The reply from the function (*struct).
+    Error         error      // After completion, the error status.
+    Done          chan *Call // Receives *Call when Go is complete.
+}
+

type Client

Client represents an RPC Client. There may be multiple outstanding Calls associated with a single Client, and a Client may be used by multiple goroutines simultaneously.

+
type Client struct {
+    // contains filtered or unexported fields
+}
+

func Dial

func Dial(network, address string) (*Client, error)

Dial connects to an RPC server at the specified network address.

+

func DialHTTP

func DialHTTP(network, address string) (*Client, error)

DialHTTP connects to an HTTP RPC server at the specified network address listening on the default HTTP RPC path.

+

func DialHTTPPath

func DialHTTPPath(network, address, path string) (*Client, error)

DialHTTPPath connects to an HTTP RPC server at the specified network address and path.

+

func NewClient

func NewClient(conn io.ReadWriteCloser) *Client

NewClient returns a new Client to handle requests to the set of services at the other end of the connection. It adds a buffer to the write side of the connection so the header and payload are sent as a unit.

+

The read and write halves of the connection are serialized independently, so no interlocking is required. However each half may be accessed concurrently so the implementation of conn should protect against concurrent reads or concurrent writes.

+

func NewClientWithCodec

func NewClientWithCodec(codec ClientCodec) *Client

NewClientWithCodec is like NewClient but uses the specified codec to encode requests and decode responses.

+

func (*Client) Call

func (client *Client) Call(serviceMethod string, args any, reply any) error

Call invokes the named function, waits for it to complete, and returns its error status.

+

func (*Client) Close

func (client *Client) Close() error

Close calls the underlying codec's Close method. If the connection is already shutting down, ErrShutdown is returned.

+

func (*Client) Go

func (client *Client) Go(serviceMethod string, args any, reply any, done chan *Call) *Call

Go invokes the function asynchronously. It returns the Call structure representing the invocation. The done channel will signal when the call is complete by returning the same Call object. If done is nil, Go will allocate a new channel. If non-nil, done must be buffered or Go will deliberately crash.

+

type ClientCodec

A ClientCodec implements writing of RPC requests and reading of RPC responses for the client side of an RPC session. The client calls [ClientCodec.WriteRequest] to write a request to the connection and calls [ClientCodec.ReadResponseHeader] and [ClientCodec.ReadResponseBody] in pairs to read responses. The client calls [ClientCodec.Close] when finished with the connection. ReadResponseBody may be called with a nil argument to force the body of the response to be read and then discarded. See NewClient's comment for information about concurrent access.

+
type ClientCodec interface {
+    WriteRequest(*Request, any) error
+    ReadResponseHeader(*Response) error
+    ReadResponseBody(any) error
+
+    Close() error
+}

type Request

Request is a header written before every RPC call. It is used internally but documented here as an aid to debugging, such as when analyzing network traffic.

+
type Request struct {
+    ServiceMethod string // format: "Service.Method"
+    Seq           uint64 // sequence number chosen by client
+    // contains filtered or unexported fields
+}
+

type Response

Response is a header written before every RPC return. It is used internally but documented here as an aid to debugging, such as when analyzing network traffic.

+
type Response struct {
+    ServiceMethod string // echoes that of the Request
+    Seq           uint64 // echoes that of the request
+    Error         string // error, if any.
+    // contains filtered or unexported fields
+}
+

type Server

Server represents an RPC Server.

+
type Server struct {
+    // contains filtered or unexported fields
+}
+

func NewServer

func NewServer() *Server

NewServer returns a new Server.

+

func (*Server) Accept

func (server *Server) Accept(lis net.Listener)

Accept accepts connections on the listener and serves requests for each incoming connection. Accept blocks until the listener returns a non-nil error. The caller typically invokes Accept in a go statement.

+

func (*Server) HandleHTTP

func (server *Server) HandleHTTP(rpcPath, debugPath string)

HandleHTTP registers an HTTP handler for RPC messages on rpcPath, and a debugging handler on debugPath. It is still necessary to invoke http.Serve(), typically in a go statement.

+

func (*Server) Register

func (server *Server) Register(rcvr any) error

Register publishes in the server the set of methods of the receiver value that satisfy the following conditions:

+

It returns an error if the receiver is not an exported type or has no suitable methods. It also logs the error using package log. The client accesses each method using a string of the form "Type.Method", where Type is the receiver's concrete type.

+

func (*Server) RegisterName

func (server *Server) RegisterName(name string, rcvr any) error

RegisterName is like Register but uses the provided name for the type instead of the receiver's concrete type.

+

func (*Server) ServeCodec

func (server *Server) ServeCodec(codec ServerCodec)

ServeCodec is like ServeConn but uses the specified codec to decode requests and encode responses.

+

func (*Server) ServeConn

func (server *Server) ServeConn(conn io.ReadWriteCloser)

ServeConn runs the server on a single connection. ServeConn blocks, serving the connection until the client hangs up. The caller typically invokes ServeConn in a go statement. ServeConn uses the gob wire format (see package gob) on the connection. To use an alternate codec, use ServeCodec. See NewClient's comment for information about concurrent access.

+

func (*Server) ServeHTTP

func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements an http.Handler that answers RPC requests.

+

func (*Server) ServeRequest

func (server *Server) ServeRequest(codec ServerCodec) error

ServeRequest is like ServeCodec but synchronously serves a single request. It does not close the codec upon completion.

+

type ServerCodec

A ServerCodec implements reading of RPC requests and writing of RPC responses for the server side of an RPC session. The server calls [ServerCodec.ReadRequestHeader] and [ServerCodec.ReadRequestBody] in pairs to read requests from the connection, and it calls [ServerCodec.WriteResponse] to write a response back. The server calls [ServerCodec.Close] when finished with the connection. ReadRequestBody may be called with a nil argument to force the body of the request to be read and discarded. See NewClient's comment for information about concurrent access.

+
type ServerCodec interface {
+    ReadRequestHeader(*Request) error
+    ReadRequestBody(any) error
+    WriteResponse(*Response, any) error
+
+    // Close can be called multiple times and must be idempotent.
+    Close() error
+}

type ServerError

ServerError represents an error that has been returned from the remote side of the RPC connection.

+
type ServerError string

func (ServerError) Error

func (e ServerError) Error() string

Subdirectories

Name Synopsis
..
jsonrpc Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/rpc/ +

+
diff --git a/devdocs/go/net%2Frpc%2Fjsonrpc%2Findex.html b/devdocs/go/net%2Frpc%2Fjsonrpc%2Findex.html new file mode 100644 index 00000000..8a32f580 --- /dev/null +++ b/devdocs/go/net%2Frpc%2Fjsonrpc%2Findex.html @@ -0,0 +1,20 @@ +

Package jsonrpc

Overview

Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package. For JSON-RPC 2.0 support, see https://godoc.org/?q=json-rpc+2.0

Index

Package files

client.go server.go

func Dial

func Dial(network, address string) (*rpc.Client, error)

Dial connects to a JSON-RPC server at the specified network address.

+

func NewClient

func NewClient(conn io.ReadWriteCloser) *rpc.Client

NewClient returns a new rpc.Client to handle requests to the set of services at the other end of the connection.

+

func NewClientCodec

func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec

NewClientCodec returns a new rpc.ClientCodec using JSON-RPC on conn.

+

func NewServerCodec

func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec

NewServerCodec returns a new rpc.ServerCodec using JSON-RPC on conn.

+

func ServeConn

func ServeConn(conn io.ReadWriteCloser)

ServeConn runs the JSON-RPC server on a single connection. ServeConn blocks, serving the connection until the client hangs up. The caller typically invokes ServeConn in a go statement.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/rpc/jsonrpc/ +

+
diff --git a/devdocs/go/net%2Fsmtp%2Findex.html b/devdocs/go/net%2Fsmtp%2Findex.html new file mode 100644 index 00000000..83ae06f8 --- /dev/null +++ b/devdocs/go/net%2Fsmtp%2Findex.html @@ -0,0 +1,168 @@ +

Package smtp

Overview

Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321. It also implements the following extensions:

+
8BITMIME  RFC 1652
+AUTH      RFC 2554
+STARTTLS  RFC 3207
+

Additional extensions may be handled by clients.

+

The smtp package is frozen and is not accepting new features. Some external packages provide more functionality. See:

+
https://godoc.org/?q=smtp
+

Example +

Code:

+// Connect to the remote SMTP server.
+c, err := smtp.Dial("mail.example.com:25")
+if err != nil {
+    log.Fatal(err)
+}
+
+// Set the sender and recipient first
+if err := c.Mail("sender@example.org"); err != nil {
+    log.Fatal(err)
+}
+if err := c.Rcpt("recipient@example.net"); err != nil {
+    log.Fatal(err)
+}
+
+// Send the email body.
+wc, err := c.Data()
+if err != nil {
+    log.Fatal(err)
+}
+_, err = fmt.Fprintf(wc, "This is the email body")
+if err != nil {
+    log.Fatal(err)
+}
+err = wc.Close()
+if err != nil {
+    log.Fatal(err)
+}
+
+// Send the QUIT command and close the connection.
+err = c.Quit()
+if err != nil {
+    log.Fatal(err)
+}
+

Index

Examples

Package
PlainAuth
SendMail

Package files

auth.go smtp.go

func SendMail

func SendMail(addr string, a Auth, from string, to []string, msg []byte) error

SendMail connects to the server at addr, switches to TLS if possible, authenticates with the optional mechanism a if possible, and then sends an email from address from, to addresses to, with message msg. The addr must include a port, as in "mail.example.com:smtp".

+

The addresses in the to parameter are the SMTP RCPT addresses.

+

The msg parameter should be an RFC 822-style email with headers first, a blank line, and then the message body. The lines of msg should be CRLF terminated. The msg headers should usually include fields such as "From", "To", "Subject", and "Cc". Sending "Bcc" messages is accomplished by including an email address in the to parameter but not including it in the msg headers.

+

The SendMail function and the net/smtp package are low-level mechanisms and provide no support for DKIM signing, MIME attachments (see the mime/multipart package), or other mail functionality. Higher-level packages exist outside of the standard library.

Example +

Code:

+// Set up authentication information.
+auth := smtp.PlainAuth("", "user@example.com", "password", "mail.example.com")
+
+// Connect to the server, authenticate, set the sender and recipient,
+// and send the email all in one step.
+to := []string{"recipient@example.net"}
+msg := []byte("To: recipient@example.net\r\n" +
+    "Subject: discount Gophers!\r\n" +
+    "\r\n" +
+    "This is the email body.\r\n")
+err := smtp.SendMail("mail.example.com:25", auth, "sender@example.org", to, msg)
+if err != nil {
+    log.Fatal(err)
+}
+

type Auth

Auth is implemented by an SMTP authentication mechanism.

+
type Auth interface {
+    // Start begins an authentication with a server.
+    // It returns the name of the authentication protocol
+    // and optionally data to include in the initial AUTH message
+    // sent to the server.
+    // If it returns a non-nil error, the SMTP client aborts
+    // the authentication attempt and closes the connection.
+    Start(server *ServerInfo) (proto string, toServer []byte, err error)
+
+    // Next continues the authentication. The server has just sent
+    // the fromServer data. If more is true, the server expects a
+    // response, which Next should return as toServer; otherwise
+    // Next should return toServer == nil.
+    // If Next returns a non-nil error, the SMTP client aborts
+    // the authentication attempt and closes the connection.
+    Next(fromServer []byte, more bool) (toServer []byte, err error)
+}

func CRAMMD5Auth

func CRAMMD5Auth(username, secret string) Auth

CRAMMD5Auth returns an Auth that implements the CRAM-MD5 authentication mechanism as defined in RFC 2195. The returned Auth uses the given username and secret to authenticate to the server using the challenge-response mechanism.

+

func PlainAuth

func PlainAuth(identity, username, password, host string) Auth

PlainAuth returns an Auth that implements the PLAIN authentication mechanism as defined in RFC 4616. The returned Auth uses the given username and password to authenticate to host and act as identity. Usually identity should be the empty string, to act as username.

+

PlainAuth will only send the credentials if the connection is using TLS or is connected to localhost. Otherwise authentication will fail with an error, without sending the credentials.

Example +

Code:

+// hostname is used by PlainAuth to validate the TLS certificate.
+hostname := "mail.example.com"
+auth := smtp.PlainAuth("", "user@example.com", "password", hostname)
+
+err := smtp.SendMail(hostname+":25", auth, from, recipients, msg)
+if err != nil {
+    log.Fatal(err)
+}
+

type Client

A Client represents a client connection to an SMTP server.

+
type Client struct {
+    // Text is the textproto.Conn used by the Client. It is exported to allow for
+    // clients to add extensions.
+    Text *textproto.Conn
+    // contains filtered or unexported fields
+}
+

func Dial

func Dial(addr string) (*Client, error)

Dial returns a new Client connected to an SMTP server at addr. The addr must include a port, as in "mail.example.com:smtp".

+

func NewClient

func NewClient(conn net.Conn, host string) (*Client, error)

NewClient returns a new Client using an existing connection and host as a server name to be used when authenticating.

+

func (*Client) Auth

func (c *Client) Auth(a Auth) error

Auth authenticates a client using the provided authentication mechanism. A failed authentication closes the connection. Only servers that advertise the AUTH extension support this function.

+

func (*Client) Close 1.2

func (c *Client) Close() error

Close closes the connection.

+

func (*Client) Data

func (c *Client) Data() (io.WriteCloser, error)

Data issues a DATA command to the server and returns a writer that can be used to write the mail headers and body. The caller should close the writer before calling any more methods on c. A call to Data must be preceded by one or more calls to Client.Rcpt.

+

func (*Client) Extension

func (c *Client) Extension(ext string) (bool, string)

Extension reports whether an extension is support by the server. The extension name is case-insensitive. If the extension is supported, Extension also returns a string that contains any parameters the server specifies for the extension.

+

func (*Client) Hello 1.1

func (c *Client) Hello(localName string) error

Hello sends a HELO or EHLO to the server as the given host name. Calling this method is only necessary if the client needs control over the host name used. The client will introduce itself as "localhost" automatically otherwise. If Hello is called, it must be called before any of the other methods.

+

func (*Client) Mail

func (c *Client) Mail(from string) error

Mail issues a MAIL command to the server using the provided email address. If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME parameter. If the server supports the SMTPUTF8 extension, Mail adds the SMTPUTF8 parameter. This initiates a mail transaction and is followed by one or more Client.Rcpt calls.

+

func (*Client) Noop 1.10

func (c *Client) Noop() error

Noop sends the NOOP command to the server. It does nothing but check that the connection to the server is okay.

+

func (*Client) Quit

func (c *Client) Quit() error

Quit sends the QUIT command and closes the connection to the server.

+

func (*Client) Rcpt

func (c *Client) Rcpt(to string) error

Rcpt issues a RCPT command to the server using the provided email address. A call to Rcpt must be preceded by a call to Client.Mail and may be followed by a Client.Data call or another Rcpt call.

+

func (*Client) Reset

func (c *Client) Reset() error

Reset sends the RSET command to the server, aborting the current mail transaction.

+

func (*Client) StartTLS

func (c *Client) StartTLS(config *tls.Config) error

StartTLS sends the STARTTLS command and encrypts all further communication. Only servers that advertise the STARTTLS extension support this function.

+

func (*Client) TLSConnectionState 1.5

func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool)

TLSConnectionState returns the client's TLS connection state. The return values are their zero values if Client.StartTLS did not succeed.

+

func (*Client) Verify

func (c *Client) Verify(addr string) error

Verify checks the validity of an email address on the server. If Verify returns nil, the address is valid. A non-nil return does not necessarily indicate an invalid address. Many servers will not verify addresses for security reasons.

+

type ServerInfo

ServerInfo records information about an SMTP server.

+
type ServerInfo struct {
+    Name string   // SMTP server name
+    TLS  bool     // using TLS, with valid certificate for Name
+    Auth []string // advertised authentication mechanisms
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/smtp/ +

+
diff --git a/devdocs/go/net%2Ftextproto%2Findex.html b/devdocs/go/net%2Ftextproto%2Findex.html new file mode 100644 index 00000000..5e4c4cab --- /dev/null +++ b/devdocs/go/net%2Ftextproto%2Findex.html @@ -0,0 +1,213 @@ +

Package textproto

Overview

Package textproto implements generic support for text-based request/response protocols in the style of HTTP, NNTP, and SMTP.

+

The package provides:

+

Error, which represents a numeric error response from a server.

+

Pipeline, to manage pipelined requests and responses in a client.

+

Reader, to read numeric response code lines, key: value headers, lines wrapped with leading spaces on continuation lines, and whole text blocks ending with a dot on a line by itself.

+

Writer, to write dot-encoded text blocks.

+

Conn, a convenient packaging of Reader, Writer, and Pipeline for use with a single network connection.

Index

Package files

header.go pipeline.go reader.go textproto.go writer.go

func CanonicalMIMEHeaderKey

func CanonicalMIMEHeaderKey(s string) string

CanonicalMIMEHeaderKey returns the canonical format of the MIME header key s. The canonicalization converts the first letter and any letter following a hyphen to upper case; the rest are converted to lowercase. For example, the canonical key for "accept-encoding" is "Accept-Encoding". MIME header keys are assumed to be ASCII only. If s contains a space or invalid header field bytes, it is returned without modifications.

+

func TrimBytes 1.1

func TrimBytes(b []byte) []byte

TrimBytes returns b without leading and trailing ASCII space.

+

func TrimString 1.1

func TrimString(s string) string

TrimString returns s without leading and trailing ASCII space.

+

type Conn

A Conn represents a textual network protocol connection. It consists of a Reader and Writer to manage I/O and a Pipeline to sequence concurrent requests on the connection. These embedded types carry methods with them; see the documentation of those types for details.

+
type Conn struct {
+    Reader
+    Writer
+    Pipeline
+    // contains filtered or unexported fields
+}
+

func Dial

func Dial(network, addr string) (*Conn, error)

Dial connects to the given address on the given network using net.Dial and then returns a new Conn for the connection.

+

func NewConn

func NewConn(conn io.ReadWriteCloser) *Conn

NewConn returns a new Conn using conn for I/O.

+

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection.

+

func (*Conn) Cmd

func (c *Conn) Cmd(format string, args ...any) (id uint, err error)

Cmd is a convenience method that sends a command after waiting its turn in the pipeline. The command text is the result of formatting format with args and appending \r\n. Cmd returns the id of the command, for use with StartResponse and EndResponse.

+

For example, a client might run a HELP command that returns a dot-body by using:

+
id, err := c.Cmd("HELP")
+if err != nil {
+	return nil, err
+}
+
+c.StartResponse(id)
+defer c.EndResponse(id)
+
+if _, _, err = c.ReadCodeLine(110); err != nil {
+	return nil, err
+}
+text, err := c.ReadDotBytes()
+if err != nil {
+	return nil, err
+}
+return c.ReadCodeLine(250)
+

type Error

An Error represents a numeric error response from a server.

+
type Error struct {
+    Code int
+    Msg  string
+}
+

func (*Error) Error

func (e *Error) Error() string

type MIMEHeader

A MIMEHeader represents a MIME-style header mapping keys to sets of values.

+
type MIMEHeader map[string][]string

func (MIMEHeader) Add

func (h MIMEHeader) Add(key, value string)

Add adds the key, value pair to the header. It appends to any existing values associated with key.

+

func (MIMEHeader) Del

func (h MIMEHeader) Del(key string)

Del deletes the values associated with key.

+

func (MIMEHeader) Get

func (h MIMEHeader) Get(key string) string

Get gets the first value associated with the given key. It is case insensitive; CanonicalMIMEHeaderKey is used to canonicalize the provided key. If there are no values associated with the key, Get returns "". To use non-canonical keys, access the map directly.

+

func (MIMEHeader) Set

func (h MIMEHeader) Set(key, value string)

Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key.

+

func (MIMEHeader) Values 1.14

func (h MIMEHeader) Values(key string) []string

Values returns all values associated with the given key. It is case insensitive; CanonicalMIMEHeaderKey is used to canonicalize the provided key. To use non-canonical keys, access the map directly. The returned slice is not a copy.

+

type Pipeline

A Pipeline manages a pipelined in-order request/response sequence.

+

To use a Pipeline p to manage multiple clients on a connection, each client should run:

+
id := p.Next()	// take a number
+
+p.StartRequest(id)	// wait for turn to send request
+«send request»
+p.EndRequest(id)	// notify Pipeline that request is sent
+
+p.StartResponse(id)	// wait for turn to read response
+«read response»
+p.EndResponse(id)	// notify Pipeline that response is read
+

A pipelined server can use the same calls to ensure that responses computed in parallel are written in the correct order.

+
type Pipeline struct {
+    // contains filtered or unexported fields
+}
+

func (*Pipeline) EndRequest

func (p *Pipeline) EndRequest(id uint)

EndRequest notifies p that the request with the given id has been sent (or, if this is a server, received).

+

func (*Pipeline) EndResponse

func (p *Pipeline) EndResponse(id uint)

EndResponse notifies p that the response with the given id has been received (or, if this is a server, sent).

+

func (*Pipeline) Next

func (p *Pipeline) Next() uint

Next returns the next id for a request/response pair.

+

func (*Pipeline) StartRequest

func (p *Pipeline) StartRequest(id uint)

StartRequest blocks until it is time to send (or, if this is a server, receive) the request with the given id.

+

func (*Pipeline) StartResponse

func (p *Pipeline) StartResponse(id uint)

StartResponse blocks until it is time to receive (or, if this is a server, send) the request with the given id.

+

type ProtocolError

A ProtocolError describes a protocol violation such as an invalid response or a hung-up connection.

+
type ProtocolError string

func (ProtocolError) Error

func (p ProtocolError) Error() string

type Reader

A Reader implements convenience methods for reading requests or responses from a text protocol network connection.

+
type Reader struct {
+    R *bufio.Reader
+    // contains filtered or unexported fields
+}
+

func NewReader

func NewReader(r *bufio.Reader) *Reader

NewReader returns a new Reader reading from r.

+

To avoid denial of service attacks, the provided bufio.Reader should be reading from an io.LimitReader or similar Reader to bound the size of responses.

+

func (*Reader) DotReader

func (r *Reader) DotReader() io.Reader

DotReader returns a new Reader that satisfies Reads using the decoded text of a dot-encoded block read from r. The returned Reader is only valid until the next call to a method on r.

+

Dot encoding is a common framing used for data blocks in text protocols such as SMTP. The data consists of a sequence of lines, each of which ends in "\r\n". The sequence itself ends at a line containing just a dot: ".\r\n". Lines beginning with a dot are escaped with an additional dot to avoid looking like the end of the sequence.

+

The decoded form returned by the Reader's Read method rewrites the "\r\n" line endings into the simpler "\n", removes leading dot escapes if present, and stops with error io.EOF after consuming (and discarding) the end-of-sequence line.

+

func (*Reader) ReadCodeLine

func (r *Reader) ReadCodeLine(expectCode int) (code int, message string, err error)

ReadCodeLine reads a response code line of the form

+
code message
+

where code is a three-digit status code and the message extends to the rest of the line. An example of such a line is:

+
220 plan9.bell-labs.com ESMTP
+

If the prefix of the status does not match the digits in expectCode, ReadCodeLine returns with err set to &Error{code, message}. For example, if expectCode is 31, an error will be returned if the status is not in the range [310,319].

+

If the response is multi-line, ReadCodeLine returns an error.

+

An expectCode <= 0 disables the check of the status code.

+

func (*Reader) ReadContinuedLine

func (r *Reader) ReadContinuedLine() (string, error)

ReadContinuedLine reads a possibly continued line from r, eliding the final trailing ASCII white space. Lines after the first are considered continuations if they begin with a space or tab character. In the returned data, continuation lines are separated from the previous line only by a single space: the newline and leading white space are removed.

+

For example, consider this input:

+
Line 1
+  continued...
+Line 2
+

The first call to ReadContinuedLine will return "Line 1 continued..." and the second will return "Line 2".

+

Empty lines are never continued.

+

func (*Reader) ReadContinuedLineBytes

func (r *Reader) ReadContinuedLineBytes() ([]byte, error)

ReadContinuedLineBytes is like Reader.ReadContinuedLine but returns a []byte instead of a string.

+

func (*Reader) ReadDotBytes

func (r *Reader) ReadDotBytes() ([]byte, error)

ReadDotBytes reads a dot-encoding and returns the decoded data.

+

See the documentation for the Reader.DotReader method for details about dot-encoding.

+

func (*Reader) ReadDotLines

func (r *Reader) ReadDotLines() ([]string, error)

ReadDotLines reads a dot-encoding and returns a slice containing the decoded lines, with the final \r\n or \n elided from each.

+

See the documentation for the Reader.DotReader method for details about dot-encoding.

+

func (*Reader) ReadLine

func (r *Reader) ReadLine() (string, error)

ReadLine reads a single line from r, eliding the final \n or \r\n from the returned string.

+

func (*Reader) ReadLineBytes

func (r *Reader) ReadLineBytes() ([]byte, error)

ReadLineBytes is like Reader.ReadLine but returns a []byte instead of a string.

+

func (*Reader) ReadMIMEHeader

func (r *Reader) ReadMIMEHeader() (MIMEHeader, error)

ReadMIMEHeader reads a MIME-style header from r. The header is a sequence of possibly continued Key: Value lines ending in a blank line. The returned map m maps CanonicalMIMEHeaderKey(key) to a sequence of values in the same order encountered in the input.

+

For example, consider this input:

+
My-Key: Value 1
+Long-Key: Even
+       Longer Value
+My-Key: Value 2
+

Given that input, ReadMIMEHeader returns the map:

+
map[string][]string{
+	"My-Key": {"Value 1", "Value 2"},
+	"Long-Key": {"Even Longer Value"},
+}
+

func (*Reader) ReadResponse

func (r *Reader) ReadResponse(expectCode int) (code int, message string, err error)

ReadResponse reads a multi-line response of the form:

+
code-message line 1
+code-message line 2
+...
+code message line n
+

where code is a three-digit status code. The first line starts with the code and a hyphen. The response is terminated by a line that starts with the same code followed by a space. Each line in message is separated by a newline (\n).

+

See page 36 of RFC 959 (https://www.ietf.org/rfc/rfc959.txt) for details of another form of response accepted:

+
code-message line 1
+message line 2
+...
+code message line n
+

If the prefix of the status does not match the digits in expectCode, ReadResponse returns with err set to &Error{code, message}. For example, if expectCode is 31, an error will be returned if the status is not in the range [310,319].

+

An expectCode <= 0 disables the check of the status code.

+

type Writer

A Writer implements convenience methods for writing requests or responses to a text protocol network connection.

+
type Writer struct {
+    W *bufio.Writer
+    // contains filtered or unexported fields
+}
+

func NewWriter

func NewWriter(w *bufio.Writer) *Writer

NewWriter returns a new Writer writing to w.

+

func (*Writer) DotWriter

func (w *Writer) DotWriter() io.WriteCloser

DotWriter returns a writer that can be used to write a dot-encoding to w. It takes care of inserting leading dots when necessary, translating line-ending \n into \r\n, and adding the final .\r\n line when the DotWriter is closed. The caller should close the DotWriter before the next call to a method on w.

+

See the documentation for the Reader.DotReader method for details about dot-encoding.

+

func (*Writer) PrintfLine

func (w *Writer) PrintfLine(format string, args ...any) error

PrintfLine writes the formatted output followed by \r\n.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/textproto/ +

+
diff --git a/devdocs/go/net%2Furl%2Findex.html b/devdocs/go/net%2Furl%2Findex.html new file mode 100644 index 00000000..2c773676 --- /dev/null +++ b/devdocs/go/net%2Furl%2Findex.html @@ -0,0 +1,425 @@ +

Package url

Overview

Package url parses URLs and implements query escaping.

Index

Examples

ParseQuery
PathEscape
PathUnescape
QueryEscape
QueryUnescape
URL
URL.EscapedFragment
URL.EscapedPath
URL.Hostname
URL.IsAbs
URL.MarshalBinary
URL.Parse
URL.Port
URL.Query
URL.Redacted
URL.RequestURI
URL.ResolveReference
URL.String
URL.UnmarshalBinary
URL (Roundtrip)
Values
Values.Add
Values.Del
Values.Encode
Values.Get
Values.Has
Values.Set

Package files

url.go

func JoinPath 1.19

func JoinPath(base string, elem ...string) (result string, err error)

JoinPath returns a URL string with the provided path elements joined to the existing path of base and the resulting path cleaned of any ./ or ../ elements.

+

func PathEscape 1.8

func PathEscape(s string) string

PathEscape escapes the string so it can be safely placed inside a URL path segment, replacing special characters (including /) with %XX sequences as needed.

Example +

Code:

path := url.PathEscape("my/cool+blog&about,stuff")
+fmt.Println(path)
+
+

Output:

my%2Fcool+blog&about%2Cstuff
+

func PathUnescape 1.8

func PathUnescape(s string) (string, error)

PathUnescape does the inverse transformation of PathEscape, converting each 3-byte encoded substring of the form "%AB" into the hex-decoded byte 0xAB. It returns an error if any % is not followed by two hexadecimal digits.

+

PathUnescape is identical to QueryUnescape except that it does not unescape '+' to ' ' (space).

Example +

Code:

escapedPath := "my%2Fcool+blog&about%2Cstuff"
+path, err := url.PathUnescape(escapedPath)
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(path)
+
+

Output:

my/cool+blog&about,stuff
+

func QueryEscape

func QueryEscape(s string) string

QueryEscape escapes the string so it can be safely placed inside a URL query.

Example +

Code:

query := url.QueryEscape("my/cool+blog&about,stuff")
+fmt.Println(query)
+
+

Output:

my%2Fcool%2Bblog%26about%2Cstuff
+

func QueryUnescape

func QueryUnescape(s string) (string, error)

QueryUnescape does the inverse transformation of QueryEscape, converting each 3-byte encoded substring of the form "%AB" into the hex-decoded byte 0xAB. It returns an error if any % is not followed by two hexadecimal digits.

Example +

Code:

escapedQuery := "my%2Fcool%2Bblog%26about%2Cstuff"
+query, err := url.QueryUnescape(escapedQuery)
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(query)
+
+

Output:

my/cool+blog&about,stuff
+

type Error

Error reports an error and the operation and URL that caused it.

+
type Error struct {
+    Op  string
+    URL string
+    Err error
+}
+

func (*Error) Error

func (e *Error) Error() string

func (*Error) Temporary 1.6

func (e *Error) Temporary() bool

func (*Error) Timeout 1.6

func (e *Error) Timeout() bool

func (*Error) Unwrap 1.13

func (e *Error) Unwrap() error

type EscapeError

type EscapeError string

func (EscapeError) Error

func (e EscapeError) Error() string

type InvalidHostError 1.6

type InvalidHostError string

func (InvalidHostError) Error 1.6

func (e InvalidHostError) Error() string

type URL

A URL represents a parsed URL (technically, a URI reference).

+

The general form represented is:

+
[scheme:][//[userinfo@]host][/]path[?query][#fragment]
+

URLs that do not start with a slash after the scheme are interpreted as:

+
scheme:opaque[?query][#fragment]
+

The Host field contains the host and port subcomponents of the URL. When the port is present, it is separated from the host with a colon. When the host is an IPv6 address, it must be enclosed in square brackets: "[fe80::1]:80". The net.JoinHostPort function combines a host and port into a string suitable for the Host field, adding square brackets to the host when necessary.

+

Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. A consequence is that it is impossible to tell which slashes in the Path were slashes in the raw URL and which were %2f. This distinction is rarely important, but when it is, the code should use the URL.EscapedPath method, which preserves the original encoding of Path.

+

The RawPath field is an optional field which is only set when the default encoding of Path is different from the escaped path. See the EscapedPath method for more details.

+

URL's String method uses the EscapedPath method to obtain the path.

+
type URL struct {
+    Scheme      string
+    Opaque      string    // encoded opaque data
+    User        *Userinfo // username and password information
+    Host        string    // host or host:port (see Hostname and Port methods)
+    Path        string    // path (relative paths may omit leading slash)
+    RawPath     string    // encoded path hint (see EscapedPath method); added in Go 1.5
+    OmitHost    bool      // do not emit empty host (authority); added in Go 1.19
+    ForceQuery  bool      // append a query ('?') even if RawQuery is empty; added in Go 1.7
+    RawQuery    string    // encoded query values, without '?'
+    Fragment    string    // fragment for references, without '#'
+    RawFragment string    // encoded fragment hint (see EscapedFragment method); added in Go 1.15
+}
+

Example +

Code:

u, err := url.Parse("http://bing.com/search?q=dotnet")
+if err != nil {
+    log.Fatal(err)
+}
+u.Scheme = "https"
+u.Host = "google.com"
+q := u.Query()
+q.Set("q", "golang")
+u.RawQuery = q.Encode()
+fmt.Println(u)
+

Output:

https://google.com/search?q=golang
+

Example (Roundtrip) +

Code:

// Parse + String preserve the original encoding.
+u, err := url.Parse("https://example.com/foo%2fbar")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(u.Path)
+fmt.Println(u.RawPath)
+fmt.Println(u.String())
+

Output:

/foo/bar
+/foo%2fbar
+https://example.com/foo%2fbar
+

func Parse

func Parse(rawURL string) (*URL, error)

Parse parses a raw url into a URL structure.

+

The url may be relative (a path, without a host) or absolute (starting with a scheme). Trying to parse a hostname and path without a scheme is invalid but may not necessarily return an error, due to parsing ambiguities.

+

func ParseRequestURI

func ParseRequestURI(rawURL string) (*URL, error)

ParseRequestURI parses a raw url into a URL structure. It assumes that url was received in an HTTP request, so the url is interpreted only as an absolute URI or an absolute path. The string url is assumed not to have a #fragment suffix. (Web browsers strip #fragment before sending the URL to a web server.)

+

func (*URL) EscapedFragment 1.15

func (u *URL) EscapedFragment() string

EscapedFragment returns the escaped form of u.Fragment. In general there are multiple possible escaped forms of any fragment. EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. Otherwise EscapedFragment ignores u.RawFragment and computes an escaped form on its own. The URL.String method uses EscapedFragment to construct its result. In general, code should call EscapedFragment instead of reading u.RawFragment directly.

Example +

Code:

u, err := url.Parse("http://example.com/#x/y%2Fz")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println("Fragment:", u.Fragment)
+fmt.Println("RawFragment:", u.RawFragment)
+fmt.Println("EscapedFragment:", u.EscapedFragment())
+

Output:

Fragment: x/y/z
+RawFragment: x/y%2Fz
+EscapedFragment: x/y%2Fz
+

func (*URL) EscapedPath 1.5

func (u *URL) EscapedPath() string

EscapedPath returns the escaped form of u.Path. In general there are multiple possible escaped forms of any path. EscapedPath returns u.RawPath when it is a valid escaping of u.Path. Otherwise EscapedPath ignores u.RawPath and computes an escaped form on its own. The URL.String and URL.RequestURI methods use EscapedPath to construct their results. In general, code should call EscapedPath instead of reading u.RawPath directly.

Example +

Code:

u, err := url.Parse("http://example.com/x/y%2Fz")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println("Path:", u.Path)
+fmt.Println("RawPath:", u.RawPath)
+fmt.Println("EscapedPath:", u.EscapedPath())
+

Output:

Path: /x/y/z
+RawPath: /x/y%2Fz
+EscapedPath: /x/y%2Fz
+

func (*URL) Hostname 1.8

func (u *URL) Hostname() string

Hostname returns u.Host, stripping any valid port number if present.

+

If the result is enclosed in square brackets, as literal IPv6 addresses are, the square brackets are removed from the result.

Example +

Code:

u, err := url.Parse("https://example.org:8000/path")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(u.Hostname())
+u, err = url.Parse("https://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:17000")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(u.Hostname())
+

Output:

example.org
+2001:0db8:85a3:0000:0000:8a2e:0370:7334
+

func (*URL) IsAbs

func (u *URL) IsAbs() bool

IsAbs reports whether the URL is absolute. Absolute means that it has a non-empty scheme.

Example +

Code:

u := url.URL{Host: "example.com", Path: "foo"}
+fmt.Println(u.IsAbs())
+u.Scheme = "http"
+fmt.Println(u.IsAbs())
+

Output:

false
+true
+

func (*URL) JoinPath 1.19

func (u *URL) JoinPath(elem ...string) *URL

JoinPath returns a new URL with the provided path elements joined to any existing path and the resulting path cleaned of any ./ or ../ elements. Any sequences of multiple / characters will be reduced to a single /.

+

func (*URL) MarshalBinary 1.8

func (u *URL) MarshalBinary() (text []byte, err error)

Example +

Code:

u, _ := url.Parse("https://example.org")
+b, err := u.MarshalBinary()
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%s\n", b)
+

Output:

https://example.org
+

func (*URL) Parse

func (u *URL) Parse(ref string) (*URL, error)

Parse parses a URL in the context of the receiver. The provided URL may be relative or absolute. Parse returns nil, err on parse failure, otherwise its return value is the same as URL.ResolveReference.

Example +

Code:

u, err := url.Parse("https://example.org")
+if err != nil {
+    log.Fatal(err)
+}
+rel, err := u.Parse("/foo")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(rel)
+_, err = u.Parse(":foo")
+if _, ok := err.(*url.Error); !ok {
+    log.Fatal(err)
+}
+

Output:

https://example.org/foo
+

func (*URL) Port 1.8

func (u *URL) Port() string

Port returns the port part of u.Host, without the leading colon.

+

If u.Host doesn't contain a valid numeric port, Port returns an empty string.

Example +

Code:

u, err := url.Parse("https://example.org")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(u.Port())
+u, err = url.Parse("https://example.org:8080")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(u.Port())
+

Output:

+8080
+

func (*URL) Query

func (u *URL) Query() Values

Query parses RawQuery and returns the corresponding values. It silently discards malformed value pairs. To check errors use ParseQuery.

Example +

Code:

u, err := url.Parse("https://example.org/?a=1&a=2&b=&=3&&&&")
+if err != nil {
+    log.Fatal(err)
+}
+q := u.Query()
+fmt.Println(q["a"])
+fmt.Println(q.Get("b"))
+fmt.Println(q.Get(""))
+

Output:

[1 2]
+
+3
+

func (*URL) Redacted 1.15

func (u *URL) Redacted() string

Redacted is like URL.String but replaces any password with "xxxxx". Only the password in u.User is redacted.

Example +

Code:

u := &url.URL{
+    Scheme: "https",
+    User:   url.UserPassword("user", "password"),
+    Host:   "example.com",
+    Path:   "foo/bar",
+}
+fmt.Println(u.Redacted())
+u.User = url.UserPassword("me", "newerPassword")
+fmt.Println(u.Redacted())
+

Output:

https://user:xxxxx@example.com/foo/bar
+https://me:xxxxx@example.com/foo/bar
+

func (*URL) RequestURI

func (u *URL) RequestURI() string

RequestURI returns the encoded path?query or opaque?query string that would be used in an HTTP request for u.

Example +

Code:

u, err := url.Parse("https://example.org/path?foo=bar")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(u.RequestURI())
+

Output:

/path?foo=bar
+

func (*URL) ResolveReference

func (u *URL) ResolveReference(ref *URL) *URL

ResolveReference resolves a URI reference to an absolute URI from an absolute base URI u, per RFC 3986 Section 5.2. The URI reference may be relative or absolute. ResolveReference always returns a new URL instance, even if the returned URL is identical to either the base or reference. If ref is an absolute URL, then ResolveReference ignores base and returns a copy of ref.

Example +

Code:

u, err := url.Parse("../../..//search?q=dotnet")
+if err != nil {
+    log.Fatal(err)
+}
+base, err := url.Parse("http://example.com/directory/")
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(base.ResolveReference(u))
+

Output:

http://example.com/search?q=dotnet
+

func (*URL) String

func (u *URL) String() string

String reassembles the URL into a valid URL string. The general form of the result is one of:

+
scheme:opaque?query#fragment
+scheme://userinfo@host/path?query#fragment
+

If u.Opaque is non-empty, String uses the first form; otherwise it uses the second form. Any non-ASCII characters in host are escaped. To obtain the path, String uses u.EscapedPath().

+

In the second form, the following rules apply:

+

Example +

Code:

u := &url.URL{
+    Scheme:   "https",
+    User:     url.UserPassword("me", "pass"),
+    Host:     "example.com",
+    Path:     "foo/bar",
+    RawQuery: "x=1&y=2",
+    Fragment: "anchor",
+}
+fmt.Println(u.String())
+u.Opaque = "opaque"
+fmt.Println(u.String())
+

Output:

https://me:pass@example.com/foo/bar?x=1&y=2#anchor
+https:opaque?x=1&y=2#anchor
+

func (*URL) UnmarshalBinary 1.8

func (u *URL) UnmarshalBinary(text []byte) error

Example +

Code:

u := &url.URL{}
+err := u.UnmarshalBinary([]byte("https://example.org/foo"))
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%s\n", u)
+

Output:

https://example.org/foo
+

type Userinfo

The Userinfo type is an immutable encapsulation of username and password details for a URL. An existing Userinfo value is guaranteed to have a username set (potentially empty, as allowed by RFC 2396), and optionally a password.

+
type Userinfo struct {
+    // contains filtered or unexported fields
+}
+

func User

func User(username string) *Userinfo

User returns a Userinfo containing the provided username and no password set.

+

func UserPassword

func UserPassword(username, password string) *Userinfo

UserPassword returns a Userinfo containing the provided username and password.

+

This functionality should only be used with legacy web sites. RFC 2396 warns that interpreting Userinfo this way “is NOT RECOMMENDED, because the passing of authentication information in clear text (such as URI) has proven to be a security risk in almost every case where it has been used.”

+

func (*Userinfo) Password

func (u *Userinfo) Password() (string, bool)

Password returns the password in case it is set, and whether it is set.

+

func (*Userinfo) String

func (u *Userinfo) String() string

String returns the encoded userinfo information in the standard form of "username[:password]".

+

func (*Userinfo) Username

func (u *Userinfo) Username() string

Username returns the username.

+

type Values

Values maps a string key to a list of values. It is typically used for query parameters and form values. Unlike in the http.Header map, the keys in a Values map are case-sensitive.

+
type Values map[string][]string

Example +

Code:

v := url.Values{}
+v.Set("name", "Ava")
+v.Add("friend", "Jess")
+v.Add("friend", "Sarah")
+v.Add("friend", "Zoe")
+// v.Encode() == "name=Ava&friend=Jess&friend=Sarah&friend=Zoe"
+fmt.Println(v.Get("name"))
+fmt.Println(v.Get("friend"))
+fmt.Println(v["friend"])
+

Output:

Ava
+Jess
+[Jess Sarah Zoe]
+

func ParseQuery

func ParseQuery(query string) (Values, error)

ParseQuery parses the URL-encoded query string and returns a map listing the values specified for each key. ParseQuery always returns a non-nil map containing all the valid query parameters found; err describes the first decoding error encountered, if any.

+

Query is expected to be a list of key=value settings separated by ampersands. A setting without an equals sign is interpreted as a key set to an empty value. Settings containing a non-URL-encoded semicolon are considered invalid.

Example +

Code:

m, err := url.ParseQuery(`x=1&y=2&y=3`)
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Println(toJSON(m))
+

Output:

{"x":["1"], "y":["2", "3"]}
+

func (Values) Add

func (v Values) Add(key, value string)

Add adds the value to key. It appends to any existing values associated with key.

Example +

Code:

v := url.Values{}
+v.Add("cat sounds", "meow")
+v.Add("cat sounds", "mew")
+v.Add("cat sounds", "mau")
+fmt.Println(v["cat sounds"])
+
+

Output:

[meow mew mau]
+

func (Values) Del

func (v Values) Del(key string)

Del deletes the values associated with key.

Example +

Code:

v := url.Values{}
+v.Add("cat sounds", "meow")
+v.Add("cat sounds", "mew")
+v.Add("cat sounds", "mau")
+fmt.Println(v["cat sounds"])
+
+v.Del("cat sounds")
+fmt.Println(v["cat sounds"])
+
+

Output:

[meow mew mau]
+[]
+

func (Values) Encode

func (v Values) Encode() string

Encode encodes the values into “URL encoded” form ("bar=baz&foo=quux") sorted by key.

Example +

Code:

v := url.Values{}
+v.Add("cat sounds", "meow")
+v.Add("cat sounds", "mew/")
+v.Add("cat sounds", "mau$")
+fmt.Println(v.Encode())
+
+

Output:

cat+sounds=meow&cat+sounds=mew%2F&cat+sounds=mau%24
+

func (Values) Get

func (v Values) Get(key string) string

Get gets the first value associated with the given key. If there are no values associated with the key, Get returns the empty string. To access multiple values, use the map directly.

Example +

Code:

v := url.Values{}
+v.Add("cat sounds", "meow")
+v.Add("cat sounds", "mew")
+v.Add("cat sounds", "mau")
+fmt.Printf("%q\n", v.Get("cat sounds"))
+fmt.Printf("%q\n", v.Get("dog sounds"))
+
+

Output:

"meow"
+""
+

func (Values) Has 1.17

func (v Values) Has(key string) bool

Has checks whether a given key is set.

Example +

Code:

v := url.Values{}
+v.Add("cat sounds", "meow")
+v.Add("cat sounds", "mew")
+v.Add("cat sounds", "mau")
+fmt.Println(v.Has("cat sounds"))
+fmt.Println(v.Has("dog sounds"))
+
+

Output:

true
+false
+

func (Values) Set

func (v Values) Set(key, value string)

Set sets the key to value. It replaces any existing values.

Example +

Code:

v := url.Values{}
+v.Add("cat sounds", "meow")
+v.Add("cat sounds", "mew")
+v.Add("cat sounds", "mau")
+fmt.Println(v["cat sounds"])
+
+v.Set("cat sounds", "meow")
+fmt.Println(v["cat sounds"])
+
+

Output:

[meow mew mau]
+[meow]
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/net/url/ +

+
diff --git a/devdocs/go/os%2Fexec%2Findex.html b/devdocs/go/os%2Fexec%2Findex.html new file mode 100644 index 00000000..ab15963c --- /dev/null +++ b/devdocs/go/os%2Fexec%2Findex.html @@ -0,0 +1,413 @@ +

Package exec

Overview

Package exec runs external commands. It wraps os.StartProcess to make it easier to remap stdin and stdout, connect I/O with pipes, and do other adjustments.

+

Unlike the "system" library call from C and other languages, the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells. The package behaves more like C's "exec" family of functions. To expand glob patterns, either call the shell directly, taking care to escape any dangerous input, or use the path/filepath package's Glob function. To expand environment variables, use package os's ExpandEnv.

+

Note that the examples in this package assume a Unix system. They may not run on Windows, and they do not run in the Go Playground used by golang.org and godoc.org.

+

Executables in the current directory

The functions Command and LookPath look for a program in the directories listed in the current path, following the conventions of the host operating system. Operating systems have for decades included the current directory in this search, sometimes implicitly and sometimes configured explicitly that way by default. Modern practice is that including the current directory is usually unexpected and often leads to security problems.

+

To avoid those security problems, as of Go 1.19, this package will not resolve a program using an implicit or explicit path entry relative to the current directory. That is, if you run exec.LookPath("go"), it will not successfully return ./go on Unix nor .\go.exe on Windows, no matter how the path is configured. Instead, if the usual path algorithms would result in that answer, these functions return an error err satisfying errors.Is(err, ErrDot).

+

For example, consider these two program snippets:

+
path, err := exec.LookPath("prog")
+if err != nil {
+	log.Fatal(err)
+}
+use(path)
+

and

+
cmd := exec.Command("prog")
+if err := cmd.Run(); err != nil {
+	log.Fatal(err)
+}
+

These will not find and run ./prog or .\prog.exe, no matter how the current path is configured.

+

Code that always wants to run a program from the current directory can be rewritten to say "./prog" instead of "prog".

+

Code that insists on including results from relative path entries can instead override the error using an errors.Is check:

+
path, err := exec.LookPath("prog")
+if errors.Is(err, exec.ErrDot) {
+	err = nil
+}
+if err != nil {
+	log.Fatal(err)
+}
+use(path)
+

and

+
cmd := exec.Command("prog")
+if errors.Is(cmd.Err, exec.ErrDot) {
+	cmd.Err = nil
+}
+if err := cmd.Run(); err != nil {
+	log.Fatal(err)
+}
+

Setting the environment variable GODEBUG=execerrdot=0 disables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19 behavior for programs that are unable to apply more targeted fixes. A future version of Go may remove support for this variable.

+

Before adding such overrides, make sure you understand the security implications of doing so. See https://go.dev/blog/path-security for more information.

Index

Examples

Cmd.CombinedOutput
Cmd.Environ
Cmd.Output
Cmd.Run
Cmd.Start
Cmd.StderrPipe
Cmd.StdinPipe
Cmd.StdoutPipe
Command
CommandContext
Command (Environment)
LookPath

Package files

exec.go exec_unix.go lp_unix.go

Variables

ErrDot indicates that a path lookup resolved to an executable in the current directory due to ‘.’ being in the path, either implicitly or explicitly. See the package documentation for details.

+

Note that functions in this package do not return ErrDot directly. Code should use errors.Is(err, ErrDot), not err == ErrDot, to test whether a returned error err is due to this condition.

+
var ErrDot = errors.New("cannot run executable found relative to current directory")

ErrNotFound is the error resulting if a path search failed to find an executable file.

+
var ErrNotFound = errors.New("executable file not found in $PATH")

ErrWaitDelay is returned by (*Cmd).Wait if the process exits with a successful status code but its output pipes are not closed before the command's WaitDelay expires.

+
var ErrWaitDelay = errors.New("exec: WaitDelay expired before I/O complete")

func LookPath

func LookPath(file string) (string, error)

LookPath searches for an executable named file in the directories named by the PATH environment variable. If file contains a slash, it is tried directly and the PATH is not consulted. Otherwise, on success, the result is an absolute path.

+

In older versions of Go, LookPath could return a path relative to the current directory. As of Go 1.19, LookPath will instead return that path along with an error satisfying errors.Is(err, ErrDot). See the package documentation for more details.

Example +

Code:

+path, err := exec.LookPath("fortune")
+if err != nil {
+    log.Fatal("installing fortune is in your future")
+}
+fmt.Printf("fortune is available at %s\n", path)
+

type Cmd

Cmd represents an external command being prepared or run.

+

A Cmd cannot be reused after calling its Run, Output or CombinedOutput methods.

+
type Cmd struct {
+    // Path is the path of the command to run.
+    //
+    // This is the only field that must be set to a non-zero
+    // value. If Path is relative, it is evaluated relative
+    // to Dir.
+    Path string
+
+    // Args holds command line arguments, including the command as Args[0].
+    // If the Args field is empty or nil, Run uses {Path}.
+    //
+    // In typical use, both Path and Args are set by calling Command.
+    Args []string
+
+    // Env specifies the environment of the process.
+    // Each entry is of the form "key=value".
+    // If Env is nil, the new process uses the current process's
+    // environment.
+    // If Env contains duplicate environment keys, only the last
+    // value in the slice for each duplicate key is used.
+    // As a special case on Windows, SYSTEMROOT is always added if
+    // missing and not explicitly set to the empty string.
+    Env []string
+
+    // Dir specifies the working directory of the command.
+    // If Dir is the empty string, Run runs the command in the
+    // calling process's current directory.
+    Dir string
+
+    // Stdin specifies the process's standard input.
+    //
+    // If Stdin is nil, the process reads from the null device (os.DevNull).
+    //
+    // If Stdin is an *os.File, the process's standard input is connected
+    // directly to that file.
+    //
+    // Otherwise, during the execution of the command a separate
+    // goroutine reads from Stdin and delivers that data to the command
+    // over a pipe. In this case, Wait does not complete until the goroutine
+    // stops copying, either because it has reached the end of Stdin
+    // (EOF or a read error), or because writing to the pipe returned an error,
+    // or because a nonzero WaitDelay was set and expired.
+    Stdin io.Reader
+
+    // Stdout and Stderr specify the process's standard output and error.
+    //
+    // If either is nil, Run connects the corresponding file descriptor
+    // to the null device (os.DevNull).
+    //
+    // If either is an *os.File, the corresponding output from the process
+    // is connected directly to that file.
+    //
+    // Otherwise, during the execution of the command a separate goroutine
+    // reads from the process over a pipe and delivers that data to the
+    // corresponding Writer. In this case, Wait does not complete until the
+    // goroutine reaches EOF or encounters an error or a nonzero WaitDelay
+    // expires.
+    //
+    // If Stdout and Stderr are the same writer, and have a type that can
+    // be compared with ==, at most one goroutine at a time will call Write.
+    Stdout io.Writer
+    Stderr io.Writer
+
+    // ExtraFiles specifies additional open files to be inherited by the
+    // new process. It does not include standard input, standard output, or
+    // standard error. If non-nil, entry i becomes file descriptor 3+i.
+    //
+    // ExtraFiles is not supported on Windows.
+    ExtraFiles []*os.File
+
+    // SysProcAttr holds optional, operating system-specific attributes.
+    // Run passes it to os.StartProcess as the os.ProcAttr's Sys field.
+    SysProcAttr *syscall.SysProcAttr
+
+    // Process is the underlying process, once started.
+    Process *os.Process
+
+    // ProcessState contains information about an exited process.
+    // If the process was started successfully, Wait or Run will
+    // populate its ProcessState when the command completes.
+    ProcessState *os.ProcessState
+
+    Err error // LookPath error, if any; added in Go 1.19
+
+    // If Cancel is non-nil, the command must have been created with
+    // CommandContext and Cancel will be called when the command's
+    // Context is done. By default, CommandContext sets Cancel to
+    // call the Kill method on the command's Process.
+    //
+    // Typically a custom Cancel will send a signal to the command's
+    // Process, but it may instead take other actions to initiate cancellation,
+    // such as closing a stdin or stdout pipe or sending a shutdown request on a
+    // network socket.
+    //
+    // If the command exits with a success status after Cancel is
+    // called, and Cancel does not return an error equivalent to
+    // os.ErrProcessDone, then Wait and similar methods will return a non-nil
+    // error: either an error wrapping the one returned by Cancel,
+    // or the error from the Context.
+    // (If the command exits with a non-success status, or Cancel
+    // returns an error that wraps os.ErrProcessDone, Wait and similar methods
+    // continue to return the command's usual exit status.)
+    //
+    // If Cancel is set to nil, nothing will happen immediately when the command's
+    // Context is done, but a nonzero WaitDelay will still take effect. That may
+    // be useful, for example, to work around deadlocks in commands that do not
+    // support shutdown signals but are expected to always finish quickly.
+    //
+    // Cancel will not be called if Start returns a non-nil error.
+    Cancel func() error // Go 1.20
+
+    // If WaitDelay is non-zero, it bounds the time spent waiting on two sources
+    // of unexpected delay in Wait: a child process that fails to exit after the
+    // associated Context is canceled, and a child process that exits but leaves
+    // its I/O pipes unclosed.
+    //
+    // The WaitDelay timer starts when either the associated Context is done or a
+    // call to Wait observes that the child process has exited, whichever occurs
+    // first. When the delay has elapsed, the command shuts down the child process
+    // and/or its I/O pipes.
+    //
+    // If the child process has failed to exit — perhaps because it ignored or
+    // failed to receive a shutdown signal from a Cancel function, or because no
+    // Cancel function was set — then it will be terminated using os.Process.Kill.
+    //
+    // Then, if the I/O pipes communicating with the child process are still open,
+    // those pipes are closed in order to unblock any goroutines currently blocked
+    // on Read or Write calls.
+    //
+    // If pipes are closed due to WaitDelay, no Cancel call has occurred,
+    // and the command has otherwise exited with a successful status, Wait and
+    // similar methods will return ErrWaitDelay instead of nil.
+    //
+    // If WaitDelay is zero (the default), I/O pipes will be read until EOF,
+    // which might not occur until orphaned subprocesses of the command have
+    // also closed their descriptors for the pipes.
+    WaitDelay time.Duration // Go 1.20
+    // contains filtered or unexported fields
+}
+

func Command

func Command(name string, arg ...string) *Cmd

Command returns the Cmd struct to execute the named program with the given arguments.

+

It sets only the Path and Args in the returned structure.

+

If name contains no path separators, Command uses LookPath to resolve name to a complete path if possible. Otherwise it uses name directly as Path.

+

The returned Cmd's Args field is constructed from the command name followed by the elements of arg, so arg should not include the command name itself. For example, Command("echo", "hello"). Args[0] is always name, not the possibly resolved Path.

+

On Windows, processes receive the whole command line as a single string and do their own parsing. Command combines and quotes Args into a command line string with an algorithm compatible with applications using CommandLineToArgvW (which is the most common way). Notable exceptions are msiexec.exe and cmd.exe (and thus, all batch files), which have a different unquoting algorithm. In these or other similar cases, you can do the quoting yourself and provide the full command line in SysProcAttr.CmdLine, leaving Args empty.

Example +

Code:

+cmd := exec.Command("tr", "a-z", "A-Z")
+cmd.Stdin = strings.NewReader("some input")
+var out strings.Builder
+cmd.Stdout = &out
+err := cmd.Run()
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("in all caps: %q\n", out.String())
+

Example (Environment) +

Code:

+cmd := exec.Command("prog")
+cmd.Env = append(os.Environ(),
+    "FOO=duplicate_value", // ignored
+    "FOO=actual_value",    // this value is used
+)
+if err := cmd.Run(); err != nil {
+    log.Fatal(err)
+}
+

func CommandContext 1.7

func CommandContext(ctx context.Context, name string, arg ...string) *Cmd

CommandContext is like Command but includes a context.

+

The provided context is used to interrupt the process (by calling cmd.Cancel or os.Process.Kill) if the context becomes done before the command completes on its own.

+

CommandContext sets the command's Cancel function to invoke the Kill method on its Process, and leaves its WaitDelay unset. The caller may change the cancellation behavior by modifying those fields before starting the command.

Example +

Code:

+ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+defer cancel()
+
+if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
+    // This will fail after 100 milliseconds. The 5 second sleep
+    // will be interrupted.
+}
+

func (*Cmd) CombinedOutput

func (c *Cmd) CombinedOutput() ([]byte, error)

CombinedOutput runs the command and returns its combined standard output and standard error.

Example +

Code:

+cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr")
+stdoutStderr, err := cmd.CombinedOutput()
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%s\n", stdoutStderr)
+

func (*Cmd) Environ 1.19

func (c *Cmd) Environ() []string

Environ returns a copy of the environment in which the command would be run as it is currently configured.

Example +

Code:

+cmd := exec.Command("pwd")
+
+// Set Dir before calling cmd.Environ so that it will include an
+// updated PWD variable (on platforms where that is used).
+cmd.Dir = ".."
+cmd.Env = append(cmd.Environ(), "POSIXLY_CORRECT=1")
+
+out, err := cmd.Output()
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%s\n", out)
+

func (*Cmd) Output

func (c *Cmd) Output() ([]byte, error)

Output runs the command and returns its standard output. Any returned error will usually be of type *ExitError. If c.Stderr was nil, Output populates ExitError.Stderr.

Example +

Code:

+out, err := exec.Command("date").Output()
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("The date is %s\n", out)
+

func (*Cmd) Run

func (c *Cmd) Run() error

Run starts the specified command and waits for it to complete.

+

The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

+

If the command starts but does not complete successfully, the error is of type *ExitError. Other error types may be returned for other situations.

+

If the calling goroutine has locked the operating system thread with runtime.LockOSThread and modified any inheritable OS-level thread state (for example, Linux or Plan 9 name spaces), the new process will inherit the caller's thread state.

Example +

Code:

+cmd := exec.Command("sleep", "1")
+log.Printf("Running command and waiting for it to finish...")
+err := cmd.Run()
+log.Printf("Command finished with error: %v", err)
+

func (*Cmd) Start

func (c *Cmd) Start() error

Start starts the specified command but does not wait for it to complete.

+

If Start returns successfully, the c.Process field will be set.

+

After a successful call to Start the Wait method must be called in order to release associated system resources.

Example +

Code:

+cmd := exec.Command("sleep", "5")
+err := cmd.Start()
+if err != nil {
+    log.Fatal(err)
+}
+log.Printf("Waiting for command to finish...")
+err = cmd.Wait()
+log.Printf("Command finished with error: %v", err)
+

func (*Cmd) StderrPipe

func (c *Cmd) StderrPipe() (io.ReadCloser, error)

StderrPipe returns a pipe that will be connected to the command's standard error when the command starts.

+

Wait will close the pipe after seeing the command exit, so most callers need not close the pipe themselves. It is thus incorrect to call Wait before all reads from the pipe have completed. For the same reason, it is incorrect to use Run when using StderrPipe. See the StdoutPipe example for idiomatic usage.

Example +

Code:

+cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr")
+stderr, err := cmd.StderrPipe()
+if err != nil {
+    log.Fatal(err)
+}
+
+if err := cmd.Start(); err != nil {
+    log.Fatal(err)
+}
+
+slurp, _ := io.ReadAll(stderr)
+fmt.Printf("%s\n", slurp)
+
+if err := cmd.Wait(); err != nil {
+    log.Fatal(err)
+}
+

func (*Cmd) StdinPipe

func (c *Cmd) StdinPipe() (io.WriteCloser, error)

StdinPipe returns a pipe that will be connected to the command's standard input when the command starts. The pipe will be closed automatically after Wait sees the command exit. A caller need only call Close to force the pipe to close sooner. For example, if the command being run will not exit until standard input is closed, the caller must close the pipe.

Example +

Code:

+cmd := exec.Command("cat")
+stdin, err := cmd.StdinPipe()
+if err != nil {
+    log.Fatal(err)
+}
+
+go func() {
+    defer stdin.Close()
+    io.WriteString(stdin, "values written to stdin are passed to cmd's standard input")
+}()
+
+out, err := cmd.CombinedOutput()
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("%s\n", out)
+

func (*Cmd) StdoutPipe

func (c *Cmd) StdoutPipe() (io.ReadCloser, error)

StdoutPipe returns a pipe that will be connected to the command's standard output when the command starts.

+

Wait will close the pipe after seeing the command exit, so most callers need not close the pipe themselves. It is thus incorrect to call Wait before all reads from the pipe have completed. For the same reason, it is incorrect to call Run when using StdoutPipe. See the example for idiomatic usage.

Example +

Code:

+cmd := exec.Command("echo", "-n", `{"Name": "Bob", "Age": 32}`)
+stdout, err := cmd.StdoutPipe()
+if err != nil {
+    log.Fatal(err)
+}
+if err := cmd.Start(); err != nil {
+    log.Fatal(err)
+}
+var person struct {
+    Name string
+    Age  int
+}
+if err := json.NewDecoder(stdout).Decode(&person); err != nil {
+    log.Fatal(err)
+}
+if err := cmd.Wait(); err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%s is %d years old\n", person.Name, person.Age)
+

func (*Cmd) String 1.13

func (c *Cmd) String() string

String returns a human-readable description of c. It is intended only for debugging. In particular, it is not suitable for use as input to a shell. The output of String may vary across Go releases.

+

func (*Cmd) Wait

func (c *Cmd) Wait() error

Wait waits for the command to exit and waits for any copying to stdin or copying from stdout or stderr to complete.

+

The command must have been started by Start.

+

The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

+

If the command fails to run or doesn't complete successfully, the error is of type *ExitError. Other error types may be returned for I/O problems.

+

If any of c.Stdin, c.Stdout or c.Stderr are not an *os.File, Wait also waits for the respective I/O loop copying to or from the process to complete.

+

Wait releases any resources associated with the Cmd.

+

type Error

Error is returned by LookPath when it fails to classify a file as an executable.

+
type Error struct {
+    // Name is the file name for which the error occurred.
+    Name string
+    // Err is the underlying error.
+    Err error
+}
+

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap 1.13

func (e *Error) Unwrap() error

type ExitError

An ExitError reports an unsuccessful exit by a command.

+
type ExitError struct {
+    *os.ProcessState
+
+    // Stderr holds a subset of the standard error output from the
+    // Cmd.Output method if standard error was not otherwise being
+    // collected.
+    //
+    // If the error output is long, Stderr may contain only a prefix
+    // and suffix of the output, with the middle replaced with
+    // text about the number of omitted bytes.
+    //
+    // Stderr is provided for debugging, for inclusion in error messages.
+    // Users with other needs should redirect Cmd.Stderr as needed.
+    Stderr []byte // Go 1.6
+}
+

func (*ExitError) Error

func (e *ExitError) Error() string

Subdirectories

Name Synopsis
..
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/os/exec/ +

+
diff --git a/devdocs/go/os%2Findex.html b/devdocs/go/os%2Findex.html new file mode 100644 index 00000000..148102b9 --- /dev/null +++ b/devdocs/go/os%2Findex.html @@ -0,0 +1,787 @@ +

Package os

Overview

Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is available within the error. For example, if a call that takes a file name fails, such as Open or Stat, the error will include the failing file name when printed and will be of type *PathError, which may be unpacked for more information.

+

The os interface is intended to be uniform across all operating systems. Features not generally available appear in the system-specific package syscall.

+

Here is a simple example, opening a file and reading some of it.

+
file, err := os.Open("file.go") // For read access.
+if err != nil {
+	log.Fatal(err)
+}
+

If the open fails, the error string will be self-explanatory, like

+
open file.go: no such file or directory
+

The file's data can then be read into a slice of bytes. Read and Write take their byte counts from the length of the argument slice.

+
data := make([]byte, 100)
+count, err := file.Read(data)
+if err != nil {
+	log.Fatal(err)
+}
+fmt.Printf("read %d bytes: %q\n", count, data[:count])
+

Note: The maximum number of concurrent operations on a File may be limited by the OS or the system. The number should be high, but exceeding it may degrade performance or cause other issues.

Index

Examples

Chmod
Chtimes
CreateTemp
CreateTemp (Suffix)
ErrNotExist
Expand
ExpandEnv
FileMode
Getenv
LookupEnv
Mkdir
MkdirAll
MkdirTemp
MkdirTemp (Suffix)
OpenFile
OpenFile (Append)
ReadDir
ReadFile
Readlink
Unsetenv
UserCacheDir
UserConfigDir
WriteFile

Package files

dir.go dir_unix.go dirent_linux.go endian_little.go env.go error.go error_errno.go error_posix.go exec.go exec_posix.go exec_unix.go executable.go executable_procfs.go file.go file_open_unix.go file_posix.go file_unix.go getwd.go path.go path_unix.go pipe2_unix.go proc.go rawconn.go removeall_at.go stat.go stat_linux.go stat_unix.go sticky_notbsd.go sys.go sys_linux.go sys_unix.go tempfile.go types.go types_unix.go wait_waitid.go zero_copy_linux.go

Constants

Flags to OpenFile wrapping those of the underlying system. Not all flags may be implemented on a given system.

+
const (
+    // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
+    O_RDONLY int = syscall.O_RDONLY // open the file read-only.
+    O_WRONLY int = syscall.O_WRONLY // open the file write-only.
+    O_RDWR   int = syscall.O_RDWR   // open the file read-write.
+    // The remaining values may be or'ed in to control behavior.
+    O_APPEND int = syscall.O_APPEND // append data to the file when writing.
+    O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
+    O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist.
+    O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
+    O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.
+)

Seek whence values.

+

Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.

+
const (
+    SEEK_SET int = 0 // seek relative to the origin of the file
+    SEEK_CUR int = 1 // seek relative to the current offset
+    SEEK_END int = 2 // seek relative to the end
+)
const (
+    PathSeparator     = '/' // OS-specific path separator
+    PathListSeparator = ':' // OS-specific path list separator
+)

The defined file mode bits are the most significant bits of the FileMode. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

+
const (
+    // The single letters are the abbreviations
+    // used by the String method's formatting.
+    ModeDir        = fs.ModeDir        // d: is a directory
+    ModeAppend     = fs.ModeAppend     // a: append-only
+    ModeExclusive  = fs.ModeExclusive  // l: exclusive use
+    ModeTemporary  = fs.ModeTemporary  // T: temporary file; Plan 9 only
+    ModeSymlink    = fs.ModeSymlink    // L: symbolic link
+    ModeDevice     = fs.ModeDevice     // D: device file
+    ModeNamedPipe  = fs.ModeNamedPipe  // p: named pipe (FIFO)
+    ModeSocket     = fs.ModeSocket     // S: Unix domain socket
+    ModeSetuid     = fs.ModeSetuid     // u: setuid
+    ModeSetgid     = fs.ModeSetgid     // g: setgid
+    ModeCharDevice = fs.ModeCharDevice // c: Unix character device, when ModeDevice is set
+    ModeSticky     = fs.ModeSticky     // t: sticky
+    ModeIrregular  = fs.ModeIrregular  // ?: non-regular file; nothing else is known about this file
+
+    // Mask for the type bits. For regular files, none will be set.
+    ModeType = fs.ModeType
+
+    ModePerm = fs.ModePerm // Unix permission bits, 0o777
+)

DevNull is the name of the operating system's “null device.” On Unix-like systems, it is "/dev/null"; on Windows, "NUL".

+
const DevNull = "/dev/null"

Variables

Portable analogs of some common system call errors.

+

Errors returned from this package may be tested against these errors with errors.Is.

+
var (
+    // ErrInvalid indicates an invalid argument.
+    // Methods on File will return this error when the receiver is nil.
+    ErrInvalid = fs.ErrInvalid // "invalid argument"
+
+    ErrPermission = fs.ErrPermission // "permission denied"
+    ErrExist      = fs.ErrExist      // "file already exists"
+    ErrNotExist   = fs.ErrNotExist   // "file does not exist"
+    ErrClosed     = fs.ErrClosed     // "file already closed"
+
+    ErrNoDeadline       = errNoDeadline()       // "file type does not support deadline"
+    ErrDeadlineExceeded = errDeadlineExceeded() // "i/o timeout"
+)

Stdin, Stdout, and Stderr are open Files pointing to the standard input, standard output, and standard error file descriptors.

+

Note that the Go runtime writes to standard error for panics and crashes; closing Stderr may cause those messages to go elsewhere, perhaps to a file opened later.

+
var (
+    Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
+    Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
+    Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
+)

Args hold the command-line arguments, starting with the program name.

+
var Args []string

ErrProcessDone indicates a Process has finished.

+
var ErrProcessDone = errors.New("os: process already finished")

func Chdir

func Chdir(dir string) error

Chdir changes the current working directory to the named directory. If there is an error, it will be of type *PathError.

+

func Chmod

func Chmod(name string, mode FileMode) error

Chmod changes the mode of the named file to mode. If the file is a symbolic link, it changes the mode of the link's target. If there is an error, it will be of type *PathError.

+

A different subset of the mode bits are used, depending on the operating system.

+

On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and ModeSticky are used.

+

On Windows, only the 0200 bit (owner writable) of mode is used; it controls whether the file's read-only attribute is set or cleared. The other bits are currently unused. For compatibility with Go 1.12 and earlier, use a non-zero mode. Use mode 0400 for a read-only file and 0600 for a readable+writable file.

+

On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive, and ModeTemporary are used.

Example +

Code:

+if err := os.Chmod("some-filename", 0644); err != nil {
+    log.Fatal(err)
+}
+

func Chown

func Chown(name string, uid, gid int) error

Chown changes the numeric uid and gid of the named file. If the file is a symbolic link, it changes the uid and gid of the link's target. A uid or gid of -1 means to not change that value. If there is an error, it will be of type *PathError.

+

On Windows or Plan 9, Chown always returns the syscall.EWINDOWS or EPLAN9 error, wrapped in *PathError.

+

func Chtimes

func Chtimes(name string, atime time.Time, mtime time.Time) error

Chtimes changes the access and modification times of the named file, similar to the Unix utime() or utimes() functions. A zero time.Time value will leave the corresponding file time unchanged.

+

The underlying filesystem may truncate or round the values to a less precise time unit. If there is an error, it will be of type *PathError.

Example +

Code:

+mtime := time.Date(2006, time.February, 1, 3, 4, 5, 0, time.UTC)
+atime := time.Date(2007, time.March, 2, 4, 5, 6, 0, time.UTC)
+if err := os.Chtimes("some-filename", atime, mtime); err != nil {
+    log.Fatal(err)
+}
+

func Clearenv

func Clearenv()

Clearenv deletes all environment variables.

+

func DirFS 1.16

func DirFS(dir string) fs.FS

DirFS returns a file system (an fs.FS) for the tree of files rooted at the directory dir.

+

Note that DirFS("/prefix") only guarantees that the Open calls it makes to the operating system will begin with "/prefix": DirFS("/prefix").Open("file") is the same as os.Open("/prefix/file"). So if /prefix/file is a symbolic link pointing outside the /prefix tree, then using DirFS does not stop the access any more than using os.Open does. Additionally, the root of the fs.FS returned for a relative path, DirFS("prefix"), will be affected by later calls to Chdir. DirFS is therefore not a general substitute for a chroot-style security mechanism when the directory tree contains arbitrary content.

+

The directory dir must not be "".

+

The result implements io/fs.StatFS, io/fs.ReadFileFS and io/fs.ReadDirFS.

+

func Environ

func Environ() []string

Environ returns a copy of strings representing the environment, in the form "key=value".

+

func Executable 1.8

func Executable() (string, error)

Executable returns the path name for the executable that started the current process. There is no guarantee that the path is still pointing to the correct executable. If a symlink was used to start the process, depending on the operating system, the result might be the symlink or the path it pointed to. If a stable result is needed, path/filepath.EvalSymlinks might help.

+

Executable returns an absolute path unless an error occurred.

+

The main use case is finding resources located relative to an executable.

+

func Exit

func Exit(code int)

Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run.

+

For portability, the status code should be in the range [0, 125].

+

func Expand

func Expand(s string, mapping func(string) string) string

Expand replaces ${var} or $var in the string based on the mapping function. For example, os.ExpandEnv(s) is equivalent to os.Expand(s, os.Getenv).

Example +

Code:

mapper := func(placeholderName string) string {
+    switch placeholderName {
+    case "DAY_PART":
+        return "morning"
+    case "NAME":
+        return "Gopher"
+    }
+
+    return ""
+}
+
+fmt.Println(os.Expand("Good ${DAY_PART}, $NAME!", mapper))
+
+

Output:

Good morning, Gopher!
+

func ExpandEnv

func ExpandEnv(s string) string

ExpandEnv replaces ${var} or $var in the string according to the values of the current environment variables. References to undefined variables are replaced by the empty string.

Example +

Code:

os.Setenv("NAME", "gopher")
+os.Setenv("BURROW", "/usr/gopher")
+
+fmt.Println(os.ExpandEnv("$NAME lives in ${BURROW}."))
+
+

Output:

gopher lives in /usr/gopher.
+

func Getegid

func Getegid() int

Getegid returns the numeric effective group id of the caller.

+

On Windows, it returns -1.

+

func Getenv

func Getenv(key string) string

Getenv retrieves the value of the environment variable named by the key. It returns the value, which will be empty if the variable is not present. To distinguish between an empty value and an unset value, use LookupEnv.

Example +

Code:

os.Setenv("NAME", "gopher")
+os.Setenv("BURROW", "/usr/gopher")
+
+fmt.Printf("%s lives in %s.\n", os.Getenv("NAME"), os.Getenv("BURROW"))
+
+

Output:

gopher lives in /usr/gopher.
+

func Geteuid

func Geteuid() int

Geteuid returns the numeric effective user id of the caller.

+

On Windows, it returns -1.

+

func Getgid

func Getgid() int

Getgid returns the numeric group id of the caller.

+

On Windows, it returns -1.

+

func Getgroups

func Getgroups() ([]int, error)

Getgroups returns a list of the numeric ids of groups that the caller belongs to.

+

On Windows, it returns syscall.EWINDOWS. See the os/user package for a possible alternative.

+

func Getpagesize

func Getpagesize() int

Getpagesize returns the underlying system's memory page size.

+

func Getpid

func Getpid() int

Getpid returns the process id of the caller.

+

func Getppid

func Getppid() int

Getppid returns the process id of the caller's parent.

+

func Getuid

func Getuid() int

Getuid returns the numeric user id of the caller.

+

On Windows, it returns -1.

+

func Getwd

func Getwd() (dir string, err error)

Getwd returns a rooted path name corresponding to the current directory. If the current directory can be reached via multiple paths (due to symbolic links), Getwd may return any one of them.

+

func Hostname

func Hostname() (name string, err error)

Hostname returns the host name reported by the kernel.

+

func IsExist

func IsExist(err error) bool

IsExist returns a boolean indicating whether the error is known to report that a file or directory already exists. It is satisfied by ErrExist as well as some syscall errors.

+

This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrExist).

+

func IsNotExist

func IsNotExist(err error) bool

IsNotExist returns a boolean indicating whether the error is known to report that a file or directory does not exist. It is satisfied by ErrNotExist as well as some syscall errors.

+

This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrNotExist).

+

func IsPathSeparator

func IsPathSeparator(c uint8) bool

IsPathSeparator reports whether c is a directory separator character.

+

func IsPermission

func IsPermission(err error) bool

IsPermission returns a boolean indicating whether the error is known to report that permission is denied. It is satisfied by ErrPermission as well as some syscall errors.

+

This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrPermission).

+

func IsTimeout 1.10

func IsTimeout(err error) bool

IsTimeout returns a boolean indicating whether the error is known to report that a timeout occurred.

+

This function predates errors.Is, and the notion of whether an error indicates a timeout can be ambiguous. For example, the Unix error EWOULDBLOCK sometimes indicates a timeout and sometimes does not. New code should use errors.Is with a value appropriate to the call returning the error, such as os.ErrDeadlineExceeded.

+

func Lchown

func Lchown(name string, uid, gid int) error

Lchown changes the numeric uid and gid of the named file. If the file is a symbolic link, it changes the uid and gid of the link itself. If there is an error, it will be of type *PathError.

+

On Windows, it always returns the syscall.EWINDOWS error, wrapped in *PathError.

+
func Link(oldname, newname string) error

Link creates newname as a hard link to the oldname file. If there is an error, it will be of type *LinkError.

+

func LookupEnv 1.5

func LookupEnv(key string) (string, bool)

LookupEnv retrieves the value of the environment variable named by the key. If the variable is present in the environment the value (which may be empty) is returned and the boolean is true. Otherwise the returned value will be empty and the boolean will be false.

Example +

Code:

show := func(key string) {
+    val, ok := os.LookupEnv(key)
+    if !ok {
+        fmt.Printf("%s not set\n", key)
+    } else {
+        fmt.Printf("%s=%s\n", key, val)
+    }
+}
+
+os.Setenv("SOME_KEY", "value")
+os.Setenv("EMPTY_KEY", "")
+
+show("SOME_KEY")
+show("EMPTY_KEY")
+show("MISSING_KEY")
+
+

Output:

SOME_KEY=value
+EMPTY_KEY=
+MISSING_KEY not set
+

func Mkdir

func Mkdir(name string, perm FileMode) error

Mkdir creates a new directory with the specified name and permission bits (before umask). If there is an error, it will be of type *PathError.

Example +

Code:

+err := os.Mkdir("testdir", 0750)
+if err != nil && !os.IsExist(err) {
+    log.Fatal(err)
+}
+err = os.WriteFile("testdir/testfile.txt", []byte("Hello, Gophers!"), 0660)
+if err != nil {
+    log.Fatal(err)
+}
+

func MkdirAll

func MkdirAll(path string, perm FileMode) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm (before umask) are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

Example +

Code:

+err := os.MkdirAll("test/subdir", 0750)
+if err != nil {
+    log.Fatal(err)
+}
+err = os.WriteFile("test/subdir/testfile.txt", []byte("Hello, Gophers!"), 0660)
+if err != nil {
+    log.Fatal(err)
+}
+

func MkdirTemp 1.16

func MkdirTemp(dir, pattern string) (string, error)

MkdirTemp creates a new temporary directory in the directory dir and returns the pathname of the new directory. The new directory's name is generated by adding a random string to the end of pattern. If pattern includes a "*", the random string replaces the last "*" instead. If dir is the empty string, MkdirTemp uses the default directory for temporary files, as returned by TempDir. Multiple programs or goroutines calling MkdirTemp simultaneously will not choose the same directory. It is the caller's responsibility to remove the directory when it is no longer needed.

Example +

Code:

+dir, err := os.MkdirTemp("", "example")
+if err != nil {
+    log.Fatal(err)
+}
+defer os.RemoveAll(dir) // clean up
+
+file := filepath.Join(dir, "tmpfile")
+if err := os.WriteFile(file, []byte("content"), 0666); err != nil {
+    log.Fatal(err)
+}
+

Example (Suffix) +

Code:

+logsDir, err := os.MkdirTemp("", "*-logs")
+if err != nil {
+    log.Fatal(err)
+}
+defer os.RemoveAll(logsDir) // clean up
+
+// Logs can be cleaned out earlier if needed by searching
+// for all directories whose suffix ends in *-logs.
+globPattern := filepath.Join(os.TempDir(), "*-logs")
+matches, err := filepath.Glob(globPattern)
+if err != nil {
+    log.Fatalf("Failed to match %q: %v", globPattern, err)
+}
+
+for _, match := range matches {
+    if err := os.RemoveAll(match); err != nil {
+        log.Printf("Failed to remove %q: %v", match, err)
+    }
+}
+

func NewSyscallError

func NewSyscallError(syscall string, err error) error

NewSyscallError returns, as an error, a new SyscallError with the given system call name and error details. As a convenience, if err is nil, NewSyscallError returns nil.

+

func Pipe

func Pipe() (r *File, w *File, err error)

Pipe returns a connected pair of Files; reads from r return bytes written to w. It returns the files and an error, if any.

+

func ReadFile 1.16

func ReadFile(name string) ([]byte, error)

ReadFile reads the named file and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

Example +

Code:

data, err := os.ReadFile("testdata/hello")
+if err != nil {
+    log.Fatal(err)
+}
+os.Stdout.Write(data)
+
+

Output:

Hello, Gophers!
+
func Readlink(name string) (string, error)

Readlink returns the destination of the named symbolic link. If there is an error, it will be of type *PathError.

+

If the link destination is relative, Readlink returns the relative path without resolving it to an absolute one.

Code:

// First, we create a relative symlink to a file.
+d, err := os.MkdirTemp("", "")
+if err != nil {
+    log.Fatal(err)
+}
+defer os.RemoveAll(d)
+targetPath := filepath.Join(d, "hello.txt")
+if err := os.WriteFile(targetPath, []byte("Hello, Gophers!"), 0644); err != nil {
+    log.Fatal(err)
+}
+linkPath := filepath.Join(d, "hello.link")
+if err := os.Symlink("hello.txt", filepath.Join(d, "hello.link")); err != nil {
+    if errors.Is(err, errors.ErrUnsupported) {
+        // Allow the example to run on platforms that do not support symbolic links.
+        fmt.Printf("%s links to %s\n", filepath.Base(linkPath), "hello.txt")
+        return
+    }
+    log.Fatal(err)
+}
+
+// Readlink returns the relative path as passed to os.Symlink.
+dst, err := os.Readlink(linkPath)
+if err != nil {
+    log.Fatal(err)
+}
+fmt.Printf("%s links to %s\n", filepath.Base(linkPath), dst)
+
+var dstAbs string
+if filepath.IsAbs(dst) {
+    dstAbs = dst
+} else {
+    // Symlink targets are relative to the directory containing the link.
+    dstAbs = filepath.Join(filepath.Dir(linkPath), dst)
+}
+
+// Check that the target is correct by comparing it with os.Stat
+// on the original target path.
+dstInfo, err := os.Stat(dstAbs)
+if err != nil {
+    log.Fatal(err)
+}
+targetInfo, err := os.Stat(targetPath)
+if err != nil {
+    log.Fatal(err)
+}
+if !os.SameFile(dstInfo, targetInfo) {
+    log.Fatalf("link destination (%s) is not the same file as %s", dstAbs, targetPath)
+}
+
+

Output:

hello.link links to hello.txt
+

func Remove

func Remove(name string) error

Remove removes the named file or (empty) directory. If there is an error, it will be of type *PathError.

+

func RemoveAll

func RemoveAll(path string) error

RemoveAll removes path and any children it contains. It removes everything it can but returns the first error it encounters. If the path does not exist, RemoveAll returns nil (no error). If there is an error, it will be of type *PathError.

+

func Rename

func Rename(oldpath, newpath string) error

Rename renames (moves) oldpath to newpath. If newpath already exists and is not a directory, Rename replaces it. OS-specific restrictions may apply when oldpath and newpath are in different directories. Even within the same directory, on non-Unix platforms Rename is not an atomic operation. If there is an error, it will be of type *LinkError.

+

func SameFile

func SameFile(fi1, fi2 FileInfo) bool

SameFile reports whether fi1 and fi2 describe the same file. For example, on Unix this means that the device and inode fields of the two underlying structures are identical; on other systems the decision may be based on the path names. SameFile only applies to results returned by this package's Stat. It returns false in other cases.

+

func Setenv

func Setenv(key, value string) error

Setenv sets the value of the environment variable named by the key. It returns an error, if any.

+
func Symlink(oldname, newname string) error

Symlink creates newname as a symbolic link to oldname. On Windows, a symlink to a non-existent oldname creates a file symlink; if oldname is later created as a directory the symlink will not work. If there is an error, it will be of type *LinkError.

+

func TempDir

func TempDir() string

TempDir returns the default directory to use for temporary files.

+

On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, it uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp.

+

The directory is neither guaranteed to exist nor have accessible permissions.

+

func Truncate

func Truncate(name string, size int64) error

Truncate changes the size of the named file. If the file is a symbolic link, it changes the size of the link's target. If there is an error, it will be of type *PathError.

+

func Unsetenv 1.4

func Unsetenv(key string) error

Unsetenv unsets a single environment variable.

Example +

Code:

+os.Setenv("TMPDIR", "/my/tmp")
+defer os.Unsetenv("TMPDIR")
+

func UserCacheDir 1.11

func UserCacheDir() (string, error)

UserCacheDir returns the default root directory to use for user-specific cached data. Users should create their own application-specific subdirectory within this one and use that.

+

On Unix systems, it returns $XDG_CACHE_HOME as specified by https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.cache. On Darwin, it returns $HOME/Library/Caches. On Windows, it returns %LocalAppData%. On Plan 9, it returns $home/lib/cache.

+

If the location cannot be determined (for example, $HOME is not defined), then it will return an error.

Example +

Code:

dir, dirErr := os.UserCacheDir()
+if dirErr == nil {
+    dir = filepath.Join(dir, "ExampleUserCacheDir")
+}
+
+getCache := func(name string) ([]byte, error) {
+    if dirErr != nil {
+        return nil, &os.PathError{Op: "getCache", Path: name, Err: os.ErrNotExist}
+    }
+    return os.ReadFile(filepath.Join(dir, name))
+}
+
+var mkdirOnce sync.Once
+putCache := func(name string, b []byte) error {
+    if dirErr != nil {
+        return &os.PathError{Op: "putCache", Path: name, Err: dirErr}
+    }
+    mkdirOnce.Do(func() {
+        if err := os.MkdirAll(dir, 0700); err != nil {
+            log.Printf("can't create user cache dir: %v", err)
+        }
+    })
+    return os.WriteFile(filepath.Join(dir, name), b, 0600)
+}
+
+// Read and store cached data.
+// …
+_ = getCache
+_ = putCache
+
+

func UserConfigDir 1.13

func UserConfigDir() (string, error)

UserConfigDir returns the default root directory to use for user-specific configuration data. Users should create their own application-specific subdirectory within this one and use that.

+

On Unix systems, it returns $XDG_CONFIG_HOME as specified by https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.config. On Darwin, it returns $HOME/Library/Application Support. On Windows, it returns %AppData%. On Plan 9, it returns $home/lib.

+

If the location cannot be determined (for example, $HOME is not defined), then it will return an error.

Example +

Code:

dir, dirErr := os.UserConfigDir()
+
+var (
+    configPath string
+    origConfig []byte
+)
+if dirErr == nil {
+    configPath = filepath.Join(dir, "ExampleUserConfigDir", "example.conf")
+    var err error
+    origConfig, err = os.ReadFile(configPath)
+    if err != nil && !os.IsNotExist(err) {
+        // The user has a config file but we couldn't read it.
+        // Report the error instead of ignoring their configuration.
+        log.Fatal(err)
+    }
+}
+
+// Use and perhaps make changes to the config.
+config := bytes.Clone(origConfig)
+// …
+
+// Save changes.
+if !bytes.Equal(config, origConfig) {
+    if configPath == "" {
+        log.Printf("not saving config changes: %v", dirErr)
+    } else {
+        err := os.MkdirAll(filepath.Dir(configPath), 0700)
+        if err == nil {
+            err = os.WriteFile(configPath, config, 0600)
+        }
+        if err != nil {
+            log.Printf("error saving config changes: %v", err)
+        }
+    }
+}
+
+

func UserHomeDir 1.12

func UserHomeDir() (string, error)

UserHomeDir returns the current user's home directory.

+

On Unix, including macOS, it returns the $HOME environment variable. On Windows, it returns %USERPROFILE%. On Plan 9, it returns the $home environment variable.

+

If the expected variable is not set in the environment, UserHomeDir returns either a platform-specific default value or a non-nil error.

+

func WriteFile 1.16

func WriteFile(name string, data []byte, perm FileMode) error

WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions. Since WriteFile requires multiple system calls to complete, a failure mid-operation can leave the file in a partially written state.

Example +

Code:

+err := os.WriteFile("testdata/hello", []byte("Hello, Gophers!"), 0666)
+if err != nil {
+    log.Fatal(err)
+}
+

type DirEntry 1.16

A DirEntry is an entry read from a directory (using the ReadDir function or a File's ReadDir method).

+
type DirEntry = fs.DirEntry

func ReadDir 1.16

func ReadDir(name string) ([]DirEntry, error)

ReadDir reads the named directory, returning all its directory entries sorted by filename. If an error occurs reading the directory, ReadDir returns the entries it was able to read before the error, along with the error.

Example +

Code:

+files, err := os.ReadDir(".")
+if err != nil {
+    log.Fatal(err)
+}
+
+for _, file := range files {
+    fmt.Println(file.Name())
+}
+

type File

File represents an open file descriptor.

+
type File struct {
+    // contains filtered or unexported fields
+}
+

func Create

func Create(name string) (*File, error)

Create creates or truncates the named file. If the file already exists, it is truncated. If the file does not exist, it is created with mode 0666 (before umask). If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR. If there is an error, it will be of type *PathError.

+

func CreateTemp 1.16

func CreateTemp(dir, pattern string) (*File, error)

CreateTemp creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting file. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a "*", the random string replaces the last "*". If dir is the empty string, CreateTemp uses the default directory for temporary files, as returned by TempDir. Multiple programs or goroutines calling CreateTemp simultaneously will not choose the same file. The caller can use the file's Name method to find the pathname of the file. It is the caller's responsibility to remove the file when it is no longer needed.

Example +

Code:

+f, err := os.CreateTemp("", "example")
+if err != nil {
+    log.Fatal(err)
+}
+defer os.Remove(f.Name()) // clean up
+
+if _, err := f.Write([]byte("content")); err != nil {
+    log.Fatal(err)
+}
+if err := f.Close(); err != nil {
+    log.Fatal(err)
+}
+

Example (Suffix) +

Code:

+f, err := os.CreateTemp("", "example.*.txt")
+if err != nil {
+    log.Fatal(err)
+}
+defer os.Remove(f.Name()) // clean up
+
+if _, err := f.Write([]byte("content")); err != nil {
+    f.Close()
+    log.Fatal(err)
+}
+if err := f.Close(); err != nil {
+    log.Fatal(err)
+}
+

func NewFile

func NewFile(fd uintptr, name string) *File

NewFile returns a new File with the given file descriptor and name. The returned value will be nil if fd is not a valid file descriptor. On Unix systems, if the file descriptor is in non-blocking mode, NewFile will attempt to return a pollable File (one for which the SetDeadline methods work).

+

After passing it to NewFile, fd may become invalid under the same conditions described in the comments of the Fd method, and the same constraints apply.

+

func Open

func Open(name string) (*File, error)

Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

+

func OpenFile

func OpenFile(name string, flag int, perm FileMode) (*File, error)

OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag is passed, it is created with mode perm (before umask). If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.

Example +

Code:

+f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0644)
+if err != nil {
+    log.Fatal(err)
+}
+if err := f.Close(); err != nil {
+    log.Fatal(err)
+}
+

Example (Append) +

Code:

+// If the file doesn't exist, create it, or append to the file
+f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
+if err != nil {
+    log.Fatal(err)
+}
+if _, err := f.Write([]byte("appended some data\n")); err != nil {
+    f.Close() // ignore error; Write error takes precedence
+    log.Fatal(err)
+}
+if err := f.Close(); err != nil {
+    log.Fatal(err)
+}
+

func (*File) Chdir

func (f *File) Chdir() error

Chdir changes the current working directory to the file, which must be a directory. If there is an error, it will be of type *PathError.

+

func (*File) Chmod

func (f *File) Chmod(mode FileMode) error

Chmod changes the mode of the file to mode. If there is an error, it will be of type *PathError.

+

func (*File) Chown

func (f *File) Chown(uid, gid int) error

Chown changes the numeric uid and gid of the named file. If there is an error, it will be of type *PathError.

+

On Windows, it always returns the syscall.EWINDOWS error, wrapped in *PathError.

+

func (*File) Close

func (f *File) Close() error

Close closes the File, rendering it unusable for I/O. On files that support SetDeadline, any pending I/O operations will be canceled and return immediately with an ErrClosed error. Close will return an error if it has already been called.

+

func (*File) Fd

func (f *File) Fd() uintptr

Fd returns the integer Unix file descriptor referencing the open file. If f is closed, the file descriptor becomes invalid. If f is garbage collected, a finalizer may close the file descriptor, making it invalid; see runtime.SetFinalizer for more information on when a finalizer might be run. On Unix systems this will cause the SetDeadline methods to stop working. Because file descriptors can be reused, the returned file descriptor may only be closed through the Close method of f, or by its finalizer during garbage collection. Otherwise, during garbage collection the finalizer may close an unrelated file descriptor with the same (reused) number.

+

As an alternative, see the f.SyscallConn method.

+

func (*File) Name

func (f *File) Name() string

Name returns the name of the file as presented to Open.

+

func (*File) Read

func (f *File) Read(b []byte) (n int, err error)

Read reads up to len(b) bytes from the File and stores them in b. It returns the number of bytes read and any error encountered. At end of file, Read returns 0, io.EOF.

+

func (*File) ReadAt

func (f *File) ReadAt(b []byte, off int64) (n int, err error)

ReadAt reads len(b) bytes from the File starting at byte offset off. It returns the number of bytes read and the error, if any. ReadAt always returns a non-nil error when n < len(b). At end of file, that error is io.EOF.

+

func (*File) ReadDir 1.16

func (f *File) ReadDir(n int) ([]DirEntry, error)

ReadDir reads the contents of the directory associated with the file f and returns a slice of DirEntry values in directory order. Subsequent calls on the same file will yield later DirEntry records in the directory.

+

If n > 0, ReadDir returns at most n DirEntry records. In this case, if ReadDir returns an empty slice, it will return an error explaining why. At the end of a directory, the error is io.EOF.

+

If n <= 0, ReadDir returns all the DirEntry records remaining in the directory. When it succeeds, it returns a nil error (not io.EOF).

+

func (*File) ReadFrom 1.15

func (f *File) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom implements io.ReaderFrom.

+

func (*File) Readdir

func (f *File) Readdir(n int) ([]FileInfo, error)

Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.

+

If n > 0, Readdir returns at most n FileInfo structures. In this case, if Readdir returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is io.EOF.

+

If n <= 0, Readdir returns all the FileInfo from the directory in a single slice. In this case, if Readdir succeeds (reads all the way to the end of the directory), it returns the slice and a nil error. If it encounters an error before the end of the directory, Readdir returns the FileInfo read until that point and a non-nil error.

+

Most clients are better served by the more efficient ReadDir method.

+

func (*File) Readdirnames

func (f *File) Readdirnames(n int) (names []string, err error)

Readdirnames reads the contents of the directory associated with file and returns a slice of up to n names of files in the directory, in directory order. Subsequent calls on the same file will yield further names.

+

If n > 0, Readdirnames returns at most n names. In this case, if Readdirnames returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is io.EOF.

+

If n <= 0, Readdirnames returns all the names from the directory in a single slice. In this case, if Readdirnames succeeds (reads all the way to the end of the directory), it returns the slice and a nil error. If it encounters an error before the end of the directory, Readdirnames returns the names read until that point and a non-nil error.

+

func (*File) Seek

func (f *File) Seek(offset int64, whence int) (ret int64, err error)

Seek sets the offset for the next Read or Write on file to offset, interpreted according to whence: 0 means relative to the origin of the file, 1 means relative to the current offset, and 2 means relative to the end. It returns the new offset and an error, if any. The behavior of Seek on a file opened with O_APPEND is not specified.

+

func (*File) SetDeadline 1.10

func (f *File) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines for a File. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.

+

Only some kinds of files support setting a deadline. Calls to SetDeadline for files that do not support deadlines will return ErrNoDeadline. On most systems ordinary files do not support deadlines, but pipes do.

+

A deadline is an absolute time after which I/O operations fail with an error instead of blocking. The deadline applies to all future and pending I/O, not just the immediately following call to Read or Write. After a deadline has been exceeded, the connection can be refreshed by setting a deadline in the future.

+

If the deadline is exceeded a call to Read or Write or to other I/O methods will return an error that wraps ErrDeadlineExceeded. This can be tested using errors.Is(err, os.ErrDeadlineExceeded). That error implements the Timeout method, and calling the Timeout method will return true, but there are other possible errors for which the Timeout will return true even if the deadline has not been exceeded.

+

An idle timeout can be implemented by repeatedly extending the deadline after successful Read or Write calls.

+

A zero value for t means I/O operations will not time out.

+

func (*File) SetReadDeadline 1.10

func (f *File) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future Read calls and any currently-blocked Read call. A zero value for t means Read will not time out. Not all files support setting deadlines; see SetDeadline.

+

func (*File) SetWriteDeadline 1.10

func (f *File) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for any future Write calls and any currently-blocked Write call. Even if Write times out, it may return n > 0, indicating that some of the data was successfully written. A zero value for t means Write will not time out. Not all files support setting deadlines; see SetDeadline.

+

func (*File) Stat

func (f *File) Stat() (FileInfo, error)

Stat returns the FileInfo structure describing file. If there is an error, it will be of type *PathError.

+

func (*File) Sync

func (f *File) Sync() error

Sync commits the current contents of the file to stable storage. Typically, this means flushing the file system's in-memory copy of recently written data to disk.

+

func (*File) SyscallConn 1.12

func (f *File) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw file. This implements the syscall.Conn interface.

+

func (*File) Truncate

func (f *File) Truncate(size int64) error

Truncate changes the size of the file. It does not change the I/O offset. If there is an error, it will be of type *PathError.

+

func (*File) Write

func (f *File) Write(b []byte) (n int, err error)

Write writes len(b) bytes from b to the File. It returns the number of bytes written and an error, if any. Write returns a non-nil error when n != len(b).

+

func (*File) WriteAt

func (f *File) WriteAt(b []byte, off int64) (n int, err error)

WriteAt writes len(b) bytes to the File starting at byte offset off. It returns the number of bytes written and an error, if any. WriteAt returns a non-nil error when n != len(b).

+

If file was opened with the O_APPEND flag, WriteAt returns an error.

+

func (*File) WriteString

func (f *File) WriteString(s string) (n int, err error)

WriteString is like Write, but writes the contents of string s rather than a slice of bytes.

+

func (*File) WriteTo 1.22

func (f *File) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements io.WriterTo.

+

type FileInfo

A FileInfo describes a file and is returned by Stat and Lstat.

+
type FileInfo = fs.FileInfo

func Lstat

func Lstat(name string) (FileInfo, error)

Lstat returns a FileInfo describing the named file. If the file is a symbolic link, the returned FileInfo describes the symbolic link. Lstat makes no attempt to follow the link. If there is an error, it will be of type *PathError.

+

On Windows, if the file is a reparse point that is a surrogate for another named entity (such as a symbolic link or mounted folder), the returned FileInfo describes the reparse point, and makes no attempt to resolve it.

+

func Stat

func Stat(name string) (FileInfo, error)

Stat returns a FileInfo describing the named file. If there is an error, it will be of type *PathError.

+

type FileMode

A FileMode represents a file's mode and permission bits. The bits have the same definition on all systems, so that information about files can be moved from one system to another portably. Not all bits apply to all systems. The only required bit is ModeDir for directories.

+
type FileMode = fs.FileMode

Example +

Code:

+fi, err := os.Lstat("some-filename")
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Printf("permissions: %#o\n", fi.Mode().Perm()) // 0400, 0777, etc.
+switch mode := fi.Mode(); {
+case mode.IsRegular():
+    fmt.Println("regular file")
+case mode.IsDir():
+    fmt.Println("directory")
+case mode&fs.ModeSymlink != 0:
+    fmt.Println("symbolic link")
+case mode&fs.ModeNamedPipe != 0:
+    fmt.Println("named pipe")
+}
+

type LinkError

LinkError records an error during a link or symlink or rename system call and the paths that caused it.

+
type LinkError struct {
+    Op  string
+    Old string
+    New string
+    Err error
+}
+

func (*LinkError) Error

func (e *LinkError) Error() string

func (*LinkError) Unwrap 1.13

func (e *LinkError) Unwrap() error

type PathError

PathError records an error and the operation and file path that caused it.

+
type PathError = fs.PathError

type ProcAttr

ProcAttr holds the attributes that will be applied to a new process started by StartProcess.

+
type ProcAttr struct {
+    // If Dir is non-empty, the child changes into the directory before
+    // creating the process.
+    Dir string
+    // If Env is non-nil, it gives the environment variables for the
+    // new process in the form returned by Environ.
+    // If it is nil, the result of Environ will be used.
+    Env []string
+    // Files specifies the open files inherited by the new process. The
+    // first three entries correspond to standard input, standard output, and
+    // standard error. An implementation may support additional entries,
+    // depending on the underlying operating system. A nil entry corresponds
+    // to that file being closed when the process starts.
+    // On Unix systems, StartProcess will change these File values
+    // to blocking mode, which means that SetDeadline will stop working
+    // and calling Close will not interrupt a Read or Write.
+    Files []*File
+
+    // Operating system-specific process creation attributes.
+    // Note that setting this field means that your program
+    // may not execute properly or even compile on some
+    // operating systems.
+    Sys *syscall.SysProcAttr
+}
+

type Process

Process stores the information about a process created by StartProcess.

+
type Process struct {
+    Pid int
+    // contains filtered or unexported fields
+}
+

func FindProcess

func FindProcess(pid int) (*Process, error)

FindProcess looks for a running process by its pid.

+

The Process it returns can be used to obtain information about the underlying operating system process.

+

On Unix systems, FindProcess always succeeds and returns a Process for the given pid, regardless of whether the process exists. To test whether the process actually exists, see whether p.Signal(syscall.Signal(0)) reports an error.

+

func StartProcess

func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)

StartProcess starts a new process with the program, arguments and attributes specified by name, argv and attr. The argv slice will become os.Args in the new process, so it normally starts with the program name.

+

If the calling goroutine has locked the operating system thread with runtime.LockOSThread and modified any inheritable OS-level thread state (for example, Linux or Plan 9 name spaces), the new process will inherit the caller's thread state.

+

StartProcess is a low-level interface. The os/exec package provides higher-level interfaces.

+

If there is an error, it will be of type *PathError.

+

func (*Process) Kill

func (p *Process) Kill() error

Kill causes the Process to exit immediately. Kill does not wait until the Process has actually exited. This only kills the Process itself, not any other processes it may have started.

+

func (*Process) Release

func (p *Process) Release() error

Release releases any resources associated with the Process p, rendering it unusable in the future. Release only needs to be called if Wait is not.

+

func (*Process) Signal

func (p *Process) Signal(sig Signal) error

Signal sends a signal to the Process. Sending Interrupt on Windows is not implemented.

+

func (*Process) Wait

func (p *Process) Wait() (*ProcessState, error)

Wait waits for the Process to exit, and then returns a ProcessState describing its status and an error, if any. Wait releases any resources associated with the Process. On most operating systems, the Process must be a child of the current process or an error will be returned.

+

type ProcessState

ProcessState stores information about a process, as reported by Wait.

+
type ProcessState struct {
+    // contains filtered or unexported fields
+}
+

func (*ProcessState) ExitCode 1.12

func (p *ProcessState) ExitCode() int

ExitCode returns the exit code of the exited process, or -1 if the process hasn't exited or was terminated by a signal.

+

func (*ProcessState) Exited

func (p *ProcessState) Exited() bool

Exited reports whether the program has exited. On Unix systems this reports true if the program exited due to calling exit, but false if the program terminated due to a signal.

+

func (*ProcessState) Pid

func (p *ProcessState) Pid() int

Pid returns the process id of the exited process.

+

func (*ProcessState) String

func (p *ProcessState) String() string

func (*ProcessState) Success

func (p *ProcessState) Success() bool

Success reports whether the program exited successfully, such as with exit status 0 on Unix.

+

func (*ProcessState) Sys

func (p *ProcessState) Sys() any

Sys returns system-dependent exit information about the process. Convert it to the appropriate underlying type, such as syscall.WaitStatus on Unix, to access its contents.

+

func (*ProcessState) SysUsage

func (p *ProcessState) SysUsage() any

SysUsage returns system-dependent resource usage information about the exited process. Convert it to the appropriate underlying type, such as *syscall.Rusage on Unix, to access its contents. (On Unix, *syscall.Rusage matches struct rusage as defined in the getrusage(2) manual page.)

+

func (*ProcessState) SystemTime

func (p *ProcessState) SystemTime() time.Duration

SystemTime returns the system CPU time of the exited process and its children.

+

func (*ProcessState) UserTime

func (p *ProcessState) UserTime() time.Duration

UserTime returns the user CPU time of the exited process and its children.

+

type Signal

A Signal represents an operating system signal. The usual underlying implementation is operating system-dependent: on Unix it is syscall.Signal.

+
type Signal interface {
+    String() string
+    Signal() // to distinguish from other Stringers
+}

The only signal values guaranteed to be present in the os package on all systems are os.Interrupt (send the process an interrupt) and os.Kill (force the process to exit). On Windows, sending os.Interrupt to a process with os.Process.Signal is not implemented; it will return an error instead of sending a signal.

+
var (
+    Interrupt Signal = syscall.SIGINT
+    Kill      Signal = syscall.SIGKILL
+)

type SyscallError

SyscallError records an error from a specific system call.

+
type SyscallError struct {
+    Syscall string
+    Err     error
+}
+

func (*SyscallError) Error

func (e *SyscallError) Error() string

func (*SyscallError) Timeout 1.10

func (e *SyscallError) Timeout() bool

Timeout reports whether this error represents a timeout.

+

func (*SyscallError) Unwrap 1.13

func (e *SyscallError) Unwrap() error

Subdirectories

Name Synopsis
..
exec Package exec runs external commands.
signal Package signal implements access to incoming signals.
user Package user allows user account lookups by name or id.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/os/ +

+
diff --git a/devdocs/go/os%2Fsignal%2Findex.html b/devdocs/go/os%2Fsignal%2Findex.html new file mode 100644 index 00000000..6156a266 --- /dev/null +++ b/devdocs/go/os%2Fsignal%2Findex.html @@ -0,0 +1,127 @@ +

Package signal

Overview

Package signal implements access to incoming signals.

+

Signals are primarily used on Unix-like systems. For the use of this package on Windows and Plan 9, see below.

+

Types of signals

The signals SIGKILL and SIGSTOP may not be caught by a program, and therefore cannot be affected by this package.

+

Synchronous signals are signals triggered by errors in program execution: SIGBUS, SIGFPE, and SIGSEGV. These are only considered synchronous when caused by program execution, not when sent using os.Process.Kill or the kill program or some similar mechanism. In general, except as discussed below, Go programs will convert a synchronous signal into a run-time panic.

+

The remaining signals are asynchronous signals. They are not triggered by program errors, but are instead sent from the kernel or from some other program.

+

Of the asynchronous signals, the SIGHUP signal is sent when a program loses its controlling terminal. The SIGINT signal is sent when the user at the controlling terminal presses the interrupt character, which by default is ^C (Control-C). The SIGQUIT signal is sent when the user at the controlling terminal presses the quit character, which by default is ^\ (Control-Backslash). In general you can cause a program to simply exit by pressing ^C, and you can cause it to exit with a stack dump by pressing ^\.

+

Default behavior of signals in Go programs

By default, a synchronous signal is converted into a run-time panic. A SIGHUP, SIGINT, or SIGTERM signal causes the program to exit. A SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGSTKFLT, SIGEMT, or SIGSYS signal causes the program to exit with a stack dump. A SIGTSTP, SIGTTIN, or SIGTTOU signal gets the system default behavior (these signals are used by the shell for job control). The SIGPROF signal is handled directly by the Go runtime to implement runtime.CPUProfile. Other signals will be caught but no action will be taken.

+

If the Go program is started with either SIGHUP or SIGINT ignored (signal handler set to SIG_IGN), they will remain ignored.

+

If the Go program is started with a non-empty signal mask, that will generally be honored. However, some signals are explicitly unblocked: the synchronous signals, SIGILL, SIGTRAP, SIGSTKFLT, SIGCHLD, SIGPROF, and, on Linux, signals 32 (SIGCANCEL) and 33 (SIGSETXID) (SIGCANCEL and SIGSETXID are used internally by glibc). Subprocesses started by os.Exec, or by os/exec, will inherit the modified signal mask.

+

Changing the behavior of signals in Go programs

The functions in this package allow a program to change the way Go programs handle signals.

+

Notify disables the default behavior for a given set of asynchronous signals and instead delivers them over one or more registered channels. Specifically, it applies to the signals SIGHUP, SIGINT, SIGQUIT, SIGABRT, and SIGTERM. It also applies to the job control signals SIGTSTP, SIGTTIN, and SIGTTOU, in which case the system default behavior does not occur. It also applies to some signals that otherwise cause no action: SIGUSR1, SIGUSR2, SIGPIPE, SIGALRM, SIGCHLD, SIGCONT, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGWINCH, SIGIO, SIGPWR, SIGSYS, SIGINFO, SIGTHR, SIGWAITING, SIGLWP, SIGFREEZE, SIGTHAW, SIGLOST, SIGXRES, SIGJVM1, SIGJVM2, and any real time signals used on the system. Note that not all of these signals are available on all systems.

+

If the program was started with SIGHUP or SIGINT ignored, and Notify is called for either signal, a signal handler will be installed for that signal and it will no longer be ignored. If, later, Reset or Ignore is called for that signal, or Stop is called on all channels passed to Notify for that signal, the signal will once again be ignored. Reset will restore the system default behavior for the signal, while Ignore will cause the system to ignore the signal entirely.

+

If the program is started with a non-empty signal mask, some signals will be explicitly unblocked as described above. If Notify is called for a blocked signal, it will be unblocked. If, later, Reset is called for that signal, or Stop is called on all channels passed to Notify for that signal, the signal will once again be blocked.

+

SIGPIPE

When a Go program writes to a broken pipe, the kernel will raise a SIGPIPE signal.

+

If the program has not called Notify to receive SIGPIPE signals, then the behavior depends on the file descriptor number. A write to a broken pipe on file descriptors 1 or 2 (standard output or standard error) will cause the program to exit with a SIGPIPE signal. A write to a broken pipe on some other file descriptor will take no action on the SIGPIPE signal, and the write will fail with an EPIPE error.

+

If the program has called Notify to receive SIGPIPE signals, the file descriptor number does not matter. The SIGPIPE signal will be delivered to the Notify channel, and the write will fail with an EPIPE error.

+

This means that, by default, command line programs will behave like typical Unix command line programs, while other programs will not crash with SIGPIPE when writing to a closed network connection.

+

Go programs that use cgo or SWIG

In a Go program that includes non-Go code, typically C/C++ code accessed using cgo or SWIG, Go's startup code normally runs first. It configures the signal handlers as expected by the Go runtime, before the non-Go startup code runs. If the non-Go startup code wishes to install its own signal handlers, it must take certain steps to keep Go working well. This section documents those steps and the overall effect changes to signal handler settings by the non-Go code can have on Go programs. In rare cases, the non-Go code may run before the Go code, in which case the next section also applies.

+

If the non-Go code called by the Go program does not change any signal handlers or masks, then the behavior is the same as for a pure Go program.

+

If the non-Go code installs any signal handlers, it must use the SA_ONSTACK flag with sigaction. Failing to do so is likely to cause the program to crash if the signal is received. Go programs routinely run with a limited stack, and therefore set up an alternate signal stack.

+

If the non-Go code installs a signal handler for any of the synchronous signals (SIGBUS, SIGFPE, SIGSEGV), then it should record the existing Go signal handler. If those signals occur while executing Go code, it should invoke the Go signal handler (whether the signal occurs while executing Go code can be determined by looking at the PC passed to the signal handler). Otherwise some Go run-time panics will not occur as expected.

+

If the non-Go code installs a signal handler for any of the asynchronous signals, it may invoke the Go signal handler or not as it chooses. Naturally, if it does not invoke the Go signal handler, the Go behavior described above will not occur. This can be an issue with the SIGPROF signal in particular.

+

The non-Go code should not change the signal mask on any threads created by the Go runtime. If the non-Go code starts new threads of its own, it may set the signal mask as it pleases.

+

If the non-Go code starts a new thread, changes the signal mask, and then invokes a Go function in that thread, the Go runtime will automatically unblock certain signals: the synchronous signals, SIGILL, SIGTRAP, SIGSTKFLT, SIGCHLD, SIGPROF, SIGCANCEL, and SIGSETXID. When the Go function returns, the non-Go signal mask will be restored.

+

If the Go signal handler is invoked on a non-Go thread not running Go code, the handler generally forwards the signal to the non-Go code, as follows. If the signal is SIGPROF, the Go handler does nothing. Otherwise, the Go handler removes itself, unblocks the signal, and raises it again, to invoke any non-Go handler or default system handler. If the program does not exit, the Go handler then reinstalls itself and continues execution of the program.

+

If a SIGPIPE signal is received, the Go program will invoke the special handling described above if the SIGPIPE is received on a Go thread. If the SIGPIPE is received on a non-Go thread the signal will be forwarded to the non-Go handler, if any; if there is none the default system handler will cause the program to terminate.

+

Non-Go programs that call Go code

When Go code is built with options like -buildmode=c-shared, it will be run as part of an existing non-Go program. The non-Go code may have already installed signal handlers when the Go code starts (that may also happen in unusual cases when using cgo or SWIG; in that case, the discussion here applies). For -buildmode=c-archive the Go runtime will initialize signals at global constructor time. For -buildmode=c-shared the Go runtime will initialize signals when the shared library is loaded.

+

If the Go runtime sees an existing signal handler for the SIGCANCEL or SIGSETXID signals (which are used only on Linux), it will turn on the SA_ONSTACK flag and otherwise keep the signal handler.

+

For the synchronous signals and SIGPIPE, the Go runtime will install a signal handler. It will save any existing signal handler. If a synchronous signal arrives while executing non-Go code, the Go runtime will invoke the existing signal handler instead of the Go signal handler.

+

Go code built with -buildmode=c-archive or -buildmode=c-shared will not install any other signal handlers by default. If there is an existing signal handler, the Go runtime will turn on the SA_ONSTACK flag and otherwise keep the signal handler. If Notify is called for an asynchronous signal, a Go signal handler will be installed for that signal. If, later, Reset is called for that signal, the original handling for that signal will be reinstalled, restoring the non-Go signal handler if any.

+

Go code built without -buildmode=c-archive or -buildmode=c-shared will install a signal handler for the asynchronous signals listed above, and save any existing signal handler. If a signal is delivered to a non-Go thread, it will act as described above, except that if there is an existing non-Go signal handler, that handler will be installed before raising the signal.

+

Windows

On Windows a ^C (Control-C) or ^BREAK (Control-Break) normally cause the program to exit. If Notify is called for os.Interrupt, ^C or ^BREAK will cause os.Interrupt to be sent on the channel, and the program will not exit. If Reset is called, or Stop is called on all channels passed to Notify, then the default behavior will be restored.

+

Additionally, if Notify is called, and Windows sends CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT or CTRL_SHUTDOWN_EVENT to the process, Notify will return syscall.SIGTERM. Unlike Control-C and Control-Break, Notify does not change process behavior when either CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT or CTRL_SHUTDOWN_EVENT is received - the process will still get terminated unless it exits. But receiving syscall.SIGTERM will give the process an opportunity to clean up before termination.

+

Plan 9

On Plan 9, signals have type syscall.Note, which is a string. Calling Notify with a syscall.Note will cause that value to be sent on the channel when that string is posted as a note.

Index

Examples

Notify
NotifyContext
Notify (AllSignals)

Package files

doc.go signal.go signal_unix.go

func Ignore 1.5

func Ignore(sig ...os.Signal)

Ignore causes the provided signals to be ignored. If they are received by the program, nothing will happen. Ignore undoes the effect of any prior calls to Notify for the provided signals. If no signals are provided, all incoming signals will be ignored.

+

func Ignored 1.11

func Ignored(sig os.Signal) bool

Ignored reports whether sig is currently ignored.

+

func Notify

func Notify(c chan<- os.Signal, sig ...os.Signal)

Notify causes package signal to relay incoming signals to c. If no signals are provided, all incoming signals will be relayed to c. Otherwise, just the provided signals will.

+

Package signal will not block sending to c: the caller must ensure that c has sufficient buffer space to keep up with the expected signal rate. For a channel used for notification of just one signal value, a buffer of size 1 is sufficient.

+

It is allowed to call Notify multiple times with the same channel: each call expands the set of signals sent to that channel. The only way to remove signals from the set is to call Stop.

+

It is allowed to call Notify multiple times with different channels and the same signals: each channel receives copies of incoming signals independently.

Example +

Code:

+// Set up channel on which to send signal notifications.
+// We must use a buffered channel or risk missing the signal
+// if we're not ready to receive when the signal is sent.
+c := make(chan os.Signal, 1)
+signal.Notify(c, os.Interrupt)
+
+// Block until a signal is received.
+s := <-c
+fmt.Println("Got signal:", s)
+

Example (AllSignals) +

Code:

+// Set up channel on which to send signal notifications.
+// We must use a buffered channel or risk missing the signal
+// if we're not ready to receive when the signal is sent.
+c := make(chan os.Signal, 1)
+
+// Passing no signals to Notify means that
+// all signals will be sent to the channel.
+signal.Notify(c)
+
+// Block until any signal is received.
+s := <-c
+fmt.Println("Got signal:", s)
+

func NotifyContext 1.16

func NotifyContext(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc)

NotifyContext returns a copy of the parent context that is marked done (its Done channel is closed) when one of the listed signals arrives, when the returned stop function is called, or when the parent context's Done channel is closed, whichever happens first.

+

The stop function unregisters the signal behavior, which, like signal.Reset, may restore the default behavior for a given signal. For example, the default behavior of a Go program receiving os.Interrupt is to exit. Calling NotifyContext(parent, os.Interrupt) will change the behavior to cancel the returned context. Future interrupts received will not trigger the default (exit) behavior until the returned stop function is called.

+

The stop function releases resources associated with it, so code should call stop as soon as the operations running in this Context complete and signals no longer need to be diverted to the context.

Example +

This example passes a context with a signal to tell a blocking function that it should abandon its work after a signal is received.

Code:

package signal_test
+
+import (
+    "context"
+    "fmt"
+    "log"
+    "os"
+    "os/signal"
+)
+
+var neverReady = make(chan struct{}) // never closed
+
+// This example passes a context with a signal to tell a blocking function that
+// it should abandon its work after a signal is received.
+func ExampleNotifyContext() {
+    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
+    defer stop()
+
+    p, err := os.FindProcess(os.Getpid())
+    if err != nil {
+        log.Fatal(err)
+    }
+
+    // On a Unix-like system, pressing Ctrl+C on a keyboard sends a
+    // SIGINT signal to the process of the program in execution.
+    //
+    // This example simulates that by sending a SIGINT signal to itself.
+    if err := p.Signal(os.Interrupt); err != nil {
+        log.Fatal(err)
+    }
+
+    select {
+    case <-neverReady:
+        fmt.Println("ready")
+    case <-ctx.Done():
+        fmt.Println(ctx.Err()) // prints "context canceled"
+        stop()                 // stop receiving signal notifications as soon as possible.
+    }
+
+    // Output:
+    // context canceled
+}
+

func Reset 1.5

func Reset(sig ...os.Signal)

Reset undoes the effect of any prior calls to Notify for the provided signals. If no signals are provided, all signal handlers will be reset.

+

func Stop 1.1

func Stop(c chan<- os.Signal)

Stop causes package signal to stop relaying incoming signals to c. It undoes the effect of all prior calls to Notify using c. When Stop returns, it is guaranteed that c will receive no more signals.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/os/signal/ +

+
diff --git a/devdocs/go/os%2Fuser%2Findex.html b/devdocs/go/os%2Fuser%2Findex.html new file mode 100644 index 00000000..a69f79e8 --- /dev/null +++ b/devdocs/go/os%2Fuser%2Findex.html @@ -0,0 +1,79 @@ +

Package user

Overview

Package user allows user account lookups by name or id.

+

For most Unix systems, this package has two internal implementations of resolving user and group ids to names, and listing supplementary group IDs. One is written in pure Go and parses /etc/passwd and /etc/group. The other is cgo-based and relies on the standard C library (libc) routines such as getpwuid_r, getgrnam_r, and getgrouplist.

+

When cgo is available, and the required routines are implemented in libc for a particular platform, cgo-based (libc-backed) code is used. This can be overridden by using osusergo build tag, which enforces the pure Go implementation.

Index

Package files

cgo_listgroups_unix.go cgo_lookup_cgo.go cgo_lookup_unix.go getgrouplist_unix.go lookup.go user.go

type Group 1.7

Group represents a grouping of users.

+

On POSIX systems Gid contains a decimal number representing the group ID.

+
type Group struct {
+    Gid  string // group ID
+    Name string // group name
+}
+

func LookupGroup 1.7

func LookupGroup(name string) (*Group, error)

LookupGroup looks up a group by name. If the group cannot be found, the returned error is of type UnknownGroupError.

+

func LookupGroupId 1.7

func LookupGroupId(gid string) (*Group, error)

LookupGroupId looks up a group by groupid. If the group cannot be found, the returned error is of type UnknownGroupIdError.

+

type UnknownGroupError 1.7

UnknownGroupError is returned by LookupGroup when a group cannot be found.

+
type UnknownGroupError string

func (UnknownGroupError) Error 1.7

func (e UnknownGroupError) Error() string

type UnknownGroupIdError 1.7

UnknownGroupIdError is returned by LookupGroupId when a group cannot be found.

+
type UnknownGroupIdError string

func (UnknownGroupIdError) Error 1.7

func (e UnknownGroupIdError) Error() string

type UnknownUserError

UnknownUserError is returned by Lookup when a user cannot be found.

+
type UnknownUserError string

func (UnknownUserError) Error

func (e UnknownUserError) Error() string

type UnknownUserIdError

UnknownUserIdError is returned by LookupId when a user cannot be found.

+
type UnknownUserIdError int

func (UnknownUserIdError) Error

func (e UnknownUserIdError) Error() string

type User

User represents a user account.

+
type User struct {
+    // Uid is the user ID.
+    // On POSIX systems, this is a decimal number representing the uid.
+    // On Windows, this is a security identifier (SID) in a string format.
+    // On Plan 9, this is the contents of /dev/user.
+    Uid string
+    // Gid is the primary group ID.
+    // On POSIX systems, this is a decimal number representing the gid.
+    // On Windows, this is a SID in a string format.
+    // On Plan 9, this is the contents of /dev/user.
+    Gid string
+    // Username is the login name.
+    Username string
+    // Name is the user's real or display name.
+    // It might be blank.
+    // On POSIX systems, this is the first (or only) entry in the GECOS field
+    // list.
+    // On Windows, this is the user's display name.
+    // On Plan 9, this is the contents of /dev/user.
+    Name string
+    // HomeDir is the path to the user's home directory (if they have one).
+    HomeDir string
+}
+

func Current

func Current() (*User, error)

Current returns the current user.

+

The first call will cache the current user information. Subsequent calls will return the cached value and will not reflect changes to the current user.

+

func Lookup

func Lookup(username string) (*User, error)

Lookup looks up a user by username. If the user cannot be found, the returned error is of type UnknownUserError.

+

func LookupId

func LookupId(uid string) (*User, error)

LookupId looks up a user by userid. If the user cannot be found, the returned error is of type UnknownUserIdError.

+

func (*User) GroupIds 1.7

func (u *User) GroupIds() ([]string, error)

GroupIds returns the list of group IDs that the user is a member of.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/os/user/ +

+
diff --git a/devdocs/go/path%2Ffilepath%2Findex.html b/devdocs/go/path%2Ffilepath%2Findex.html new file mode 100644 index 00000000..f93880d1 --- /dev/null +++ b/devdocs/go/path%2Ffilepath%2Findex.html @@ -0,0 +1,305 @@ +

Package filepath

Overview

Package filepath implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file paths.

+

The filepath package uses either forward slashes or backslashes, depending on the operating system. To process paths such as URLs that always use forward slashes regardless of the operating system, see the path package.

Index

Examples

Base
Dir
Ext
IsAbs
Join
Match
Rel
Split
SplitList
Walk

Package files

match.go path.go path_nonwindows.go path_unix.go symlink.go symlink_unix.go

Constants

const (
+    Separator     = os.PathSeparator
+    ListSeparator = os.PathListSeparator
+)

Variables

ErrBadPattern indicates a pattern was malformed.

+
var ErrBadPattern = errors.New("syntax error in pattern")

SkipAll is used as a return value from WalkFunc to indicate that all remaining files and directories are to be skipped. It is not returned as an error by any function.

+
var SkipAll error = fs.SkipAll

SkipDir is used as a return value from WalkFunc to indicate that the directory named in the call is to be skipped. It is not returned as an error by any function.

+
var SkipDir error = fs.SkipDir

func Abs

func Abs(path string) (string, error)

Abs returns an absolute representation of path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path. The absolute path name for a given file is not guaranteed to be unique. Abs calls Clean on the result.

+

func Base

func Base(path string) string

Base returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of separators, Base returns a single separator.

Example +

Code:

fmt.Println("On Unix:")
+fmt.Println(filepath.Base("/foo/bar/baz.js"))
+fmt.Println(filepath.Base("/foo/bar/baz"))
+fmt.Println(filepath.Base("/foo/bar/baz/"))
+fmt.Println(filepath.Base("dev.txt"))
+fmt.Println(filepath.Base("../todo.txt"))
+fmt.Println(filepath.Base(".."))
+fmt.Println(filepath.Base("."))
+fmt.Println(filepath.Base("/"))
+fmt.Println(filepath.Base(""))
+
+

Output:

On Unix:
+baz.js
+baz
+baz
+dev.txt
+todo.txt
+..
+.
+/
+.
+

func Clean

func Clean(path string) string

Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:

+
  1. Replace multiple Separator elements with a single one.
  2. +
  3. Eliminate each . path name element (the current directory).
  4. +
  5. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  6. +
  7. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path, assuming Separator is '/'.
  8. +

The returned path ends in a slash only if it represents a root directory, such as "/" on Unix or `C:\` on Windows.

+

Finally, any occurrences of slash are replaced by Separator.

+

If the result of this process is an empty string, Clean returns the string ".".

+

On Windows, Clean does not modify the volume name other than to replace occurrences of "/" with `\`. For example, Clean("//host/share/../x") returns `\\host\share\x`.

+

See also Rob Pike, “Lexical File Names in Plan 9 or Getting Dot-Dot Right,” https://9p.io/sys/doc/lexnames.html

+

func Dir

func Dir(path string) string

Dir returns all but the last element of path, typically the path's directory. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed. If the path is empty, Dir returns ".". If the path consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory.

Example +

Code:

fmt.Println("On Unix:")
+fmt.Println(filepath.Dir("/foo/bar/baz.js"))
+fmt.Println(filepath.Dir("/foo/bar/baz"))
+fmt.Println(filepath.Dir("/foo/bar/baz/"))
+fmt.Println(filepath.Dir("/dirty//path///"))
+fmt.Println(filepath.Dir("dev.txt"))
+fmt.Println(filepath.Dir("../todo.txt"))
+fmt.Println(filepath.Dir(".."))
+fmt.Println(filepath.Dir("."))
+fmt.Println(filepath.Dir("/"))
+fmt.Println(filepath.Dir(""))
+
+

Output:

On Unix:
+/foo/bar
+/foo/bar
+/foo/bar/baz
+/dirty/path
+.
+..
+.
+.
+/
+.
+
func EvalSymlinks(path string) (string, error)

EvalSymlinks returns the path name after the evaluation of any symbolic links. If path is relative the result will be relative to the current directory, unless one of the components is an absolute symbolic link. EvalSymlinks calls Clean on the result.

+

func Ext

func Ext(path string) string

Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final element of path; it is empty if there is no dot.

Example +

Code:

fmt.Printf("No dots: %q\n", filepath.Ext("index"))
+fmt.Printf("One dot: %q\n", filepath.Ext("index.js"))
+fmt.Printf("Two dots: %q\n", filepath.Ext("main.test.js"))
+

Output:

No dots: ""
+One dot: ".js"
+Two dots: ".js"
+

func FromSlash

func FromSlash(path string) string

FromSlash returns the result of replacing each slash ('/') character in path with a separator character. Multiple slashes are replaced by multiple separators.

+

func Glob

func Glob(pattern string) (matches []string, err error)

Glob returns the names of all files matching pattern or nil if there is no matching file. The syntax of patterns is the same as in Match. The pattern may describe hierarchical names such as /usr/*/bin/ed (assuming the Separator is '/').

+

Glob ignores file system errors such as I/O errors reading directories. The only possible returned error is ErrBadPattern, when pattern is malformed.

+

func HasPrefix

func HasPrefix(p, prefix string) bool

HasPrefix exists for historical compatibility and should not be used.

+

Deprecated: HasPrefix does not respect path boundaries and does not ignore case when required.

+

func IsAbs

func IsAbs(path string) bool

IsAbs reports whether the path is absolute.

Example +

Code:

fmt.Println("On Unix:")
+fmt.Println(filepath.IsAbs("/home/gopher"))
+fmt.Println(filepath.IsAbs(".bashrc"))
+fmt.Println(filepath.IsAbs(".."))
+fmt.Println(filepath.IsAbs("."))
+fmt.Println(filepath.IsAbs("/"))
+fmt.Println(filepath.IsAbs(""))
+
+

Output:

On Unix:
+true
+false
+false
+false
+true
+false
+

func IsLocal 1.20

func IsLocal(path string) bool

IsLocal reports whether path, using lexical analysis only, has all of these properties:

+

If IsLocal(path) returns true, then Join(base, path) will always produce a path contained within base and Clean(path) will always produce an unrooted path with no ".." path elements.

+

IsLocal is a purely lexical operation. In particular, it does not account for the effect of any symbolic links that may exist in the filesystem.

+

func Join

func Join(elem ...string) string

Join joins any number of path elements into a single path, separating them with an OS specific Separator. Empty elements are ignored. The result is Cleaned. However, if the argument list is empty or all its elements are empty, Join returns an empty string. On Windows, the result will only be a UNC path if the first non-empty element is a UNC path.

Example +

Code:

fmt.Println("On Unix:")
+fmt.Println(filepath.Join("a", "b", "c"))
+fmt.Println(filepath.Join("a", "b/c"))
+fmt.Println(filepath.Join("a/b", "c"))
+fmt.Println(filepath.Join("a/b", "/c"))
+
+fmt.Println(filepath.Join("a/b", "../../../xyz"))
+
+

Output:

On Unix:
+a/b/c
+a/b/c
+a/b/c
+a/b/c
+../xyz
+

func Match

func Match(pattern, name string) (matched bool, err error)

Match reports whether name matches the shell file name pattern. The pattern syntax is:

+
pattern:
+	{ term }
+term:
+	'*'         matches any sequence of non-Separator characters
+	'?'         matches any single non-Separator character
+	'[' [ '^' ] { character-range } ']'
+	            character class (must be non-empty)
+	c           matches character c (c != '*', '?', '\\', '[')
+	'\\' c      matches character c
+
+character-range:
+	c           matches character c (c != '\\', '-', ']')
+	'\\' c      matches character c
+	lo '-' hi   matches character c for lo <= c <= hi
+

Match requires pattern to match all of name, not just a substring. The only possible returned error is ErrBadPattern, when pattern is malformed.

+

On Windows, escaping is disabled. Instead, '\\' is treated as path separator.

Example +

Code:

fmt.Println("On Unix:")
+fmt.Println(filepath.Match("/home/catch/*", "/home/catch/foo"))
+fmt.Println(filepath.Match("/home/catch/*", "/home/catch/foo/bar"))
+fmt.Println(filepath.Match("/home/?opher", "/home/gopher"))
+fmt.Println(filepath.Match("/home/\\*", "/home/*"))
+
+

Output:

On Unix:
+true <nil>
+false <nil>
+true <nil>
+true <nil>
+

func Rel

func Rel(basepath, targpath string) (string, error)

Rel returns a relative path that is lexically equivalent to targpath when joined to basepath with an intervening separator. That is, Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself. On success, the returned path will always be relative to basepath, even if basepath and targpath share no elements. An error is returned if targpath can't be made relative to basepath or if knowing the current working directory would be necessary to compute it. Rel calls Clean on the result.

Example +

Code:

paths := []string{
+    "/a/b/c",
+    "/b/c",
+    "./b/c",
+}
+base := "/a"
+
+fmt.Println("On Unix:")
+for _, p := range paths {
+    rel, err := filepath.Rel(base, p)
+    fmt.Printf("%q: %q %v\n", p, rel, err)
+}
+
+

Output:

On Unix:
+"/a/b/c": "b/c" <nil>
+"/b/c": "../b/c" <nil>
+"./b/c": "" Rel: can't make ./b/c relative to /a
+

func Split

func Split(path string) (dir, file string)

Split splits path immediately following the final Separator, separating it into a directory and file name component. If there is no Separator in path, Split returns an empty dir and file set to path. The returned values have the property that path = dir+file.

Example +

Code:

paths := []string{
+    "/home/arnie/amelia.jpg",
+    "/mnt/photos/",
+    "rabbit.jpg",
+    "/usr/local//go",
+}
+fmt.Println("On Unix:")
+for _, p := range paths {
+    dir, file := filepath.Split(p)
+    fmt.Printf("input: %q\n\tdir: %q\n\tfile: %q\n", p, dir, file)
+}
+

Output:

On Unix:
+input: "/home/arnie/amelia.jpg"
+	dir: "/home/arnie/"
+	file: "amelia.jpg"
+input: "/mnt/photos/"
+	dir: "/mnt/photos/"
+	file: ""
+input: "rabbit.jpg"
+	dir: ""
+	file: "rabbit.jpg"
+input: "/usr/local//go"
+	dir: "/usr/local//"
+	file: "go"
+

func SplitList

func SplitList(path string) []string

SplitList splits a list of paths joined by the OS-specific ListSeparator, usually found in PATH or GOPATH environment variables. Unlike strings.Split, SplitList returns an empty slice when passed an empty string.

Example +

Code:

fmt.Println("On Unix:", filepath.SplitList("/a/b/c:/usr/bin"))
+

Output:

On Unix: [/a/b/c /usr/bin]
+

func ToSlash

func ToSlash(path string) string

ToSlash returns the result of replacing each separator character in path with a slash ('/') character. Multiple separators are replaced by multiple slashes.

+

func VolumeName

func VolumeName(path string) string

VolumeName returns leading volume name. Given "C:\foo\bar" it returns "C:" on Windows. Given "\\host\share\foo" it returns "\\host\share". On other platforms it returns "".

+

func Walk

func Walk(root string, fn WalkFunc) error

Walk walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.

+

All errors that arise visiting files and directories are filtered by fn: see the WalkFunc documentation for details.

+

The files are walked in lexical order, which makes the output deterministic but requires Walk to read an entire directory into memory before proceeding to walk that directory.

+

Walk does not follow symbolic links.

+

Walk is less efficient than WalkDir, introduced in Go 1.16, which avoids calling os.Lstat on every visited file or directory.

Example +

Code:

package filepath_test
+
+import (
+    "fmt"
+    "io/fs"
+    "os"
+    "path/filepath"
+)
+
+func prepareTestDirTree(tree string) (string, error) {
+    tmpDir, err := os.MkdirTemp("", "")
+    if err != nil {
+        return "", fmt.Errorf("error creating temp directory: %v\n", err)
+    }
+
+    err = os.MkdirAll(filepath.Join(tmpDir, tree), 0755)
+    if err != nil {
+        os.RemoveAll(tmpDir)
+        return "", err
+    }
+
+    return tmpDir, nil
+}
+
+func ExampleWalk() {
+    tmpDir, err := prepareTestDirTree("dir/to/walk/skip")
+    if err != nil {
+        fmt.Printf("unable to create test dir tree: %v\n", err)
+        return
+    }
+    defer os.RemoveAll(tmpDir)
+    os.Chdir(tmpDir)
+
+    subDirToSkip := "skip"
+
+    fmt.Println("On Unix:")
+    err = filepath.Walk(".", func(path string, info fs.FileInfo, err error) error {
+        if err != nil {
+            fmt.Printf("prevent panic by handling failure accessing a path %q: %v\n", path, err)
+            return err
+        }
+        if info.IsDir() && info.Name() == subDirToSkip {
+            fmt.Printf("skipping a dir without errors: %+v \n", info.Name())
+            return filepath.SkipDir
+        }
+        fmt.Printf("visited file or dir: %q\n", path)
+        return nil
+    })
+    if err != nil {
+        fmt.Printf("error walking the path %q: %v\n", tmpDir, err)
+        return
+    }
+    // Output:
+    // On Unix:
+    // visited file or dir: "."
+    // visited file or dir: "dir"
+    // visited file or dir: "dir/to"
+    // visited file or dir: "dir/to/walk"
+    // skipping a dir without errors: skip
+}
+

func WalkDir 1.16

func WalkDir(root string, fn fs.WalkDirFunc) error

WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.

+

All errors that arise visiting files and directories are filtered by fn: see the fs.WalkDirFunc documentation for details.

+

The files are walked in lexical order, which makes the output deterministic but requires WalkDir to read an entire directory into memory before proceeding to walk that directory.

+

WalkDir does not follow symbolic links.

+

WalkDir calls fn with paths that use the separator character appropriate for the operating system. This is unlike io/fs.WalkDir, which always uses slash separated paths.

+

type WalkFunc

WalkFunc is the type of the function called by Walk to visit each file or directory.

+

The path argument contains the argument to Walk as a prefix. That is, if Walk is called with root argument "dir" and finds a file named "a" in that directory, the walk function will be called with argument "dir/a".

+

The directory and file are joined with Join, which may clean the directory name: if Walk is called with the root argument "x/../dir" and finds a file named "a" in that directory, the walk function will be called with argument "dir/a", not "x/../dir/a".

+

The info argument is the fs.FileInfo for the named path.

+

The error result returned by the function controls how Walk continues. If the function returns the special value SkipDir, Walk skips the current directory (path if info.IsDir() is true, otherwise path's parent directory). If the function returns the special value SkipAll, Walk skips all remaining files and directories. Otherwise, if the function returns a non-nil error, Walk stops entirely and returns that error.

+

The err argument reports an error related to path, signaling that Walk will not walk into that directory. The function can decide how to handle that error; as described earlier, returning the error will cause Walk to stop walking the entire tree.

+

Walk calls the function with a non-nil err argument in two cases.

+

First, if an os.Lstat on the root directory or any directory or file in the tree fails, Walk calls the function with path set to that directory or file's path, info set to nil, and err set to the error from os.Lstat.

+

Second, if a directory's Readdirnames method fails, Walk calls the function with path set to the directory's path, info, set to an fs.FileInfo describing the directory, and err set to the error from Readdirnames.

+
type WalkFunc func(path string, info fs.FileInfo, err error) error
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/path/filepath/ +

+
diff --git a/devdocs/go/path%2Findex.html b/devdocs/go/path%2Findex.html new file mode 100644 index 00000000..1a65498c --- /dev/null +++ b/devdocs/go/path%2Findex.html @@ -0,0 +1,132 @@ +

Package path

Overview

Package path implements utility routines for manipulating slash-separated paths.

+

The path package should only be used for paths separated by forward slashes, such as the paths in URLs. This package does not deal with Windows paths with drive letters or backslashes; to manipulate operating system paths, use the path/filepath package.

Index

Examples

Base
Clean
Dir
Ext
IsAbs
Join
Match
Split

Package files

match.go path.go

Variables

ErrBadPattern indicates a pattern was malformed.

+
var ErrBadPattern = errors.New("syntax error in pattern")

func Base

func Base(path string) string

Base returns the last element of path. Trailing slashes are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of slashes, Base returns "/".

Example +

Code:

fmt.Println(path.Base("/a/b"))
+fmt.Println(path.Base("/"))
+fmt.Println(path.Base(""))
+

Output:

b
+/
+.
+

func Clean

func Clean(path string) string

Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:

+
  1. Replace multiple slashes with a single slash.
  2. +
  3. Eliminate each . path name element (the current directory).
  4. +
  5. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  6. +
  7. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.
  8. +

The returned path ends in a slash only if it is the root "/".

+

If the result of this process is an empty string, Clean returns the string ".".

+

See also Rob Pike, “Lexical File Names in Plan 9 or Getting Dot-Dot Right,” https://9p.io/sys/doc/lexnames.html

Example +

Code:

paths := []string{
+    "a/c",
+    "a//c",
+    "a/c/.",
+    "a/c/b/..",
+    "/../a/c",
+    "/../a/b/../././/c",
+    "",
+}
+
+for _, p := range paths {
+    fmt.Printf("Clean(%q) = %q\n", p, path.Clean(p))
+}
+
+

Output:

Clean("a/c") = "a/c"
+Clean("a//c") = "a/c"
+Clean("a/c/.") = "a/c"
+Clean("a/c/b/..") = "a/c"
+Clean("/../a/c") = "/a/c"
+Clean("/../a/b/../././/c") = "/a/c"
+Clean("") = "."
+

func Dir

func Dir(path string) string

Dir returns all but the last element of path, typically the path's directory. After dropping the final element using Split, the path is Cleaned and trailing slashes are removed. If the path is empty, Dir returns ".". If the path consists entirely of slashes followed by non-slash bytes, Dir returns a single slash. In any other case, the returned path does not end in a slash.

Example +

Code:

fmt.Println(path.Dir("/a/b/c"))
+fmt.Println(path.Dir("a/b/c"))
+fmt.Println(path.Dir("/a/"))
+fmt.Println(path.Dir("a/"))
+fmt.Println(path.Dir("/"))
+fmt.Println(path.Dir(""))
+

Output:

/a/b
+a/b
+/a
+a
+/
+.
+

func Ext

func Ext(path string) string

Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final slash-separated element of path; it is empty if there is no dot.

Example +

Code:

fmt.Println(path.Ext("/a/b/c/bar.css"))
+fmt.Println(path.Ext("/"))
+fmt.Println(path.Ext(""))
+

Output:

.css
+

func IsAbs

func IsAbs(path string) bool

IsAbs reports whether the path is absolute.

Example +

Code:

fmt.Println(path.IsAbs("/dev/null"))
+

Output:

true
+

func Join

func Join(elem ...string) string

Join joins any number of path elements into a single path, separating them with slashes. Empty elements are ignored. The result is Cleaned. However, if the argument list is empty or all its elements are empty, Join returns an empty string.

Example +

Code:

fmt.Println(path.Join("a", "b", "c"))
+fmt.Println(path.Join("a", "b/c"))
+fmt.Println(path.Join("a/b", "c"))
+
+fmt.Println(path.Join("a/b", "../../../xyz"))
+
+fmt.Println(path.Join("", ""))
+fmt.Println(path.Join("a", ""))
+fmt.Println(path.Join("", "a"))
+
+

Output:

a/b/c
+a/b/c
+a/b/c
+../xyz
+
+a
+a
+

func Match

func Match(pattern, name string) (matched bool, err error)

Match reports whether name matches the shell pattern. The pattern syntax is:

+
pattern:
+	{ term }
+term:
+	'*'         matches any sequence of non-/ characters
+	'?'         matches any single non-/ character
+	'[' [ '^' ] { character-range } ']'
+	            character class (must be non-empty)
+	c           matches character c (c != '*', '?', '\\', '[')
+	'\\' c      matches character c
+
+character-range:
+	c           matches character c (c != '\\', '-', ']')
+	'\\' c      matches character c
+	lo '-' hi   matches character c for lo <= c <= hi
+

Match requires pattern to match all of name, not just a substring. The only possible returned error is ErrBadPattern, when pattern is malformed.

Example +

Code:

fmt.Println(path.Match("abc", "abc"))
+fmt.Println(path.Match("a*", "abc"))
+fmt.Println(path.Match("a*/b", "a/c/b"))
+

Output:

true <nil>
+true <nil>
+false <nil>
+

func Split

func Split(path string) (dir, file string)

Split splits path immediately following the final slash, separating it into a directory and file name component. If there is no slash in path, Split returns an empty dir and file set to path. The returned values have the property that path = dir+file.

Example +

Code:

split := func(s string) {
+    dir, file := path.Split(s)
+    fmt.Printf("path.Split(%q) = dir: %q, file: %q\n", s, dir, file)
+}
+split("static/myfile.css")
+split("myfile.css")
+split("")
+

Output:

path.Split("static/myfile.css") = dir: "static/", file: "myfile.css"
+path.Split("myfile.css") = dir: "", file: "myfile.css"
+path.Split("") = dir: "", file: ""
+

Subdirectories

Name Synopsis
..
filepath Package filepath implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file paths.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/path/ +

+
diff --git a/devdocs/go/plugin%2Findex.html b/devdocs/go/plugin%2Findex.html new file mode 100644 index 00000000..bc061022 --- /dev/null +++ b/devdocs/go/plugin%2Findex.html @@ -0,0 +1,60 @@ +

Package plugin

Overview

Package plugin implements loading and symbol resolution of Go plugins.

+

A plugin is a Go main package with exported functions and variables that has been built with:

+
go build -buildmode=plugin
+

When a plugin is first opened, the init functions of all packages not already part of the program are called. The main function is not run. A plugin is only initialized once, and cannot be closed.

+

Warnings

The ability to dynamically load parts of an application during execution, perhaps based on user-defined configuration, may be a useful building block in some designs. In particular, because applications and dynamically loaded functions can share data structures directly, plugins may enable very high-performance integration of separate parts.

+

However, the plugin mechanism has many significant drawbacks that should be considered carefully during the design. For example:

+

For these reasons, many users decide that traditional interprocess communication (IPC) mechanisms such as sockets, pipes, remote procedure call (RPC), shared memory mappings, or file system operations may be more suitable despite the performance overheads.

Index

Package files

plugin.go plugin_dlopen.go

type Plugin 1.8

Plugin is a loaded Go plugin.

+
type Plugin struct {
+    // contains filtered or unexported fields
+}
+

func Open 1.8

func Open(path string) (*Plugin, error)

Open opens a Go plugin. If a path has already been opened, then the existing *Plugin is returned. It is safe for concurrent use by multiple goroutines.

+

func (*Plugin) Lookup 1.8

func (p *Plugin) Lookup(symName string) (Symbol, error)

Lookup searches for a symbol named symName in plugin p. A symbol is any exported variable or function. It reports an error if the symbol is not found. It is safe for concurrent use by multiple goroutines.

+

type Symbol 1.8

A Symbol is a pointer to a variable or function.

+

For example, a plugin defined as

+
package main
+
+import "fmt"
+
+var V int
+
+func F() { fmt.Printf("Hello, number %d\n", V) }
+

may be loaded with the Open function and then the exported package symbols V and F can be accessed

+
p, err := plugin.Open("plugin_name.so")
+if err != nil {
+	panic(err)
+}
+v, err := p.Lookup("V")
+if err != nil {
+	panic(err)
+}
+f, err := p.Lookup("F")
+if err != nil {
+	panic(err)
+}
+*v.(*int) = 7
+f.(func())() // prints "Hello, number 7"
+
type Symbol any
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/plugin/ +

+
diff --git a/devdocs/go/reflect%2Findex.html b/devdocs/go/reflect%2Findex.html new file mode 100644 index 00000000..fe71a6d0 --- /dev/null +++ b/devdocs/go/reflect%2Findex.html @@ -0,0 +1,870 @@ +

Package reflect

Overview

Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types. The typical use is to take a value with static type interface{} and extract its dynamic type information by calling TypeOf, which returns a Type.

+

A call to ValueOf returns a Value representing the run-time data. Zero takes a Type and returns a Value representing a zero value for that type.

+

See "The Laws of Reflection" for an introduction to reflection in Go: https://golang.org/doc/articles/laws_of_reflection.html

Index

Examples

Kind
MakeFunc
StructOf
StructTag
StructTag.Lookup
TypeOf
Value.FieldByIndex
Value.FieldByName

Package files

abi.go deepequal.go float32reg_generic.go makefunc.go swapper.go type.go value.go visiblefields.go

Constants

Ptr is the old name for the Pointer kind.

+
const Ptr = Pointer

func Copy

func Copy(dst, src Value) int

Copy copies the contents of src into dst until either dst has been filled or src has been exhausted. It returns the number of elements copied. Dst and src each must have kind Slice or Array, and dst and src must have the same element type.

+

As a special case, src can have kind String if the element type of dst is kind Uint8.

+

func DeepEqual

func DeepEqual(x, y any) bool

DeepEqual reports whether x and y are “deeply equal,” defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal.

+

Array values are deeply equal when their corresponding elements are deeply equal.

+

Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.

+

Func values are deeply equal if both are nil; otherwise they are not deeply equal.

+

Interface values are deeply equal if they hold deeply equal concrete values.

+

Map values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they are the same map object or their corresponding keys (matched using Go equality) map to deeply equal values.

+

Pointer values are deeply equal if they are equal using Go's == operator or if they point to deeply equal values.

+

Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.

+

Other values - numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.

+

In general DeepEqual is a recursive relaxation of Go's == operator. However, this idea is impossible to implement without some inconsistency. Specifically, it is possible for a value to be unequal to itself, either because it is of func type (uncomparable in general) or because it is a floating-point NaN value (not equal to itself in floating-point comparison), or because it is an array, struct, or interface containing such a value. On the other hand, pointer values are always equal to themselves, even if they point at or contain such problematic values, because they compare equal using Go's == operator, and that is a sufficient condition to be deeply equal, regardless of content. DeepEqual has been defined so that the same short-cut applies to slices and maps: if x and y are the same slice or the same map, they are deeply equal regardless of content.

+

As DeepEqual traverses the data values it may find a cycle. The second and subsequent times that DeepEqual compares two pointer values that have been compared before, it treats the values as equal rather than examining the values to which they point. This ensures that DeepEqual terminates.

+

func Swapper 1.8

func Swapper(slice any) func(i, j int)

Swapper returns a function that swaps the elements in the provided slice.

+

Swapper panics if the provided interface is not a slice.

+

type ChanDir

ChanDir represents a channel type's direction.

+
type ChanDir int
const (
+    RecvDir ChanDir             = 1 << iota // <-chan
+    SendDir                                 // chan<-
+    BothDir = RecvDir | SendDir             // chan
+)

func (ChanDir) String

func (d ChanDir) String() string

type Kind

A Kind represents the specific kind of type that a Type represents. The zero Kind is not a valid kind.

+
type Kind uint
const (
+    Invalid Kind = iota
+    Bool
+    Int
+    Int8
+    Int16
+    Int32
+    Int64
+    Uint
+    Uint8
+    Uint16
+    Uint32
+    Uint64
+    Uintptr
+    Float32
+    Float64
+    Complex64
+    Complex128
+    Array
+    Chan
+    Func
+    Interface
+    Map
+    Pointer
+    Slice
+    String
+    Struct
+    UnsafePointer
+)

Example +

Code:

for _, v := range []any{"hi", 42, func() {}} {
+    switch v := reflect.ValueOf(v); v.Kind() {
+    case reflect.String:
+        fmt.Println(v.String())
+    case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+        fmt.Println(v.Int())
+    default:
+        fmt.Printf("unhandled kind %s", v.Kind())
+    }
+}
+
+

Output:

hi
+42
+unhandled kind func
+

func (Kind) String

func (k Kind) String() string

String returns the name of k.

+

type MapIter 1.12

A MapIter is an iterator for ranging over a map. See Value.MapRange.

+
type MapIter struct {
+    // contains filtered or unexported fields
+}
+

func (*MapIter) Key 1.12

func (iter *MapIter) Key() Value

Key returns the key of iter's current map entry.

+

func (*MapIter) Next 1.12

func (iter *MapIter) Next() bool

Next advances the map iterator and reports whether there is another entry. It returns false when iter is exhausted; subsequent calls to MapIter.Key, MapIter.Value, or MapIter.Next will panic.

+

func (*MapIter) Reset 1.18

func (iter *MapIter) Reset(v Value)

Reset modifies iter to iterate over v. It panics if v's Kind is not Map and v is not the zero Value. Reset(Value{}) causes iter to not to refer to any map, which may allow the previously iterated-over map to be garbage collected.

+

func (*MapIter) Value 1.12

func (iter *MapIter) Value() Value

Value returns the value of iter's current map entry.

+

type Method

Method represents a single method.

+
type Method struct {
+    // Name is the method name.
+    Name string
+
+    // PkgPath is the package path that qualifies a lower case (unexported)
+    // method name. It is empty for upper case (exported) method names.
+    // The combination of PkgPath and Name uniquely identifies a method
+    // in a method set.
+    // See https://golang.org/ref/spec#Uniqueness_of_identifiers
+    PkgPath string
+
+    Type  Type  // method type
+    Func  Value // func with receiver as first argument
+    Index int   // index for Type.Method
+}
+

func (Method) IsExported 1.17

func (m Method) IsExported() bool

IsExported reports whether the method is exported.

+

type SelectCase 1.1

A SelectCase describes a single case in a select operation. The kind of case depends on Dir, the communication direction.

+

If Dir is SelectDefault, the case represents a default case. Chan and Send must be zero Values.

+

If Dir is SelectSend, the case represents a send operation. Normally Chan's underlying value must be a channel, and Send's underlying value must be assignable to the channel's element type. As a special case, if Chan is a zero Value, then the case is ignored, and the field Send will also be ignored and may be either zero or non-zero.

+

If Dir is SelectRecv, the case represents a receive operation. Normally Chan's underlying value must be a channel and Send must be a zero Value. If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value. When a receive operation is selected, the received Value is returned by Select.

+
type SelectCase struct {
+    Dir  SelectDir // direction of case
+    Chan Value     // channel to use (for send or receive)
+    Send Value     // value to send (for send)
+}
+

type SelectDir 1.1

A SelectDir describes the communication direction of a select case.

+
type SelectDir int
const (
+    SelectSend    SelectDir // case Chan <- Send
+    SelectRecv              // case <-Chan:
+    SelectDefault           // default
+)

type SliceHeader

SliceHeader is the runtime representation of a slice. It cannot be used safely or portably and its representation may change in a later release. Moreover, the Data field is not sufficient to guarantee the data it references will not be garbage collected, so programs must keep a separate, correctly typed pointer to the underlying data.

+

Deprecated: Use unsafe.Slice or unsafe.SliceData instead.

+
type SliceHeader struct {
+    Data uintptr
+    Len  int
+    Cap  int
+}
+

type StringHeader

StringHeader is the runtime representation of a string. It cannot be used safely or portably and its representation may change in a later release. Moreover, the Data field is not sufficient to guarantee the data it references will not be garbage collected, so programs must keep a separate, correctly typed pointer to the underlying data.

+

Deprecated: Use unsafe.String or unsafe.StringData instead.

+
type StringHeader struct {
+    Data uintptr
+    Len  int
+}
+

type StructField

A StructField describes a single field in a struct.

+
type StructField struct {
+    // Name is the field name.
+    Name string
+
+    // PkgPath is the package path that qualifies a lower case (unexported)
+    // field name. It is empty for upper case (exported) field names.
+    // See https://golang.org/ref/spec#Uniqueness_of_identifiers
+    PkgPath string
+
+    Type      Type      // field type
+    Tag       StructTag // field tag string
+    Offset    uintptr   // offset within struct, in bytes
+    Index     []int     // index sequence for Type.FieldByIndex
+    Anonymous bool      // is an embedded field
+}
+

func VisibleFields 1.17

func VisibleFields(t Type) []StructField

VisibleFields returns all the visible fields in t, which must be a struct type. A field is defined as visible if it's accessible directly with a FieldByName call. The returned fields include fields inside anonymous struct members and unexported fields. They follow the same order found in the struct, with anonymous fields followed immediately by their promoted fields.

+

For each element e of the returned slice, the corresponding field can be retrieved from a value v of type t by calling v.FieldByIndex(e.Index).

+

func (StructField) IsExported 1.17

func (f StructField) IsExported() bool

IsExported reports whether the field is exported.

+

type StructTag

A StructTag is the tag string in a struct field.

+

By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

+
type StructTag string

Example +

Code:

type S struct {
+    F string `species:"gopher" color:"blue"`
+}
+
+s := S{}
+st := reflect.TypeOf(s)
+field := st.Field(0)
+fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
+
+

Output:

blue gopher
+

func (StructTag) Get

func (tag StructTag) Get(key string) string

Get returns the value associated with key in the tag string. If there is no such key in the tag, Get returns the empty string. If the tag does not have the conventional format, the value returned by Get is unspecified. To determine whether a tag is explicitly set to the empty string, use Lookup.

+

func (StructTag) Lookup 1.7

func (tag StructTag) Lookup(key string) (value string, ok bool)

Lookup returns the value associated with key in the tag string. If the key is present in the tag the value (which may be empty) is returned. Otherwise the returned value will be the empty string. The ok return value reports whether the value was explicitly set in the tag string. If the tag does not have the conventional format, the value returned by Lookup is unspecified.

Example +

Code:

type S struct {
+    F0 string `alias:"field_0"`
+    F1 string `alias:""`
+    F2 string
+}
+
+s := S{}
+st := reflect.TypeOf(s)
+for i := 0; i < st.NumField(); i++ {
+    field := st.Field(i)
+    if alias, ok := field.Tag.Lookup("alias"); ok {
+        if alias == "" {
+            fmt.Println("(blank)")
+        } else {
+            fmt.Println(alias)
+        }
+    } else {
+        fmt.Println("(not specified)")
+    }
+}
+
+

Output:

field_0
+(blank)
+(not specified)
+

type Type

Type is the representation of a Go type.

+

Not all methods apply to all kinds of types. Restrictions, if any, are noted in the documentation for each method. Use the Kind method to find out the kind of type before calling kind-specific methods. Calling a method inappropriate to the kind of type causes a run-time panic.

+

Type values are comparable, such as with the == operator, so they can be used as map keys. Two Type values are equal if they represent identical types.

+
type Type interface {
+
+    // Align returns the alignment in bytes of a value of
+    // this type when allocated in memory.
+    Align() int
+
+    // FieldAlign returns the alignment in bytes of a value of
+    // this type when used as a field in a struct.
+    FieldAlign() int
+
+    // Method returns the i'th method in the type's method set.
+    // It panics if i is not in the range [0, NumMethod()).
+    //
+    // For a non-interface type T or *T, the returned Method's Type and Func
+    // fields describe a function whose first argument is the receiver,
+    // and only exported methods are accessible.
+    //
+    // For an interface type, the returned Method's Type field gives the
+    // method signature, without a receiver, and the Func field is nil.
+    //
+    // Methods are sorted in lexicographic order.
+    Method(int) Method
+
+    // MethodByName returns the method with that name in the type's
+    // method set and a boolean indicating if the method was found.
+    //
+    // For a non-interface type T or *T, the returned Method's Type and Func
+    // fields describe a function whose first argument is the receiver.
+    //
+    // For an interface type, the returned Method's Type field gives the
+    // method signature, without a receiver, and the Func field is nil.
+    MethodByName(string) (Method, bool)
+
+    // NumMethod returns the number of methods accessible using Method.
+    //
+    // For a non-interface type, it returns the number of exported methods.
+    //
+    // For an interface type, it returns the number of exported and unexported methods.
+    NumMethod() int
+
+    // Name returns the type's name within its package for a defined type.
+    // For other (non-defined) types it returns the empty string.
+    Name() string
+
+    // PkgPath returns a defined type's package path, that is, the import path
+    // that uniquely identifies the package, such as "encoding/base64".
+    // If the type was predeclared (string, error) or not defined (*T, struct{},
+    // []int, or A where A is an alias for a non-defined type), the package path
+    // will be the empty string.
+    PkgPath() string
+
+    // Size returns the number of bytes needed to store
+    // a value of the given type; it is analogous to unsafe.Sizeof.
+    Size() uintptr
+
+    // String returns a string representation of the type.
+    // The string representation may use shortened package names
+    // (e.g., base64 instead of "encoding/base64") and is not
+    // guaranteed to be unique among types. To test for type identity,
+    // compare the Types directly.
+    String() string
+
+    // Kind returns the specific kind of this type.
+    Kind() Kind
+
+    // Implements reports whether the type implements the interface type u.
+    Implements(u Type) bool
+
+    // AssignableTo reports whether a value of the type is assignable to type u.
+    AssignableTo(u Type) bool
+
+    // ConvertibleTo reports whether a value of the type is convertible to type u.
+    // Even if ConvertibleTo returns true, the conversion may still panic.
+    // For example, a slice of type []T is convertible to *[N]T,
+    // but the conversion will panic if its length is less than N.
+    ConvertibleTo(u Type) bool
+
+    // Comparable reports whether values of this type are comparable.
+    // Even if Comparable returns true, the comparison may still panic.
+    // For example, values of interface type are comparable,
+    // but the comparison will panic if their dynamic type is not comparable.
+    Comparable() bool
+
+    // Bits returns the size of the type in bits.
+    // It panics if the type's Kind is not one of the
+    // sized or unsized Int, Uint, Float, or Complex kinds.
+    Bits() int
+
+    // ChanDir returns a channel type's direction.
+    // It panics if the type's Kind is not Chan.
+    ChanDir() ChanDir
+
+    // IsVariadic reports whether a function type's final input parameter
+    // is a "..." parameter. If so, t.In(t.NumIn() - 1) returns the parameter's
+    // implicit actual type []T.
+    //
+    // For concreteness, if t represents func(x int, y ... float64), then
+    //
+    //	t.NumIn() == 2
+    //	t.In(0) is the reflect.Type for "int"
+    //	t.In(1) is the reflect.Type for "[]float64"
+    //	t.IsVariadic() == true
+    //
+    // IsVariadic panics if the type's Kind is not Func.
+    IsVariadic() bool
+
+    // Elem returns a type's element type.
+    // It panics if the type's Kind is not Array, Chan, Map, Pointer, or Slice.
+    Elem() Type
+
+    // Field returns a struct type's i'th field.
+    // It panics if the type's Kind is not Struct.
+    // It panics if i is not in the range [0, NumField()).
+    Field(i int) StructField
+
+    // FieldByIndex returns the nested field corresponding
+    // to the index sequence. It is equivalent to calling Field
+    // successively for each index i.
+    // It panics if the type's Kind is not Struct.
+    FieldByIndex(index []int) StructField
+
+    // FieldByName returns the struct field with the given name
+    // and a boolean indicating if the field was found.
+    // If the returned field is promoted from an embedded struct,
+    // then Offset in the returned StructField is the offset in
+    // the embedded struct.
+    FieldByName(name string) (StructField, bool)
+
+    // FieldByNameFunc returns the struct field with a name
+    // that satisfies the match function and a boolean indicating if
+    // the field was found.
+    //
+    // FieldByNameFunc considers the fields in the struct itself
+    // and then the fields in any embedded structs, in breadth first order,
+    // stopping at the shallowest nesting depth containing one or more
+    // fields satisfying the match function. If multiple fields at that depth
+    // satisfy the match function, they cancel each other
+    // and FieldByNameFunc returns no match.
+    // This behavior mirrors Go's handling of name lookup in
+    // structs containing embedded fields.
+    //
+    // If the returned field is promoted from an embedded struct,
+    // then Offset in the returned StructField is the offset in
+    // the embedded struct.
+    FieldByNameFunc(match func(string) bool) (StructField, bool)
+
+    // In returns the type of a function type's i'th input parameter.
+    // It panics if the type's Kind is not Func.
+    // It panics if i is not in the range [0, NumIn()).
+    In(i int) Type
+
+    // Key returns a map type's key type.
+    // It panics if the type's Kind is not Map.
+    Key() Type
+
+    // Len returns an array type's length.
+    // It panics if the type's Kind is not Array.
+    Len() int
+
+    // NumField returns a struct type's field count.
+    // It panics if the type's Kind is not Struct.
+    NumField() int
+
+    // NumIn returns a function type's input parameter count.
+    // It panics if the type's Kind is not Func.
+    NumIn() int
+
+    // NumOut returns a function type's output parameter count.
+    // It panics if the type's Kind is not Func.
+    NumOut() int
+
+    // Out returns the type of a function type's i'th output parameter.
+    // It panics if the type's Kind is not Func.
+    // It panics if i is not in the range [0, NumOut()).
+    Out(i int) Type
+    // contains filtered or unexported methods
+}

func ArrayOf 1.5

func ArrayOf(length int, elem Type) Type

ArrayOf returns the array type with the given length and element type. For example, if t represents int, ArrayOf(5, t) represents [5]int.

+

If the resulting type would be larger than the available address space, ArrayOf panics.

+

func ChanOf 1.1

func ChanOf(dir ChanDir, t Type) Type

ChanOf returns the channel type with the given direction and element type. For example, if t represents int, ChanOf(RecvDir, t) represents <-chan int.

+

The gc runtime imposes a limit of 64 kB on channel element types. If t's size is equal to or exceeds this limit, ChanOf panics.

+

func FuncOf 1.5

func FuncOf(in, out []Type, variadic bool) Type

FuncOf returns the function type with the given argument and result types. For example if k represents int and e represents string, FuncOf([]Type{k}, []Type{e}, false) represents func(int) string.

+

The variadic argument controls whether the function is variadic. FuncOf panics if the in[len(in)-1] does not represent a slice and variadic is true.

+

func MapOf 1.1

func MapOf(key, elem Type) Type

MapOf returns the map type with the given key and element types. For example, if k represents int and e represents string, MapOf(k, e) represents map[int]string.

+

If the key type is not a valid map key type (that is, if it does not implement Go's == operator), MapOf panics.

+

func PointerTo 1.18

func PointerTo(t Type) Type

PointerTo returns the pointer type with element t. For example, if t represents type Foo, PointerTo(t) represents *Foo.

+

func PtrTo

func PtrTo(t Type) Type

PtrTo returns the pointer type with element t. For example, if t represents type Foo, PtrTo(t) represents *Foo.

+

PtrTo is the old spelling of PointerTo. The two functions behave identically.

+

Deprecated: Superseded by PointerTo.

+

func SliceOf 1.1

func SliceOf(t Type) Type

SliceOf returns the slice type with element type t. For example, if t represents int, SliceOf(t) represents []int.

+

func StructOf 1.7

func StructOf(fields []StructField) Type

StructOf returns the struct type containing fields. The Offset and Index fields are ignored and computed as they would be by the compiler.

+

StructOf currently does not support promoted methods of embedded fields and panics if passed unexported StructFields.

Example +

Code:

typ := reflect.StructOf([]reflect.StructField{
+    {
+        Name: "Height",
+        Type: reflect.TypeOf(float64(0)),
+        Tag:  `json:"height"`,
+    },
+    {
+        Name: "Age",
+        Type: reflect.TypeOf(int(0)),
+        Tag:  `json:"age"`,
+    },
+})
+
+v := reflect.New(typ).Elem()
+v.Field(0).SetFloat(0.4)
+v.Field(1).SetInt(2)
+s := v.Addr().Interface()
+
+w := new(bytes.Buffer)
+if err := json.NewEncoder(w).Encode(s); err != nil {
+    panic(err)
+}
+
+fmt.Printf("value: %+v\n", s)
+fmt.Printf("json:  %s", w.Bytes())
+
+r := bytes.NewReader([]byte(`{"height":1.5,"age":10}`))
+if err := json.NewDecoder(r).Decode(s); err != nil {
+    panic(err)
+}
+fmt.Printf("value: %+v\n", s)
+
+

Output:

value: &{Height:0.4 Age:2}
+json:  {"height":0.4,"age":2}
+value: &{Height:1.5 Age:10}
+

func TypeFor

func TypeFor[T any]() Type

TypeFor returns the Type that represents the type argument T.

+

func TypeOf

func TypeOf(i any) Type

TypeOf returns the reflection Type that represents the dynamic type of i. If i is a nil interface value, TypeOf returns nil.

Example +

Code:

// As interface types are only used for static typing, a
+// common idiom to find the reflection Type for an interface
+// type Foo is to use a *Foo value.
+writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()
+
+fileType := reflect.TypeOf((*os.File)(nil))
+fmt.Println(fileType.Implements(writerType))
+
+

Output:

true
+

type Value

Value is the reflection interface to a Go value.

+

Not all methods apply to all kinds of values. Restrictions, if any, are noted in the documentation for each method. Use the Kind method to find out the kind of value before calling kind-specific methods. Calling a method inappropriate to the kind of type causes a run time panic.

+

The zero Value represents no value. Its IsValid method returns false, its Kind method returns Invalid, its String method returns "<invalid Value>", and all other methods panic. Most functions and methods never return an invalid value. If one does, its documentation states the conditions explicitly.

+

A Value can be used concurrently by multiple goroutines provided that the underlying Go value can be used concurrently for the equivalent direct operations.

+

To compare two Values, compare the results of the Interface method. Using == on two Values does not compare the underlying values they represent.

+
type Value struct {
+    // contains filtered or unexported fields
+}
+

func Append

func Append(s Value, x ...Value) Value

Append appends the values x to a slice s and returns the resulting slice. As in Go, each x's value must be assignable to the slice's element type.

+

func AppendSlice

func AppendSlice(s, t Value) Value

AppendSlice appends a slice t to a slice s and returns the resulting slice. The slices s and t must have the same element type.

+

func Indirect

func Indirect(v Value) Value

Indirect returns the value that v points to. If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v.

+

func MakeChan

func MakeChan(typ Type, buffer int) Value

MakeChan creates a new channel with the specified type and buffer size.

+

func MakeFunc 1.1

func MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value

MakeFunc returns a new function of the given Type that wraps the function fn. When called, that new function does the following:

+

The implementation fn can assume that the argument Value slice has the number and type of arguments given by typ. If typ describes a variadic function, the final Value is itself a slice representing the variadic arguments, as in the body of a variadic function. The result Value slice returned by fn must have the number and type of results given by typ.

+

The Value.Call method allows the caller to invoke a typed function in terms of Values; in contrast, MakeFunc allows the caller to implement a typed function in terms of Values.

+

The Examples section of the documentation includes an illustration of how to use MakeFunc to build a swap function for different types.

Example +

Code:

// swap is the implementation passed to MakeFunc.
+// It must work in terms of reflect.Values so that it is possible
+// to write code without knowing beforehand what the types
+// will be.
+swap := func(in []reflect.Value) []reflect.Value {
+    return []reflect.Value{in[1], in[0]}
+}
+
+// makeSwap expects fptr to be a pointer to a nil function.
+// It sets that pointer to a new function created with MakeFunc.
+// When the function is invoked, reflect turns the arguments
+// into Values, calls swap, and then turns swap's result slice
+// into the values returned by the new function.
+makeSwap := func(fptr any) {
+    // fptr is a pointer to a function.
+    // Obtain the function value itself (likely nil) as a reflect.Value
+    // so that we can query its type and then set the value.
+    fn := reflect.ValueOf(fptr).Elem()
+
+    // Make a function of the right type.
+    v := reflect.MakeFunc(fn.Type(), swap)
+
+    // Assign it to the value fn represents.
+    fn.Set(v)
+}
+
+// Make and call a swap function for ints.
+var intSwap func(int, int) (int, int)
+makeSwap(&intSwap)
+fmt.Println(intSwap(0, 1))
+
+// Make and call a swap function for float64s.
+var floatSwap func(float64, float64) (float64, float64)
+makeSwap(&floatSwap)
+fmt.Println(floatSwap(2.72, 3.14))
+
+

Output:

1 0
+3.14 2.72
+

func MakeMap

func MakeMap(typ Type) Value

MakeMap creates a new map with the specified type.

+

func MakeMapWithSize 1.9

func MakeMapWithSize(typ Type, n int) Value

MakeMapWithSize creates a new map with the specified type and initial space for approximately n elements.

+

func MakeSlice

func MakeSlice(typ Type, len, cap int) Value

MakeSlice creates a new zero-initialized slice value for the specified slice type, length, and capacity.

+

func New

func New(typ Type) Value

New returns a Value representing a pointer to a new zero value for the specified type. That is, the returned Value's Type is PointerTo(typ).

+

func NewAt

func NewAt(typ Type, p unsafe.Pointer) Value

NewAt returns a Value representing a pointer to a value of the specified type, using p as that pointer.

+

func Select 1.1

func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool)

Select executes a select operation described by the list of cases. Like the Go select statement, it blocks until at least one of the cases can proceed, makes a uniform pseudo-random choice, and then executes that case. It returns the index of the chosen case and, if that case was a receive operation, the value received and a boolean indicating whether the value corresponds to a send on the channel (as opposed to a zero value received because the channel is closed). Select supports a maximum of 65536 cases.

+

func ValueOf

func ValueOf(i any) Value

ValueOf returns a new Value initialized to the concrete value stored in the interface i. ValueOf(nil) returns the zero Value.

+

func Zero

func Zero(typ Type) Value

Zero returns a Value representing the zero value for the specified type. The result is different from the zero value of the Value struct, which represents no value at all. For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0. The returned value is neither addressable nor settable.

+

func (Value) Addr

func (v Value) Addr() Value

Addr returns a pointer value representing the address of v. It panics if Value.CanAddr returns false. Addr is typically used to obtain a pointer to a struct field or slice element in order to call a method that requires a pointer receiver.

+

func (Value) Bool

func (v Value) Bool() bool

Bool returns v's underlying value. It panics if v's kind is not Bool.

+

func (Value) Bytes

func (v Value) Bytes() []byte

Bytes returns v's underlying value. It panics if v's underlying value is not a slice of bytes or an addressable array of bytes.

+

func (Value) Call

func (v Value) Call(in []Value) []Value

Call calls the function v with the input arguments in. For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]). Call panics if v's Kind is not Func. It returns the output results as Values. As in Go, each input argument must be assignable to the type of the function's corresponding input parameter. If v is a variadic function, Call creates the variadic slice parameter itself, copying in the corresponding values.

+

func (Value) CallSlice

func (v Value) CallSlice(in []Value) []Value

CallSlice calls the variadic function v with the input arguments in, assigning the slice in[len(in)-1] to v's final variadic argument. For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...). CallSlice panics if v's Kind is not Func or if v is not variadic. It returns the output results as Values. As in Go, each input argument must be assignable to the type of the function's corresponding input parameter.

+

func (Value) CanAddr

func (v Value) CanAddr() bool

CanAddr reports whether the value's address can be obtained with Value.Addr. Such values are called addressable. A value is addressable if it is an element of a slice, an element of an addressable array, a field of an addressable struct, or the result of dereferencing a pointer. If CanAddr returns false, calling Value.Addr will panic.

+

func (Value) CanComplex 1.18

func (v Value) CanComplex() bool

CanComplex reports whether Value.Complex can be used without panicking.

+

func (Value) CanConvert 1.17

func (v Value) CanConvert(t Type) bool

CanConvert reports whether the value v can be converted to type t. If v.CanConvert(t) returns true then v.Convert(t) will not panic.

+

func (Value) CanFloat 1.18

func (v Value) CanFloat() bool

CanFloat reports whether Value.Float can be used without panicking.

+

func (Value) CanInt 1.18

func (v Value) CanInt() bool

CanInt reports whether Int can be used without panicking.

+

func (Value) CanInterface

func (v Value) CanInterface() bool

CanInterface reports whether Value.Interface can be used without panicking.

+

func (Value) CanSet

func (v Value) CanSet() bool

CanSet reports whether the value of v can be changed. A Value can be changed only if it is addressable and was not obtained by the use of unexported struct fields. If CanSet returns false, calling Value.Set or any type-specific setter (e.g., Value.SetBool, Value.SetInt) will panic.

+

func (Value) CanUint 1.18

func (v Value) CanUint() bool

CanUint reports whether Value.Uint can be used without panicking.

+

func (Value) Cap

func (v Value) Cap() int

Cap returns v's capacity. It panics if v's Kind is not Array, Chan, Slice or pointer to Array.

+

func (Value) Clear 1.21

func (v Value) Clear()

Clear clears the contents of a map or zeros the contents of a slice.

+

It panics if v's Kind is not Map or Slice.

+

func (Value) Close

func (v Value) Close()

Close closes the channel v. It panics if v's Kind is not Chan or v is a receive-only channel.

+

func (Value) Comparable 1.20

func (v Value) Comparable() bool

Comparable reports whether the value v is comparable. If the type of v is an interface, this checks the dynamic type. If this reports true then v.Interface() == x will not panic for any x, nor will v.Equal(u) for any Value u.

+

func (Value) Complex

func (v Value) Complex() complex128

Complex returns v's underlying value, as a complex128. It panics if v's Kind is not Complex64 or Complex128

+

func (Value) Convert 1.1

func (v Value) Convert(t Type) Value

Convert returns the value v converted to type t. If the usual Go conversion rules do not allow conversion of the value v to type t, or if converting v to type t panics, Convert panics.

+

func (Value) Elem

func (v Value) Elem() Value

Elem returns the value that the interface v contains or that the pointer v points to. It panics if v's Kind is not Interface or Pointer. It returns the zero Value if v is nil.

+

func (Value) Equal 1.20

func (v Value) Equal(u Value) bool

Equal reports true if v is equal to u. For two invalid values, Equal will report true. For an interface value, Equal will compare the value within the interface. Otherwise, If the values have different types, Equal will report false. Otherwise, for arrays and structs Equal will compare each element in order, and report false if it finds non-equal elements. During all comparisons, if values of the same type are compared, and the type is not comparable, Equal will panic.

+

func (Value) Field

func (v Value) Field(i int) Value

Field returns the i'th field of the struct v. It panics if v's Kind is not Struct or i is out of range.

+

func (Value) FieldByIndex

func (v Value) FieldByIndex(index []int) Value

FieldByIndex returns the nested field corresponding to index. It panics if evaluation requires stepping through a nil pointer or a field that is not a struct.

Example +

Code:

// This example shows a case in which the name of a promoted field
+// is hidden by another field: FieldByName will not work, so
+// FieldByIndex must be used instead.
+type user struct {
+    firstName string
+    lastName  string
+}
+
+type data struct {
+    user
+    firstName string
+    lastName  string
+}
+
+u := data{
+    user:      user{"Embedded John", "Embedded Doe"},
+    firstName: "John",
+    lastName:  "Doe",
+}
+
+s := reflect.ValueOf(u).FieldByIndex([]int{0, 1})
+fmt.Println("embedded last name:", s)
+
+

Output:

embedded last name: Embedded Doe
+

func (Value) FieldByIndexErr 1.18

func (v Value) FieldByIndexErr(index []int) (Value, error)

FieldByIndexErr returns the nested field corresponding to index. It returns an error if evaluation requires stepping through a nil pointer, but panics if it must step through a field that is not a struct.

+

func (Value) FieldByName

func (v Value) FieldByName(name string) Value

FieldByName returns the struct field with the given name. It returns the zero Value if no field was found. It panics if v's Kind is not Struct.

Example +

Code:

type user struct {
+    firstName string
+    lastName  string
+}
+u := user{firstName: "John", lastName: "Doe"}
+s := reflect.ValueOf(u)
+
+fmt.Println("Name:", s.FieldByName("firstName"))
+

Output:

Name: John
+

func (Value) FieldByNameFunc

func (v Value) FieldByNameFunc(match func(string) bool) Value

FieldByNameFunc returns the struct field with a name that satisfies the match function. It panics if v's Kind is not Struct. It returns the zero Value if no field was found.

+

func (Value) Float

func (v Value) Float() float64

Float returns v's underlying value, as a float64. It panics if v's Kind is not Float32 or Float64

+

func (Value) Grow 1.20

func (v Value) Grow(n int)

Grow increases the slice's capacity, if necessary, to guarantee space for another n elements. After Grow(n), at least n elements can be appended to the slice without another allocation.

+

It panics if v's Kind is not a Slice or if n is negative or too large to allocate the memory.

+

func (Value) Index

func (v Value) Index(i int) Value

Index returns v's i'th element. It panics if v's Kind is not Array, Slice, or String or i is out of range.

+

func (Value) Int

func (v Value) Int() int64

Int returns v's underlying value, as an int64. It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.

+

func (Value) Interface

func (v Value) Interface() (i any)

Interface returns v's current value as an interface{}. It is equivalent to:

+
var i interface{} = (v's underlying value)
+

It panics if the Value was obtained by accessing unexported struct fields.

+

func (Value) InterfaceData

func (v Value) InterfaceData() [2]uintptr

InterfaceData returns a pair of unspecified uintptr values. It panics if v's Kind is not Interface.

+

In earlier versions of Go, this function returned the interface's value as a uintptr pair. As of Go 1.4, the implementation of interface values precludes any defined use of InterfaceData.

+

Deprecated: The memory representation of interface values is not compatible with InterfaceData.

+

func (Value) IsNil

func (v Value) IsNil() bool

IsNil reports whether its argument v is nil. The argument must be a chan, func, interface, map, pointer, or slice value; if it is not, IsNil panics. Note that IsNil is not always equivalent to a regular comparison with nil in Go. For example, if v was created by calling ValueOf with an uninitialized interface variable i, i==nil will be true but v.IsNil will panic as v will be the zero Value.

+

func (Value) IsValid

func (v Value) IsValid() bool

IsValid reports whether v represents a value. It returns false if v is the zero Value. If IsValid returns false, all other methods except String panic. Most functions and methods never return an invalid Value. If one does, its documentation states the conditions explicitly.

+

func (Value) IsZero 1.13

func (v Value) IsZero() bool

IsZero reports whether v is the zero value for its type. It panics if the argument is invalid.

+

func (Value) Kind

func (v Value) Kind() Kind

Kind returns v's Kind. If v is the zero Value (Value.IsValid returns false), Kind returns Invalid.

+

func (Value) Len

func (v Value) Len() int

Len returns v's length. It panics if v's Kind is not Array, Chan, Map, Slice, String, or pointer to Array.

+

func (Value) MapIndex

func (v Value) MapIndex(key Value) Value

MapIndex returns the value associated with key in the map v. It panics if v's Kind is not Map. It returns the zero Value if key is not found in the map or if v represents a nil map. As in Go, the key's value must be assignable to the map's key type.

+

func (Value) MapKeys

func (v Value) MapKeys() []Value

MapKeys returns a slice containing all the keys present in the map, in unspecified order. It panics if v's Kind is not Map. It returns an empty slice if v represents a nil map.

+

func (Value) MapRange 1.12

func (v Value) MapRange() *MapIter

MapRange returns a range iterator for a map. It panics if v's Kind is not Map.

+

Call MapIter.Next to advance the iterator, and MapIter.Key/MapIter.Value to access each entry. MapIter.Next returns false when the iterator is exhausted. MapRange follows the same iteration semantics as a range statement.

+

Example:

+
iter := reflect.ValueOf(m).MapRange()
+for iter.Next() {
+	k := iter.Key()
+	v := iter.Value()
+	...
+}
+

func (Value) Method

func (v Value) Method(i int) Value

Method returns a function value corresponding to v's i'th method. The arguments to a Call on the returned function should not include a receiver; the returned function will always use v as the receiver. Method panics if i is out of range or if v is a nil interface value.

+

func (Value) MethodByName

func (v Value) MethodByName(name string) Value

MethodByName returns a function value corresponding to the method of v with the given name. The arguments to a Call on the returned function should not include a receiver; the returned function will always use v as the receiver. It returns the zero Value if no method was found.

+

func (Value) NumField

func (v Value) NumField() int

NumField returns the number of fields in the struct v. It panics if v's Kind is not Struct.

+

func (Value) NumMethod

func (v Value) NumMethod() int

NumMethod returns the number of methods in the value's method set.

+

For a non-interface type, it returns the number of exported methods.

+

For an interface type, it returns the number of exported and unexported methods.

+

func (Value) OverflowComplex

func (v Value) OverflowComplex(x complex128) bool

OverflowComplex reports whether the complex128 x cannot be represented by v's type. It panics if v's Kind is not Complex64 or Complex128.

+

func (Value) OverflowFloat

func (v Value) OverflowFloat(x float64) bool

OverflowFloat reports whether the float64 x cannot be represented by v's type. It panics if v's Kind is not Float32 or Float64.

+

func (Value) OverflowInt

func (v Value) OverflowInt(x int64) bool

OverflowInt reports whether the int64 x cannot be represented by v's type. It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.

+

func (Value) OverflowUint

func (v Value) OverflowUint(x uint64) bool

OverflowUint reports whether the uint64 x cannot be represented by v's type. It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.

+

func (Value) Pointer

func (v Value) Pointer() uintptr

Pointer returns v's value as a uintptr. It panics if v's Kind is not Chan, Func, Map, Pointer, Slice, or UnsafePointer.

+

If v's Kind is Func, the returned pointer is an underlying code pointer, but not necessarily enough to identify a single function uniquely. The only guarantee is that the result is zero if and only if v is a nil func Value.

+

If v's Kind is Slice, the returned pointer is to the first element of the slice. If the slice is nil the returned value is 0. If the slice is empty but non-nil the return value is non-zero.

+

It's preferred to use uintptr(Value.UnsafePointer()) to get the equivalent result.

+

func (Value) Recv

func (v Value) Recv() (x Value, ok bool)

Recv receives and returns a value from the channel v. It panics if v's Kind is not Chan. The receive blocks until a value is ready. The boolean value ok is true if the value x corresponds to a send on the channel, false if it is a zero value received because the channel is closed.

+

func (Value) Send

func (v Value) Send(x Value)

Send sends x on the channel v. It panics if v's kind is not Chan or if x's type is not the same type as v's element type. As in Go, x's value must be assignable to the channel's element type.

+

func (Value) Set

func (v Value) Set(x Value)

Set assigns x to the value v. It panics if Value.CanSet returns false. As in Go, x's value must be assignable to v's type and must not be derived from an unexported field.

+

func (Value) SetBool

func (v Value) SetBool(x bool)

SetBool sets v's underlying value. It panics if v's Kind is not Bool or if Value.CanSet returns false.

+

func (Value) SetBytes

func (v Value) SetBytes(x []byte)

SetBytes sets v's underlying value. It panics if v's underlying value is not a slice of bytes.

+

func (Value) SetCap 1.2

func (v Value) SetCap(n int)

SetCap sets v's capacity to n. It panics if v's Kind is not Slice or if n is smaller than the length or greater than the capacity of the slice.

+

func (Value) SetComplex

func (v Value) SetComplex(x complex128)

SetComplex sets v's underlying value to x. It panics if v's Kind is not Complex64 or Complex128, or if Value.CanSet returns false.

+

func (Value) SetFloat

func (v Value) SetFloat(x float64)

SetFloat sets v's underlying value to x. It panics if v's Kind is not Float32 or Float64, or if Value.CanSet returns false.

+

func (Value) SetInt

func (v Value) SetInt(x int64)

SetInt sets v's underlying value to x. It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if Value.CanSet returns false.

+

func (Value) SetIterKey 1.18

func (v Value) SetIterKey(iter *MapIter)

SetIterKey assigns to v the key of iter's current map entry. It is equivalent to v.Set(iter.Key()), but it avoids allocating a new Value. As in Go, the key must be assignable to v's type and must not be derived from an unexported field.

+

func (Value) SetIterValue 1.18

func (v Value) SetIterValue(iter *MapIter)

SetIterValue assigns to v the value of iter's current map entry. It is equivalent to v.Set(iter.Value()), but it avoids allocating a new Value. As in Go, the value must be assignable to v's type and must not be derived from an unexported field.

+

func (Value) SetLen

func (v Value) SetLen(n int)

SetLen sets v's length to n. It panics if v's Kind is not Slice or if n is negative or greater than the capacity of the slice.

+

func (Value) SetMapIndex

func (v Value) SetMapIndex(key, elem Value)

SetMapIndex sets the element associated with key in the map v to elem. It panics if v's Kind is not Map. If elem is the zero Value, SetMapIndex deletes the key from the map. Otherwise if v holds a nil map, SetMapIndex will panic. As in Go, key's elem must be assignable to the map's key type, and elem's value must be assignable to the map's elem type.

+

func (Value) SetPointer

func (v Value) SetPointer(x unsafe.Pointer)

SetPointer sets the unsafe.Pointer value v to x. It panics if v's Kind is not UnsafePointer.

+

func (Value) SetString

func (v Value) SetString(x string)

SetString sets v's underlying value to x. It panics if v's Kind is not String or if Value.CanSet returns false.

+

func (Value) SetUint

func (v Value) SetUint(x uint64)

SetUint sets v's underlying value to x. It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if Value.CanSet returns false.

+

func (Value) SetZero 1.20

func (v Value) SetZero()

SetZero sets v to be the zero value of v's type. It panics if Value.CanSet returns false.

+

func (Value) Slice

func (v Value) Slice(i, j int) Value

Slice returns v[i:j]. It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array, or if the indexes are out of bounds.

+

func (Value) Slice3 1.2

func (v Value) Slice3(i, j, k int) Value

Slice3 is the 3-index form of the slice operation: it returns v[i:j:k]. It panics if v's Kind is not Array or Slice, or if v is an unaddressable array, or if the indexes are out of bounds.

+

func (Value) String

func (v Value) String() string

String returns the string v's underlying value, as a string. String is a special case because of Go's String method convention. Unlike the other getters, it does not panic if v's Kind is not String. Instead, it returns a string of the form "<T value>" where T is v's type. The fmt package treats Values specially. It does not call their String method implicitly but instead prints the concrete values they hold.

+

func (Value) TryRecv

func (v Value) TryRecv() (x Value, ok bool)

TryRecv attempts to receive a value from the channel v but will not block. It panics if v's Kind is not Chan. If the receive delivers a value, x is the transferred value and ok is true. If the receive cannot finish without blocking, x is the zero Value and ok is false. If the channel is closed, x is the zero value for the channel's element type and ok is false.

+

func (Value) TrySend

func (v Value) TrySend(x Value) bool

TrySend attempts to send x on the channel v but will not block. It panics if v's Kind is not Chan. It reports whether the value was sent. As in Go, x's value must be assignable to the channel's element type.

+

func (Value) Type

func (v Value) Type() Type

Type returns v's type.

+

func (Value) Uint

func (v Value) Uint() uint64

Uint returns v's underlying value, as a uint64. It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.

+

func (Value) UnsafeAddr

func (v Value) UnsafeAddr() uintptr

UnsafeAddr returns a pointer to v's data, as a uintptr. It panics if v is not addressable.

+

It's preferred to use uintptr(Value.Addr().UnsafePointer()) to get the equivalent result.

+

func (Value) UnsafePointer 1.18

func (v Value) UnsafePointer() unsafe.Pointer

UnsafePointer returns v's value as a unsafe.Pointer. It panics if v's Kind is not Chan, Func, Map, Pointer, Slice, or UnsafePointer.

+

If v's Kind is Func, the returned pointer is an underlying code pointer, but not necessarily enough to identify a single function uniquely. The only guarantee is that the result is zero if and only if v is a nil func Value.

+

If v's Kind is Slice, the returned pointer is to the first element of the slice. If the slice is nil the returned value is nil. If the slice is empty but non-nil the return value is non-nil.

+

type ValueError

A ValueError occurs when a Value method is invoked on a Value that does not support it. Such cases are documented in the description of each method.

+
type ValueError struct {
+    Method string
+    Kind   Kind
+}
+

func (*ValueError) Error

func (e *ValueError) Error() string

Bugs

Subdirectories

Name Synopsis
..
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/reflect/ +

+
diff --git a/devdocs/go/regexp%2Findex.html b/devdocs/go/regexp%2Findex.html new file mode 100644 index 00000000..e5fe3bd5 --- /dev/null +++ b/devdocs/go/regexp%2Findex.html @@ -0,0 +1,501 @@ +

Package regexp

Overview

Package regexp implements regular expression search.

+

The syntax of the regular expressions accepted is the same general syntax used by Perl, Python, and other languages. More precisely, it is the syntax accepted by RE2 and described at https://golang.org/s/re2syntax, except for \C. For an overview of the syntax, see the regexp/syntax package.

+

The regexp implementation provided by this package is guaranteed to run in time linear in the size of the input. (This is a property not guaranteed by most open source implementations of regular expressions.) For more information about this property, see

+
https://swtch.com/~rsc/regexp/regexp1.html
+

or any book about automata theory.

+

All characters are UTF-8-encoded code points. Following utf8.DecodeRune, each byte of an invalid UTF-8 sequence is treated as if it encoded utf8.RuneError (U+FFFD).

+

There are 16 methods of Regexp that match a regular expression and identify the matched text. Their names are matched by this regular expression:

+
Find(All)?(String)?(Submatch)?(Index)?
+

If 'All' is present, the routine matches successive non-overlapping matches of the entire expression. Empty matches abutting a preceding match are ignored. The return value is a slice containing the successive return values of the corresponding non-'All' routine. These routines take an extra integer argument, n. If n >= 0, the function returns at most n matches/submatches; otherwise, it returns all of them.

+

If 'String' is present, the argument is a string; otherwise it is a slice of bytes; return values are adjusted as appropriate.

+

If 'Submatch' is present, the return value is a slice identifying the successive submatches of the expression. Submatches are matches of parenthesized subexpressions (also known as capturing groups) within the regular expression, numbered from left to right in order of opening parenthesis. Submatch 0 is the match of the entire expression, submatch 1 is the match of the first parenthesized subexpression, and so on.

+

If 'Index' is present, matches and submatches are identified by byte index pairs within the input string: result[2*n:2*n+2] identifies the indexes of the nth submatch. The pair for n==0 identifies the match of the entire expression. If 'Index' is not present, the match is identified by the text of the match/submatch. If an index is negative or text is nil, it means that subexpression did not match any string in the input. For 'String' versions an empty string means either no match or an empty match.

+

There is also a subset of the methods that can be applied to text read from a RuneReader:

+
MatchReader, FindReaderIndex, FindReaderSubmatchIndex
+

This set may grow. Note that regular expression matches may need to examine text beyond the text returned by a match, so the methods that match text from a RuneReader may read arbitrarily far into the input before returning.

+

(There are a few other methods that do not match this pattern.)

Example +

Code:

// Compile the expression once, usually at init time.
+// Use raw strings to avoid having to quote the backslashes.
+var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)
+
+fmt.Println(validID.MatchString("adam[23]"))
+fmt.Println(validID.MatchString("eve[7]"))
+fmt.Println(validID.MatchString("Job[48]"))
+fmt.Println(validID.MatchString("snakey"))
+

Output:

true
+true
+false
+false
+

Index

Examples

Package
Match
MatchString
QuoteMeta
Regexp.Expand
Regexp.ExpandString
Regexp.Find
Regexp.FindAll
Regexp.FindAllIndex
Regexp.FindAllString
Regexp.FindAllStringSubmatch
Regexp.FindAllStringSubmatchIndex
Regexp.FindAllSubmatch
Regexp.FindAllSubmatchIndex
Regexp.FindIndex
Regexp.FindString
Regexp.FindStringIndex
Regexp.FindStringSubmatch
Regexp.FindSubmatch
Regexp.FindSubmatchIndex
Regexp.Longest
Regexp.Match
Regexp.MatchString
Regexp.NumSubexp
Regexp.ReplaceAll
Regexp.ReplaceAllLiteralString
Regexp.ReplaceAllString
Regexp.ReplaceAllStringFunc
Regexp.Split
Regexp.SubexpIndex
Regexp.SubexpNames

Package files

backtrack.go exec.go onepass.go regexp.go

func Match

func Match(pattern string, b []byte) (matched bool, err error)

Match reports whether the byte slice b contains any match of the regular expression pattern. More complicated queries need to use Compile and the full Regexp interface.

Example +

Code:

matched, err := regexp.Match(`foo.*`, []byte(`seafood`))
+fmt.Println(matched, err)
+matched, err = regexp.Match(`bar.*`, []byte(`seafood`))
+fmt.Println(matched, err)
+matched, err = regexp.Match(`a(b`, []byte(`seafood`))
+fmt.Println(matched, err)
+
+

Output:

true <nil>
+false <nil>
+false error parsing regexp: missing closing ): `a(b`
+

func MatchReader

func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)

MatchReader reports whether the text returned by the RuneReader contains any match of the regular expression pattern. More complicated queries need to use Compile and the full Regexp interface.

+

func MatchString

func MatchString(pattern string, s string) (matched bool, err error)

MatchString reports whether the string s contains any match of the regular expression pattern. More complicated queries need to use Compile and the full Regexp interface.

Example +

Code:

matched, err := regexp.MatchString(`foo.*`, "seafood")
+fmt.Println(matched, err)
+matched, err = regexp.MatchString(`bar.*`, "seafood")
+fmt.Println(matched, err)
+matched, err = regexp.MatchString(`a(b`, "seafood")
+fmt.Println(matched, err)
+

Output:

true <nil>
+false <nil>
+false error parsing regexp: missing closing ): `a(b`
+

func QuoteMeta

func QuoteMeta(s string) string

QuoteMeta returns a string that escapes all regular expression metacharacters inside the argument text; the returned string is a regular expression matching the literal text.

Example +

Code:

fmt.Println(regexp.QuoteMeta(`Escaping symbols like: .+*?()|[]{}^$`))
+

Output:

Escaping symbols like: \.\+\*\?\(\)\|\[\]\{\}\^\$
+

type Regexp

Regexp is the representation of a compiled regular expression. A Regexp is safe for concurrent use by multiple goroutines, except for configuration methods, such as Regexp.Longest.

+
type Regexp struct {
+    // contains filtered or unexported fields
+}
+

func Compile

func Compile(expr string) (*Regexp, error)

Compile parses a regular expression and returns, if successful, a Regexp object that can be used to match against text.

+

When matching against text, the regexp returns a match that begins as early as possible in the input (leftmost), and among those it chooses the one that a backtracking search would have found first. This so-called leftmost-first matching is the same semantics that Perl, Python, and other implementations use, although this package implements it without the expense of backtracking. For POSIX leftmost-longest matching, see CompilePOSIX.

+

func CompilePOSIX

func CompilePOSIX(expr string) (*Regexp, error)

CompilePOSIX is like Compile but restricts the regular expression to POSIX ERE (egrep) syntax and changes the match semantics to leftmost-longest.

+

That is, when matching against text, the regexp returns a match that begins as early as possible in the input (leftmost), and among those it chooses a match that is as long as possible. This so-called leftmost-longest matching is the same semantics that early regular expression implementations used and that POSIX specifies.

+

However, there can be multiple leftmost-longest matches, with different submatch choices, and here this package diverges from POSIX. Among the possible leftmost-longest matches, this package chooses the one that a backtracking search would have found first, while POSIX specifies that the match be chosen to maximize the length of the first subexpression, then the second, and so on from left to right. The POSIX rule is computationally prohibitive and not even well-defined. See https://swtch.com/~rsc/regexp/regexp2.html#posix for details.

+

func MustCompile

func MustCompile(str string) *Regexp

MustCompile is like Compile but panics if the expression cannot be parsed. It simplifies safe initialization of global variables holding compiled regular expressions.

+

func MustCompilePOSIX

func MustCompilePOSIX(str string) *Regexp

MustCompilePOSIX is like CompilePOSIX but panics if the expression cannot be parsed. It simplifies safe initialization of global variables holding compiled regular expressions.

+

func (*Regexp) Copy 1.6

func (re *Regexp) Copy() *Regexp

Copy returns a new Regexp object copied from re. Calling Regexp.Longest on one copy does not affect another.

+

Deprecated: In earlier releases, when using a Regexp in multiple goroutines, giving each goroutine its own copy helped to avoid lock contention. As of Go 1.12, using Copy is no longer necessary to avoid lock contention. Copy may still be appropriate if the reason for its use is to make two copies with different Regexp.Longest settings.

+

func (*Regexp) Expand

func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte

Expand appends template to dst and returns the result; during the append, Expand replaces variables in the template with corresponding matches drawn from src. The match slice should have been returned by Regexp.FindSubmatchIndex.

+

In the template, a variable is denoted by a substring of the form $name or ${name}, where name is a non-empty sequence of letters, digits, and underscores. A purely numeric name like $1 refers to the submatch with the corresponding index; other names refer to capturing parentheses named with the (?P<name>...) syntax. A reference to an out of range or unmatched index or a name that is not present in the regular expression is replaced with an empty slice.

+

In the $name form, name is taken to be as long as possible: $1x is equivalent to ${1x}, not ${1}x, and, $10 is equivalent to ${10}, not ${1}0.

+

To insert a literal $ in the output, use $$ in the template.

Example +

Code:

content := []byte(`
+    # comment line
+    option1: value1
+    option2: value2
+
+    # another comment line
+    option3: value3
+`)
+
+// Regex pattern captures "key: value" pair from the content.
+pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
+
+// Template to convert "key: value" to "key=value" by
+// referencing the values captured by the regex pattern.
+template := []byte("$key=$value\n")
+
+result := []byte{}
+
+// For each match of the regex in the content.
+for _, submatches := range pattern.FindAllSubmatchIndex(content, -1) {
+    // Apply the captured submatches to the template and append the output
+    // to the result.
+    result = pattern.Expand(result, template, content, submatches)
+}
+fmt.Println(string(result))
+

Output:

option1=value1
+option2=value2
+option3=value3
+

func (*Regexp) ExpandString

func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte

ExpandString is like Regexp.Expand but the template and source are strings. It appends to and returns a byte slice in order to give the calling code control over allocation.

Example +

Code:

content := `
+    # comment line
+    option1: value1
+    option2: value2
+
+    # another comment line
+    option3: value3
+`
+
+// Regex pattern captures "key: value" pair from the content.
+pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
+
+// Template to convert "key: value" to "key=value" by
+// referencing the values captured by the regex pattern.
+template := "$key=$value\n"
+
+result := []byte{}
+
+// For each match of the regex in the content.
+for _, submatches := range pattern.FindAllStringSubmatchIndex(content, -1) {
+    // Apply the captured submatches to the template and append the output
+    // to the result.
+    result = pattern.ExpandString(result, template, content, submatches)
+}
+fmt.Println(string(result))
+

Output:

option1=value1
+option2=value2
+option3=value3
+

func (*Regexp) Find

func (re *Regexp) Find(b []byte) []byte

Find returns a slice holding the text of the leftmost match in b of the regular expression. A return value of nil indicates no match.

Example +

Code:

re := regexp.MustCompile(`foo.?`)
+fmt.Printf("%q\n", re.Find([]byte(`seafood fool`)))
+
+

Output:

"food"
+

func (*Regexp) FindAll

func (re *Regexp) FindAll(b []byte, n int) [][]byte

FindAll is the 'All' version of Find; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

Example +

Code:

re := regexp.MustCompile(`foo.?`)
+fmt.Printf("%q\n", re.FindAll([]byte(`seafood fool`), -1))
+
+

Output:

["food" "fool"]
+

func (*Regexp) FindAllIndex

func (re *Regexp) FindAllIndex(b []byte, n int) [][]int

FindAllIndex is the 'All' version of Regexp.FindIndex; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

Example +

Code:

content := []byte("London")
+re := regexp.MustCompile(`o.`)
+fmt.Println(re.FindAllIndex(content, 1))
+fmt.Println(re.FindAllIndex(content, -1))
+

Output:

[[1 3]]
+[[1 3] [4 6]]
+

func (*Regexp) FindAllString

func (re *Regexp) FindAllString(s string, n int) []string

FindAllString is the 'All' version of Regexp.FindString; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

Example +

Code:

re := regexp.MustCompile(`a.`)
+fmt.Println(re.FindAllString("paranormal", -1))
+fmt.Println(re.FindAllString("paranormal", 2))
+fmt.Println(re.FindAllString("graal", -1))
+fmt.Println(re.FindAllString("none", -1))
+

Output:

[ar an al]
+[ar an]
+[aa]
+[]
+

func (*Regexp) FindAllStringIndex

func (re *Regexp) FindAllStringIndex(s string, n int) [][]int

FindAllStringIndex is the 'All' version of Regexp.FindStringIndex; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

+

func (*Regexp) FindAllStringSubmatch

func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string

FindAllStringSubmatch is the 'All' version of Regexp.FindStringSubmatch; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

Example +

Code:

re := regexp.MustCompile(`a(x*)b`)
+fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-", -1))
+fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-", -1))
+fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-axb-", -1))
+fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-ab-", -1))
+

Output:

[["ab" ""]]
+[["axxb" "xx"]]
+[["ab" ""] ["axb" "x"]]
+[["axxb" "xx"] ["ab" ""]]
+

func (*Regexp) FindAllStringSubmatchIndex

func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int

FindAllStringSubmatchIndex is the 'All' version of Regexp.FindStringSubmatchIndex; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

Example +

Code:

re := regexp.MustCompile(`a(x*)b`)
+// Indices:
+//    01234567   012345678
+//    -ab-axb-   -axxb-ab-
+fmt.Println(re.FindAllStringSubmatchIndex("-ab-", -1))
+fmt.Println(re.FindAllStringSubmatchIndex("-axxb-", -1))
+fmt.Println(re.FindAllStringSubmatchIndex("-ab-axb-", -1))
+fmt.Println(re.FindAllStringSubmatchIndex("-axxb-ab-", -1))
+fmt.Println(re.FindAllStringSubmatchIndex("-foo-", -1))
+

Output:

[[1 3 2 2]]
+[[1 5 2 4]]
+[[1 3 2 2] [4 7 5 6]]
+[[1 5 2 4] [6 8 7 7]]
+[]
+

func (*Regexp) FindAllSubmatch

func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte

FindAllSubmatch is the 'All' version of Regexp.FindSubmatch; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

Example +

Code:

re := regexp.MustCompile(`foo(.?)`)
+fmt.Printf("%q\n", re.FindAllSubmatch([]byte(`seafood fool`), -1))
+
+

Output:

[["food" "d"] ["fool" "l"]]
+

func (*Regexp) FindAllSubmatchIndex

func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int

FindAllSubmatchIndex is the 'All' version of Regexp.FindSubmatchIndex; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

Example +

Code:

content := []byte(`
+    # comment line
+    option1: value1
+    option2: value2
+`)
+// Regex pattern captures "key: value" pair from the content.
+pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
+allIndexes := pattern.FindAllSubmatchIndex(content, -1)
+for _, loc := range allIndexes {
+    fmt.Println(loc)
+    fmt.Println(string(content[loc[0]:loc[1]]))
+    fmt.Println(string(content[loc[2]:loc[3]]))
+    fmt.Println(string(content[loc[4]:loc[5]]))
+}
+

Output:

[18 33 18 25 27 33]
+option1: value1
+option1
+value1
+[35 50 35 42 44 50]
+option2: value2
+option2
+value2
+

func (*Regexp) FindIndex

func (re *Regexp) FindIndex(b []byte) (loc []int)

FindIndex returns a two-element slice of integers defining the location of the leftmost match in b of the regular expression. The match itself is at b[loc[0]:loc[1]]. A return value of nil indicates no match.

Example +

Code:

content := []byte(`
+    # comment line
+    option1: value1
+    option2: value2
+`)
+// Regex pattern captures "key: value" pair from the content.
+pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
+
+loc := pattern.FindIndex(content)
+fmt.Println(loc)
+fmt.Println(string(content[loc[0]:loc[1]]))
+

Output:

[18 33]
+option1: value1
+

func (*Regexp) FindReaderIndex

func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int)

FindReaderIndex returns a two-element slice of integers defining the location of the leftmost match of the regular expression in text read from the io.RuneReader. The match text was found in the input stream at byte offset loc[0] through loc[1]-1. A return value of nil indicates no match.

+

func (*Regexp) FindReaderSubmatchIndex

func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []int

FindReaderSubmatchIndex returns a slice holding the index pairs identifying the leftmost match of the regular expression of text read by the io.RuneReader, and the matches, if any, of its subexpressions, as defined by the 'Submatch' and 'Index' descriptions in the package comment. A return value of nil indicates no match.

+

func (*Regexp) FindString

func (re *Regexp) FindString(s string) string

FindString returns a string holding the text of the leftmost match in s of the regular expression. If there is no match, the return value is an empty string, but it will also be empty if the regular expression successfully matches an empty string. Use Regexp.FindStringIndex or Regexp.FindStringSubmatch if it is necessary to distinguish these cases.

Example +

Code:

re := regexp.MustCompile(`foo.?`)
+fmt.Printf("%q\n", re.FindString("seafood fool"))
+fmt.Printf("%q\n", re.FindString("meat"))
+

Output:

"food"
+""
+

func (*Regexp) FindStringIndex

func (re *Regexp) FindStringIndex(s string) (loc []int)

FindStringIndex returns a two-element slice of integers defining the location of the leftmost match in s of the regular expression. The match itself is at s[loc[0]:loc[1]]. A return value of nil indicates no match.

Example +

Code:

re := regexp.MustCompile(`ab?`)
+fmt.Println(re.FindStringIndex("tablett"))
+fmt.Println(re.FindStringIndex("foo") == nil)
+

Output:

[1 3]
+true
+

func (*Regexp) FindStringSubmatch

func (re *Regexp) FindStringSubmatch(s string) []string

FindStringSubmatch returns a slice of strings holding the text of the leftmost match of the regular expression in s and the matches, if any, of its subexpressions, as defined by the 'Submatch' description in the package comment. A return value of nil indicates no match.

Example +

Code:

re := regexp.MustCompile(`a(x*)b(y|z)c`)
+fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))
+fmt.Printf("%q\n", re.FindStringSubmatch("-abzc-"))
+

Output:

["axxxbyc" "xxx" "y"]
+["abzc" "" "z"]
+

func (*Regexp) FindStringSubmatchIndex

func (re *Regexp) FindStringSubmatchIndex(s string) []int

FindStringSubmatchIndex returns a slice holding the index pairs identifying the leftmost match of the regular expression in s and the matches, if any, of its subexpressions, as defined by the 'Submatch' and 'Index' descriptions in the package comment. A return value of nil indicates no match.

+

func (*Regexp) FindSubmatch

func (re *Regexp) FindSubmatch(b []byte) [][]byte

FindSubmatch returns a slice of slices holding the text of the leftmost match of the regular expression in b and the matches, if any, of its subexpressions, as defined by the 'Submatch' descriptions in the package comment. A return value of nil indicates no match.

Example +

Code:

re := regexp.MustCompile(`foo(.?)`)
+fmt.Printf("%q\n", re.FindSubmatch([]byte(`seafood fool`)))
+
+

Output:

["food" "d"]
+

func (*Regexp) FindSubmatchIndex

func (re *Regexp) FindSubmatchIndex(b []byte) []int

FindSubmatchIndex returns a slice holding the index pairs identifying the leftmost match of the regular expression in b and the matches, if any, of its subexpressions, as defined by the 'Submatch' and 'Index' descriptions in the package comment. A return value of nil indicates no match.

Example +

Code:

re := regexp.MustCompile(`a(x*)b`)
+// Indices:
+//    01234567   012345678
+//    -ab-axb-   -axxb-ab-
+fmt.Println(re.FindSubmatchIndex([]byte("-ab-")))
+fmt.Println(re.FindSubmatchIndex([]byte("-axxb-")))
+fmt.Println(re.FindSubmatchIndex([]byte("-ab-axb-")))
+fmt.Println(re.FindSubmatchIndex([]byte("-axxb-ab-")))
+fmt.Println(re.FindSubmatchIndex([]byte("-foo-")))
+

Output:

[1 3 2 2]
+[1 5 2 4]
+[1 3 2 2]
+[1 5 2 4]
+[]
+

func (*Regexp) LiteralPrefix

func (re *Regexp) LiteralPrefix() (prefix string, complete bool)

LiteralPrefix returns a literal string that must begin any match of the regular expression re. It returns the boolean true if the literal string comprises the entire regular expression.

+

func (*Regexp) Longest 1.1

func (re *Regexp) Longest()

Longest makes future searches prefer the leftmost-longest match. That is, when matching against text, the regexp returns a match that begins as early as possible in the input (leftmost), and among those it chooses a match that is as long as possible. This method modifies the Regexp and may not be called concurrently with any other methods.

Example +

Code:

re := regexp.MustCompile(`a(|b)`)
+fmt.Println(re.FindString("ab"))
+re.Longest()
+fmt.Println(re.FindString("ab"))
+

Output:

a
+ab
+

func (*Regexp) MarshalText 1.21

func (re *Regexp) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler. The output matches that of calling the Regexp.String method.

+

Note that the output is lossy in some cases: This method does not indicate POSIX regular expressions (i.e. those compiled by calling CompilePOSIX), or those for which the Regexp.Longest method has been called.

+

func (*Regexp) Match

func (re *Regexp) Match(b []byte) bool

Match reports whether the byte slice b contains any match of the regular expression re.

Example +

Code:

re := regexp.MustCompile(`foo.?`)
+fmt.Println(re.Match([]byte(`seafood fool`)))
+fmt.Println(re.Match([]byte(`something else`)))
+
+

Output:

true
+false
+

func (*Regexp) MatchReader

func (re *Regexp) MatchReader(r io.RuneReader) bool

MatchReader reports whether the text returned by the io.RuneReader contains any match of the regular expression re.

+

func (*Regexp) MatchString

func (re *Regexp) MatchString(s string) bool

MatchString reports whether the string s contains any match of the regular expression re.

Example +

Code:

re := regexp.MustCompile(`(gopher){2}`)
+fmt.Println(re.MatchString("gopher"))
+fmt.Println(re.MatchString("gophergopher"))
+fmt.Println(re.MatchString("gophergophergopher"))
+

Output:

false
+true
+true
+

func (*Regexp) NumSubexp

func (re *Regexp) NumSubexp() int

NumSubexp returns the number of parenthesized subexpressions in this Regexp.

Example +

Code:

re0 := regexp.MustCompile(`a.`)
+fmt.Printf("%d\n", re0.NumSubexp())
+
+re := regexp.MustCompile(`(.*)((a)b)(.*)a`)
+fmt.Println(re.NumSubexp())
+

Output:

0
+4
+

func (*Regexp) ReplaceAll

func (re *Regexp) ReplaceAll(src, repl []byte) []byte

ReplaceAll returns a copy of src, replacing matches of the Regexp with the replacement text repl. Inside repl, $ signs are interpreted as in Regexp.Expand.

Example +

Code:

re := regexp.MustCompile(`a(x*)b`)
+fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("T")))
+fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1")))
+fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
+fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
+
+re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
+fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
+fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
+
+

Output:

-T-T-
+--xx-
+---
+-W-xxW-
+--xx-
+-W-xxW-
+

func (*Regexp) ReplaceAllFunc

func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte

ReplaceAllFunc returns a copy of src in which all matches of the Regexp have been replaced by the return value of function repl applied to the matched byte slice. The replacement returned by repl is substituted directly, without using Regexp.Expand.

+

func (*Regexp) ReplaceAllLiteral

func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte

ReplaceAllLiteral returns a copy of src, replacing matches of the Regexp with the replacement bytes repl. The replacement repl is substituted directly, without using Regexp.Expand.

+

func (*Regexp) ReplaceAllLiteralString

func (re *Regexp) ReplaceAllLiteralString(src, repl string) string

ReplaceAllLiteralString returns a copy of src, replacing matches of the Regexp with the replacement string repl. The replacement repl is substituted directly, without using Regexp.Expand.

Example +

Code:

re := regexp.MustCompile(`a(x*)b`)
+fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "T"))
+fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "$1"))
+fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "${1}"))
+

Output:

-T-T-
+-$1-$1-
+-${1}-${1}-
+

func (*Regexp) ReplaceAllString

func (re *Regexp) ReplaceAllString(src, repl string) string

ReplaceAllString returns a copy of src, replacing matches of the Regexp with the replacement string repl. Inside repl, $ signs are interpreted as in Regexp.Expand.

Example +

Code:

re := regexp.MustCompile(`a(x*)b`)
+fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))
+fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
+fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
+fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
+
+re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
+fmt.Printf("%s\n", re2.ReplaceAllString("-ab-axxb-", "$1W"))
+fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
+
+

Output:

-T-T-
+--xx-
+---
+-W-xxW-
+--xx-
+-W-xxW-
+

func (*Regexp) ReplaceAllStringFunc

func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string

ReplaceAllStringFunc returns a copy of src in which all matches of the Regexp have been replaced by the return value of function repl applied to the matched substring. The replacement returned by repl is substituted directly, without using Regexp.Expand.

Example +

Code:

re := regexp.MustCompile(`[^aeiou]`)
+fmt.Println(re.ReplaceAllStringFunc("seafood fool", strings.ToUpper))
+

Output:

SeaFooD FooL
+

func (*Regexp) Split 1.1

func (re *Regexp) Split(s string, n int) []string

Split slices s into substrings separated by the expression and returns a slice of the substrings between those expression matches.

+

The slice returned by this method consists of all the substrings of s not contained in the slice returned by Regexp.FindAllString. When called on an expression that contains no metacharacters, it is equivalent to strings.SplitN.

+

Example:

+
s := regexp.MustCompile("a*").Split("abaabaccadaaae", 5)
+// s: ["", "b", "b", "c", "cadaaae"]
+

The count determines the number of substrings to return:

+
n > 0: at most n substrings; the last substring will be the unsplit remainder.
+n == 0: the result is nil (zero substrings)
+n < 0: all substrings
+

Example +

Code:

a := regexp.MustCompile(`a`)
+fmt.Println(a.Split("banana", -1))
+fmt.Println(a.Split("banana", 0))
+fmt.Println(a.Split("banana", 1))
+fmt.Println(a.Split("banana", 2))
+zp := regexp.MustCompile(`z+`)
+fmt.Println(zp.Split("pizza", -1))
+fmt.Println(zp.Split("pizza", 0))
+fmt.Println(zp.Split("pizza", 1))
+fmt.Println(zp.Split("pizza", 2))
+

Output:

[b n n ]
+[]
+[banana]
+[b nana]
+[pi a]
+[]
+[pizza]
+[pi a]
+

func (*Regexp) String

func (re *Regexp) String() string

String returns the source text used to compile the regular expression.

+

func (*Regexp) SubexpIndex 1.15

func (re *Regexp) SubexpIndex(name string) int

SubexpIndex returns the index of the first subexpression with the given name, or -1 if there is no subexpression with that name.

+

Note that multiple subexpressions can be written using the same name, as in (?P<bob>a+)(?P<bob>b+), which declares two subexpressions named "bob". In this case, SubexpIndex returns the index of the leftmost such subexpression in the regular expression.

Example +

Code:

re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
+fmt.Println(re.MatchString("Alan Turing"))
+matches := re.FindStringSubmatch("Alan Turing")
+lastIndex := re.SubexpIndex("last")
+fmt.Printf("last => %d\n", lastIndex)
+fmt.Println(matches[lastIndex])
+

Output:

true
+last => 2
+Turing
+

func (*Regexp) SubexpNames

func (re *Regexp) SubexpNames() []string

SubexpNames returns the names of the parenthesized subexpressions in this Regexp. The name for the first sub-expression is names[1], so that if m is a match slice, the name for m[i] is SubexpNames()[i]. Since the Regexp as a whole cannot be named, names[0] is always the empty string. The slice should not be modified.

Example +

Code:

re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
+fmt.Println(re.MatchString("Alan Turing"))
+fmt.Printf("%q\n", re.SubexpNames())
+reversed := fmt.Sprintf("${%s} ${%s}", re.SubexpNames()[2], re.SubexpNames()[1])
+fmt.Println(reversed)
+fmt.Println(re.ReplaceAllString("Alan Turing", reversed))
+

Output:

true
+["" "first" "last"]
+${last} ${first}
+Turing Alan
+

func (*Regexp) UnmarshalText 1.21

func (re *Regexp) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler by calling Compile on the encoded value.

+

Subdirectories

Name Synopsis
..
syntax Package syntax parses regular expressions into parse trees and compiles parse trees into programs.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/regexp/ +

+
diff --git a/devdocs/go/regexp%2Fsyntax%2Findex.html b/devdocs/go/regexp%2Fsyntax%2Findex.html new file mode 100644 index 00000000..641bf891 --- /dev/null +++ b/devdocs/go/regexp%2Fsyntax%2Findex.html @@ -0,0 +1,284 @@ +

Package syntax

Overview

Package syntax parses regular expressions into parse trees and compiles parse trees into programs. Most clients of regular expressions will use the facilities of package regexp (such as Compile and Match) instead of this package.

+

Syntax

The regular expression syntax understood by this package when parsing with the Perl flag is as follows. Parts of the syntax can be disabled by passing alternate flags to Parse.

+

Single characters:

+
.              any character, possibly including newline (flag s=true)
+[xyz]          character class
+[^xyz]         negated character class
+\d             Perl character class
+\D             negated Perl character class
+[[:alpha:]]    ASCII character class
+[[:^alpha:]]   negated ASCII character class
+\pN            Unicode character class (one-letter name)
+\p{Greek}      Unicode character class
+\PN            negated Unicode character class (one-letter name)
+\P{Greek}      negated Unicode character class
+

Composites:

+
xy             x followed by y
+x|y            x or y (prefer x)
+

Repetitions:

+
x*             zero or more x, prefer more
+x+             one or more x, prefer more
+x?             zero or one x, prefer one
+x{n,m}         n or n+1 or ... or m x, prefer more
+x{n,}          n or more x, prefer more
+x{n}           exactly n x
+x*?            zero or more x, prefer fewer
+x+?            one or more x, prefer fewer
+x??            zero or one x, prefer zero
+x{n,m}?        n or n+1 or ... or m x, prefer fewer
+x{n,}?         n or more x, prefer fewer
+x{n}?          exactly n x
+

Implementation restriction: The counting forms x{n,m}, x{n,}, and x{n} reject forms that create a minimum or maximum repetition count above 1000. Unlimited repetitions are not subject to this restriction.

+

Grouping:

+
(re)           numbered capturing group (submatch)
+(?P<name>re)   named & numbered capturing group (submatch)
+(?<name>re)    named & numbered capturing group (submatch)
+(?:re)         non-capturing group
+(?flags)       set flags within current group; non-capturing
+(?flags:re)    set flags during re; non-capturing
+
+Flag syntax is xyz (set) or -xyz (clear) or xy-z (set xy, clear z). The flags are:
+
+i              case-insensitive (default false)
+m              multi-line mode: ^ and $ match begin/end line in addition to begin/end text (default false)
+s              let . match \n (default false)
+U              ungreedy: swap meaning of x* and x*?, x+ and x+?, etc (default false)
+

Empty strings:

+
^              at beginning of text or line (flag m=true)
+$              at end of text (like \z not \Z) or line (flag m=true)
+\A             at beginning of text
+\b             at ASCII word boundary (\w on one side and \W, \A, or \z on the other)
+\B             not at ASCII word boundary
+\z             at end of text
+

Escape sequences:

+
\a             bell (== \007)
+\f             form feed (== \014)
+\t             horizontal tab (== \011)
+\n             newline (== \012)
+\r             carriage return (== \015)
+\v             vertical tab character (== \013)
+\*             literal *, for any punctuation character *
+\123           octal character code (up to three digits)
+\x7F           hex character code (exactly two digits)
+\x{10FFFF}     hex character code
+\Q...\E        literal text ... even if ... has punctuation
+

Character class elements:

+
x              single character
+A-Z            character range (inclusive)
+\d             Perl character class
+[:foo:]        ASCII character class foo
+\p{Foo}        Unicode character class Foo
+\pF            Unicode character class F (one-letter name)
+

Named character classes as character class elements:

+
[\d]           digits (== \d)
+[^\d]          not digits (== \D)
+[\D]           not digits (== \D)
+[^\D]          not not digits (== \d)
+[[:name:]]     named ASCII class inside character class (== [:name:])
+[^[:name:]]    named ASCII class inside negated character class (== [:^name:])
+[\p{Name}]     named Unicode property inside character class (== \p{Name})
+[^\p{Name}]    named Unicode property inside negated character class (== \P{Name})
+

Perl character classes (all ASCII-only):

+
\d             digits (== [0-9])
+\D             not digits (== [^0-9])
+\s             whitespace (== [\t\n\f\r ])
+\S             not whitespace (== [^\t\n\f\r ])
+\w             word characters (== [0-9A-Za-z_])
+\W             not word characters (== [^0-9A-Za-z_])
+

ASCII character classes:

+
[[:alnum:]]    alphanumeric (== [0-9A-Za-z])
+[[:alpha:]]    alphabetic (== [A-Za-z])
+[[:ascii:]]    ASCII (== [\x00-\x7F])
+[[:blank:]]    blank (== [\t ])
+[[:cntrl:]]    control (== [\x00-\x1F\x7F])
+[[:digit:]]    digits (== [0-9])
+[[:graph:]]    graphical (== [!-~] == [A-Za-z0-9!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])
+[[:lower:]]    lower case (== [a-z])
+[[:print:]]    printable (== [ -~] == [ [:graph:]])
+[[:punct:]]    punctuation (== [!-/:-@[-`{-~])
+[[:space:]]    whitespace (== [\t\n\v\f\r ])
+[[:upper:]]    upper case (== [A-Z])
+[[:word:]]     word characters (== [0-9A-Za-z_])
+[[:xdigit:]]   hex digit (== [0-9A-Fa-f])
+

Unicode character classes are those in unicode.Categories and unicode.Scripts.

Index

Package files

compile.go doc.go op_string.go parse.go perl_groups.go prog.go regexp.go simplify.go

func IsWordChar

func IsWordChar(r rune) bool

IsWordChar reports whether r is considered a “word character” during the evaluation of the \b and \B zero-width assertions. These assertions are ASCII-only: the word characters are [A-Za-z0-9_].

+

type EmptyOp

An EmptyOp specifies a kind or mixture of zero-width assertions.

+
type EmptyOp uint8
const (
+    EmptyBeginLine EmptyOp = 1 << iota
+    EmptyEndLine
+    EmptyBeginText
+    EmptyEndText
+    EmptyWordBoundary
+    EmptyNoWordBoundary
+)

func EmptyOpContext

func EmptyOpContext(r1, r2 rune) EmptyOp

EmptyOpContext returns the zero-width assertions satisfied at the position between the runes r1 and r2. Passing r1 == -1 indicates that the position is at the beginning of the text. Passing r2 == -1 indicates that the position is at the end of the text.

+

type Error

An Error describes a failure to parse a regular expression and gives the offending expression.

+
type Error struct {
+    Code ErrorCode
+    Expr string
+}
+

func (*Error) Error

func (e *Error) Error() string

type ErrorCode

An ErrorCode describes a failure to parse a regular expression.

+
type ErrorCode string
const (
+    // Unexpected error
+    ErrInternalError ErrorCode = "regexp/syntax: internal error"
+
+    // Parse errors
+    ErrInvalidCharClass      ErrorCode = "invalid character class"
+    ErrInvalidCharRange      ErrorCode = "invalid character class range"
+    ErrInvalidEscape         ErrorCode = "invalid escape sequence"
+    ErrInvalidNamedCapture   ErrorCode = "invalid named capture"
+    ErrInvalidPerlOp         ErrorCode = "invalid or unsupported Perl syntax"
+    ErrInvalidRepeatOp       ErrorCode = "invalid nested repetition operator"
+    ErrInvalidRepeatSize     ErrorCode = "invalid repeat count"
+    ErrInvalidUTF8           ErrorCode = "invalid UTF-8"
+    ErrMissingBracket        ErrorCode = "missing closing ]"
+    ErrMissingParen          ErrorCode = "missing closing )"
+    ErrMissingRepeatArgument ErrorCode = "missing argument to repetition operator"
+    ErrTrailingBackslash     ErrorCode = "trailing backslash at end of expression"
+    ErrUnexpectedParen       ErrorCode = "unexpected )"
+    ErrNestingDepth          ErrorCode = "expression nests too deeply"
+    ErrLarge                 ErrorCode = "expression too large"
+)

func (ErrorCode) String

func (e ErrorCode) String() string

type Flags

Flags control the behavior of the parser and record information about regexp context.

+
type Flags uint16
const (
+    FoldCase      Flags = 1 << iota // case-insensitive match
+    Literal                         // treat pattern as literal string
+    ClassNL                         // allow character classes like [^a-z] and [[:space:]] to match newline
+    DotNL                           // allow . to match newline
+    OneLine                         // treat ^ and $ as only matching at beginning and end of text
+    NonGreedy                       // make repetition operators default to non-greedy
+    PerlX                           // allow Perl extensions
+    UnicodeGroups                   // allow \p{Han}, \P{Han} for Unicode group and negation
+    WasDollar                       // regexp OpEndText was $, not \z
+    Simple                          // regexp contains no counted repetition
+
+    MatchNL = ClassNL | DotNL
+
+    Perl        = ClassNL | OneLine | PerlX | UnicodeGroups // as close to Perl as possible
+    POSIX Flags = 0                                         // POSIX syntax
+)

type Inst

An Inst is a single instruction in a regular expression program.

+
type Inst struct {
+    Op   InstOp
+    Out  uint32 // all but InstMatch, InstFail
+    Arg  uint32 // InstAlt, InstAltMatch, InstCapture, InstEmptyWidth
+    Rune []rune
+}
+

func (*Inst) MatchEmptyWidth

func (i *Inst) MatchEmptyWidth(before rune, after rune) bool

MatchEmptyWidth reports whether the instruction matches an empty string between the runes before and after. It should only be called when i.Op == InstEmptyWidth.

+

func (*Inst) MatchRune

func (i *Inst) MatchRune(r rune) bool

MatchRune reports whether the instruction matches (and consumes) r. It should only be called when i.Op == InstRune.

+

func (*Inst) MatchRunePos 1.3

func (i *Inst) MatchRunePos(r rune) int

MatchRunePos checks whether the instruction matches (and consumes) r. If so, MatchRunePos returns the index of the matching rune pair (or, when len(i.Rune) == 1, rune singleton). If not, MatchRunePos returns -1. MatchRunePos should only be called when i.Op == InstRune.

+

func (*Inst) String

func (i *Inst) String() string

type InstOp

An InstOp is an instruction opcode.

+
type InstOp uint8
const (
+    InstAlt InstOp = iota
+    InstAltMatch
+    InstCapture
+    InstEmptyWidth
+    InstMatch
+    InstFail
+    InstNop
+    InstRune
+    InstRune1
+    InstRuneAny
+    InstRuneAnyNotNL
+)

func (InstOp) String 1.3

func (i InstOp) String() string

type Op

An Op is a single regular expression operator.

+
type Op uint8
const (
+    OpNoMatch        Op = 1 + iota // matches no strings
+    OpEmptyMatch                   // matches empty string
+    OpLiteral                      // matches Runes sequence
+    OpCharClass                    // matches Runes interpreted as range pair list
+    OpAnyCharNotNL                 // matches any character except newline
+    OpAnyChar                      // matches any character
+    OpBeginLine                    // matches empty string at beginning of line
+    OpEndLine                      // matches empty string at end of line
+    OpBeginText                    // matches empty string at beginning of text
+    OpEndText                      // matches empty string at end of text
+    OpWordBoundary                 // matches word boundary `\b`
+    OpNoWordBoundary               // matches word non-boundary `\B`
+    OpCapture                      // capturing subexpression with index Cap, optional name Name
+    OpStar                         // matches Sub[0] zero or more times
+    OpPlus                         // matches Sub[0] one or more times
+    OpQuest                        // matches Sub[0] zero or one times
+    OpRepeat                       // matches Sub[0] at least Min times, at most Max (Max == -1 is no limit)
+    OpConcat                       // matches concatenation of Subs
+    OpAlternate                    // matches alternation of Subs
+)

func (Op) String 1.11

func (i Op) String() string

type Prog

A Prog is a compiled regular expression program.

+
type Prog struct {
+    Inst   []Inst
+    Start  int // index of start instruction
+    NumCap int // number of InstCapture insts in re
+}
+

func Compile

func Compile(re *Regexp) (*Prog, error)

Compile compiles the regexp into a program to be executed. The regexp should have been simplified already (returned from re.Simplify).

+

func (*Prog) Prefix

func (p *Prog) Prefix() (prefix string, complete bool)

Prefix returns a literal string that all matches for the regexp must start with. Complete is true if the prefix is the entire match.

+

func (*Prog) StartCond

func (p *Prog) StartCond() EmptyOp

StartCond returns the leading empty-width conditions that must be true in any match. It returns ^EmptyOp(0) if no matches are possible.

+

func (*Prog) String

func (p *Prog) String() string

type Regexp

A Regexp is a node in a regular expression syntax tree.

+
type Regexp struct {
+    Op       Op // operator
+    Flags    Flags
+    Sub      []*Regexp  // subexpressions, if any
+    Sub0     [1]*Regexp // storage for short Sub
+    Rune     []rune     // matched runes, for OpLiteral, OpCharClass
+    Rune0    [2]rune    // storage for short Rune
+    Min, Max int        // min, max for OpRepeat
+    Cap      int        // capturing index, for OpCapture
+    Name     string     // capturing name, for OpCapture
+}
+

func Parse

func Parse(s string, flags Flags) (*Regexp, error)

Parse parses a regular expression string s, controlled by the specified Flags, and returns a regular expression parse tree. The syntax is described in the top-level comment.

+

func (*Regexp) CapNames

func (re *Regexp) CapNames() []string

CapNames walks the regexp to find the names of capturing groups.

+

func (*Regexp) Equal

func (x *Regexp) Equal(y *Regexp) bool

Equal reports whether x and y have identical structure.

+

func (*Regexp) MaxCap

func (re *Regexp) MaxCap() int

MaxCap walks the regexp to find the maximum capture index.

+

func (*Regexp) Simplify

func (re *Regexp) Simplify() *Regexp

Simplify returns a regexp equivalent to re but without counted repetitions and with various other simplifications, such as rewriting /(?:a+)+/ to /a+/. The resulting regexp will execute correctly but its string representation will not produce the same parse tree, because capturing parentheses may have been duplicated or removed. For example, the simplified form for /(x){1,2}/ is /(x)(x)?/ but both parentheses capture as $1. The returned regexp may share structure with or be the original.

+

func (*Regexp) String

func (re *Regexp) String() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/regexp/syntax/ +

+
diff --git a/devdocs/go/runtime%2Fasan%2Findex.html b/devdocs/go/runtime%2Fasan%2Findex.html new file mode 100644 index 00000000..01d57008 --- /dev/null +++ b/devdocs/go/runtime%2Fasan%2Findex.html @@ -0,0 +1,6 @@ +

Command asan

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/runtime/asan/ +

+
diff --git a/devdocs/go/runtime%2Fcgo%2Findex.html b/devdocs/go/runtime%2Fcgo%2Findex.html new file mode 100644 index 00000000..1f504a91 --- /dev/null +++ b/devdocs/go/runtime%2Fcgo%2Findex.html @@ -0,0 +1,96 @@ +

Package cgo

Overview

Package cgo contains runtime support for code generated by the cgo tool. See the documentation for the cgo command for details on using cgo.

Index

Package files

callbacks.go callbacks_traceback.go cgo.go handle.go iscgo.go linux.go mmap.go setenv.go sigaction.go

type Handle

Handle provides a way to pass values that contain Go pointers (pointers to memory allocated by Go) between Go and C without breaking the cgo pointer passing rules. A Handle is an integer value that can represent any Go value. A Handle can be passed through C and back to Go, and Go code can use the Handle to retrieve the original Go value.

+

The underlying type of Handle is guaranteed to fit in an integer type that is large enough to hold the bit pattern of any pointer. The zero value of a Handle is not valid, and thus is safe to use as a sentinel in C APIs.

+

For instance, on the Go side:

+
package main
+
+/*
+#include <stdint.h> // for uintptr_t
+
+extern void MyGoPrint(uintptr_t handle);
+void myprint(uintptr_t handle);
+*/
+import "C"
+import "runtime/cgo"
+
+//export MyGoPrint
+func MyGoPrint(handle C.uintptr_t) {
+	h := cgo.Handle(handle)
+	val := h.Value().(string)
+	println(val)
+	h.Delete()
+}
+
+func main() {
+	val := "hello Go"
+	C.myprint(C.uintptr_t(cgo.NewHandle(val)))
+	// Output: hello Go
+}
+

and on the C side:

+
#include <stdint.h> // for uintptr_t
+
+// A Go function
+extern void MyGoPrint(uintptr_t handle);
+
+// A C function
+void myprint(uintptr_t handle) {
+    MyGoPrint(handle);
+}
+

Some C functions accept a void* argument that points to an arbitrary data value supplied by the caller. It is not safe to coerce a cgo.Handle (an integer) to a Go unsafe.Pointer, but instead we can pass the address of the cgo.Handle to the void* parameter, as in this variant of the previous example:

+
package main
+
+/*
+extern void MyGoPrint(void *context);
+static inline void myprint(void *context) {
+    MyGoPrint(context);
+}
+*/
+import "C"
+import (
+	"runtime/cgo"
+	"unsafe"
+)
+
+//export MyGoPrint
+func MyGoPrint(context unsafe.Pointer) {
+	h := *(*cgo.Handle)(context)
+	val := h.Value().(string)
+	println(val)
+	h.Delete()
+}
+
+func main() {
+	val := "hello Go"
+	h := cgo.NewHandle(val)
+	C.myprint(unsafe.Pointer(&h))
+	// Output: hello Go
+}
+
type Handle uintptr

func NewHandle

func NewHandle(v any) Handle

NewHandle returns a handle for a given value.

+

The handle is valid until the program calls Delete on it. The handle uses resources, and this package assumes that C code may hold on to the handle, so a program must explicitly call Delete when the handle is no longer needed.

+

The intended use is to pass the returned handle to C code, which passes it back to Go, which calls Value.

+

func (Handle) Delete

func (h Handle) Delete()

Delete invalidates a handle. This method should only be called once the program no longer needs to pass the handle to C and the C code no longer has a copy of the handle value.

+

The method panics if the handle is invalid.

+

func (Handle) Value

func (h Handle) Value() any

Value returns the associated Go value for a valid handle.

+

The method panics if the handle is invalid.

+

type Incomplete

Incomplete is used specifically for the semantics of incomplete C types.

+
type Incomplete struct {
+    // contains filtered or unexported fields
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/runtime/cgo/ +

+
diff --git a/devdocs/go/runtime%2Fcoverage%2Findex.html b/devdocs/go/runtime%2Fcoverage%2Findex.html new file mode 100644 index 00000000..f62b083b --- /dev/null +++ b/devdocs/go/runtime%2Fcoverage%2Findex.html @@ -0,0 +1,20 @@ +

Package coverage

Overview

Index

Package files

apis.go emit.go hooks.go testsupport.go

func ClearCounters 1.20

func ClearCounters() error

ClearCounters clears/resets all coverage counter variables in the currently running program. It returns an error if the program in question was not built with the "-cover" flag. Clearing of coverage counters is also not supported for programs not using atomic counter mode (see more detailed comments below for the rationale here).

+

func WriteCounters 1.20

func WriteCounters(w io.Writer) error

WriteCounters writes coverage counter-data content for the currently running program to the writer 'w'. An error will be returned if the operation can't be completed successfully (for example, if the currently running program was not built with "-cover", or if a write fails). The counter data written will be a snapshot taken at the point of the invocation.

+

func WriteCountersDir 1.20

func WriteCountersDir(dir string) error

WriteCountersDir writes a coverage counter-data file for the currently running program to the directory specified in 'dir'. An error will be returned if the operation can't be completed successfully (for example, if the currently running program was not built with "-cover", or if the directory does not exist). The counter data written will be a snapshot taken at the point of the call.

+

func WriteMeta 1.20

func WriteMeta(w io.Writer) error

WriteMeta writes the meta-data content (the payload that would normally be emitted to a meta-data file) for the currently running program to the writer 'w'. An error will be returned if the operation can't be completed successfully (for example, if the currently running program was not built with "-cover", or if a write fails).

+

func WriteMetaDir 1.20

func WriteMetaDir(dir string) error

WriteMetaDir writes a coverage meta-data file for the currently running program to the directory specified in 'dir'. An error will be returned if the operation can't be completed successfully (for example, if the currently running program was not built with "-cover", or if the directory does not exist).

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/runtime/coverage/ +

+
diff --git a/devdocs/go/runtime%2Fdebug%2Findex.html b/devdocs/go/runtime%2Fdebug%2Findex.html new file mode 100644 index 00000000..1b21523b --- /dev/null +++ b/devdocs/go/runtime%2Fdebug%2Findex.html @@ -0,0 +1,120 @@ +

Package debug

Overview

Package debug contains facilities for programs to debug themselves while they are running.

Index

Package files

garbage.go mod.go stack.go stubs.go

func FreeOSMemory 1.1

func FreeOSMemory()

FreeOSMemory forces a garbage collection followed by an attempt to return as much memory to the operating system as possible. (Even if this is not called, the runtime gradually returns memory to the operating system in a background task.)

+

func PrintStack

func PrintStack()

PrintStack prints to standard error the stack trace returned by runtime.Stack.

+

func ReadGCStats 1.1

func ReadGCStats(stats *GCStats)

ReadGCStats reads statistics about garbage collection into stats. The number of entries in the pause history is system-dependent; stats.Pause slice will be reused if large enough, reallocated otherwise. ReadGCStats may use the full capacity of the stats.Pause slice. If stats.PauseQuantiles is non-empty, ReadGCStats fills it with quantiles summarizing the distribution of pause time. For example, if len(stats.PauseQuantiles) is 5, it will be filled with the minimum, 25%, 50%, 75%, and maximum pause times.

+

func SetGCPercent 1.1

func SetGCPercent(percent int) int

SetGCPercent sets the garbage collection target percentage: a collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. SetGCPercent returns the previous setting. The initial setting is the value of the GOGC environment variable at startup, or 100 if the variable is not set. This setting may be effectively reduced in order to maintain a memory limit. A negative percentage effectively disables garbage collection, unless the memory limit is reached. See SetMemoryLimit for more details.

+

func SetMaxStack 1.2

func SetMaxStack(bytes int) int

SetMaxStack sets the maximum amount of memory that can be used by a single goroutine stack. If any goroutine exceeds this limit while growing its stack, the program crashes. SetMaxStack returns the previous setting. The initial setting is 1 GB on 64-bit systems, 250 MB on 32-bit systems. There may be a system-imposed maximum stack limit regardless of the value provided to SetMaxStack.

+

SetMaxStack is useful mainly for limiting the damage done by goroutines that enter an infinite recursion. It only limits future stack growth.

+

func SetMaxThreads 1.2

func SetMaxThreads(threads int) int

SetMaxThreads sets the maximum number of operating system threads that the Go program can use. If it attempts to use more than this many, the program crashes. SetMaxThreads returns the previous setting. The initial setting is 10,000 threads.

+

The limit controls the number of operating system threads, not the number of goroutines. A Go program creates a new thread only when a goroutine is ready to run but all the existing threads are blocked in system calls, cgo calls, or are locked to other goroutines due to use of runtime.LockOSThread.

+

SetMaxThreads is useful mainly for limiting the damage done by programs that create an unbounded number of threads. The idea is to take down the program before it takes down the operating system.

+

func SetMemoryLimit 1.19

func SetMemoryLimit(limit int64) int64

SetMemoryLimit provides the runtime with a soft memory limit.

+

The runtime undertakes several processes to try to respect this memory limit, including adjustments to the frequency of garbage collections and returning memory to the underlying system more aggressively. This limit will be respected even if GOGC=off (or, if SetGCPercent(-1) is executed).

+

The input limit is provided as bytes, and includes all memory mapped, managed, and not released by the Go runtime. Notably, it does not account for space used by the Go binary and memory external to Go, such as memory managed by the underlying system on behalf of the process, or memory managed by non-Go code inside the same process. Examples of excluded memory sources include: OS kernel memory held on behalf of the process, memory allocated by C code, and memory mapped by syscall.Mmap (because it is not managed by the Go runtime).

+

More specifically, the following expression accurately reflects the value the runtime attempts to maintain as the limit:

+
runtime.MemStats.Sys - runtime.MemStats.HeapReleased
+

or in terms of the runtime/metrics package:

+
/memory/classes/total:bytes - /memory/classes/heap/released:bytes
+

A zero limit or a limit that's lower than the amount of memory used by the Go runtime may cause the garbage collector to run nearly continuously. However, the application may still make progress.

+

The memory limit is always respected by the Go runtime, so to effectively disable this behavior, set the limit very high. math.MaxInt64 is the canonical value for disabling the limit, but values much greater than the available memory on the underlying system work just as well.

+

See https://go.dev/doc/gc-guide for a detailed guide explaining the soft memory limit in more detail, as well as a variety of common use-cases and scenarios.

+

The initial setting is math.MaxInt64 unless the GOMEMLIMIT environment variable is set, in which case it provides the initial setting. GOMEMLIMIT is a numeric value in bytes with an optional unit suffix. The supported suffixes include B, KiB, MiB, GiB, and TiB. These suffixes represent quantities of bytes as defined by the IEC 80000-13 standard. That is, they are based on powers of two: KiB means 2^10 bytes, MiB means 2^20 bytes, and so on.

+

SetMemoryLimit returns the previously set memory limit. A negative input does not adjust the limit, and allows for retrieval of the currently set memory limit.

+

func SetPanicOnFault 1.3

func SetPanicOnFault(enabled bool) bool

SetPanicOnFault controls the runtime's behavior when a program faults at an unexpected (non-nil) address. Such faults are typically caused by bugs such as runtime memory corruption, so the default response is to crash the program. Programs working with memory-mapped files or unsafe manipulation of memory may cause faults at non-nil addresses in less dramatic situations; SetPanicOnFault allows such programs to request that the runtime trigger only a panic, not a crash. The runtime.Error that the runtime panics with may have an additional method:

+
Addr() uintptr
+

If that method exists, it returns the memory address which triggered the fault. The results of Addr are best-effort and the veracity of the result may depend on the platform. SetPanicOnFault applies only to the current goroutine. It returns the previous setting.

+

func SetTraceback 1.6

func SetTraceback(level string)

SetTraceback sets the amount of detail printed by the runtime in the traceback it prints before exiting due to an unrecovered panic or an internal runtime error. The level argument takes the same values as the GOTRACEBACK environment variable. For example, SetTraceback("all") ensure that the program prints all goroutines when it crashes. See the package runtime documentation for details. If SetTraceback is called with a level lower than that of the environment variable, the call is ignored.

+

func Stack

func Stack() []byte

Stack returns a formatted stack trace of the goroutine that calls it. It calls runtime.Stack with a large enough buffer to capture the entire trace.

+

func WriteHeapDump 1.3

func WriteHeapDump(fd uintptr)

WriteHeapDump writes a description of the heap and the objects in it to the given file descriptor.

+

WriteHeapDump suspends the execution of all goroutines until the heap dump is completely written. Thus, the file descriptor must not be connected to a pipe or socket whose other end is in the same Go process; instead, use a temporary file or network socket.

+

The heap dump format is defined at https://golang.org/s/go15heapdump.

+

type BuildInfo 1.12

BuildInfo represents the build information read from a Go binary.

+
type BuildInfo struct {
+    // GoVersion is the version of the Go toolchain that built the binary
+    // (for example, "go1.19.2").
+    GoVersion string // Go 1.18
+
+    // Path is the package path of the main package for the binary
+    // (for example, "golang.org/x/tools/cmd/stringer").
+    Path string
+
+    // Main describes the module that contains the main package for the binary.
+    Main Module
+
+    // Deps describes all the dependency modules, both direct and indirect,
+    // that contributed packages to the build of this binary.
+    Deps []*Module
+
+    // Settings describes the build settings used to build the binary.
+    Settings []BuildSetting // Go 1.18
+}
+

func ParseBuildInfo 1.18

func ParseBuildInfo(data string) (bi *BuildInfo, err error)

func ReadBuildInfo 1.12

func ReadBuildInfo() (info *BuildInfo, ok bool)

ReadBuildInfo returns the build information embedded in the running binary. The information is available only in binaries built with module support.

+

func (*BuildInfo) String 1.18

func (bi *BuildInfo) String() string

type BuildSetting 1.18

A BuildSetting is a key-value pair describing one setting that influenced a build.

+

Defined keys include:

+
type BuildSetting struct {
+    // Key and Value describe the build setting.
+    // Key must not contain an equals sign, space, tab, or newline.
+    // Value must not contain newlines ('\n').
+    Key, Value string
+}
+

type GCStats 1.1

GCStats collect information about recent garbage collections.

+
type GCStats struct {
+    LastGC         time.Time       // time of last collection
+    NumGC          int64           // number of garbage collections
+    PauseTotal     time.Duration   // total pause for all collections
+    Pause          []time.Duration // pause history, most recent first
+    PauseEnd       []time.Time     // pause end times history, most recent first; added in Go 1.4
+    PauseQuantiles []time.Duration
+}
+

type Module 1.12

A Module describes a single module included in a build.

+
type Module struct {
+    Path    string  // module path
+    Version string  // module version
+    Sum     string  // checksum
+    Replace *Module // replaced by this module
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/runtime/debug/ +

+
diff --git a/devdocs/go/runtime%2Findex.html b/devdocs/go/runtime%2Findex.html new file mode 100644 index 00000000..cab9d5b8 --- /dev/null +++ b/devdocs/go/runtime%2Findex.html @@ -0,0 +1,810 @@ +

Package runtime

Overview

Package runtime contains operations that interact with Go's runtime system, such as functions to control goroutines. It also includes the low-level type information used by the reflect package; see reflect's documentation for the programmable interface to the run-time type system.

+

Environment Variables

The following environment variables ($name or %name%, depending on the host operating system) control the run-time behavior of Go programs. The meanings and use may change from release to release.

+

The GOGC variable sets the initial garbage collection target percentage. A collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. The default is GOGC=100. Setting GOGC=off disables the garbage collector entirely. runtime/debug.SetGCPercent allows changing this percentage at run time.

+

The GOMEMLIMIT variable sets a soft memory limit for the runtime. This memory limit includes the Go heap and all other memory managed by the runtime, and excludes external memory sources such as mappings of the binary itself, memory managed in other languages, and memory held by the operating system on behalf of the Go program. GOMEMLIMIT is a numeric value in bytes with an optional unit suffix. The supported suffixes include B, KiB, MiB, GiB, and TiB. These suffixes represent quantities of bytes as defined by the IEC 80000-13 standard. That is, they are based on powers of two: KiB means 2^10 bytes, MiB means 2^20 bytes, and so on. The default setting is math.MaxInt64, which effectively disables the memory limit. runtime/debug.SetMemoryLimit allows changing this limit at run time.

+

The GODEBUG variable controls debugging variables within the runtime. It is a comma-separated list of name=val pairs setting these named variables:

+
allocfreetrace: setting allocfreetrace=1 causes every allocation to be
+profiled and a stack trace printed on each object's allocation and free.
+
+clobberfree: setting clobberfree=1 causes the garbage collector to
+clobber the memory content of an object with bad content when it frees
+the object.
+
+cpu.*: cpu.all=off disables the use of all optional instruction set extensions.
+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
+as listed in internal/cpu package. As an example cpu.avx=off disables runtime detection
+and thereby use of AVX instructions.
+
+cgocheck: setting cgocheck=0 disables all checks for packages
+using cgo to incorrectly pass Go pointers to non-Go code.
+Setting cgocheck=1 (the default) enables relatively cheap
+checks that may miss some errors. A more complete, but slow,
+cgocheck mode can be enabled using GOEXPERIMENT (which
+requires a rebuild), see https://pkg.go.dev/internal/goexperiment for details.
+
+disablethp: setting disablethp=1 on Linux disables transparent huge pages for the heap.
+It has no effect on other platforms. disablethp is meant for compatibility with versions
+of Go before 1.21, which stopped working around a Linux kernel default that can result
+in significant memory overuse. See https://go.dev/issue/64332. This setting will be
+removed in a future release, so operators should tweak their Linux configuration to suit
+their needs before then. See https://go.dev/doc/gc-guide#Linux_transparent_huge_pages.
+
+dontfreezetheworld: by default, the start of a fatal panic or throw
+"freezes the world", preempting all threads to stop all running
+goroutines, which makes it possible to traceback all goroutines, and
+keeps their state close to the point of panic. Setting
+dontfreezetheworld=1 disables this preemption, allowing goroutines to
+continue executing during panic processing. Note that goroutines that
+naturally enter the scheduler will still stop. This can be useful when
+debugging the runtime scheduler, as freezetheworld perturbs scheduler
+state and thus may hide problems.
+
+efence: setting efence=1 causes the allocator to run in a mode
+where each object is allocated on a unique page and addresses are
+never recycled.
+
+gccheckmark: setting gccheckmark=1 enables verification of the
+garbage collector's concurrent mark phase by performing a
+second mark pass while the world is stopped.  If the second
+pass finds a reachable object that was not found by concurrent
+mark, the garbage collector will panic.
+
+gcpacertrace: setting gcpacertrace=1 causes the garbage collector to
+print information about the internal state of the concurrent pacer.
+
+gcshrinkstackoff: setting gcshrinkstackoff=1 disables moving goroutines
+onto smaller stacks. In this mode, a goroutine's stack can only grow.
+
+gcstoptheworld: setting gcstoptheworld=1 disables concurrent garbage collection,
+making every garbage collection a stop-the-world event. Setting gcstoptheworld=2
+also disables concurrent sweeping after the garbage collection finishes.
+
+gctrace: setting gctrace=1 causes the garbage collector to emit a single line to standard
+error at each collection, summarizing the amount of memory collected and the
+length of the pause. The format of this line is subject to change. Included in
+the explanation below is also the relevant runtime/metrics metric for each field.
+Currently, it is:
+	gc # @#s #%: #+#+# ms clock, #+#/#/#+# ms cpu, #->#-># MB, # MB goal, # MB stacks, #MB globals, # P
+where the fields are as follows:
+	gc #         the GC number, incremented at each GC
+	@#s          time in seconds since program start
+	#%           percentage of time spent in GC since program start
+	#+...+#      wall-clock/CPU times for the phases of the GC
+	#->#-># MB   heap size at GC start, at GC end, and live heap, or /gc/scan/heap:bytes
+	# MB goal    goal heap size, or /gc/heap/goal:bytes
+	# MB stacks  estimated scannable stack size, or /gc/scan/stack:bytes
+	# MB globals scannable global size, or /gc/scan/globals:bytes
+	# P          number of processors used, or /sched/gomaxprocs:threads
+The phases are stop-the-world (STW) sweep termination, concurrent
+mark and scan, and STW mark termination. The CPU times
+for mark/scan are broken down in to assist time (GC performed in
+line with allocation), background GC time, and idle GC time.
+If the line ends with "(forced)", this GC was forced by a
+runtime.GC() call.
+
+harddecommit: setting harddecommit=1 causes memory that is returned to the OS to
+also have protections removed on it. This is the only mode of operation on Windows,
+but is helpful in debugging scavenger-related issues on other platforms. Currently,
+only supported on Linux.
+
+inittrace: setting inittrace=1 causes the runtime to emit a single line to standard
+error for each package with init work, summarizing the execution time and memory
+allocation. No information is printed for inits executed as part of plugin loading
+and for packages without both user defined and compiler generated init work.
+The format of this line is subject to change. Currently, it is:
+	init # @#ms, # ms clock, # bytes, # allocs
+where the fields are as follows:
+	init #      the package name
+	@# ms       time in milliseconds when the init started since program start
+	# clock     wall-clock time for package initialization work
+	# bytes     memory allocated on the heap
+	# allocs    number of heap allocations
+
+madvdontneed: setting madvdontneed=0 will use MADV_FREE
+instead of MADV_DONTNEED on Linux when returning memory to the
+kernel. This is more efficient, but means RSS numbers will
+drop only when the OS is under memory pressure. On the BSDs and
+Illumos/Solaris, setting madvdontneed=1 will use MADV_DONTNEED instead
+of MADV_FREE. This is less efficient, but causes RSS numbers to drop
+more quickly.
+
+memprofilerate: setting memprofilerate=X will update the value of runtime.MemProfileRate.
+When set to 0 memory profiling is disabled.  Refer to the description of
+MemProfileRate for the default value.
+
+pagetrace: setting pagetrace=/path/to/file will write out a trace of page events
+that can be viewed, analyzed, and visualized using the x/debug/cmd/pagetrace tool.
+Build your program with GOEXPERIMENT=pagetrace to enable this functionality. Do not
+enable this functionality if your program is a setuid binary as it introduces a security
+risk in that scenario. Currently not supported on Windows, plan9 or js/wasm. Setting this
+option for some applications can produce large traces, so use with care.
+
+panicnil: setting panicnil=1 disables the runtime error when calling panic with nil
+interface value or an untyped nil.
+
+runtimecontentionstacks: setting runtimecontentionstacks=1 enables inclusion of call stacks
+related to contention on runtime-internal locks in the "mutex" profile, subject to the
+MutexProfileFraction setting. When runtimecontentionstacks=0, contention on
+runtime-internal locks will report as "runtime._LostContendedRuntimeLock". When
+runtimecontentionstacks=1, the call stacks will correspond to the unlock call that released
+the lock. But instead of the value corresponding to the amount of contention that call
+stack caused, it corresponds to the amount of time the caller of unlock had to wait in its
+original call to lock. A future release is expected to align those and remove this setting.
+
+invalidptr: invalidptr=1 (the default) causes the garbage collector and stack
+copier to crash the program if an invalid pointer value (for example, 1)
+is found in a pointer-typed location. Setting invalidptr=0 disables this check.
+This should only be used as a temporary workaround to diagnose buggy code.
+The real fix is to not store integers in pointer-typed locations.
+
+sbrk: setting sbrk=1 replaces the memory allocator and garbage collector
+with a trivial allocator that obtains memory from the operating system and
+never reclaims any memory.
+
+scavtrace: setting scavtrace=1 causes the runtime to emit a single line to standard
+error, roughly once per GC cycle, summarizing the amount of work done by the
+scavenger as well as the total amount of memory returned to the operating system
+and an estimate of physical memory utilization. The format of this line is subject
+to change, but currently it is:
+	scav # KiB work (bg), # KiB work (eager), # KiB total, #% util
+where the fields are as follows:
+	# KiB work (bg)    the amount of memory returned to the OS in the background since
+	                   the last line
+	# KiB work (eager) the amount of memory returned to the OS eagerly since the last line
+	# KiB now          the amount of address space currently returned to the OS
+	#% util            the fraction of all unscavenged heap memory which is in-use
+If the line ends with "(forced)", then scavenging was forced by a
+debug.FreeOSMemory() call.
+
+scheddetail: setting schedtrace=X and scheddetail=1 causes the scheduler to emit
+detailed multiline info every X milliseconds, describing state of the scheduler,
+processors, threads and goroutines.
+
+schedtrace: setting schedtrace=X causes the scheduler to emit a single line to standard
+error every X milliseconds, summarizing the scheduler state.
+
+tracebackancestors: setting tracebackancestors=N extends tracebacks with the stacks at
+which goroutines were created, where N limits the number of ancestor goroutines to
+report. This also extends the information returned by runtime.Stack. Ancestor's goroutine
+IDs will refer to the ID of the goroutine at the time of creation; it's possible for this
+ID to be reused for another goroutine. Setting N to 0 will report no ancestry information.
+
+tracefpunwindoff: setting tracefpunwindoff=1 forces the execution tracer to
+use the runtime's default stack unwinder instead of frame pointer unwinding.
+This increases tracer overhead, but could be helpful as a workaround or for
+debugging unexpected regressions caused by frame pointer unwinding.
+
+traceadvanceperiod: the approximate period in nanoseconds between trace generations. Only
+applies if a program is built with GOEXPERIMENT=exectracer2. Used primarily for testing
+and debugging the execution tracer.
+
+asyncpreemptoff: asyncpreemptoff=1 disables signal-based
+asynchronous goroutine preemption. This makes some loops
+non-preemptible for long periods, which may delay GC and
+goroutine scheduling. This is useful for debugging GC issues
+because it also disables the conservative stack scanning used
+for asynchronously preempted goroutines.
+

The net and net/http packages also refer to debugging variables in GODEBUG. See the documentation for those packages for details.

+

The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously. There is no limit to the number of threads that can be blocked in system calls on behalf of Go code; those do not count against the GOMAXPROCS limit. This package's GOMAXPROCS function queries and changes the limit.

+

The GORACE variable configures the race detector, for programs built using -race. See the Race Detector article for details.

+

The GOTRACEBACK variable controls the amount of output generated when a Go program fails due to an unrecovered panic or an unexpected runtime condition. By default, a failure prints a stack trace for the current goroutine, eliding functions internal to the run-time system, and then exits with exit code 2. The failure prints stack traces for all goroutines if there is no current goroutine or the failure is internal to the run-time. GOTRACEBACK=none omits the goroutine stack traces entirely. GOTRACEBACK=single (the default) behaves as described above. GOTRACEBACK=all adds stack traces for all user-created goroutines. GOTRACEBACK=system is like “all” but adds stack frames for run-time functions and shows goroutines created internally by the run-time. GOTRACEBACK=crash is like “system” but crashes in an operating system-specific manner instead of exiting. For example, on Unix systems, the crash raises SIGABRT to trigger a core dump. GOTRACEBACK=wer is like “crash” but doesn't disable Windows Error Reporting (WER). For historical reasons, the GOTRACEBACK settings 0, 1, and 2 are synonyms for none, all, and system, respectively. The runtime/debug.SetTraceback function allows increasing the amount of output at run time, but it cannot reduce the amount below that specified by the environment variable.

+

The GOARCH, GOOS, GOPATH, and GOROOT environment variables complete the set of Go environment variables. They influence the building of Go programs (see cmd/go and go/build). GOARCH, GOOS, and GOROOT are recorded at compile time and made available by constants or functions in this package, but they do not influence the execution of the run-time system.

+

Security

On Unix platforms, Go's runtime system behaves slightly differently when a binary is setuid/setgid or executed with setuid/setgid-like properties, in order to prevent dangerous behaviors. On Linux this is determined by checking for the AT_SECURE flag in the auxiliary vector, on the BSDs and Solaris/Illumos it is determined by checking the issetugid syscall, and on AIX it is determined by checking if the uid/gid match the effective uid/gid.

+

When the runtime determines the binary is setuid/setgid-like, it does three main things:

+

Index

Examples

Frames

Package files

alg.go arena.go asan0.go atomic_pointer.go cgo.go cgo_mmap.go cgo_sigaction.go cgocall.go cgocallback.go cgocheck.go chan.go checkptr.go compiler.go complex.go coro.go covercounter.go covermeta.go cpuflags.go cpuflags_amd64.go cpuprof.go cputicks.go create_file_unix.go debug.go debugcall.go debuglog.go debuglog_off.go defs_linux_amd64.go env_posix.go error.go exithook.go extern.go fastlog2.go fastlog2table.go fds_unix.go float.go hash64.go heapdump.go histogram.go iface.go lfstack.go lock_futex.go lockrank.go lockrank_off.go malloc.go map.go map_fast32.go map_fast64.go map_faststr.go mbarrier.go mbitmap.go mbitmap_allocheaders.go mcache.go mcentral.go mcheckmark.go mem.go mem_linux.go metrics.go mfinal.go mfixalloc.go mgc.go mgclimit.go mgcmark.go mgcpacer.go mgcscavenge.go mgcstack.go mgcsweep.go mgcwork.go mheap.go minmax.go mpagealloc.go mpagealloc_64bit.go mpagecache.go mpallocbits.go mprof.go mranges.go msan0.go msize_allocheaders.go mspanset.go mstats.go mwbbuf.go nbpipe_pipe2.go netpoll.go netpoll_epoll.go nonwindows_stub.go os_linux.go os_linux_generic.go os_linux_noauxv.go os_linux_x86.go os_nonopenbsd.go os_unix.go pagetrace_off.go panic.go pinner.go plugin.go preempt.go preempt_nonwindows.go print.go proc.go profbuf.go proflabel.go race0.go rand.go rdebug.go retry.go runtime.go runtime1.go runtime2.go runtime_boring.go rwmutex.go security_linux.go security_unix.go select.go sema.go signal_amd64.go signal_linux_amd64.go signal_unix.go sigqueue.go sigqueue_note.go sigtab_linux_generic.go sizeclasses.go slice.go softfloat64.go stack.go stkframe.go string.go stubs.go stubs2.go stubs3.go stubs_amd64.go stubs_linux.go symtab.go symtabinl.go sys_nonppc64x.go sys_x86.go tagptr.go tagptr_64bit.go test_amd64.go time.go time_nofake.go timeasm.go tls_stub.go trace2.go trace2buf.go trace2cpu.go trace2event.go trace2map.go trace2region.go trace2runtime.go trace2stack.go trace2status.go trace2string.go trace2time.go traceback.go type.go typekind.go unsafe.go utf8.go vdso_elf64.go vdso_linux.go vdso_linux_amd64.go write_err.go

Constants

Compiler is the name of the compiler toolchain that built the running binary. Known toolchains are:

+
gc      Also known as cmd/compile.
+gccgo   The gccgo front end, part of the GCC compiler suite.
+
const Compiler = "gc"

GOARCH is the running program's architecture target: one of 386, amd64, arm, s390x, and so on.

+
const GOARCH string = goarch.GOARCH

GOOS is the running program's operating system target: one of darwin, freebsd, linux, and so on. To view possible combinations of GOOS and GOARCH, run "go tool dist list".

+
const GOOS string = goos.GOOS

Variables

MemProfileRate controls the fraction of memory allocations that are recorded and reported in the memory profile. The profiler aims to sample an average of one allocation per MemProfileRate bytes allocated.

+

To include every allocated block in the profile, set MemProfileRate to 1. To turn off profiling entirely, set MemProfileRate to 0.

+

The tools that process the memory profiles assume that the profile rate is constant across the lifetime of the program and equal to the current value. Programs that change the memory profiling rate should do so just once, as early as possible in the execution of the program (for example, at the beginning of main).

+
var MemProfileRate int = 512 * 1024

func BlockProfile 1.1

func BlockProfile(p []BlockProfileRecord) (n int, ok bool)

BlockProfile returns n, the number of records in the current blocking profile. If len(p) >= n, BlockProfile copies the profile into p and returns n, true. If len(p) < n, BlockProfile does not change p and returns n, false.

+

Most clients should use the runtime/pprof package or the testing package's -test.blockprofile flag instead of calling BlockProfile directly.

+

func Breakpoint

func Breakpoint()

Breakpoint executes a breakpoint trap.

+

func CPUProfile

func CPUProfile() []byte

CPUProfile panics. It formerly provided raw access to chunks of a pprof-format profile generated by the runtime. The details of generating that format have changed, so this functionality has been removed.

+

Deprecated: Use the runtime/pprof package, or the handlers in the net/http/pprof package, or the testing package's -test.cpuprofile flag instead.

+

func Caller

func Caller(skip int) (pc uintptr, file string, line int, ok bool)

Caller reports file and line number information about function invocations on the calling goroutine's stack. The argument skip is the number of stack frames to ascend, with 0 identifying the caller of Caller. (For historical reasons the meaning of skip differs between Caller and Callers.) The return values report the program counter, file name, and line number within the file of the corresponding call. The boolean ok is false if it was not possible to recover the information.

+

func Callers

func Callers(skip int, pc []uintptr) int

Callers fills the slice pc with the return program counters of function invocations on the calling goroutine's stack. The argument skip is the number of stack frames to skip before recording in pc, with 0 identifying the frame for Callers itself and 1 identifying the caller of Callers. It returns the number of entries written to pc.

+

To translate these PCs into symbolic information such as function names and line numbers, use CallersFrames. CallersFrames accounts for inlined functions and adjusts the return program counters into call program counters. Iterating over the returned slice of PCs directly is discouraged, as is using FuncForPC on any of the returned PCs, since these cannot account for inlining or return program counter adjustment.

+

func GC

func GC()

GC runs a garbage collection and blocks the caller until the garbage collection is complete. It may also block the entire program.

+

func GOMAXPROCS

func GOMAXPROCS(n int) int

GOMAXPROCS sets the maximum number of CPUs that can be executing simultaneously and returns the previous setting. It defaults to the value of runtime.NumCPU. If n < 1, it does not change the current setting. This call will go away when the scheduler improves.

+

func GOROOT

func GOROOT() string

GOROOT returns the root of the Go tree. It uses the GOROOT environment variable, if set at process start, or else the root used during the Go build.

+

func Goexit

func Goexit()

Goexit terminates the goroutine that calls it. No other goroutine is affected. Goexit runs all deferred calls before terminating the goroutine. Because Goexit is not a panic, any recover calls in those deferred functions will return nil.

+

Calling Goexit from the main goroutine terminates that goroutine without func main returning. Since func main has not returned, the program continues execution of other goroutines. If all other goroutines exit, the program crashes.

+

func GoroutineProfile

func GoroutineProfile(p []StackRecord) (n int, ok bool)

GoroutineProfile returns n, the number of records in the active goroutine stack profile. If len(p) >= n, GoroutineProfile copies the profile into p and returns n, true. If len(p) < n, GoroutineProfile does not change p and returns n, false.

+

Most clients should use the runtime/pprof package instead of calling GoroutineProfile directly.

+

func Gosched

func Gosched()

Gosched yields the processor, allowing other goroutines to run. It does not suspend the current goroutine, so execution resumes automatically.

+

func KeepAlive 1.7

func KeepAlive(x any)

KeepAlive marks its argument as currently reachable. This ensures that the object is not freed, and its finalizer is not run, before the point in the program where KeepAlive is called.

+

A very simplified example showing where KeepAlive is required:

+
type File struct { d int }
+d, err := syscall.Open("/file/path", syscall.O_RDONLY, 0)
+// ... do something if err != nil ...
+p := &File{d}
+runtime.SetFinalizer(p, func(p *File) { syscall.Close(p.d) })
+var buf [10]byte
+n, err := syscall.Read(p.d, buf[:])
+// Ensure p is not finalized until Read returns.
+runtime.KeepAlive(p)
+// No more uses of p after this point.
+

Without the KeepAlive call, the finalizer could run at the start of syscall.Read, closing the file descriptor before syscall.Read makes the actual system call.

+

Note: KeepAlive should only be used to prevent finalizers from running prematurely. In particular, when used with unsafe.Pointer, the rules for valid uses of unsafe.Pointer still apply.

+

func LockOSThread

func LockOSThread()

LockOSThread wires the calling goroutine to its current operating system thread. The calling goroutine will always execute in that thread, and no other goroutine will execute in it, until the calling goroutine has made as many calls to UnlockOSThread as to LockOSThread. If the calling goroutine exits without unlocking the thread, the thread will be terminated.

+

All init functions are run on the startup thread. Calling LockOSThread from an init function will cause the main function to be invoked on that thread.

+

A goroutine should call LockOSThread before calling OS services or non-Go library functions that depend on per-thread state.

+

func MemProfile

func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool)

MemProfile returns a profile of memory allocated and freed per allocation site.

+

MemProfile returns n, the number of records in the current memory profile. If len(p) >= n, MemProfile copies the profile into p and returns n, true. If len(p) < n, MemProfile does not change p and returns n, false.

+

If inuseZero is true, the profile includes allocation records where r.AllocBytes > 0 but r.AllocBytes == r.FreeBytes. These are sites where memory was allocated, but it has all been released back to the runtime.

+

The returned profile may be up to two garbage collection cycles old. This is to avoid skewing the profile toward allocations; because allocations happen in real time but frees are delayed until the garbage collector performs sweeping, the profile only accounts for allocations that have had a chance to be freed by the garbage collector.

+

Most clients should use the runtime/pprof package or the testing package's -test.memprofile flag instead of calling MemProfile directly.

+

func MutexProfile 1.8

func MutexProfile(p []BlockProfileRecord) (n int, ok bool)

MutexProfile returns n, the number of records in the current mutex profile. If len(p) >= n, MutexProfile copies the profile into p and returns n, true. Otherwise, MutexProfile does not change p, and returns n, false.

+

Most clients should use the runtime/pprof package instead of calling MutexProfile directly.

+

func NumCPU

func NumCPU() int

NumCPU returns the number of logical CPUs usable by the current process.

+

The set of available CPUs is checked by querying the operating system at process startup. Changes to operating system CPU allocation after process startup are not reflected.

+

func NumCgoCall

func NumCgoCall() int64

NumCgoCall returns the number of cgo calls made by the current process.

+

func NumGoroutine

func NumGoroutine() int

NumGoroutine returns the number of goroutines that currently exist.

+

func ReadMemStats

func ReadMemStats(m *MemStats)

ReadMemStats populates m with memory allocator statistics.

+

The returned memory allocator statistics are up to date as of the call to ReadMemStats. This is in contrast with a heap profile, which is a snapshot as of the most recently completed garbage collection cycle.

+

func ReadTrace 1.5

func ReadTrace() []byte

ReadTrace returns the next chunk of binary tracing data, blocking until data is available. If tracing is turned off and all the data accumulated while it was on has been returned, ReadTrace returns nil. The caller must copy the returned data before calling ReadTrace again. ReadTrace must be called from one goroutine at a time.

+

func SetBlockProfileRate 1.1

func SetBlockProfileRate(rate int)

SetBlockProfileRate controls the fraction of goroutine blocking events that are reported in the blocking profile. The profiler aims to sample an average of one blocking event per rate nanoseconds spent blocked.

+

To include every blocking event in the profile, pass rate = 1. To turn off profiling entirely, pass rate <= 0.

+

func SetCPUProfileRate

func SetCPUProfileRate(hz int)

SetCPUProfileRate sets the CPU profiling rate to hz samples per second. If hz <= 0, SetCPUProfileRate turns off profiling. If the profiler is on, the rate cannot be changed without first turning it off.

+

Most clients should use the runtime/pprof package or the testing package's -test.cpuprofile flag instead of calling SetCPUProfileRate directly.

+

func SetCgoTraceback 1.7

func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer)

SetCgoTraceback records three C functions to use to gather traceback information from C code and to convert that traceback information into symbolic information. These are used when printing stack traces for a program that uses cgo.

+

The traceback and context functions may be called from a signal handler, and must therefore use only async-signal safe functions. The symbolizer function may be called while the program is crashing, and so must be cautious about using memory. None of the functions may call back into Go.

+

The context function will be called with a single argument, a pointer to a struct:

+
struct {
+	Context uintptr
+}
+

In C syntax, this struct will be

+
struct {
+	uintptr_t Context;
+};
+

If the Context field is 0, the context function is being called to record the current traceback context. It should record in the Context field whatever information is needed about the current point of execution to later produce a stack trace, probably the stack pointer and PC. In this case the context function will be called from C code.

+

If the Context field is not 0, then it is a value returned by a previous call to the context function. This case is called when the context is no longer needed; that is, when the Go code is returning to its C code caller. This permits the context function to release any associated resources.

+

While it would be correct for the context function to record a complete a stack trace whenever it is called, and simply copy that out in the traceback function, in a typical program the context function will be called many times without ever recording a traceback for that context. Recording a complete stack trace in a call to the context function is likely to be inefficient.

+

The traceback function will be called with a single argument, a pointer to a struct:

+
struct {
+	Context    uintptr
+	SigContext uintptr
+	Buf        *uintptr
+	Max        uintptr
+}
+

In C syntax, this struct will be

+
struct {
+	uintptr_t  Context;
+	uintptr_t  SigContext;
+	uintptr_t* Buf;
+	uintptr_t  Max;
+};
+

The Context field will be zero to gather a traceback from the current program execution point. In this case, the traceback function will be called from C code.

+

Otherwise Context will be a value previously returned by a call to the context function. The traceback function should gather a stack trace from that saved point in the program execution. The traceback function may be called from an execution thread other than the one that recorded the context, but only when the context is known to be valid and unchanging. The traceback function may also be called deeper in the call stack on the same thread that recorded the context. The traceback function may be called multiple times with the same Context value; it will usually be appropriate to cache the result, if possible, the first time this is called for a specific context value.

+

If the traceback function is called from a signal handler on a Unix system, SigContext will be the signal context argument passed to the signal handler (a C ucontext_t* cast to uintptr_t). This may be used to start tracing at the point where the signal occurred. If the traceback function is not called from a signal handler, SigContext will be zero.

+

Buf is where the traceback information should be stored. It should be PC values, such that Buf[0] is the PC of the caller, Buf[1] is the PC of that function's caller, and so on. Max is the maximum number of entries to store. The function should store a zero to indicate the top of the stack, or that the caller is on a different stack, presumably a Go stack.

+

Unlike runtime.Callers, the PC values returned should, when passed to the symbolizer function, return the file/line of the call instruction. No additional subtraction is required or appropriate.

+

On all platforms, the traceback function is invoked when a call from Go to C to Go requests a stack trace. On linux/amd64, linux/ppc64le, linux/arm64, and freebsd/amd64, the traceback function is also invoked when a signal is received by a thread that is executing a cgo call. The traceback function should not make assumptions about when it is called, as future versions of Go may make additional calls.

+

The symbolizer function will be called with a single argument, a pointer to a struct:

+
struct {
+	PC      uintptr // program counter to fetch information for
+	File    *byte   // file name (NUL terminated)
+	Lineno  uintptr // line number
+	Func    *byte   // function name (NUL terminated)
+	Entry   uintptr // function entry point
+	More    uintptr // set non-zero if more info for this PC
+	Data    uintptr // unused by runtime, available for function
+}
+

In C syntax, this struct will be

+
struct {
+	uintptr_t PC;
+	char*     File;
+	uintptr_t Lineno;
+	char*     Func;
+	uintptr_t Entry;
+	uintptr_t More;
+	uintptr_t Data;
+};
+

The PC field will be a value returned by a call to the traceback function.

+

The first time the function is called for a particular traceback, all the fields except PC will be 0. The function should fill in the other fields if possible, setting them to 0/nil if the information is not available. The Data field may be used to store any useful information across calls. The More field should be set to non-zero if there is more information for this PC, zero otherwise. If More is set non-zero, the function will be called again with the same PC, and may return different information (this is intended for use with inlined functions). If More is zero, the function will be called with the next PC value in the traceback. When the traceback is complete, the function will be called once more with PC set to zero; this may be used to free any information. Each call will leave the fields of the struct set to the same values they had upon return, except for the PC field when the More field is zero. The function must not keep a copy of the struct pointer between calls.

+

When calling SetCgoTraceback, the version argument is the version number of the structs that the functions expect to receive. Currently this must be zero.

+

The symbolizer function may be nil, in which case the results of the traceback function will be displayed as numbers. If the traceback function is nil, the symbolizer function will never be called. The context function may be nil, in which case the traceback function will only be called with the context field set to zero. If the context function is nil, then calls from Go to C to Go will not show a traceback for the C portion of the call stack.

+

SetCgoTraceback should be called only once, ideally from an init function.

+

func SetFinalizer

func SetFinalizer(obj any, finalizer any)

SetFinalizer sets the finalizer associated with obj to the provided finalizer function. When the garbage collector finds an unreachable block with an associated finalizer, it clears the association and runs finalizer(obj) in a separate goroutine. This makes obj reachable again, but now without an associated finalizer. Assuming that SetFinalizer is not called again, the next time the garbage collector sees that obj is unreachable, it will free obj.

+

SetFinalizer(obj, nil) clears any finalizer associated with obj.

+

The argument obj must be a pointer to an object allocated by calling new, by taking the address of a composite literal, or by taking the address of a local variable. The argument finalizer must be a function that takes a single argument to which obj's type can be assigned, and can have arbitrary ignored return values. If either of these is not true, SetFinalizer may abort the program.

+

Finalizers are run in dependency order: if A points at B, both have finalizers, and they are otherwise unreachable, only the finalizer for A runs; once A is freed, the finalizer for B can run. If a cyclic structure includes a block with a finalizer, that cycle is not guaranteed to be garbage collected and the finalizer is not guaranteed to run, because there is no ordering that respects the dependencies.

+

The finalizer is scheduled to run at some arbitrary time after the program can no longer reach the object to which obj points. There is no guarantee that finalizers will run before a program exits, so typically they are useful only for releasing non-memory resources associated with an object during a long-running program. For example, an os.File object could use a finalizer to close the associated operating system file descriptor when a program discards an os.File without calling Close, but it would be a mistake to depend on a finalizer to flush an in-memory I/O buffer such as a bufio.Writer, because the buffer would not be flushed at program exit.

+

It is not guaranteed that a finalizer will run if the size of *obj is zero bytes, because it may share same address with other zero-size objects in memory. See https://go.dev/ref/spec#Size_and_alignment_guarantees.

+

It is not guaranteed that a finalizer will run for objects allocated in initializers for package-level variables. Such objects may be linker-allocated, not heap-allocated.

+

Note that because finalizers may execute arbitrarily far into the future after an object is no longer referenced, the runtime is allowed to perform a space-saving optimization that batches objects together in a single allocation slot. The finalizer for an unreferenced object in such an allocation may never run if it always exists in the same batch as a referenced object. Typically, this batching only happens for tiny (on the order of 16 bytes or less) and pointer-free objects.

+

A finalizer may run as soon as an object becomes unreachable. In order to use finalizers correctly, the program must ensure that the object is reachable until it is no longer required. Objects stored in global variables, or that can be found by tracing pointers from a global variable, are reachable. For other objects, pass the object to a call of the KeepAlive function to mark the last point in the function where the object must be reachable.

+

For example, if p points to a struct, such as os.File, that contains a file descriptor d, and p has a finalizer that closes that file descriptor, and if the last use of p in a function is a call to syscall.Write(p.d, buf, size), then p may be unreachable as soon as the program enters syscall.Write. The finalizer may run at that moment, closing p.d, causing syscall.Write to fail because it is writing to a closed file descriptor (or, worse, to an entirely different file descriptor opened by a different goroutine). To avoid this problem, call KeepAlive(p) after the call to syscall.Write.

+

A single goroutine runs all finalizers for a program, sequentially. If a finalizer must run for a long time, it should do so by starting a new goroutine.

+

In the terminology of the Go memory model, a call SetFinalizer(x, f) “synchronizes before” the finalization call f(x). However, there is no guarantee that KeepAlive(x) or any other use of x “synchronizes before” f(x), so in general a finalizer should use a mutex or other synchronization mechanism if it needs to access mutable state in x. For example, consider a finalizer that inspects a mutable field in x that is modified from time to time in the main program before x becomes unreachable and the finalizer is invoked. The modifications in the main program and the inspection in the finalizer need to use appropriate synchronization, such as mutexes or atomic updates, to avoid read-write races.

+

func SetMutexProfileFraction 1.8

func SetMutexProfileFraction(rate int) int

SetMutexProfileFraction controls the fraction of mutex contention events that are reported in the mutex profile. On average 1/rate events are reported. The previous rate is returned.

+

To turn off profiling entirely, pass rate 0. To just read the current rate, pass rate < 0. (For n>1 the details of sampling may change.)

+

func Stack

func Stack(buf []byte, all bool) int

Stack formats a stack trace of the calling goroutine into buf and returns the number of bytes written to buf. If all is true, Stack formats stack traces of all other goroutines into buf after the trace for the current goroutine.

+

func StartTrace 1.5

func StartTrace() error

StartTrace enables tracing for the current process. While tracing, the data will be buffered and available via ReadTrace. StartTrace returns an error if tracing is already enabled. Most clients should use the runtime/trace package or the testing package's -test.trace flag instead of calling StartTrace directly.

+

func StopTrace 1.5

func StopTrace()

StopTrace stops tracing, if it was previously enabled. StopTrace only returns after all the reads for the trace have completed.

+

func ThreadCreateProfile

func ThreadCreateProfile(p []StackRecord) (n int, ok bool)

ThreadCreateProfile returns n, the number of records in the thread creation profile. If len(p) >= n, ThreadCreateProfile copies the profile into p and returns n, true. If len(p) < n, ThreadCreateProfile does not change p and returns n, false.

+

Most clients should use the runtime/pprof package instead of calling ThreadCreateProfile directly.

+

func UnlockOSThread

func UnlockOSThread()

UnlockOSThread undoes an earlier call to LockOSThread. If this drops the number of active LockOSThread calls on the calling goroutine to zero, it unwires the calling goroutine from its fixed operating system thread. If there are no active LockOSThread calls, this is a no-op.

+

Before calling UnlockOSThread, the caller must ensure that the OS thread is suitable for running other goroutines. If the caller made any permanent changes to the state of the thread that would affect other goroutines, it should not call this function and thus leave the goroutine locked to the OS thread until the goroutine (and hence the thread) exits.

+

func Version

func Version() string

Version returns the Go tree's version string. It is either the commit hash and date at the time of the build or, when possible, a release tag like "go1.3".

+

type BlockProfileRecord 1.1

BlockProfileRecord describes blocking events originated at a particular call sequence (stack trace).

+
type BlockProfileRecord struct {
+    Count  int64
+    Cycles int64
+    StackRecord
+}
+

type Error

The Error interface identifies a run time error.

+
type Error interface {
+    error
+
+    // RuntimeError is a no-op function but
+    // serves to distinguish types that are run time
+    // errors from ordinary errors: a type is a
+    // run time error if it has a RuntimeError method.
+    RuntimeError()
+}

type Frame 1.7

Frame is the information returned by Frames for each call frame.

+
type Frame struct {
+    // PC is the program counter for the location in this frame.
+    // For a frame that calls another frame, this will be the
+    // program counter of a call instruction. Because of inlining,
+    // multiple frames may have the same PC value, but different
+    // symbolic information.
+    PC uintptr
+
+    // Func is the Func value of this call frame. This may be nil
+    // for non-Go code or fully inlined functions.
+    Func *Func
+
+    // Function is the package path-qualified function name of
+    // this call frame. If non-empty, this string uniquely
+    // identifies a single function in the program.
+    // This may be the empty string if not known.
+    // If Func is not nil then Function == Func.Name().
+    Function string
+
+    // File and Line are the file name and line number of the
+    // location in this frame. For non-leaf frames, this will be
+    // the location of a call. These may be the empty string and
+    // zero, respectively, if not known.
+    File string
+    Line int
+
+    // Entry point program counter for the function; may be zero
+    // if not known. If Func is not nil then Entry ==
+    // Func.Entry().
+    Entry uintptr
+    // contains filtered or unexported fields
+}
+

type Frames 1.7

Frames may be used to get function/file/line information for a slice of PC values returned by Callers.

+
type Frames struct {
+    // contains filtered or unexported fields
+}
+

Example +

Code:

c := func() {
+    // Ask runtime.Callers for up to 10 PCs, including runtime.Callers itself.
+    pc := make([]uintptr, 10)
+    n := runtime.Callers(0, pc)
+    if n == 0 {
+        // No PCs available. This can happen if the first argument to
+        // runtime.Callers is large.
+        //
+        // Return now to avoid processing the zero Frame that would
+        // otherwise be returned by frames.Next below.
+        return
+    }
+
+    pc = pc[:n] // pass only valid pcs to runtime.CallersFrames
+    frames := runtime.CallersFrames(pc)
+
+    // Loop to get frames.
+    // A fixed number of PCs can expand to an indefinite number of Frames.
+    for {
+        frame, more := frames.Next()
+
+        // Process this frame.
+        //
+        // To keep this example's output stable
+        // even if there are changes in the testing package,
+        // stop unwinding when we leave package runtime.
+        if !strings.Contains(frame.File, "runtime/") {
+            break
+        }
+        fmt.Printf("- more:%v | %s\n", more, frame.Function)
+
+        // Check whether there are more frames to process after this one.
+        if !more {
+            break
+        }
+    }
+}
+
+b := func() { c() }
+a := func() { b() }
+
+a()
+

Output:

- more:true | runtime.Callers
+- more:true | runtime_test.ExampleFrames.func1
+- more:true | runtime_test.ExampleFrames.func2
+- more:true | runtime_test.ExampleFrames.func3
+- more:true | runtime_test.ExampleFrames
+

func CallersFrames 1.7

func CallersFrames(callers []uintptr) *Frames

CallersFrames takes a slice of PC values returned by Callers and prepares to return function/file/line information. Do not change the slice until you are done with the Frames.

+

func (*Frames) Next 1.7

func (ci *Frames) Next() (frame Frame, more bool)

Next returns a Frame representing the next call frame in the slice of PC values. If it has already returned all call frames, Next returns a zero Frame.

+

The more result indicates whether the next call to Next will return a valid Frame. It does not necessarily indicate whether this call returned one.

+

See the Frames example for idiomatic usage.

+

type Func

A Func represents a Go function in the running binary.

+
type Func struct {
+    // contains filtered or unexported fields
+}
+

func FuncForPC

func FuncForPC(pc uintptr) *Func

FuncForPC returns a *Func describing the function that contains the given program counter address, or else nil.

+

If pc represents multiple functions because of inlining, it returns the *Func describing the innermost function, but with an entry of the outermost function.

+

func (*Func) Entry

func (f *Func) Entry() uintptr

Entry returns the entry address of the function.

+

func (*Func) FileLine

func (f *Func) FileLine(pc uintptr) (file string, line int)

FileLine returns the file name and line number of the source code corresponding to the program counter pc. The result will not be accurate if pc is not a program counter within f.

+

func (*Func) Name

func (f *Func) Name() string

Name returns the name of the function.

+

type MemProfileRecord

A MemProfileRecord describes the live objects allocated by a particular call sequence (stack trace).

+
type MemProfileRecord struct {
+    AllocBytes, FreeBytes     int64       // number of bytes allocated, freed
+    AllocObjects, FreeObjects int64       // number of objects allocated, freed
+    Stack0                    [32]uintptr // stack trace for this record; ends at first 0 entry
+}
+

func (*MemProfileRecord) InUseBytes

func (r *MemProfileRecord) InUseBytes() int64

InUseBytes returns the number of bytes in use (AllocBytes - FreeBytes).

+

func (*MemProfileRecord) InUseObjects

func (r *MemProfileRecord) InUseObjects() int64

InUseObjects returns the number of objects in use (AllocObjects - FreeObjects).

+

func (*MemProfileRecord) Stack

func (r *MemProfileRecord) Stack() []uintptr

Stack returns the stack trace associated with the record, a prefix of r.Stack0.

+

type MemStats

A MemStats records statistics about the memory allocator.

+
type MemStats struct {
+
+    // Alloc is bytes of allocated heap objects.
+    //
+    // This is the same as HeapAlloc (see below).
+    Alloc uint64
+
+    // TotalAlloc is cumulative bytes allocated for heap objects.
+    //
+    // TotalAlloc increases as heap objects are allocated, but
+    // unlike Alloc and HeapAlloc, it does not decrease when
+    // objects are freed.
+    TotalAlloc uint64
+
+    // Sys is the total bytes of memory obtained from the OS.
+    //
+    // Sys is the sum of the XSys fields below. Sys measures the
+    // virtual address space reserved by the Go runtime for the
+    // heap, stacks, and other internal data structures. It's
+    // likely that not all of the virtual address space is backed
+    // by physical memory at any given moment, though in general
+    // it all was at some point.
+    Sys uint64
+
+    // Lookups is the number of pointer lookups performed by the
+    // runtime.
+    //
+    // This is primarily useful for debugging runtime internals.
+    Lookups uint64
+
+    // Mallocs is the cumulative count of heap objects allocated.
+    // The number of live objects is Mallocs - Frees.
+    Mallocs uint64
+
+    // Frees is the cumulative count of heap objects freed.
+    Frees uint64
+
+    // HeapAlloc is bytes of allocated heap objects.
+    //
+    // "Allocated" heap objects include all reachable objects, as
+    // well as unreachable objects that the garbage collector has
+    // not yet freed. Specifically, HeapAlloc increases as heap
+    // objects are allocated and decreases as the heap is swept
+    // and unreachable objects are freed. Sweeping occurs
+    // incrementally between GC cycles, so these two processes
+    // occur simultaneously, and as a result HeapAlloc tends to
+    // change smoothly (in contrast with the sawtooth that is
+    // typical of stop-the-world garbage collectors).
+    HeapAlloc uint64
+
+    // HeapSys is bytes of heap memory obtained from the OS.
+    //
+    // HeapSys measures the amount of virtual address space
+    // reserved for the heap. This includes virtual address space
+    // that has been reserved but not yet used, which consumes no
+    // physical memory, but tends to be small, as well as virtual
+    // address space for which the physical memory has been
+    // returned to the OS after it became unused (see HeapReleased
+    // for a measure of the latter).
+    //
+    // HeapSys estimates the largest size the heap has had.
+    HeapSys uint64
+
+    // HeapIdle is bytes in idle (unused) spans.
+    //
+    // Idle spans have no objects in them. These spans could be
+    // (and may already have been) returned to the OS, or they can
+    // be reused for heap allocations, or they can be reused as
+    // stack memory.
+    //
+    // HeapIdle minus HeapReleased estimates the amount of memory
+    // that could be returned to the OS, but is being retained by
+    // the runtime so it can grow the heap without requesting more
+    // memory from the OS. If this difference is significantly
+    // larger than the heap size, it indicates there was a recent
+    // transient spike in live heap size.
+    HeapIdle uint64
+
+    // HeapInuse is bytes in in-use spans.
+    //
+    // In-use spans have at least one object in them. These spans
+    // can only be used for other objects of roughly the same
+    // size.
+    //
+    // HeapInuse minus HeapAlloc estimates the amount of memory
+    // that has been dedicated to particular size classes, but is
+    // not currently being used. This is an upper bound on
+    // fragmentation, but in general this memory can be reused
+    // efficiently.
+    HeapInuse uint64
+
+    // HeapReleased is bytes of physical memory returned to the OS.
+    //
+    // This counts heap memory from idle spans that was returned
+    // to the OS and has not yet been reacquired for the heap.
+    HeapReleased uint64
+
+    // HeapObjects is the number of allocated heap objects.
+    //
+    // Like HeapAlloc, this increases as objects are allocated and
+    // decreases as the heap is swept and unreachable objects are
+    // freed.
+    HeapObjects uint64
+
+    // StackInuse is bytes in stack spans.
+    //
+    // In-use stack spans have at least one stack in them. These
+    // spans can only be used for other stacks of the same size.
+    //
+    // There is no StackIdle because unused stack spans are
+    // returned to the heap (and hence counted toward HeapIdle).
+    StackInuse uint64
+
+    // StackSys is bytes of stack memory obtained from the OS.
+    //
+    // StackSys is StackInuse, plus any memory obtained directly
+    // from the OS for OS thread stacks.
+    //
+    // In non-cgo programs this metric is currently equal to StackInuse
+    // (but this should not be relied upon, and the value may change in
+    // the future).
+    //
+    // In cgo programs this metric includes OS thread stacks allocated
+    // directly from the OS. Currently, this only accounts for one stack in
+    // c-shared and c-archive build modes and other sources of stacks from
+    // the OS (notably, any allocated by C code) are not currently measured.
+    // Note this too may change in the future.
+    StackSys uint64
+
+    // MSpanInuse is bytes of allocated mspan structures.
+    MSpanInuse uint64
+
+    // MSpanSys is bytes of memory obtained from the OS for mspan
+    // structures.
+    MSpanSys uint64
+
+    // MCacheInuse is bytes of allocated mcache structures.
+    MCacheInuse uint64
+
+    // MCacheSys is bytes of memory obtained from the OS for
+    // mcache structures.
+    MCacheSys uint64
+
+    // BuckHashSys is bytes of memory in profiling bucket hash tables.
+    BuckHashSys uint64
+
+    // GCSys is bytes of memory in garbage collection metadata.
+    GCSys uint64 // Go 1.2
+
+    // OtherSys is bytes of memory in miscellaneous off-heap
+    // runtime allocations.
+    OtherSys uint64 // Go 1.2
+
+    // NextGC is the target heap size of the next GC cycle.
+    //
+    // The garbage collector's goal is to keep HeapAlloc ≤ NextGC.
+    // At the end of each GC cycle, the target for the next cycle
+    // is computed based on the amount of reachable data and the
+    // value of GOGC.
+    NextGC uint64
+
+    // LastGC is the time the last garbage collection finished, as
+    // nanoseconds since 1970 (the UNIX epoch).
+    LastGC uint64
+
+    // PauseTotalNs is the cumulative nanoseconds in GC
+    // stop-the-world pauses since the program started.
+    //
+    // During a stop-the-world pause, all goroutines are paused
+    // and only the garbage collector can run.
+    PauseTotalNs uint64
+
+    // PauseNs is a circular buffer of recent GC stop-the-world
+    // pause times in nanoseconds.
+    //
+    // The most recent pause is at PauseNs[(NumGC+255)%256]. In
+    // general, PauseNs[N%256] records the time paused in the most
+    // recent N%256th GC cycle. There may be multiple pauses per
+    // GC cycle; this is the sum of all pauses during a cycle.
+    PauseNs [256]uint64
+
+    // PauseEnd is a circular buffer of recent GC pause end times,
+    // as nanoseconds since 1970 (the UNIX epoch).
+    //
+    // This buffer is filled the same way as PauseNs. There may be
+    // multiple pauses per GC cycle; this records the end of the
+    // last pause in a cycle.
+    PauseEnd [256]uint64 // Go 1.4
+
+    // NumGC is the number of completed GC cycles.
+    NumGC uint32
+
+    // NumForcedGC is the number of GC cycles that were forced by
+    // the application calling the GC function.
+    NumForcedGC uint32 // Go 1.8
+
+    // GCCPUFraction is the fraction of this program's available
+    // CPU time used by the GC since the program started.
+    //
+    // GCCPUFraction is expressed as a number between 0 and 1,
+    // where 0 means GC has consumed none of this program's CPU. A
+    // program's available CPU time is defined as the integral of
+    // GOMAXPROCS since the program started. That is, if
+    // GOMAXPROCS is 2 and a program has been running for 10
+    // seconds, its "available CPU" is 20 seconds. GCCPUFraction
+    // does not include CPU time used for write barrier activity.
+    //
+    // This is the same as the fraction of CPU reported by
+    // GODEBUG=gctrace=1.
+    GCCPUFraction float64 // Go 1.5
+
+    // EnableGC indicates that GC is enabled. It is always true,
+    // even if GOGC=off.
+    EnableGC bool
+
+    // DebugGC is currently unused.
+    DebugGC bool
+
+    // BySize reports per-size class allocation statistics.
+    //
+    // BySize[N] gives statistics for allocations of size S where
+    // BySize[N-1].Size < S ≤ BySize[N].Size.
+    //
+    // This does not report allocations larger than BySize[60].Size.
+    BySize [61]struct {
+        // Size is the maximum byte size of an object in this
+        // size class.
+        Size uint32
+
+        // Mallocs is the cumulative count of heap objects
+        // allocated in this size class. The cumulative bytes
+        // of allocation is Size*Mallocs. The number of live
+        // objects in this size class is Mallocs - Frees.
+        Mallocs uint64
+
+        // Frees is the cumulative count of heap objects freed
+        // in this size class.
+        Frees uint64
+    }
+}
+

type PanicNilError 1.21

A PanicNilError happens when code calls panic(nil).

+

Before Go 1.21, programs that called panic(nil) observed recover returning nil. Starting in Go 1.21, programs that call panic(nil) observe recover returning a *PanicNilError. Programs can change back to the old behavior by setting GODEBUG=panicnil=1.

+
type PanicNilError struct {
+    // contains filtered or unexported fields
+}
+

func (*PanicNilError) Error 1.21

func (*PanicNilError) Error() string

func (*PanicNilError) RuntimeError 1.21

func (*PanicNilError) RuntimeError()

type Pinner 1.21

A Pinner is a set of Go objects each pinned to a fixed location in memory. The Pinner.Pin method pins one object, while Pinner.Unpin unpins all pinned objects. See their comments for more information.

+
type Pinner struct {
+    // contains filtered or unexported fields
+}
+

func (*Pinner) Pin 1.21

func (p *Pinner) Pin(pointer any)

Pin pins a Go object, preventing it from being moved or freed by the garbage collector until the Pinner.Unpin method has been called.

+

A pointer to a pinned object can be directly stored in C memory or can be contained in Go memory passed to C functions. If the pinned object itself contains pointers to Go objects, these objects must be pinned separately if they are going to be accessed from C code.

+

The argument must be a pointer of any type or an unsafe.Pointer. It's safe to call Pin on non-Go pointers, in which case Pin will do nothing.

+

func (*Pinner) Unpin 1.21

func (p *Pinner) Unpin()

Unpin unpins all pinned objects of the Pinner.

+

type StackRecord

A StackRecord describes a single execution stack.

+
type StackRecord struct {
+    Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry
+}
+

func (*StackRecord) Stack

func (r *StackRecord) Stack() []uintptr

Stack returns the stack trace associated with the record, a prefix of r.Stack0.

+

type TypeAssertionError

A TypeAssertionError explains a failed type assertion.

+
type TypeAssertionError struct {
+    // contains filtered or unexported fields
+}
+

func (*TypeAssertionError) Error

func (e *TypeAssertionError) Error() string

func (*TypeAssertionError) RuntimeError

func (*TypeAssertionError) RuntimeError()

Subdirectories

Name Synopsis
..
asan
cgo Package cgo contains runtime support for code generated by the cgo tool.
coverage
debug Package debug contains facilities for programs to debug themselves while they are running.
metrics Package metrics provides a stable interface to access implementation-defined metrics exported by the Go runtime.
msan
pprof Package pprof writes runtime profiling data in the format expected by the pprof visualization tool.
race Package race implements data race detection logic.
trace Package trace contains facilities for programs to generate traces for the Go execution tracer.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/runtime/ +

+
diff --git a/devdocs/go/runtime%2Fmetrics%2Findex.html b/devdocs/go/runtime%2Fmetrics%2Findex.html new file mode 100644 index 00000000..b26400d7 --- /dev/null +++ b/devdocs/go/runtime%2Fmetrics%2Findex.html @@ -0,0 +1,618 @@ +

Package metrics

Overview

Package metrics provides a stable interface to access implementation-defined metrics exported by the Go runtime. This package is similar to existing functions like runtime.ReadMemStats and runtime/debug.ReadGCStats, but significantly more general.

+

The set of metrics defined by this package may evolve as the runtime itself evolves, and also enables variation across Go implementations, whose relevant metric sets may not intersect.

+

Interface

Metrics are designated by a string key, rather than, for example, a field name in a struct. The full list of supported metrics is always available in the slice of Descriptions returned by All. Each Description also includes useful information about the metric.

+

Thus, users of this API are encouraged to sample supported metrics defined by the slice returned by All to remain compatible across Go versions. Of course, situations arise where reading specific metrics is critical. For these cases, users are encouraged to use build tags, and although metrics may be deprecated and removed, users should consider this to be an exceptional and rare event, coinciding with a very large change in a particular Go implementation.

+

Each metric key also has a "kind" (see ValueKind) that describes the format of the metric's value. In the interest of not breaking users of this package, the "kind" for a given metric is guaranteed not to change. If it must change, then a new metric will be introduced with a new key and a new "kind."

+

Metric key format

As mentioned earlier, metric keys are strings. Their format is simple and well-defined, designed to be both human and machine readable. It is split into two components, separated by a colon: a rooted path and a unit. The choice to include the unit in the key is motivated by compatibility: if a metric's unit changes, its semantics likely did also, and a new key should be introduced.

+

For more details on the precise definition of the metric key's path and unit formats, see the documentation of the Name field of the Description struct.

+

A note about floats

This package supports metrics whose values have a floating-point representation. In order to improve ease-of-use, this package promises to never produce the following classes of floating-point values: NaN, infinity.

+

Supported metrics

Below is the full list of supported metrics, ordered lexicographically.

+
/cgo/go-to-c-calls:calls
+	Count of calls made from Go to C by the current process.
+
+/cpu/classes/gc/mark/assist:cpu-seconds
+	Estimated total CPU time goroutines spent performing GC
+	tasks to assist the GC and prevent it from falling behind the
+	application. This metric is an overestimate, and not directly
+	comparable to system CPU time measurements. Compare only with
+	other /cpu/classes metrics.
+
+/cpu/classes/gc/mark/dedicated:cpu-seconds
+	Estimated total CPU time spent performing GC tasks on processors
+	(as defined by GOMAXPROCS) dedicated to those tasks. This metric
+	is an overestimate, and not directly comparable to system CPU
+	time measurements. Compare only with other /cpu/classes metrics.
+
+/cpu/classes/gc/mark/idle:cpu-seconds
+	Estimated total CPU time spent performing GC tasks on spare CPU
+	resources that the Go scheduler could not otherwise find a use
+	for. This should be subtracted from the total GC CPU time to
+	obtain a measure of compulsory GC CPU time. This metric is an
+	overestimate, and not directly comparable to system CPU time
+	measurements. Compare only with other /cpu/classes metrics.
+
+/cpu/classes/gc/pause:cpu-seconds
+	Estimated total CPU time spent with the application paused by
+	the GC. Even if only one thread is running during the pause,
+	this is computed as GOMAXPROCS times the pause latency because
+	nothing else can be executing. This is the exact sum of samples
+	in /sched/pauses/total/gc:seconds if each sample is multiplied
+	by GOMAXPROCS at the time it is taken. This metric is an
+	overestimate, and not directly comparable to system CPU time
+	measurements. Compare only with other /cpu/classes metrics.
+
+/cpu/classes/gc/total:cpu-seconds
+	Estimated total CPU time spent performing GC tasks. This metric
+	is an overestimate, and not directly comparable to system CPU
+	time measurements. Compare only with other /cpu/classes metrics.
+	Sum of all metrics in /cpu/classes/gc.
+
+/cpu/classes/idle:cpu-seconds
+	Estimated total available CPU time not spent executing
+	any Go or Go runtime code. In other words, the part of
+	/cpu/classes/total:cpu-seconds that was unused. This metric is
+	an overestimate, and not directly comparable to system CPU time
+	measurements. Compare only with other /cpu/classes metrics.
+
+/cpu/classes/scavenge/assist:cpu-seconds
+	Estimated total CPU time spent returning unused memory to the
+	underlying platform in response eagerly in response to memory
+	pressure. This metric is an overestimate, and not directly
+	comparable to system CPU time measurements. Compare only with
+	other /cpu/classes metrics.
+
+/cpu/classes/scavenge/background:cpu-seconds
+	Estimated total CPU time spent performing background tasks to
+	return unused memory to the underlying platform. This metric is
+	an overestimate, and not directly comparable to system CPU time
+	measurements. Compare only with other /cpu/classes metrics.
+
+/cpu/classes/scavenge/total:cpu-seconds
+	Estimated total CPU time spent performing tasks that return
+	unused memory to the underlying platform. This metric is an
+	overestimate, and not directly comparable to system CPU time
+	measurements. Compare only with other /cpu/classes metrics.
+	Sum of all metrics in /cpu/classes/scavenge.
+
+/cpu/classes/total:cpu-seconds
+	Estimated total available CPU time for user Go code or the Go
+	runtime, as defined by GOMAXPROCS. In other words, GOMAXPROCS
+	integrated over the wall-clock duration this process has been
+	executing for. This metric is an overestimate, and not directly
+	comparable to system CPU time measurements. Compare only with
+	other /cpu/classes metrics. Sum of all metrics in /cpu/classes.
+
+/cpu/classes/user:cpu-seconds
+	Estimated total CPU time spent running user Go code. This may
+	also include some small amount of time spent in the Go runtime.
+	This metric is an overestimate, and not directly comparable
+	to system CPU time measurements. Compare only with other
+	/cpu/classes metrics.
+
+/gc/cycles/automatic:gc-cycles
+	Count of completed GC cycles generated by the Go runtime.
+
+/gc/cycles/forced:gc-cycles
+	Count of completed GC cycles forced by the application.
+
+/gc/cycles/total:gc-cycles
+	Count of all completed GC cycles.
+
+/gc/gogc:percent
+	Heap size target percentage configured by the user, otherwise
+	100. This value is set by the GOGC environment variable, and the
+	runtime/debug.SetGCPercent function.
+
+/gc/gomemlimit:bytes
+	Go runtime memory limit configured by the user, otherwise
+	math.MaxInt64. This value is set by the GOMEMLIMIT environment
+	variable, and the runtime/debug.SetMemoryLimit function.
+
+/gc/heap/allocs-by-size:bytes
+	Distribution of heap allocations by approximate size.
+	Bucket counts increase monotonically. Note that this does not
+	include tiny objects as defined by /gc/heap/tiny/allocs:objects,
+	only tiny blocks.
+
+/gc/heap/allocs:bytes
+	Cumulative sum of memory allocated to the heap by the
+	application.
+
+/gc/heap/allocs:objects
+	Cumulative count of heap allocations triggered by the
+	application. Note that this does not include tiny objects as
+	defined by /gc/heap/tiny/allocs:objects, only tiny blocks.
+
+/gc/heap/frees-by-size:bytes
+	Distribution of freed heap allocations by approximate size.
+	Bucket counts increase monotonically. Note that this does not
+	include tiny objects as defined by /gc/heap/tiny/allocs:objects,
+	only tiny blocks.
+
+/gc/heap/frees:bytes
+	Cumulative sum of heap memory freed by the garbage collector.
+
+/gc/heap/frees:objects
+	Cumulative count of heap allocations whose storage was freed
+	by the garbage collector. Note that this does not include tiny
+	objects as defined by /gc/heap/tiny/allocs:objects, only tiny
+	blocks.
+
+/gc/heap/goal:bytes
+	Heap size target for the end of the GC cycle.
+
+/gc/heap/live:bytes
+	Heap memory occupied by live objects that were marked by the
+	previous GC.
+
+/gc/heap/objects:objects
+	Number of objects, live or unswept, occupying heap memory.
+
+/gc/heap/tiny/allocs:objects
+	Count of small allocations that are packed together into blocks.
+	These allocations are counted separately from other allocations
+	because each individual allocation is not tracked by the
+	runtime, only their block. Each block is already accounted for
+	in allocs-by-size and frees-by-size.
+
+/gc/limiter/last-enabled:gc-cycle
+	GC cycle the last time the GC CPU limiter was enabled.
+	This metric is useful for diagnosing the root cause of an
+	out-of-memory error, because the limiter trades memory for CPU
+	time when the GC's CPU time gets too high. This is most likely
+	to occur with use of SetMemoryLimit. The first GC cycle is cycle
+	1, so a value of 0 indicates that it was never enabled.
+
+/gc/pauses:seconds
+	Deprecated. Prefer the identical /sched/pauses/total/gc:seconds.
+
+/gc/scan/globals:bytes
+	The total amount of global variable space that is scannable.
+
+/gc/scan/heap:bytes
+	The total amount of heap space that is scannable.
+
+/gc/scan/stack:bytes
+	The number of bytes of stack that were scanned last GC cycle.
+
+/gc/scan/total:bytes
+	The total amount space that is scannable. Sum of all metrics in
+	/gc/scan.
+
+/gc/stack/starting-size:bytes
+	The stack size of new goroutines.
+
+/godebug/non-default-behavior/execerrdot:events
+	The number of non-default behaviors executed by the os/exec
+	package due to a non-default GODEBUG=execerrdot=... setting.
+
+/godebug/non-default-behavior/gocachehash:events
+	The number of non-default behaviors executed by the cmd/go
+	package due to a non-default GODEBUG=gocachehash=... setting.
+
+/godebug/non-default-behavior/gocachetest:events
+	The number of non-default behaviors executed by the cmd/go
+	package due to a non-default GODEBUG=gocachetest=... setting.
+
+/godebug/non-default-behavior/gocacheverify:events
+	The number of non-default behaviors executed by the cmd/go
+	package due to a non-default GODEBUG=gocacheverify=... setting.
+
+/godebug/non-default-behavior/gotypesalias:events
+	The number of non-default behaviors executed by the go/types
+	package due to a non-default GODEBUG=gotypesalias=... setting.
+
+/godebug/non-default-behavior/http2client:events
+	The number of non-default behaviors executed by the net/http
+	package due to a non-default GODEBUG=http2client=... setting.
+
+/godebug/non-default-behavior/http2server:events
+	The number of non-default behaviors executed by the net/http
+	package due to a non-default GODEBUG=http2server=... setting.
+
+/godebug/non-default-behavior/httplaxcontentlength:events
+	The number of non-default behaviors executed by the net/http
+	package due to a non-default GODEBUG=httplaxcontentlength=...
+	setting.
+
+/godebug/non-default-behavior/httpmuxgo121:events
+	The number of non-default behaviors executed by the net/http
+	package due to a non-default GODEBUG=httpmuxgo121=... setting.
+
+/godebug/non-default-behavior/installgoroot:events
+	The number of non-default behaviors executed by the go/build
+	package due to a non-default GODEBUG=installgoroot=... setting.
+
+/godebug/non-default-behavior/jstmpllitinterp:events
+	The number of non-default behaviors executed by
+	the html/template package due to a non-default
+	GODEBUG=jstmpllitinterp=... setting.
+
+/godebug/non-default-behavior/multipartmaxheaders:events
+	The number of non-default behaviors executed by
+	the mime/multipart package due to a non-default
+	GODEBUG=multipartmaxheaders=... setting.
+
+/godebug/non-default-behavior/multipartmaxparts:events
+	The number of non-default behaviors executed by
+	the mime/multipart package due to a non-default
+	GODEBUG=multipartmaxparts=... setting.
+
+/godebug/non-default-behavior/multipathtcp:events
+	The number of non-default behaviors executed by the net package
+	due to a non-default GODEBUG=multipathtcp=... setting.
+
+/godebug/non-default-behavior/panicnil:events
+	The number of non-default behaviors executed by the runtime
+	package due to a non-default GODEBUG=panicnil=... setting.
+
+/godebug/non-default-behavior/randautoseed:events
+	The number of non-default behaviors executed by the math/rand
+	package due to a non-default GODEBUG=randautoseed=... setting.
+
+/godebug/non-default-behavior/tarinsecurepath:events
+	The number of non-default behaviors executed by the archive/tar
+	package due to a non-default GODEBUG=tarinsecurepath=...
+	setting.
+
+/godebug/non-default-behavior/tls10server:events
+	The number of non-default behaviors executed by the crypto/tls
+	package due to a non-default GODEBUG=tls10server=... setting.
+
+/godebug/non-default-behavior/tlsmaxrsasize:events
+	The number of non-default behaviors executed by the crypto/tls
+	package due to a non-default GODEBUG=tlsmaxrsasize=... setting.
+
+/godebug/non-default-behavior/tlsrsakex:events
+	The number of non-default behaviors executed by the crypto/tls
+	package due to a non-default GODEBUG=tlsrsakex=... setting.
+
+/godebug/non-default-behavior/tlsunsafeekm:events
+	The number of non-default behaviors executed by the crypto/tls
+	package due to a non-default GODEBUG=tlsunsafeekm=... setting.
+
+/godebug/non-default-behavior/x509sha1:events
+	The number of non-default behaviors executed by the crypto/x509
+	package due to a non-default GODEBUG=x509sha1=... setting.
+
+/godebug/non-default-behavior/x509usefallbackroots:events
+	The number of non-default behaviors executed by the crypto/x509
+	package due to a non-default GODEBUG=x509usefallbackroots=...
+	setting.
+
+/godebug/non-default-behavior/x509usepolicies:events
+	The number of non-default behaviors executed by the crypto/x509
+	package due to a non-default GODEBUG=x509usepolicies=...
+	setting.
+
+/godebug/non-default-behavior/zipinsecurepath:events
+	The number of non-default behaviors executed by the archive/zip
+	package due to a non-default GODEBUG=zipinsecurepath=...
+	setting.
+
+/memory/classes/heap/free:bytes
+	Memory that is completely free and eligible to be returned to
+	the underlying system, but has not been. This metric is the
+	runtime's estimate of free address space that is backed by
+	physical memory.
+
+/memory/classes/heap/objects:bytes
+	Memory occupied by live objects and dead objects that have not
+	yet been marked free by the garbage collector.
+
+/memory/classes/heap/released:bytes
+	Memory that is completely free and has been returned to the
+	underlying system. This metric is the runtime's estimate of free
+	address space that is still mapped into the process, but is not
+	backed by physical memory.
+
+/memory/classes/heap/stacks:bytes
+	Memory allocated from the heap that is reserved for stack space,
+	whether or not it is currently in-use. Currently, this
+	represents all stack memory for goroutines. It also includes all
+	OS thread stacks in non-cgo programs. Note that stacks may be
+	allocated differently in the future, and this may change.
+
+/memory/classes/heap/unused:bytes
+	Memory that is reserved for heap objects but is not currently
+	used to hold heap objects.
+
+/memory/classes/metadata/mcache/free:bytes
+	Memory that is reserved for runtime mcache structures, but not
+	in-use.
+
+/memory/classes/metadata/mcache/inuse:bytes
+	Memory that is occupied by runtime mcache structures that are
+	currently being used.
+
+/memory/classes/metadata/mspan/free:bytes
+	Memory that is reserved for runtime mspan structures, but not
+	in-use.
+
+/memory/classes/metadata/mspan/inuse:bytes
+	Memory that is occupied by runtime mspan structures that are
+	currently being used.
+
+/memory/classes/metadata/other:bytes
+	Memory that is reserved for or used to hold runtime metadata.
+
+/memory/classes/os-stacks:bytes
+	Stack memory allocated by the underlying operating system.
+	In non-cgo programs this metric is currently zero. This may
+	change in the future.In cgo programs this metric includes
+	OS thread stacks allocated directly from the OS. Currently,
+	this only accounts for one stack in c-shared and c-archive build
+	modes, and other sources of stacks from the OS are not measured.
+	This too may change in the future.
+
+/memory/classes/other:bytes
+	Memory used by execution trace buffers, structures for debugging
+	the runtime, finalizer and profiler specials, and more.
+
+/memory/classes/profiling/buckets:bytes
+	Memory that is used by the stack trace hash map used for
+	profiling.
+
+/memory/classes/total:bytes
+	All memory mapped by the Go runtime into the current process
+	as read-write. Note that this does not include memory mapped
+	by code called via cgo or via the syscall package. Sum of all
+	metrics in /memory/classes.
+
+/sched/gomaxprocs:threads
+	The current runtime.GOMAXPROCS setting, or the number of
+	operating system threads that can execute user-level Go code
+	simultaneously.
+
+/sched/goroutines:goroutines
+	Count of live goroutines.
+
+/sched/latencies:seconds
+	Distribution of the time goroutines have spent in the scheduler
+	in a runnable state before actually running. Bucket counts
+	increase monotonically.
+
+/sched/pauses/stopping/gc:seconds
+	Distribution of individual GC-related stop-the-world stopping
+	latencies. This is the time it takes from deciding to stop the
+	world until all Ps are stopped. This is a subset of the total
+	GC-related stop-the-world time (/sched/pauses/total/gc:seconds).
+	During this time, some threads may be executing. Bucket counts
+	increase monotonically.
+
+/sched/pauses/stopping/other:seconds
+	Distribution of individual non-GC-related stop-the-world
+	stopping latencies. This is the time it takes from deciding
+	to stop the world until all Ps are stopped. This is a
+	subset of the total non-GC-related stop-the-world time
+	(/sched/pauses/total/other:seconds). During this time, some
+	threads may be executing. Bucket counts increase monotonically.
+
+/sched/pauses/total/gc:seconds
+	Distribution of individual GC-related stop-the-world pause
+	latencies. This is the time from deciding to stop the world
+	until the world is started again. Some of this time is spent
+	getting all threads to stop (this is measured directly in
+	/sched/pauses/stopping/gc:seconds), during which some threads
+	may still be running. Bucket counts increase monotonically.
+
+/sched/pauses/total/other:seconds
+	Distribution of individual non-GC-related stop-the-world
+	pause latencies. This is the time from deciding to stop the
+	world until the world is started again. Some of this time
+	is spent getting all threads to stop (measured directly in
+	/sched/pauses/stopping/other:seconds). Bucket counts increase
+	monotonically.
+
+/sync/mutex/wait/total:seconds
+	Approximate cumulative time goroutines have spent blocked on a
+	sync.Mutex, sync.RWMutex, or runtime-internal lock. This metric
+	is useful for identifying global changes in lock contention.
+	Collect a mutex or block profile using the runtime/pprof package
+	for more detailed contention data.
+

Index

Examples

Read (ReadingAllMetrics)
Read (ReadingOneMetric)

Package files

description.go doc.go histogram.go sample.go value.go

func Read 1.16

func Read(m []Sample)

Read populates each Value field in the given slice of metric samples.

+

Desired metrics should be present in the slice with the appropriate name. The user of this API is encouraged to re-use the same slice between calls for efficiency, but is not required to do so.

+

Note that re-use has some caveats. Notably, Values should not be read or manipulated while a Read with that value is outstanding; that is a data race. This property includes pointer-typed Values (for example, Float64Histogram) whose underlying storage will be reused by Read when possible. To safely use such values in a concurrent setting, all data must be deep-copied.

+

It is safe to execute multiple Read calls concurrently, but their arguments must share no underlying memory. When in doubt, create a new []Sample from scratch, which is always safe, though may be inefficient.

+

Sample values with names not appearing in All will have their Value populated as KindBad to indicate that the name is unknown.

Example (ReadingAllMetrics) +

Code:

+// Get descriptions for all supported metrics.
+descs := metrics.All()
+
+// Create a sample for each metric.
+samples := make([]metrics.Sample, len(descs))
+for i := range samples {
+    samples[i].Name = descs[i].Name
+}
+
+// Sample the metrics. Re-use the samples slice if you can!
+metrics.Read(samples)
+
+// Iterate over all results.
+for _, sample := range samples {
+    // Pull out the name and value.
+    name, value := sample.Name, sample.Value
+
+    // Handle each sample.
+    switch value.Kind() {
+    case metrics.KindUint64:
+        fmt.Printf("%s: %d\n", name, value.Uint64())
+    case metrics.KindFloat64:
+        fmt.Printf("%s: %f\n", name, value.Float64())
+    case metrics.KindFloat64Histogram:
+        // The histogram may be quite large, so let's just pull out
+        // a crude estimate for the median for the sake of this example.
+        fmt.Printf("%s: %f\n", name, medianBucket(value.Float64Histogram()))
+    case metrics.KindBad:
+        // This should never happen because all metrics are supported
+        // by construction.
+        panic("bug in runtime/metrics package!")
+    default:
+        // This may happen as new metrics get added.
+        //
+        // The safest thing to do here is to simply log it somewhere
+        // as something to look into, but ignore it for now.
+        // In the worst case, you might temporarily miss out on a new metric.
+        fmt.Printf("%s: unexpected metric Kind: %v\n", name, value.Kind())
+    }
+}
+

Example (ReadingOneMetric) +

Code:

+// Name of the metric we want to read.
+const myMetric = "/memory/classes/heap/free:bytes"
+
+// Create a sample for the metric.
+sample := make([]metrics.Sample, 1)
+sample[0].Name = myMetric
+
+// Sample the metric.
+metrics.Read(sample)
+
+// Check if the metric is actually supported.
+// If it's not, the resulting value will always have
+// kind KindBad.
+if sample[0].Value.Kind() == metrics.KindBad {
+    panic(fmt.Sprintf("metric %q no longer supported", myMetric))
+}
+
+// Handle the result.
+//
+// It's OK to assume a particular Kind for a metric;
+// they're guaranteed not to change.
+freeBytes := sample[0].Value.Uint64()
+
+fmt.Printf("free but not released memory: %d\n", freeBytes)
+

type Description 1.16

Description describes a runtime metric.

+
type Description struct {
+    // Name is the full name of the metric which includes the unit.
+    //
+    // The format of the metric may be described by the following regular expression.
+    //
+    // 	^(?P<name>/[^:]+):(?P<unit>[^:*/]+(?:[*/][^:*/]+)*)$
+    //
+    // The format splits the name into two components, separated by a colon: a path which always
+    // starts with a /, and a machine-parseable unit. The name may contain any valid Unicode
+    // codepoint in between / characters, but by convention will try to stick to lowercase
+    // characters and hyphens. An example of such a path might be "/memory/heap/free".
+    //
+    // The unit is by convention a series of lowercase English unit names (singular or plural)
+    // without prefixes delimited by '*' or '/'. The unit names may contain any valid Unicode
+    // codepoint that is not a delimiter.
+    // Examples of units might be "seconds", "bytes", "bytes/second", "cpu-seconds",
+    // "byte*cpu-seconds", and "bytes/second/second".
+    //
+    // For histograms, multiple units may apply. For instance, the units of the buckets and
+    // the count. By convention, for histograms, the units of the count are always "samples"
+    // with the type of sample evident by the metric's name, while the unit in the name
+    // specifies the buckets' unit.
+    //
+    // A complete name might look like "/memory/heap/free:bytes".
+    Name string
+
+    // Description is an English language sentence describing the metric.
+    Description string
+
+    // Kind is the kind of value for this metric.
+    //
+    // The purpose of this field is to allow users to filter out metrics whose values are
+    // types which their application may not understand.
+    Kind ValueKind
+
+    // Cumulative is whether or not the metric is cumulative. If a cumulative metric is just
+    // a single number, then it increases monotonically. If the metric is a distribution,
+    // then each bucket count increases monotonically.
+    //
+    // This flag thus indicates whether or not it's useful to compute a rate from this value.
+    Cumulative bool
+}
+

func All 1.16

func All() []Description

All returns a slice of containing metric descriptions for all supported metrics.

+

type Float64Histogram 1.16

Float64Histogram represents a distribution of float64 values.

+
type Float64Histogram struct {
+    // Counts contains the weights for each histogram bucket.
+    //
+    // Given N buckets, Count[n] is the weight of the range
+    // [bucket[n], bucket[n+1]), for 0 <= n < N.
+    Counts []uint64
+
+    // Buckets contains the boundaries of the histogram buckets, in increasing order.
+    //
+    // Buckets[0] is the inclusive lower bound of the minimum bucket while
+    // Buckets[len(Buckets)-1] is the exclusive upper bound of the maximum bucket.
+    // Hence, there are len(Buckets)-1 counts. Furthermore, len(Buckets) != 1, always,
+    // since at least two boundaries are required to describe one bucket (and 0
+    // boundaries are used to describe 0 buckets).
+    //
+    // Buckets[0] is permitted to have value -Inf and Buckets[len(Buckets)-1] is
+    // permitted to have value Inf.
+    //
+    // For a given metric name, the value of Buckets is guaranteed not to change
+    // between calls until program exit.
+    //
+    // This slice value is permitted to alias with other Float64Histograms' Buckets
+    // fields, so the values within should only ever be read. If they need to be
+    // modified, the user must make a copy.
+    Buckets []float64
+}
+

type Sample 1.16

Sample captures a single metric sample.

+
type Sample struct {
+    // Name is the name of the metric sampled.
+    //
+    // It must correspond to a name in one of the metric descriptions
+    // returned by All.
+    Name string
+
+    // Value is the value of the metric sample.
+    Value Value
+}
+

type Value 1.16

Value represents a metric value returned by the runtime.

+
type Value struct {
+    // contains filtered or unexported fields
+}
+

func (Value) Float64 1.16

func (v Value) Float64() float64

Float64 returns the internal float64 value for the metric.

+

If v.Kind() != KindFloat64, this method panics.

+

func (Value) Float64Histogram 1.16

func (v Value) Float64Histogram() *Float64Histogram

Float64Histogram returns the internal *Float64Histogram value for the metric.

+

If v.Kind() != KindFloat64Histogram, this method panics.

+

func (Value) Kind 1.16

func (v Value) Kind() ValueKind

Kind returns the tag representing the kind of value this is.

+

func (Value) Uint64 1.16

func (v Value) Uint64() uint64

Uint64 returns the internal uint64 value for the metric.

+

If v.Kind() != KindUint64, this method panics.

+

type ValueKind 1.16

ValueKind is a tag for a metric Value which indicates its type.

+
type ValueKind int
const (
+    // KindBad indicates that the Value has no type and should not be used.
+    KindBad ValueKind = iota
+
+    // KindUint64 indicates that the type of the Value is a uint64.
+    KindUint64
+
+    // KindFloat64 indicates that the type of the Value is a float64.
+    KindFloat64
+
+    // KindFloat64Histogram indicates that the type of the Value is a *Float64Histogram.
+    KindFloat64Histogram
+)
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/runtime/metrics/ +

+
diff --git a/devdocs/go/runtime%2Fpprof%2Findex.html b/devdocs/go/runtime%2Fpprof%2Findex.html new file mode 100644 index 00000000..1d4391d7 --- /dev/null +++ b/devdocs/go/runtime%2Fpprof%2Findex.html @@ -0,0 +1,136 @@ +

Package pprof

Overview

Package pprof writes runtime profiling data in the format expected by the pprof visualization tool.

+

Profiling a Go program

The first step to profiling a Go program is to enable profiling. Support for profiling benchmarks built with the standard testing package is built into go test. For example, the following command runs benchmarks in the current directory and writes the CPU and memory profiles to cpu.prof and mem.prof:

+
go test -cpuprofile cpu.prof -memprofile mem.prof -bench .
+

To add equivalent profiling support to a standalone program, add code like the following to your main function:

+
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`")
+var memprofile = flag.String("memprofile", "", "write memory profile to `file`")
+
+func main() {
+    flag.Parse()
+    if *cpuprofile != "" {
+        f, err := os.Create(*cpuprofile)
+        if err != nil {
+            log.Fatal("could not create CPU profile: ", err)
+        }
+        defer f.Close() // error handling omitted for example
+        if err := pprof.StartCPUProfile(f); err != nil {
+            log.Fatal("could not start CPU profile: ", err)
+        }
+        defer pprof.StopCPUProfile()
+    }
+
+    // ... rest of the program ...
+
+    if *memprofile != "" {
+        f, err := os.Create(*memprofile)
+        if err != nil {
+            log.Fatal("could not create memory profile: ", err)
+        }
+        defer f.Close() // error handling omitted for example
+        runtime.GC() // get up-to-date statistics
+        if err := pprof.WriteHeapProfile(f); err != nil {
+            log.Fatal("could not write memory profile: ", err)
+        }
+    }
+}
+

There is also a standard HTTP interface to profiling data. Adding the following line will install handlers under the /debug/pprof/ URL to download live profiles:

+
import _ "net/http/pprof"
+

See the net/http/pprof package for more details.

+

Profiles can then be visualized with the pprof tool:

+
go tool pprof cpu.prof
+

There are many commands available from the pprof command line. Commonly used commands include "top", which prints a summary of the top program hot-spots, and "web", which opens an interactive graph of hot-spots and their call graphs. Use "help" for information on all pprof commands.

+

For more information about pprof, see https://github.com/google/pprof/blob/main/doc/README.md.

Index

Package files

elf.go label.go map.go pe.go pprof.go pprof_rusage.go proto.go proto_other.go protobuf.go protomem.go runtime.go

func Do 1.9

func Do(ctx context.Context, labels LabelSet, f func(context.Context))

Do calls f with a copy of the parent context with the given labels added to the parent's label map. Goroutines spawned while executing f will inherit the augmented label-set. Each key/value pair in labels is inserted into the label map in the order provided, overriding any previous value for the same key. The augmented label map will be set for the duration of the call to f and restored once f returns.

+

func ForLabels 1.9

func ForLabels(ctx context.Context, f func(key, value string) bool)

ForLabels invokes f with each label set on the context. The function f should return true to continue iteration or false to stop iteration early.

+

func Label 1.9

func Label(ctx context.Context, key string) (string, bool)

Label returns the value of the label with the given key on ctx, and a boolean indicating whether that label exists.

+

func SetGoroutineLabels 1.9

func SetGoroutineLabels(ctx context.Context)

SetGoroutineLabels sets the current goroutine's labels to match ctx. A new goroutine inherits the labels of the goroutine that created it. This is a lower-level API than Do, which should be used instead when possible.

+

func StartCPUProfile

func StartCPUProfile(w io.Writer) error

StartCPUProfile enables CPU profiling for the current process. While profiling, the profile will be buffered and written to w. StartCPUProfile returns an error if profiling is already enabled.

+

On Unix-like systems, StartCPUProfile does not work by default for Go code built with -buildmode=c-archive or -buildmode=c-shared. StartCPUProfile relies on the SIGPROF signal, but that signal will be delivered to the main program's SIGPROF signal handler (if any) not to the one used by Go. To make it work, call os/signal.Notify for syscall.SIGPROF, but note that doing so may break any profiling being done by the main program.

+

func StopCPUProfile

func StopCPUProfile()

StopCPUProfile stops the current CPU profile, if any. StopCPUProfile only returns after all the writes for the profile have completed.

+

func WithLabels 1.9

func WithLabels(ctx context.Context, labels LabelSet) context.Context

WithLabels returns a new context.Context with the given labels added. A label overwrites a prior label with the same key.

+

func WriteHeapProfile

func WriteHeapProfile(w io.Writer) error

WriteHeapProfile is shorthand for Lookup("heap").WriteTo(w, 0). It is preserved for backwards compatibility.

+

type LabelSet 1.9

LabelSet is a set of labels.

+
type LabelSet struct {
+    // contains filtered or unexported fields
+}
+

func Labels 1.9

func Labels(args ...string) LabelSet

Labels takes an even number of strings representing key-value pairs and makes a LabelSet containing them. A label overwrites a prior label with the same key. Currently only the CPU and goroutine profiles utilize any labels information. See https://golang.org/issue/23458 for details.

+

type Profile

A Profile is a collection of stack traces showing the call sequences that led to instances of a particular event, such as allocation. Packages can create and maintain their own profiles; the most common use is for tracking resources that must be explicitly closed, such as files or network connections.

+

A Profile's methods can be called from multiple goroutines simultaneously.

+

Each Profile has a unique name. A few profiles are predefined:

+
goroutine    - stack traces of all current goroutines
+heap         - a sampling of memory allocations of live objects
+allocs       - a sampling of all past memory allocations
+threadcreate - stack traces that led to the creation of new OS threads
+block        - stack traces that led to blocking on synchronization primitives
+mutex        - stack traces of holders of contended mutexes
+

These predefined profiles maintain themselves and panic on an explicit Profile.Add or Profile.Remove method call.

+

The CPU profile is not available as a Profile. It has a special API, the StartCPUProfile and StopCPUProfile functions, because it streams output to a writer during profiling.

+

Heap profile

The heap profile reports statistics as of the most recently completed garbage collection; it elides more recent allocation to avoid skewing the profile away from live data and toward garbage. If there has been no garbage collection at all, the heap profile reports all known allocations. This exception helps mainly in programs running without garbage collection enabled, usually for debugging purposes.

+

The heap profile tracks both the allocation sites for all live objects in the application memory and for all objects allocated since the program start. Pprof's -inuse_space, -inuse_objects, -alloc_space, and -alloc_objects flags select which to display, defaulting to -inuse_space (live objects, scaled by size).

+

Allocs profile

The allocs profile is the same as the heap profile but changes the default pprof display to -alloc_space, the total number of bytes allocated since the program began (including garbage-collected bytes).

+

Block profile

The block profile tracks time spent blocked on synchronization primitives, such as sync.Mutex, sync.RWMutex, sync.WaitGroup, sync.Cond, and channel send/receive/select.

+

Stack traces correspond to the location that blocked (for example, sync.Mutex.Lock).

+

Sample values correspond to cumulative time spent blocked at that stack trace, subject to time-based sampling specified by runtime.SetBlockProfileRate.

+

Mutex profile

The mutex profile tracks contention on mutexes, such as sync.Mutex, sync.RWMutex, and runtime-internal locks.

+

Stack traces correspond to the end of the critical section causing contention. For example, a lock held for a long time while other goroutines are waiting to acquire the lock will report contention when the lock is finally unlocked (that is, at sync.Mutex.Unlock).

+

Sample values correspond to the approximate cumulative time other goroutines spent blocked waiting for the lock, subject to event-based sampling specified by runtime.SetMutexProfileFraction. For example, if a caller holds a lock for 1s while 5 other goroutines are waiting for the entire second to acquire the lock, its unlock call stack will report 5s of contention.

+

Runtime-internal locks are always reported at the location "runtime._LostContendedRuntimeLock". More detailed stack traces for runtime-internal locks can be obtained by setting `GODEBUG=runtimecontentionstacks=1` (see package runtime docs for caveats).

+
type Profile struct {
+    // contains filtered or unexported fields
+}
+

func Lookup

func Lookup(name string) *Profile

Lookup returns the profile with the given name, or nil if no such profile exists.

+

func NewProfile

func NewProfile(name string) *Profile

NewProfile creates a new profile with the given name. If a profile with that name already exists, NewProfile panics. The convention is to use a 'import/path.' prefix to create separate name spaces for each package. For compatibility with various tools that read pprof data, profile names should not contain spaces.

+

func Profiles

func Profiles() []*Profile

Profiles returns a slice of all the known profiles, sorted by name.

+

func (*Profile) Add

func (p *Profile) Add(value any, skip int)

Add adds the current execution stack to the profile, associated with value. Add stores value in an internal map, so value must be suitable for use as a map key and will not be garbage collected until the corresponding call to Profile.Remove. Add panics if the profile already contains a stack for value.

+

The skip parameter has the same meaning as runtime.Caller's skip and controls where the stack trace begins. Passing skip=0 begins the trace in the function calling Add. For example, given this execution stack:

+
Add
+called from rpc.NewClient
+called from mypkg.Run
+called from main.main
+

Passing skip=0 begins the stack trace at the call to Add inside rpc.NewClient. Passing skip=1 begins the stack trace at the call to NewClient inside mypkg.Run.

+

func (*Profile) Count

func (p *Profile) Count() int

Count returns the number of execution stacks currently in the profile.

+

func (*Profile) Name

func (p *Profile) Name() string

Name returns this profile's name, which can be passed to Lookup to reobtain the profile.

+

func (*Profile) Remove

func (p *Profile) Remove(value any)

Remove removes the execution stack associated with value from the profile. It is a no-op if the value is not in the profile.

+

func (*Profile) WriteTo

func (p *Profile) WriteTo(w io.Writer, debug int) error

WriteTo writes a pprof-formatted snapshot of the profile to w. If a write to w returns an error, WriteTo returns that error. Otherwise, WriteTo returns nil.

+

The debug parameter enables additional output. Passing debug=0 writes the gzip-compressed protocol buffer described in https://github.com/google/pprof/tree/master/proto#overview. Passing debug=1 writes the legacy text format with comments translating addresses to function names and line numbers, so that a programmer can read the profile without tools.

+

The predefined profiles may assign meaning to other debug values; for example, when printing the "goroutine" profile, debug=2 means to print the goroutine stacks in the same form that a Go program uses when dying due to an unrecovered panic.

+

Bugs

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/runtime/pprof/ +

+
diff --git a/devdocs/go/runtime%2Frace%2Findex.html b/devdocs/go/runtime%2Frace%2Findex.html new file mode 100644 index 00000000..e1abbf02 --- /dev/null +++ b/devdocs/go/runtime%2Frace%2Findex.html @@ -0,0 +1,11 @@ +

Package race

Overview

Package race implements data race detection logic. No public interface is provided. For details about the race detector see https://golang.org/doc/articles/race_detector.html

Index

Package files

doc.go race_v1_amd64.go

Subdirectories

Name Synopsis
..
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/runtime/race/ +

+
diff --git a/devdocs/go/runtime%2Ftrace%2Findex.html b/devdocs/go/runtime%2Ftrace%2Findex.html new file mode 100644 index 00000000..980aa1a1 --- /dev/null +++ b/devdocs/go/runtime%2Ftrace%2Findex.html @@ -0,0 +1,136 @@ +

Package trace

Overview

Package trace contains facilities for programs to generate traces for the Go execution tracer.

+

Tracing runtime activities

The execution trace captures a wide range of execution events such as goroutine creation/blocking/unblocking, syscall enter/exit/block, GC-related events, changes of heap size, processor start/stop, etc. When CPU profiling is active, the execution tracer makes an effort to include those samples as well. A precise nanosecond-precision timestamp and a stack trace is captured for most events. The generated trace can be interpreted using `go tool trace`.

+

Support for tracing tests and benchmarks built with the standard testing package is built into `go test`. For example, the following command runs the test in the current directory and writes the trace file (trace.out).

+
go test -trace=trace.out
+

This runtime/trace package provides APIs to add equivalent tracing support to a standalone program. See the Example that demonstrates how to use this API to enable tracing.

+

There is also a standard HTTP interface to trace data. Adding the following line will install a handler under the /debug/pprof/trace URL to download a live trace:

+
import _ "net/http/pprof"
+

See the net/http/pprof package for more details about all of the debug endpoints installed by this import.

+

User annotation

Package trace provides user annotation APIs that can be used to log interesting events during execution.

+

There are three types of user annotations: log messages, regions, and tasks.

+

Log emits a timestamped message to the execution trace along with additional information such as the category of the message and which goroutine called Log. The execution tracer provides UIs to filter and group goroutines using the log category and the message supplied in Log.

+

A region is for logging a time interval during a goroutine's execution. By definition, a region starts and ends in the same goroutine. Regions can be nested to represent subintervals. For example, the following code records four regions in the execution trace to trace the durations of sequential steps in a cappuccino making operation.

+
trace.WithRegion(ctx, "makeCappuccino", func() {
+
+   // orderID allows to identify a specific order
+   // among many cappuccino order region records.
+   trace.Log(ctx, "orderID", orderID)
+
+   trace.WithRegion(ctx, "steamMilk", steamMilk)
+   trace.WithRegion(ctx, "extractCoffee", extractCoffee)
+   trace.WithRegion(ctx, "mixMilkCoffee", mixMilkCoffee)
+})
+

A task is a higher-level component that aids tracing of logical operations such as an RPC request, an HTTP request, or an interesting local operation which may require multiple goroutines working together. Since tasks can involve multiple goroutines, they are tracked via a context.Context object. NewTask creates a new task and embeds it in the returned context.Context object. Log messages and regions are attached to the task, if any, in the Context passed to Log and WithRegion.

+

For example, assume that we decided to froth milk, extract coffee, and mix milk and coffee in separate goroutines. With a task, the trace tool can identify the goroutines involved in a specific cappuccino order.

+
ctx, task := trace.NewTask(ctx, "makeCappuccino")
+trace.Log(ctx, "orderID", orderID)
+
+milk := make(chan bool)
+espresso := make(chan bool)
+
+go func() {
+        trace.WithRegion(ctx, "steamMilk", steamMilk)
+        milk <- true
+}()
+go func() {
+        trace.WithRegion(ctx, "extractCoffee", extractCoffee)
+        espresso <- true
+}()
+go func() {
+        defer task.End() // When assemble is done, the order is complete.
+        <-espresso
+        <-milk
+        trace.WithRegion(ctx, "mixMilkCoffee", mixMilkCoffee)
+}()
+

The trace tool computes the latency of a task by measuring the time between the task creation and the task end and provides latency distributions for each task type found in the trace.

Example +

Example demonstrates the use of the trace package to trace the execution of a Go program. The trace output will be written to the file trace.out

Code:

package trace_test
+
+import (
+    "fmt"
+    "log"
+    "os"
+    "runtime/trace"
+)
+
+// Example demonstrates the use of the trace package to trace
+// the execution of a Go program. The trace output will be
+// written to the file trace.out
+func Example() {
+    f, err := os.Create("trace.out")
+    if err != nil {
+        log.Fatalf("failed to create trace output file: %v", err)
+    }
+    defer func() {
+        if err := f.Close(); err != nil {
+            log.Fatalf("failed to close trace file: %v", err)
+        }
+    }()
+
+    if err := trace.Start(f); err != nil {
+        log.Fatalf("failed to start trace: %v", err)
+    }
+    defer trace.Stop()
+
+    // your program here
+    RunMyProgram()
+}
+
+func RunMyProgram() {
+    fmt.Printf("this function will be traced")
+}
+

Index

Examples

Package

Package files

annotation.go trace.go

func IsEnabled 1.11

func IsEnabled() bool

IsEnabled reports whether tracing is enabled. The information is advisory only. The tracing status may have changed by the time this function returns.

+

func Log 1.11

func Log(ctx context.Context, category, message string)

Log emits a one-off event with the given category and message. Category can be empty and the API assumes there are only a handful of unique categories in the system.

+

func Logf 1.11

func Logf(ctx context.Context, category, format string, args ...any)

Logf is like Log, but the value is formatted using the specified format spec.

+

func Start 1.5

func Start(w io.Writer) error

Start enables tracing for the current program. While tracing, the trace will be buffered and written to w. Start returns an error if tracing is already enabled.

+

func Stop 1.5

func Stop()

Stop stops the current tracing, if any. Stop only returns after all the writes for the trace have completed.

+

func WithRegion 1.11

func WithRegion(ctx context.Context, regionType string, fn func())

WithRegion starts a region associated with its calling goroutine, runs fn, and then ends the region. If the context carries a task, the region is associated with the task. Otherwise, the region is attached to the background task.

+

The regionType is used to classify regions, so there should be only a handful of unique region types.

+

type Region 1.11

Region is a region of code whose execution time interval is traced.

+
type Region struct {
+    // contains filtered or unexported fields
+}
+

func StartRegion 1.11

func StartRegion(ctx context.Context, regionType string) *Region

StartRegion starts a region and returns it. The returned Region's Region.End method must be called from the same goroutine where the region was started. Within each goroutine, regions must nest. That is, regions started after this region must be ended before this region can be ended. Recommended usage is

+
defer trace.StartRegion(ctx, "myTracedRegion").End()
+

func (*Region) End 1.11

func (r *Region) End()

End marks the end of the traced code region.

+

type Task 1.11

Task is a data type for tracing a user-defined, logical operation.

+
type Task struct {
+    // contains filtered or unexported fields
+}
+

func NewTask 1.11

func NewTask(pctx context.Context, taskType string) (ctx context.Context, task *Task)

NewTask creates a task instance with the type taskType and returns it along with a Context that carries the task. If the input context contains a task, the new task is its subtask.

+

The taskType is used to classify task instances. Analysis tools like the Go execution tracer may assume there are only a bounded number of unique task types in the system.

+

The returned Task's Task.End method is used to mark the task's end. The trace tool measures task latency as the time between task creation and when the End method is called, and provides the latency distribution per task type. If the End method is called multiple times, only the first call is used in the latency measurement.

+
ctx, task := trace.NewTask(ctx, "awesomeTask")
+trace.WithRegion(ctx, "preparation", prepWork)
+// preparation of the task
+go func() {  // continue processing the task in a separate goroutine.
+    defer task.End()
+    trace.WithRegion(ctx, "remainingWork", remainingWork)
+}()
+

func (*Task) End 1.11

func (t *Task) End()

End marks the end of the operation represented by the Task.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/runtime/trace/ +

+
diff --git a/devdocs/go/slices%2Findex.html b/devdocs/go/slices%2Findex.html new file mode 100644 index 00000000..39c60ddb --- /dev/null +++ b/devdocs/go/slices%2Findex.html @@ -0,0 +1,277 @@ +

Package slices

Overview

Package slices defines various functions useful with slices of any type.

Index

Examples

BinarySearch
BinarySearchFunc
Compact
CompactFunc
Compare
CompareFunc
ContainsFunc
Delete
DeleteFunc
Equal
EqualFunc
Index
IndexFunc
Insert
IsSorted
IsSortedFunc
Max
MaxFunc
Min
MinFunc
Replace
Reverse
Sort
SortFunc (CaseInsensitive)
SortFunc (MultiField)
SortStableFunc

Package files

slices.go sort.go zsortanyfunc.go zsortordered.go

func BinarySearch

func BinarySearch[S ~[]E, E cmp.Ordered](x S, target E) (int, bool)

BinarySearch searches for target in a sorted slice and returns the position where target is found, or the position where target would appear in the sort order; it also returns a bool saying whether the target is really found in the slice. The slice must be sorted in increasing order.

Example +

Code:

names := []string{"Alice", "Bob", "Vera"}
+n, found := slices.BinarySearch(names, "Vera")
+fmt.Println("Vera:", n, found)
+n, found = slices.BinarySearch(names, "Bill")
+fmt.Println("Bill:", n, found)
+

Output:

Vera: 2 true
+Bill: 1 false
+

func BinarySearchFunc

func BinarySearchFunc[S ~[]E, E, T any](x S, target T, cmp func(E, T) int) (int, bool)

BinarySearchFunc works like BinarySearch, but uses a custom comparison function. The slice must be sorted in increasing order, where "increasing" is defined by cmp. cmp should return 0 if the slice element matches the target, a negative number if the slice element precedes the target, or a positive number if the slice element follows the target. cmp must implement the same ordering as the slice, such that if cmp(a, t) < 0 and cmp(b, t) >= 0, then a must precede b in the slice.

Example +

Code:

type Person struct {
+    Name string
+    Age  int
+}
+people := []Person{
+    {"Alice", 55},
+    {"Bob", 24},
+    {"Gopher", 13},
+}
+n, found := slices.BinarySearchFunc(people, Person{"Bob", 0}, func(a, b Person) int {
+    return cmp.Compare(a.Name, b.Name)
+})
+fmt.Println("Bob:", n, found)
+

Output:

Bob: 1 true
+

func Clip

func Clip[S ~[]E, E any](s S) S

Clip removes unused capacity from the slice, returning s[:len(s):len(s)].

+

func Clone

func Clone[S ~[]E, E any](s S) S

Clone returns a copy of the slice. The elements are copied using assignment, so this is a shallow clone.

+

func Compact

func Compact[S ~[]E, E comparable](s S) S

Compact replaces consecutive runs of equal elements with a single copy. This is like the uniq command found on Unix. Compact modifies the contents of the slice s and returns the modified slice, which may have a smaller length. Compact zeroes the elements between the new length and the original length.

Example +

Code:

seq := []int{0, 1, 1, 2, 3, 5, 8}
+seq = slices.Compact(seq)
+fmt.Println(seq)
+

Output:

[0 1 2 3 5 8]
+

func CompactFunc

func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S

CompactFunc is like Compact but uses an equality function to compare elements. For runs of elements that compare equal, CompactFunc keeps the first one. CompactFunc zeroes the elements between the new length and the original length.

Example +

Code:

names := []string{"bob", "Bob", "alice", "Vera", "VERA"}
+names = slices.CompactFunc(names, strings.EqualFold)
+fmt.Println(names)
+

Output:

[bob alice Vera]
+

func Compare

func Compare[S ~[]E, E cmp.Ordered](s1, s2 S) int

Compare compares the elements of s1 and s2, using cmp.Compare on each pair of elements. The elements are compared sequentially, starting at index 0, until one element is not equal to the other. The result of comparing the first non-matching elements is returned. If both slices are equal until one of them ends, the shorter slice is considered less than the longer one. The result is 0 if s1 == s2, -1 if s1 < s2, and +1 if s1 > s2.

Example +

Code:

names := []string{"Alice", "Bob", "Vera"}
+fmt.Println("Equal:", slices.Compare(names, []string{"Alice", "Bob", "Vera"}))
+fmt.Println("V < X:", slices.Compare(names, []string{"Alice", "Bob", "Xena"}))
+fmt.Println("V > C:", slices.Compare(names, []string{"Alice", "Bob", "Cat"}))
+fmt.Println("3 > 2:", slices.Compare(names, []string{"Alice", "Bob"}))
+

Output:

Equal: 0
+V < X: -1
+V > C: 1
+3 > 2: 1
+

func CompareFunc

func CompareFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, cmp func(E1, E2) int) int

CompareFunc is like Compare but uses a custom comparison function on each pair of elements. The result is the first non-zero result of cmp; if cmp always returns 0 the result is 0 if len(s1) == len(s2), -1 if len(s1) < len(s2), and +1 if len(s1) > len(s2).

Example +

Code:

numbers := []int{0, 43, 8}
+strings := []string{"0", "0", "8"}
+result := slices.CompareFunc(numbers, strings, func(n int, s string) int {
+    sn, err := strconv.Atoi(s)
+    if err != nil {
+        return 1
+    }
+    return cmp.Compare(n, sn)
+})
+fmt.Println(result)
+

Output:

1
+

func Concat

func Concat[S ~[]E, E any](slices ...S) S

Concat returns a new slice concatenating the passed in slices.

+

func Contains

func Contains[S ~[]E, E comparable](s S, v E) bool

Contains reports whether v is present in s.

+

func ContainsFunc

func ContainsFunc[S ~[]E, E any](s S, f func(E) bool) bool

ContainsFunc reports whether at least one element e of s satisfies f(e).

Example +

Code:

numbers := []int{0, 42, -10, 8}
+hasNegative := slices.ContainsFunc(numbers, func(n int) bool {
+    return n < 0
+})
+fmt.Println("Has a negative:", hasNegative)
+hasOdd := slices.ContainsFunc(numbers, func(n int) bool {
+    return n%2 != 0
+})
+fmt.Println("Has an odd number:", hasOdd)
+

Output:

Has a negative: true
+Has an odd number: false
+

func Delete

func Delete[S ~[]E, E any](s S, i, j int) S

Delete removes the elements s[i:j] from s, returning the modified slice. Delete panics if j > len(s) or s[i:j] is not a valid slice of s. Delete is O(len(s)-i), so if many items must be deleted, it is better to make a single call deleting them all together than to delete one at a time. Delete zeroes the elements s[len(s)-(j-i):len(s)].

Example +

Code:

letters := []string{"a", "b", "c", "d", "e"}
+letters = slices.Delete(letters, 1, 4)
+fmt.Println(letters)
+

Output:

[a e]
+

func DeleteFunc

func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S

DeleteFunc removes any elements from s for which del returns true, returning the modified slice. DeleteFunc zeroes the elements between the new length and the original length.

Example +

Code:

seq := []int{0, 1, 1, 2, 3, 5, 8}
+seq = slices.DeleteFunc(seq, func(n int) bool {
+    return n%2 != 0 // delete the odd numbers
+})
+fmt.Println(seq)
+

Output:

[0 2 8]
+

func Equal

func Equal[S ~[]E, E comparable](s1, s2 S) bool

Equal reports whether two slices are equal: the same length and all elements equal. If the lengths are different, Equal returns false. Otherwise, the elements are compared in increasing index order, and the comparison stops at the first unequal pair. Floating point NaNs are not considered equal.

Example +

Code:

numbers := []int{0, 42, 8}
+fmt.Println(slices.Equal(numbers, []int{0, 42, 8}))
+fmt.Println(slices.Equal(numbers, []int{10}))
+

Output:

true
+false
+

func EqualFunc

func EqualFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, eq func(E1, E2) bool) bool

EqualFunc reports whether two slices are equal using an equality function on each pair of elements. If the lengths are different, EqualFunc returns false. Otherwise, the elements are compared in increasing index order, and the comparison stops at the first index for which eq returns false.

Example +

Code:

numbers := []int{0, 42, 8}
+strings := []string{"000", "42", "0o10"}
+equal := slices.EqualFunc(numbers, strings, func(n int, s string) bool {
+    sn, err := strconv.ParseInt(s, 0, 64)
+    if err != nil {
+        return false
+    }
+    return n == int(sn)
+})
+fmt.Println(equal)
+

Output:

true
+

func Grow

func Grow[S ~[]E, E any](s S, n int) S

Grow increases the slice's capacity, if necessary, to guarantee space for another n elements. After Grow(n), at least n elements can be appended to the slice without another allocation. If n is negative or too large to allocate the memory, Grow panics.

+

func Index

func Index[S ~[]E, E comparable](s S, v E) int

Index returns the index of the first occurrence of v in s, or -1 if not present.

Example +

Code:

numbers := []int{0, 42, 8}
+fmt.Println(slices.Index(numbers, 8))
+fmt.Println(slices.Index(numbers, 7))
+

Output:

2
+-1
+

func IndexFunc

func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int

IndexFunc returns the first index i satisfying f(s[i]), or -1 if none do.

Example +

Code:

numbers := []int{0, 42, -10, 8}
+i := slices.IndexFunc(numbers, func(n int) bool {
+    return n < 0
+})
+fmt.Println("First negative at index", i)
+

Output:

First negative at index 2
+

func Insert

func Insert[S ~[]E, E any](s S, i int, v ...E) S

Insert inserts the values v... into s at index i, returning the modified slice. The elements at s[i:] are shifted up to make room. In the returned slice r, r[i] == v[0], and r[i+len(v)] == value originally at r[i]. Insert panics if i is out of range. This function is O(len(s) + len(v)).

Example +

Code:

names := []string{"Alice", "Bob", "Vera"}
+names = slices.Insert(names, 1, "Bill", "Billie")
+names = slices.Insert(names, len(names), "Zac")
+fmt.Println(names)
+

Output:

[Alice Bill Billie Bob Vera Zac]
+

func IsSorted

func IsSorted[S ~[]E, E cmp.Ordered](x S) bool

IsSorted reports whether x is sorted in ascending order.

Example +

Code:

fmt.Println(slices.IsSorted([]string{"Alice", "Bob", "Vera"}))
+fmt.Println(slices.IsSorted([]int{0, 2, 1}))
+

Output:

true
+false
+

func IsSortedFunc

func IsSortedFunc[S ~[]E, E any](x S, cmp func(a, b E) int) bool

IsSortedFunc reports whether x is sorted in ascending order, with cmp as the comparison function as defined by SortFunc.

Example +

Code:

names := []string{"alice", "Bob", "VERA"}
+isSortedInsensitive := slices.IsSortedFunc(names, func(a, b string) int {
+    return cmp.Compare(strings.ToLower(a), strings.ToLower(b))
+})
+fmt.Println(isSortedInsensitive)
+fmt.Println(slices.IsSorted(names))
+

Output:

true
+false
+

func Max

func Max[S ~[]E, E cmp.Ordered](x S) E

Max returns the maximal value in x. It panics if x is empty. For floating-point E, Max propagates NaNs (any NaN value in x forces the output to be NaN).

Example +

Code:

numbers := []int{0, 42, -10, 8}
+fmt.Println(slices.Max(numbers))
+

Output:

42
+

func MaxFunc

func MaxFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E

MaxFunc returns the maximal value in x, using cmp to compare elements. It panics if x is empty. If there is more than one maximal element according to the cmp function, MaxFunc returns the first one.

Example +

Code:

type Person struct {
+    Name string
+    Age  int
+}
+people := []Person{
+    {"Gopher", 13},
+    {"Alice", 55},
+    {"Vera", 24},
+    {"Bob", 55},
+}
+firstOldest := slices.MaxFunc(people, func(a, b Person) int {
+    return cmp.Compare(a.Age, b.Age)
+})
+fmt.Println(firstOldest.Name)
+

Output:

Alice
+

func Min

func Min[S ~[]E, E cmp.Ordered](x S) E

Min returns the minimal value in x. It panics if x is empty. For floating-point numbers, Min propagates NaNs (any NaN value in x forces the output to be NaN).

Example +

Code:

numbers := []int{0, 42, -10, 8}
+fmt.Println(slices.Min(numbers))
+

Output:

-10
+

func MinFunc

func MinFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E

MinFunc returns the minimal value in x, using cmp to compare elements. It panics if x is empty. If there is more than one minimal element according to the cmp function, MinFunc returns the first one.

Example +

Code:

type Person struct {
+    Name string
+    Age  int
+}
+people := []Person{
+    {"Gopher", 13},
+    {"Bob", 5},
+    {"Vera", 24},
+    {"Bill", 5},
+}
+firstYoungest := slices.MinFunc(people, func(a, b Person) int {
+    return cmp.Compare(a.Age, b.Age)
+})
+fmt.Println(firstYoungest.Name)
+

Output:

Bob
+

func Replace

func Replace[S ~[]E, E any](s S, i, j int, v ...E) S

Replace replaces the elements s[i:j] by the given v, and returns the modified slice. Replace panics if j > len(s) or s[i:j] is not a valid slice of s. When len(v) < (j-i), Replace zeroes the elements between the new length and the original length.

Example +

Code:

names := []string{"Alice", "Bob", "Vera", "Zac"}
+names = slices.Replace(names, 1, 3, "Bill", "Billie", "Cat")
+fmt.Println(names)
+

Output:

[Alice Bill Billie Cat Zac]
+

func Reverse

func Reverse[S ~[]E, E any](s S)

Reverse reverses the elements of the slice in place.

Example +

Code:

names := []string{"alice", "Bob", "VERA"}
+slices.Reverse(names)
+fmt.Println(names)
+

Output:

[VERA Bob alice]
+

func Sort

func Sort[S ~[]E, E cmp.Ordered](x S)

Sort sorts a slice of any ordered type in ascending order. When sorting floating-point numbers, NaNs are ordered before other values.

Example +

Code:

smallInts := []int8{0, 42, -10, 8}
+slices.Sort(smallInts)
+fmt.Println(smallInts)
+

Output:

[-10 0 8 42]
+

func SortFunc

func SortFunc[S ~[]E, E any](x S, cmp func(a, b E) int)

SortFunc sorts the slice x in ascending order as determined by the cmp function. This sort is not guaranteed to be stable. cmp(a, b) should return a negative number when a < b, a positive number when a > b and zero when a == b.

+

SortFunc requires that cmp is a strict weak ordering. See https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings.

Example (CaseInsensitive) +

Code:

names := []string{"Bob", "alice", "VERA"}
+slices.SortFunc(names, func(a, b string) int {
+    return cmp.Compare(strings.ToLower(a), strings.ToLower(b))
+})
+fmt.Println(names)
+

Output:

[alice Bob VERA]
+

Example (MultiField) +

Code:

type Person struct {
+    Name string
+    Age  int
+}
+people := []Person{
+    {"Gopher", 13},
+    {"Alice", 55},
+    {"Bob", 24},
+    {"Alice", 20},
+}
+slices.SortFunc(people, func(a, b Person) int {
+    if n := cmp.Compare(a.Name, b.Name); n != 0 {
+        return n
+    }
+    // If names are equal, order by age
+    return cmp.Compare(a.Age, b.Age)
+})
+fmt.Println(people)
+

Output:

[{Alice 20} {Alice 55} {Bob 24} {Gopher 13}]
+

func SortStableFunc

func SortStableFunc[S ~[]E, E any](x S, cmp func(a, b E) int)

SortStableFunc sorts the slice x while keeping the original order of equal elements, using cmp to compare elements in the same way as SortFunc.

Example +

Code:

type Person struct {
+    Name string
+    Age  int
+}
+people := []Person{
+    {"Gopher", 13},
+    {"Alice", 20},
+    {"Bob", 24},
+    {"Alice", 55},
+}
+// Stable sort by name, keeping age ordering of Alices intact
+slices.SortStableFunc(people, func(a, b Person) int {
+    return cmp.Compare(a.Name, b.Name)
+})
+fmt.Println(people)
+

Output:

[{Alice 20} {Alice 55} {Bob 24} {Gopher 13}]
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/slices/ +

+
diff --git a/devdocs/go/sort%2Findex.html b/devdocs/go/sort%2Findex.html new file mode 100644 index 00000000..3e37b155 --- /dev/null +++ b/devdocs/go/sort%2Findex.html @@ -0,0 +1,648 @@ +

Package sort

Overview

Package sort provides primitives for sorting slices and user-defined collections.

Example +

Code:

package sort_test
+
+import (
+    "fmt"
+    "sort"
+)
+
+type Person struct {
+    Name string
+    Age  int
+}
+
+func (p Person) String() string {
+    return fmt.Sprintf("%s: %d", p.Name, p.Age)
+}
+
+// ByAge implements sort.Interface for []Person based on
+// the Age field.
+type ByAge []Person
+
+func (a ByAge) Len() int           { return len(a) }
+func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
+func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
+
+func Example() {
+    people := []Person{
+        {"Bob", 31},
+        {"John", 42},
+        {"Michael", 17},
+        {"Jenny", 26},
+    }
+
+    fmt.Println(people)
+    // There are two ways to sort a slice. First, one can define
+    // a set of methods for the slice type, as with ByAge, and
+    // call sort.Sort. In this first example we use that technique.
+    sort.Sort(ByAge(people))
+    fmt.Println(people)
+
+    // The other way is to use sort.Slice with a custom Less
+    // function, which can be provided as a closure. In this
+    // case no methods are needed. (And if they exist, they
+    // are ignored.) Here we re-sort in reverse order: compare
+    // the closure with ByAge.Less.
+    sort.Slice(people, func(i, j int) bool {
+        return people[i].Age > people[j].Age
+    })
+    fmt.Println(people)
+
+    // Output:
+    // [Bob: 31 John: 42 Michael: 17 Jenny: 26]
+    // [Michael: 17 Jenny: 26 Bob: 31 John: 42]
+    // [John: 42 Bob: 31 Jenny: 26 Michael: 17]
+}
+

Example (SortKeys) +

ExampleSortKeys demonstrates a technique for sorting a struct type using programmable sort criteria.

Code:

package sort_test
+
+import (
+    "fmt"
+    "sort"
+)
+
+// A couple of type definitions to make the units clear.
+type earthMass float64
+type au float64
+
+// A Planet defines the properties of a solar system object.
+type Planet struct {
+    name     string
+    mass     earthMass
+    distance au
+}
+
+// By is the type of a "less" function that defines the ordering of its Planet arguments.
+type By func(p1, p2 *Planet) bool
+
+// Sort is a method on the function type, By, that sorts the argument slice according to the function.
+func (by By) Sort(planets []Planet) {
+    ps := &planetSorter{
+        planets: planets,
+        by:      by, // The Sort method's receiver is the function (closure) that defines the sort order.
+    }
+    sort.Sort(ps)
+}
+
+// planetSorter joins a By function and a slice of Planets to be sorted.
+type planetSorter struct {
+    planets []Planet
+    by      func(p1, p2 *Planet) bool // Closure used in the Less method.
+}
+
+// Len is part of sort.Interface.
+func (s *planetSorter) Len() int {
+    return len(s.planets)
+}
+
+// Swap is part of sort.Interface.
+func (s *planetSorter) Swap(i, j int) {
+    s.planets[i], s.planets[j] = s.planets[j], s.planets[i]
+}
+
+// Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter.
+func (s *planetSorter) Less(i, j int) bool {
+    return s.by(&s.planets[i], &s.planets[j])
+}
+
+var planets = []Planet{
+    {"Mercury", 0.055, 0.4},
+    {"Venus", 0.815, 0.7},
+    {"Earth", 1.0, 1.0},
+    {"Mars", 0.107, 1.5},
+}
+
+// ExampleSortKeys demonstrates a technique for sorting a struct type using programmable sort criteria.
+func Example_sortKeys() {
+    // Closures that order the Planet structure.
+    name := func(p1, p2 *Planet) bool {
+        return p1.name < p2.name
+    }
+    mass := func(p1, p2 *Planet) bool {
+        return p1.mass < p2.mass
+    }
+    distance := func(p1, p2 *Planet) bool {
+        return p1.distance < p2.distance
+    }
+    decreasingDistance := func(p1, p2 *Planet) bool {
+        return distance(p2, p1)
+    }
+
+    // Sort the planets by the various criteria.
+    By(name).Sort(planets)
+    fmt.Println("By name:", planets)
+
+    By(mass).Sort(planets)
+    fmt.Println("By mass:", planets)
+
+    By(distance).Sort(planets)
+    fmt.Println("By distance:", planets)
+
+    By(decreasingDistance).Sort(planets)
+    fmt.Println("By decreasing distance:", planets)
+
+    // Output: By name: [{Earth 1 1} {Mars 0.107 1.5} {Mercury 0.055 0.4} {Venus 0.815 0.7}]
+    // By mass: [{Mercury 0.055 0.4} {Mars 0.107 1.5} {Venus 0.815 0.7} {Earth 1 1}]
+    // By distance: [{Mercury 0.055 0.4} {Venus 0.815 0.7} {Earth 1 1} {Mars 0.107 1.5}]
+    // By decreasing distance: [{Mars 0.107 1.5} {Earth 1 1} {Venus 0.815 0.7} {Mercury 0.055 0.4}]
+}
+

Example (SortMultiKeys) +

ExampleMultiKeys demonstrates a technique for sorting a struct type using different sets of multiple fields in the comparison. We chain together "Less" functions, each of which compares a single field.

Code:

package sort_test
+
+import (
+    "fmt"
+    "sort"
+)
+
+// A Change is a record of source code changes, recording user, language, and delta size.
+type Change struct {
+    user     string
+    language string
+    lines    int
+}
+
+type lessFunc func(p1, p2 *Change) bool
+
+// multiSorter implements the Sort interface, sorting the changes within.
+type multiSorter struct {
+    changes []Change
+    less    []lessFunc
+}
+
+// Sort sorts the argument slice according to the less functions passed to OrderedBy.
+func (ms *multiSorter) Sort(changes []Change) {
+    ms.changes = changes
+    sort.Sort(ms)
+}
+
+// OrderedBy returns a Sorter that sorts using the less functions, in order.
+// Call its Sort method to sort the data.
+func OrderedBy(less ...lessFunc) *multiSorter {
+    return &multiSorter{
+        less: less,
+    }
+}
+
+// Len is part of sort.Interface.
+func (ms *multiSorter) Len() int {
+    return len(ms.changes)
+}
+
+// Swap is part of sort.Interface.
+func (ms *multiSorter) Swap(i, j int) {
+    ms.changes[i], ms.changes[j] = ms.changes[j], ms.changes[i]
+}
+
+// Less is part of sort.Interface. It is implemented by looping along the
+// less functions until it finds a comparison that discriminates between
+// the two items (one is less than the other). Note that it can call the
+// less functions twice per call. We could change the functions to return
+// -1, 0, 1 and reduce the number of calls for greater efficiency: an
+// exercise for the reader.
+func (ms *multiSorter) Less(i, j int) bool {
+    p, q := &ms.changes[i], &ms.changes[j]
+    // Try all but the last comparison.
+    var k int
+    for k = 0; k < len(ms.less)-1; k++ {
+        less := ms.less[k]
+        switch {
+        case less(p, q):
+            // p < q, so we have a decision.
+            return true
+        case less(q, p):
+            // p > q, so we have a decision.
+            return false
+        }
+        // p == q; try the next comparison.
+    }
+    // All comparisons to here said "equal", so just return whatever
+    // the final comparison reports.
+    return ms.less[k](p, q)
+}
+
+var changes = []Change{
+    {"gri", "Go", 100},
+    {"ken", "C", 150},
+    {"glenda", "Go", 200},
+    {"rsc", "Go", 200},
+    {"r", "Go", 100},
+    {"ken", "Go", 200},
+    {"dmr", "C", 100},
+    {"r", "C", 150},
+    {"gri", "Smalltalk", 80},
+}
+
+// ExampleMultiKeys demonstrates a technique for sorting a struct type using different
+// sets of multiple fields in the comparison. We chain together "Less" functions, each of
+// which compares a single field.
+func Example_sortMultiKeys() {
+    // Closures that order the Change structure.
+    user := func(c1, c2 *Change) bool {
+        return c1.user < c2.user
+    }
+    language := func(c1, c2 *Change) bool {
+        return c1.language < c2.language
+    }
+    increasingLines := func(c1, c2 *Change) bool {
+        return c1.lines < c2.lines
+    }
+    decreasingLines := func(c1, c2 *Change) bool {
+        return c1.lines > c2.lines // Note: > orders downwards.
+    }
+
+    // Simple use: Sort by user.
+    OrderedBy(user).Sort(changes)
+    fmt.Println("By user:", changes)
+
+    // More examples.
+    OrderedBy(user, increasingLines).Sort(changes)
+    fmt.Println("By user,<lines:", changes)
+
+    OrderedBy(user, decreasingLines).Sort(changes)
+    fmt.Println("By user,>lines:", changes)
+
+    OrderedBy(language, increasingLines).Sort(changes)
+    fmt.Println("By language,<lines:", changes)
+
+    OrderedBy(language, increasingLines, user).Sort(changes)
+    fmt.Println("By language,<lines,user:", changes)
+
+    // Output:
+    // By user: [{dmr C 100} {glenda Go 200} {gri Go 100} {gri Smalltalk 80} {ken C 150} {ken Go 200} {r Go 100} {r C 150} {rsc Go 200}]
+    // By user,<lines: [{dmr C 100} {glenda Go 200} {gri Smalltalk 80} {gri Go 100} {ken C 150} {ken Go 200} {r Go 100} {r C 150} {rsc Go 200}]
+    // By user,>lines: [{dmr C 100} {glenda Go 200} {gri Go 100} {gri Smalltalk 80} {ken Go 200} {ken C 150} {r C 150} {r Go 100} {rsc Go 200}]
+    // By language,<lines: [{dmr C 100} {ken C 150} {r C 150} {gri Go 100} {r Go 100} {glenda Go 200} {ken Go 200} {rsc Go 200} {gri Smalltalk 80}]
+    // By language,<lines,user: [{dmr C 100} {ken C 150} {r C 150} {gri Go 100} {r Go 100} {glenda Go 200} {ken Go 200} {rsc Go 200} {gri Smalltalk 80}]
+
+}
+

Example (SortWrapper) +

Code:

package sort_test
+
+import (
+    "fmt"
+    "sort"
+)
+
+type Grams int
+
+func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }
+
+type Organ struct {
+    Name   string
+    Weight Grams
+}
+
+type Organs []*Organ
+
+func (s Organs) Len() int      { return len(s) }
+func (s Organs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+
+// ByName implements sort.Interface by providing Less and using the Len and
+// Swap methods of the embedded Organs value.
+type ByName struct{ Organs }
+
+func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }
+
+// ByWeight implements sort.Interface by providing Less and using the Len and
+// Swap methods of the embedded Organs value.
+type ByWeight struct{ Organs }
+
+func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < s.Organs[j].Weight }
+
+func Example_sortWrapper() {
+    s := []*Organ{
+        {"brain", 1340},
+        {"heart", 290},
+        {"liver", 1494},
+        {"pancreas", 131},
+        {"prostate", 62},
+        {"spleen", 162},
+    }
+
+    sort.Sort(ByWeight{s})
+    fmt.Println("Organs by weight:")
+    printOrgans(s)
+
+    sort.Sort(ByName{s})
+    fmt.Println("Organs by name:")
+    printOrgans(s)
+
+    // Output:
+    // Organs by weight:
+    // prostate (62g)
+    // pancreas (131g)
+    // spleen   (162g)
+    // heart    (290g)
+    // brain    (1340g)
+    // liver    (1494g)
+    // Organs by name:
+    // brain    (1340g)
+    // heart    (290g)
+    // liver    (1494g)
+    // pancreas (131g)
+    // prostate (62g)
+    // spleen   (162g)
+}
+
+func printOrgans(s []*Organ) {
+    for _, o := range s {
+        fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)
+    }
+}
+

Index

Examples

Package
Float64s
Float64sAreSorted
Ints
IntsAreSorted
Reverse
Search
SearchFloat64s
SearchInts
Search (DescendingOrder)
Slice
SliceStable
Strings
Package (SortKeys)
Package (SortMultiKeys)
Package (SortWrapper)

Package files

search.go slice.go sort.go sort_impl_go121.go zsortfunc.go zsortinterface.go

func Find 1.19

func Find(n int, cmp func(int) int) (i int, found bool)

Find uses binary search to find and return the smallest index i in [0, n) at which cmp(i) <= 0. If there is no such index i, Find returns i = n. The found result is true if i < n and cmp(i) == 0. Find calls cmp(i) only for i in the range [0, n).

+

To permit binary search, Find requires that cmp(i) > 0 for a leading prefix of the range, cmp(i) == 0 in the middle, and cmp(i) < 0 for the final suffix of the range. (Each subrange could be empty.) The usual way to establish this condition is to interpret cmp(i) as a comparison of a desired target value t against entry i in an underlying indexed data structure x, returning <0, 0, and >0 when t < x[i], t == x[i], and t > x[i], respectively.

+

For example, to look for a particular string in a sorted, random-access list of strings:

+
i, found := sort.Find(x.Len(), func(i int) int {
+    return strings.Compare(target, x.At(i))
+})
+if found {
+    fmt.Printf("found %s at entry %d\n", target, i)
+} else {
+    fmt.Printf("%s not found, would insert at %d", target, i)
+}
+

func Float64s

func Float64s(x []float64)

Float64s sorts a slice of float64s in increasing order. Not-a-number (NaN) values are ordered before other values.

+

Note: as of Go 1.22, this function simply calls slices.Sort.

Example +

Code:

s := []float64{5.2, -1.3, 0.7, -3.8, 2.6} // unsorted
+sort.Float64s(s)
+fmt.Println(s)
+
+s = []float64{math.Inf(1), math.NaN(), math.Inf(-1), 0.0} // unsorted
+sort.Float64s(s)
+fmt.Println(s)
+
+

Output:

[-3.8 -1.3 0.7 2.6 5.2]
+[NaN -Inf 0 +Inf]
+

func Float64sAreSorted

func Float64sAreSorted(x []float64) bool

Float64sAreSorted reports whether the slice x is sorted in increasing order, with not-a-number (NaN) values before any other values.

+

Note: as of Go 1.22, this function simply calls slices.IsSorted.

Example +

Code:

s := []float64{0.7, 1.3, 2.6, 3.8, 5.2} // sorted ascending
+fmt.Println(sort.Float64sAreSorted(s))
+
+s = []float64{5.2, 3.8, 2.6, 1.3, 0.7} // sorted descending
+fmt.Println(sort.Float64sAreSorted(s))
+
+s = []float64{5.2, 1.3, 0.7, 3.8, 2.6} // unsorted
+fmt.Println(sort.Float64sAreSorted(s))
+
+

Output:

true
+false
+false
+

func Ints

func Ints(x []int)

Ints sorts a slice of ints in increasing order.

+

Note: as of Go 1.22, this function simply calls slices.Sort.

Example +

Code:

s := []int{5, 2, 6, 3, 1, 4} // unsorted
+sort.Ints(s)
+fmt.Println(s)
+

Output:

[1 2 3 4 5 6]
+

func IntsAreSorted

func IntsAreSorted(x []int) bool

IntsAreSorted reports whether the slice x is sorted in increasing order.

+

Note: as of Go 1.22, this function simply calls slices.IsSorted.

Example +

Code:

s := []int{1, 2, 3, 4, 5, 6} // sorted ascending
+fmt.Println(sort.IntsAreSorted(s))
+
+s = []int{6, 5, 4, 3, 2, 1} // sorted descending
+fmt.Println(sort.IntsAreSorted(s))
+
+s = []int{3, 2, 4, 1, 5} // unsorted
+fmt.Println(sort.IntsAreSorted(s))
+
+

Output:

true
+false
+false
+

func IsSorted

func IsSorted(data Interface) bool

IsSorted reports whether data is sorted.

+

Note: in many situations, the newer slices.IsSortedFunc function is more ergonomic and runs faster.

+
func Search(n int, f func(int) bool) int

Search uses binary search to find and return the smallest index i in [0, n) at which f(i) is true, assuming that on the range [0, n), f(i) == true implies f(i+1) == true. That is, Search requires that f is false for some (possibly empty) prefix of the input range [0, n) and then true for the (possibly empty) remainder; Search returns the first true index. If there is no such index, Search returns n. (Note that the "not found" return value is not -1 as in, for instance, strings.Index.) Search calls f(i) only for i in the range [0, n).

+

A common use of Search is to find the index i for a value x in a sorted, indexable data structure such as an array or slice. In this case, the argument f, typically a closure, captures the value to be searched for, and how the data structure is indexed and ordered.

+

For instance, given a slice data sorted in ascending order, the call Search(len(data), func(i int) bool { return data[i] >= 23 }) returns the smallest index i such that data[i] >= 23. If the caller wants to find whether 23 is in the slice, it must test data[i] == 23 separately.

+

Searching data sorted in descending order would use the <= operator instead of the >= operator.

+

To complete the example above, the following code tries to find the value x in an integer slice data sorted in ascending order:

+
x := 23
+i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
+if i < len(data) && data[i] == x {
+	// x is present at data[i]
+} else {
+	// x is not present in data,
+	// but i is the index where it would be inserted.
+}
+

As a more whimsical example, this program guesses your number:

+
func GuessingGame() {
+	var s string
+	fmt.Printf("Pick an integer from 0 to 100.\n")
+	answer := sort.Search(100, func(i int) bool {
+		fmt.Printf("Is your number <= %d? ", i)
+		fmt.Scanf("%s", &s)
+		return s != "" && s[0] == 'y'
+	})
+	fmt.Printf("Your number is %d.\n", answer)
+}
+

This example demonstrates searching a list sorted in ascending order.

Code:

a := []int{1, 3, 6, 10, 15, 21, 28, 36, 45, 55}
+x := 6
+
+i := sort.Search(len(a), func(i int) bool { return a[i] >= x })
+if i < len(a) && a[i] == x {
+    fmt.Printf("found %d at index %d in %v\n", x, i, a)
+} else {
+    fmt.Printf("%d not found in %v\n", x, a)
+}
+

Output:

found 6 at index 2 in [1 3 6 10 15 21 28 36 45 55]
+

Example (DescendingOrder) +

This example demonstrates searching a list sorted in descending order. The approach is the same as searching a list in ascending order, but with the condition inverted.

Code:

a := []int{55, 45, 36, 28, 21, 15, 10, 6, 3, 1}
+x := 6
+
+i := sort.Search(len(a), func(i int) bool { return a[i] <= x })
+if i < len(a) && a[i] == x {
+    fmt.Printf("found %d at index %d in %v\n", x, i, a)
+} else {
+    fmt.Printf("%d not found in %v\n", x, a)
+}
+

Output:

found 6 at index 7 in [55 45 36 28 21 15 10 6 3 1]
+

func SearchFloat64s

func SearchFloat64s(a []float64, x float64) int

SearchFloat64s searches for x in a sorted slice of float64s and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.

Example +

This example demonstrates searching for float64 in a list sorted in ascending order.

Code:

a := []float64{1.0, 2.0, 3.3, 4.6, 6.1, 7.2, 8.0}
+
+x := 2.0
+i := sort.SearchFloat64s(a, x)
+fmt.Printf("found %g at index %d in %v\n", x, i, a)
+
+x = 0.5
+i = sort.SearchFloat64s(a, x)
+fmt.Printf("%g not found, can be inserted at index %d in %v\n", x, i, a)
+

Output:

found 2 at index 1 in [1 2 3.3 4.6 6.1 7.2 8]
+0.5 not found, can be inserted at index 0 in [1 2 3.3 4.6 6.1 7.2 8]
+

func SearchInts

func SearchInts(a []int, x int) int

SearchInts searches for x in a sorted slice of ints and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.

Example +

This example demonstrates searching for int in a list sorted in ascending order.

Code:

a := []int{1, 2, 3, 4, 6, 7, 8}
+
+x := 2
+i := sort.SearchInts(a, x)
+fmt.Printf("found %d at index %d in %v\n", x, i, a)
+
+x = 5
+i = sort.SearchInts(a, x)
+fmt.Printf("%d not found, can be inserted at index %d in %v\n", x, i, a)
+

Output:

found 2 at index 1 in [1 2 3 4 6 7 8]
+5 not found, can be inserted at index 4 in [1 2 3 4 6 7 8]
+

func SearchStrings

func SearchStrings(a []string, x string) int

SearchStrings searches for x in a sorted slice of strings and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.

+

func Slice 1.8

func Slice(x any, less func(i, j int) bool)

Slice sorts the slice x given the provided less function. It panics if x is not a slice.

+

The sort is not guaranteed to be stable: equal elements may be reversed from their original order. For a stable sort, use SliceStable.

+

The less function must satisfy the same requirements as the Interface type's Less method.

+

Note: in many situations, the newer slices.SortFunc function is more ergonomic and runs faster.

Example +

Code:

people := []struct {
+    Name string
+    Age  int
+}{
+    {"Gopher", 7},
+    {"Alice", 55},
+    {"Vera", 24},
+    {"Bob", 75},
+}
+sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
+fmt.Println("By name:", people)
+
+sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
+fmt.Println("By age:", people)
+

Output:

By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
+By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]
+

func SliceIsSorted 1.8

func SliceIsSorted(x any, less func(i, j int) bool) bool

SliceIsSorted reports whether the slice x is sorted according to the provided less function. It panics if x is not a slice.

+

Note: in many situations, the newer slices.IsSortedFunc function is more ergonomic and runs faster.

+

func SliceStable 1.8

func SliceStable(x any, less func(i, j int) bool)

SliceStable sorts the slice x using the provided less function, keeping equal elements in their original order. It panics if x is not a slice.

+

The less function must satisfy the same requirements as the Interface type's Less method.

+

Note: in many situations, the newer slices.SortStableFunc function is more ergonomic and runs faster.

Example +

Code:

people := []struct {
+    Name string
+    Age  int
+}{
+    {"Alice", 25},
+    {"Elizabeth", 75},
+    {"Alice", 75},
+    {"Bob", 75},
+    {"Alice", 75},
+    {"Bob", 25},
+    {"Colin", 25},
+    {"Elizabeth", 25},
+}
+
+// Sort by name, preserving original order
+sort.SliceStable(people, func(i, j int) bool { return people[i].Name < people[j].Name })
+fmt.Println("By name:", people)
+
+// Sort by age preserving name order
+sort.SliceStable(people, func(i, j int) bool { return people[i].Age < people[j].Age })
+fmt.Println("By age,name:", people)
+
+

Output:

By name: [{Alice 25} {Alice 75} {Alice 75} {Bob 75} {Bob 25} {Colin 25} {Elizabeth 75} {Elizabeth 25}]
+By age,name: [{Alice 25} {Bob 25} {Colin 25} {Elizabeth 25} {Alice 75} {Alice 75} {Bob 75} {Elizabeth 75}]
+

func Sort

func Sort(data Interface)

Sort sorts data in ascending order as determined by the Less method. It makes one call to data.Len to determine n and O(n*log(n)) calls to data.Less and data.Swap. The sort is not guaranteed to be stable.

+

Note: in many situations, the newer slices.SortFunc function is more ergonomic and runs faster.

+

func Stable 1.2

func Stable(data Interface)

Stable sorts data in ascending order as determined by the Less method, while keeping the original order of equal elements.

+

It makes one call to data.Len to determine n, O(n*log(n)) calls to data.Less and O(n*log(n)*log(n)) calls to data.Swap.

+

Note: in many situations, the newer slices.SortStableFunc function is more ergonomic and runs faster.

+

func Strings

func Strings(x []string)

Strings sorts a slice of strings in increasing order.

+

Note: as of Go 1.22, this function simply calls slices.Sort.

Example +

Code:

s := []string{"Go", "Bravo", "Gopher", "Alpha", "Grin", "Delta"}
+sort.Strings(s)
+fmt.Println(s)
+

Output:

[Alpha Bravo Delta Go Gopher Grin]
+

func StringsAreSorted

func StringsAreSorted(x []string) bool

StringsAreSorted reports whether the slice x is sorted in increasing order.

+

Note: as of Go 1.22, this function simply calls slices.IsSorted.

+

type Float64Slice

Float64Slice implements Interface for a []float64, sorting in increasing order, with not-a-number (NaN) values ordered before other values.

+
type Float64Slice []float64

func (Float64Slice) Len

func (x Float64Slice) Len() int

func (Float64Slice) Less

func (x Float64Slice) Less(i, j int) bool

Less reports whether x[i] should be ordered before x[j], as required by the sort Interface. Note that floating-point comparison by itself is not a transitive relation: it does not report a consistent ordering for not-a-number (NaN) values. This implementation of Less places NaN values before any others, by using:

+
x[i] < x[j] || (math.IsNaN(x[i]) && !math.IsNaN(x[j]))
+

func (Float64Slice) Search

func (p Float64Slice) Search(x float64) int

Search returns the result of applying SearchFloat64s to the receiver and x.

+

func (Float64Slice) Sort

func (x Float64Slice) Sort()

Sort is a convenience method: x.Sort() calls Sort(x).

+

func (Float64Slice) Swap

func (x Float64Slice) Swap(i, j int)

type IntSlice

IntSlice attaches the methods of Interface to []int, sorting in increasing order.

+
type IntSlice []int

func (IntSlice) Len

func (x IntSlice) Len() int

func (IntSlice) Less

func (x IntSlice) Less(i, j int) bool

func (IntSlice) Search

func (p IntSlice) Search(x int) int

Search returns the result of applying SearchInts to the receiver and x.

+

func (IntSlice) Sort

func (x IntSlice) Sort()

Sort is a convenience method: x.Sort() calls Sort(x).

+

func (IntSlice) Swap

func (x IntSlice) Swap(i, j int)

type Interface

An implementation of Interface can be sorted by the routines in this package. The methods refer to elements of the underlying collection by integer index.

+
type Interface interface {
+    // Len is the number of elements in the collection.
+    Len() int
+
+    // Less reports whether the element with index i
+    // must sort before the element with index j.
+    //
+    // If both Less(i, j) and Less(j, i) are false,
+    // then the elements at index i and j are considered equal.
+    // Sort may place equal elements in any order in the final result,
+    // while Stable preserves the original input order of equal elements.
+    //
+    // Less must describe a transitive ordering:
+    //  - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
+    //  - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
+    //
+    // Note that floating-point comparison (the < operator on float32 or float64 values)
+    // is not a transitive ordering when not-a-number (NaN) values are involved.
+    // See Float64Slice.Less for a correct implementation for floating-point values.
+    Less(i, j int) bool
+
+    // Swap swaps the elements with indexes i and j.
+    Swap(i, j int)
+}

func Reverse 1.1

func Reverse(data Interface) Interface

Reverse returns the reverse order for data.

Example +

Code:

s := []int{5, 2, 6, 3, 1, 4} // unsorted
+sort.Sort(sort.Reverse(sort.IntSlice(s)))
+fmt.Println(s)
+

Output:

[6 5 4 3 2 1]
+

type StringSlice

StringSlice attaches the methods of Interface to []string, sorting in increasing order.

+
type StringSlice []string

func (StringSlice) Len

func (x StringSlice) Len() int

func (StringSlice) Less

func (x StringSlice) Less(i, j int) bool

func (StringSlice) Search

func (p StringSlice) Search(x string) int

Search returns the result of applying SearchStrings to the receiver and x.

+

func (StringSlice) Sort

func (x StringSlice) Sort()

Sort is a convenience method: x.Sort() calls Sort(x).

+

func (StringSlice) Swap

func (x StringSlice) Swap(i, j int)
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/sort/ +

+
diff --git a/devdocs/go/strconv%2Findex.html b/devdocs/go/strconv%2Findex.html new file mode 100644 index 00000000..eb7a5d97 --- /dev/null +++ b/devdocs/go/strconv%2Findex.html @@ -0,0 +1,449 @@ +

Package strconv

Overview

Package strconv implements conversions to and from string representations of basic data types.

+

Numeric Conversions

The most common numeric conversions are Atoi (string to int) and Itoa (int to string).

+
i, err := strconv.Atoi("-42")
+s := strconv.Itoa(-42)
+

These assume decimal and the Go int type.

+

ParseBool, ParseFloat, ParseInt, and ParseUint convert strings to values:

+
b, err := strconv.ParseBool("true")
+f, err := strconv.ParseFloat("3.1415", 64)
+i, err := strconv.ParseInt("-42", 10, 64)
+u, err := strconv.ParseUint("42", 10, 64)
+

The parse functions return the widest type (float64, int64, and uint64), but if the size argument specifies a narrower width the result can be converted to that narrower type without data loss:

+
s := "2147483647" // biggest int32
+i64, err := strconv.ParseInt(s, 10, 32)
+...
+i := int32(i64)
+

FormatBool, FormatFloat, FormatInt, and FormatUint convert values to strings:

+
s := strconv.FormatBool(true)
+s := strconv.FormatFloat(3.1415, 'E', -1, 64)
+s := strconv.FormatInt(-42, 16)
+s := strconv.FormatUint(42, 16)
+

AppendBool, AppendFloat, AppendInt, and AppendUint are similar but append the formatted value to a destination slice.

+

String Conversions

Quote and QuoteToASCII convert strings to quoted Go string literals. The latter guarantees that the result is an ASCII string, by escaping any non-ASCII Unicode with \u:

+
q := strconv.Quote("Hello, 世界")
+q := strconv.QuoteToASCII("Hello, 世界")
+

QuoteRune and QuoteRuneToASCII are similar but accept runes and return quoted Go rune literals.

+

Unquote and UnquoteChar unquote Go string and rune literals.

Index

Examples

AppendBool
AppendFloat
AppendInt
AppendQuote
AppendQuoteRune
AppendQuoteRuneToASCII
AppendQuoteToASCII
AppendUint
Atoi
CanBackquote
FormatBool
FormatFloat
FormatInt
FormatUint
IsGraphic
IsPrint
Itoa
NumError
ParseBool
ParseFloat
ParseInt
ParseUint
Quote
QuoteRune
QuoteRuneToASCII
QuoteRuneToGraphic
QuoteToASCII
QuoteToGraphic
QuotedPrefix
Unquote
UnquoteChar

Package files

atob.go atoc.go atof.go atoi.go bytealg.go ctoa.go decimal.go doc.go eisel_lemire.go ftoa.go ftoaryu.go isprint.go itoa.go quote.go

Constants

IntSize is the size in bits of an int or uint value.

+
const IntSize = intSize

Variables

ErrRange indicates that a value is out of range for the target type.

+
var ErrRange = errors.New("value out of range")

ErrSyntax indicates that a value does not have the right syntax for the target type.

+
var ErrSyntax = errors.New("invalid syntax")

func AppendBool

func AppendBool(dst []byte, b bool) []byte

AppendBool appends "true" or "false", according to the value of b, to dst and returns the extended buffer.

Example +

Code:

b := []byte("bool:")
+b = strconv.AppendBool(b, true)
+fmt.Println(string(b))
+
+

Output:

bool:true
+

func AppendFloat

func AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte

AppendFloat appends the string form of the floating-point number f, as generated by FormatFloat, to dst and returns the extended buffer.

Example +

Code:

b32 := []byte("float32:")
+b32 = strconv.AppendFloat(b32, 3.1415926535, 'E', -1, 32)
+fmt.Println(string(b32))
+
+b64 := []byte("float64:")
+b64 = strconv.AppendFloat(b64, 3.1415926535, 'E', -1, 64)
+fmt.Println(string(b64))
+
+

Output:

float32:3.1415927E+00
+float64:3.1415926535E+00
+

func AppendInt

func AppendInt(dst []byte, i int64, base int) []byte

AppendInt appends the string form of the integer i, as generated by FormatInt, to dst and returns the extended buffer.

Example +

Code:

b10 := []byte("int (base 10):")
+b10 = strconv.AppendInt(b10, -42, 10)
+fmt.Println(string(b10))
+
+b16 := []byte("int (base 16):")
+b16 = strconv.AppendInt(b16, -42, 16)
+fmt.Println(string(b16))
+
+

Output:

int (base 10):-42
+int (base 16):-2a
+

func AppendQuote

func AppendQuote(dst []byte, s string) []byte

AppendQuote appends a double-quoted Go string literal representing s, as generated by Quote, to dst and returns the extended buffer.

Example +

Code:

b := []byte("quote:")
+b = strconv.AppendQuote(b, `"Fran & Freddie's Diner"`)
+fmt.Println(string(b))
+
+

Output:

quote:"\"Fran & Freddie's Diner\""
+

func AppendQuoteRune

func AppendQuoteRune(dst []byte, r rune) []byte

AppendQuoteRune appends a single-quoted Go character literal representing the rune, as generated by QuoteRune, to dst and returns the extended buffer.

Example +

Code:

b := []byte("rune:")
+b = strconv.AppendQuoteRune(b, '☺')
+fmt.Println(string(b))
+
+

Output:

rune:'☺'
+

func AppendQuoteRuneToASCII

func AppendQuoteRuneToASCII(dst []byte, r rune) []byte

AppendQuoteRuneToASCII appends a single-quoted Go character literal representing the rune, as generated by QuoteRuneToASCII, to dst and returns the extended buffer.

Example +

Code:

b := []byte("rune (ascii):")
+b = strconv.AppendQuoteRuneToASCII(b, '☺')
+fmt.Println(string(b))
+
+

Output:

rune (ascii):'\u263a'
+

func AppendQuoteRuneToGraphic 1.6

func AppendQuoteRuneToGraphic(dst []byte, r rune) []byte

AppendQuoteRuneToGraphic appends a single-quoted Go character literal representing the rune, as generated by QuoteRuneToGraphic, to dst and returns the extended buffer.

+

func AppendQuoteToASCII

func AppendQuoteToASCII(dst []byte, s string) []byte

AppendQuoteToASCII appends a double-quoted Go string literal representing s, as generated by QuoteToASCII, to dst and returns the extended buffer.

Example +

Code:

b := []byte("quote (ascii):")
+b = strconv.AppendQuoteToASCII(b, `"Fran & Freddie's Diner"`)
+fmt.Println(string(b))
+
+

Output:

quote (ascii):"\"Fran & Freddie's Diner\""
+

func AppendQuoteToGraphic 1.6

func AppendQuoteToGraphic(dst []byte, s string) []byte

AppendQuoteToGraphic appends a double-quoted Go string literal representing s, as generated by QuoteToGraphic, to dst and returns the extended buffer.

+

func AppendUint

func AppendUint(dst []byte, i uint64, base int) []byte

AppendUint appends the string form of the unsigned integer i, as generated by FormatUint, to dst and returns the extended buffer.

Example +

Code:

b10 := []byte("uint (base 10):")
+b10 = strconv.AppendUint(b10, 42, 10)
+fmt.Println(string(b10))
+
+b16 := []byte("uint (base 16):")
+b16 = strconv.AppendUint(b16, 42, 16)
+fmt.Println(string(b16))
+
+

Output:

uint (base 10):42
+uint (base 16):2a
+

func Atoi

func Atoi(s string) (int, error)

Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.

Example +

Code:

v := "10"
+if s, err := strconv.Atoi(v); err == nil {
+    fmt.Printf("%T, %v", s, s)
+}
+
+

Output:

int, 10
+

func CanBackquote

func CanBackquote(s string) bool

CanBackquote reports whether the string s can be represented unchanged as a single-line backquoted string without control characters other than tab.

Example +

Code:

fmt.Println(strconv.CanBackquote("Fran & Freddie's Diner ☺"))
+fmt.Println(strconv.CanBackquote("`can't backquote this`"))
+
+

Output:

true
+false
+

func FormatBool

func FormatBool(b bool) string

FormatBool returns "true" or "false" according to the value of b.

Example +

Code:

v := true
+s := strconv.FormatBool(v)
+fmt.Printf("%T, %v\n", s, s)
+
+

Output:

string, true
+

func FormatComplex 1.15

func FormatComplex(c complex128, fmt byte, prec, bitSize int) string

FormatComplex converts the complex number c to a string of the form (a+bi) where a and b are the real and imaginary parts, formatted according to the format fmt and precision prec.

+

The format fmt and precision prec have the same meaning as in FormatFloat. It rounds the result assuming that the original was obtained from a complex value of bitSize bits, which must be 64 for complex64 and 128 for complex128.

+

func FormatFloat

func FormatFloat(f float64, fmt byte, prec, bitSize int) string

FormatFloat converts the floating-point number f to a string, according to the format fmt and precision prec. It rounds the result assuming that the original was obtained from a floating-point value of bitSize bits (32 for float32, 64 for float64).

+

The format fmt is one of 'b' (-ddddp±ddd, a binary exponent), 'e' (-d.dddde±dd, a decimal exponent), 'E' (-d.ddddE±dd, a decimal exponent), 'f' (-ddd.dddd, no exponent), 'g' ('e' for large exponents, 'f' otherwise), 'G' ('E' for large exponents, 'f' otherwise), 'x' (-0xd.ddddp±ddd, a hexadecimal fraction and binary exponent), or 'X' (-0Xd.ddddP±ddd, a hexadecimal fraction and binary exponent).

+

The precision prec controls the number of digits (excluding the exponent) printed by the 'e', 'E', 'f', 'g', 'G', 'x', and 'X' formats. For 'e', 'E', 'f', 'x', and 'X', it is the number of digits after the decimal point. For 'g' and 'G' it is the maximum number of significant digits (trailing zeros are removed). The special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly.

Example +

Code:

v := 3.1415926535
+
+s32 := strconv.FormatFloat(v, 'E', -1, 32)
+fmt.Printf("%T, %v\n", s32, s32)
+
+s64 := strconv.FormatFloat(v, 'E', -1, 64)
+fmt.Printf("%T, %v\n", s64, s64)
+
+// fmt.Println uses these arguments to print floats
+fmt64 := strconv.FormatFloat(v, 'g', -1, 64)
+fmt.Printf("%T, %v\n", fmt64, fmt64)
+
+

Output:

string, 3.1415927E+00
+string, 3.1415926535E+00
+string, 3.1415926535
+

func FormatInt

func FormatInt(i int64, base int) string

FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.

Example +

Code:

v := int64(-42)
+
+s10 := strconv.FormatInt(v, 10)
+fmt.Printf("%T, %v\n", s10, s10)
+
+s16 := strconv.FormatInt(v, 16)
+fmt.Printf("%T, %v\n", s16, s16)
+
+

Output:

string, -42
+string, -2a
+

func FormatUint

func FormatUint(i uint64, base int) string

FormatUint returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.

Example +

Code:

v := uint64(42)
+
+s10 := strconv.FormatUint(v, 10)
+fmt.Printf("%T, %v\n", s10, s10)
+
+s16 := strconv.FormatUint(v, 16)
+fmt.Printf("%T, %v\n", s16, s16)
+
+

Output:

string, 42
+string, 2a
+

func IsGraphic 1.6

func IsGraphic(r rune) bool

IsGraphic reports whether the rune is defined as a Graphic by Unicode. Such characters include letters, marks, numbers, punctuation, symbols, and spaces, from categories L, M, N, P, S, and Zs.

Example +

Code:

shamrock := strconv.IsGraphic('☘')
+fmt.Println(shamrock)
+
+a := strconv.IsGraphic('a')
+fmt.Println(a)
+
+bel := strconv.IsGraphic('\007')
+fmt.Println(bel)
+
+

Output:

true
+true
+false
+

func IsPrint

func IsPrint(r rune) bool

IsPrint reports whether the rune is defined as printable by Go, with the same definition as unicode.IsPrint: letters, numbers, punctuation, symbols and ASCII space.

Example +

Code:

c := strconv.IsPrint('\u263a')
+fmt.Println(c)
+
+bel := strconv.IsPrint('\007')
+fmt.Println(bel)
+
+

Output:

true
+false
+

func Itoa

func Itoa(i int) string

Itoa is equivalent to FormatInt(int64(i), 10).

Example +

Code:

i := 10
+s := strconv.Itoa(i)
+fmt.Printf("%T, %v\n", s, s)
+
+

Output:

string, 10
+

func ParseBool

func ParseBool(str string) (bool, error)

ParseBool returns the boolean value represented by the string. It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other value returns an error.

Example +

Code:

v := "true"
+if s, err := strconv.ParseBool(v); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+
+

Output:

bool, true
+

func ParseComplex 1.15

func ParseComplex(s string, bitSize int) (complex128, error)

ParseComplex converts the string s to a complex number with the precision specified by bitSize: 64 for complex64, or 128 for complex128. When bitSize=64, the result still has type complex128, but it will be convertible to complex64 without changing its value.

+

The number represented by s must be of the form N, Ni, or N±Ni, where N stands for a floating-point number as recognized by ParseFloat, and i is the imaginary component. If the second N is unsigned, a + sign is required between the two components as indicated by the ±. If the second N is NaN, only a + sign is accepted. The form may be parenthesized and cannot contain any spaces. The resulting complex number consists of the two components converted by ParseFloat.

+

The errors that ParseComplex returns have concrete type *NumError and include err.Num = s.

+

If s is not syntactically well-formed, ParseComplex returns err.Err = ErrSyntax.

+

If s is syntactically well-formed but either component is more than 1/2 ULP away from the largest floating point number of the given component's size, ParseComplex returns err.Err = ErrRange and c = ±Inf for the respective component.

+

func ParseFloat

func ParseFloat(s string, bitSize int) (float64, error)

ParseFloat converts the string s to a floating-point number with the precision specified by bitSize: 32 for float32, or 64 for float64. When bitSize=32, the result still has type float64, but it will be convertible to float32 without changing its value.

+

ParseFloat accepts decimal and hexadecimal floating-point numbers as defined by the Go syntax for floating-point literals. If s is well-formed and near a valid floating-point number, ParseFloat returns the nearest floating-point number rounded using IEEE754 unbiased rounding. (Parsing a hexadecimal floating-point value only rounds when there are more bits in the hexadecimal representation than will fit in the mantissa.)

+

The errors that ParseFloat returns have concrete type *NumError and include err.Num = s.

+

If s is not syntactically well-formed, ParseFloat returns err.Err = ErrSyntax.

+

If s is syntactically well-formed but is more than 1/2 ULP away from the largest floating point number of the given size, ParseFloat returns f = ±Inf, err.Err = ErrRange.

+

ParseFloat recognizes the string "NaN", and the (possibly signed) strings "Inf" and "Infinity" as their respective special floating point values. It ignores case when matching.

Example +

Code:

v := "3.1415926535"
+if s, err := strconv.ParseFloat(v, 32); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+if s, err := strconv.ParseFloat(v, 64); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+if s, err := strconv.ParseFloat("NaN", 32); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+// ParseFloat is case insensitive
+if s, err := strconv.ParseFloat("nan", 32); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+if s, err := strconv.ParseFloat("inf", 32); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+if s, err := strconv.ParseFloat("+Inf", 32); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+if s, err := strconv.ParseFloat("-Inf", 32); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+if s, err := strconv.ParseFloat("-0", 32); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+if s, err := strconv.ParseFloat("+0", 32); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+
+

Output:

float64, 3.1415927410125732
+float64, 3.1415926535
+float64, NaN
+float64, NaN
+float64, +Inf
+float64, +Inf
+float64, -Inf
+float64, -0
+float64, 0
+

func ParseInt

func ParseInt(s string, base int, bitSize int) (i int64, err error)

ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.

+

The string may begin with a leading sign: "+" or "-".

+

If the base argument is 0, the true base is implied by the string's prefix following the sign (if present): 2 for "0b", 8 for "0" or "0o", 16 for "0x", and 10 otherwise. Also, for argument base 0 only, underscore characters are permitted as defined by the Go syntax for integer literals.

+

The bitSize argument specifies the integer type that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64. If bitSize is below 0 or above 64, an error is returned.

+

The errors that ParseInt returns have concrete type *NumError and include err.Num = s. If s is empty or contains invalid digits, err.Err = ErrSyntax and the returned value is 0; if the value corresponding to s cannot be represented by a signed integer of the given size, err.Err = ErrRange and the returned value is the maximum magnitude integer of the appropriate bitSize and sign.

Example +

Code:

v32 := "-354634382"
+if s, err := strconv.ParseInt(v32, 10, 32); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+if s, err := strconv.ParseInt(v32, 16, 32); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+
+v64 := "-3546343826724305832"
+if s, err := strconv.ParseInt(v64, 10, 64); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+if s, err := strconv.ParseInt(v64, 16, 64); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+
+

Output:

int64, -354634382
+int64, -3546343826724305832
+

func ParseUint

func ParseUint(s string, base int, bitSize int) (uint64, error)

ParseUint is like ParseInt but for unsigned numbers.

+

A sign prefix is not permitted.

Example +

Code:

v := "42"
+if s, err := strconv.ParseUint(v, 10, 32); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+if s, err := strconv.ParseUint(v, 10, 64); err == nil {
+    fmt.Printf("%T, %v\n", s, s)
+}
+
+

Output:

uint64, 42
+uint64, 42
+

func Quote

func Quote(s string) string

Quote returns a double-quoted Go string literal representing s. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for control characters and non-printable characters as defined by IsPrint.

Example +

Code:

// This string literal contains a tab character.
+s := strconv.Quote(`"Fran & Freddie's Diner	☺"`)
+fmt.Println(s)
+
+

Output:

"\"Fran & Freddie's Diner\t☺\""
+

func QuoteRune

func QuoteRune(r rune) string

QuoteRune returns a single-quoted Go character literal representing the rune. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for control characters and non-printable characters as defined by IsPrint. If r is not a valid Unicode code point, it is interpreted as the Unicode replacement character U+FFFD.

Example +

Code:

s := strconv.QuoteRune('☺')
+fmt.Println(s)
+
+

Output:

'☺'
+

func QuoteRuneToASCII

func QuoteRuneToASCII(r rune) string

QuoteRuneToASCII returns a single-quoted Go character literal representing the rune. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for non-ASCII characters and non-printable characters as defined by IsPrint. If r is not a valid Unicode code point, it is interpreted as the Unicode replacement character U+FFFD.

Example +

Code:

s := strconv.QuoteRuneToASCII('☺')
+fmt.Println(s)
+
+

Output:

'\u263a'
+

func QuoteRuneToGraphic 1.6

func QuoteRuneToGraphic(r rune) string

QuoteRuneToGraphic returns a single-quoted Go character literal representing the rune. If the rune is not a Unicode graphic character, as defined by IsGraphic, the returned string will use a Go escape sequence (\t, \n, \xFF, \u0100). If r is not a valid Unicode code point, it is interpreted as the Unicode replacement character U+FFFD.

Example +

Code:

s := strconv.QuoteRuneToGraphic('☺')
+fmt.Println(s)
+
+s = strconv.QuoteRuneToGraphic('\u263a')
+fmt.Println(s)
+
+s = strconv.QuoteRuneToGraphic('\u000a')
+fmt.Println(s)
+
+s = strconv.QuoteRuneToGraphic('	') // tab character
+fmt.Println(s)
+
+

Output:

'☺'
+'☺'
+'\n'
+'\t'
+

func QuoteToASCII

func QuoteToASCII(s string) string

QuoteToASCII returns a double-quoted Go string literal representing s. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for non-ASCII characters and non-printable characters as defined by IsPrint.

Example +

Code:

// This string literal contains a tab character.
+s := strconv.QuoteToASCII(`"Fran & Freddie's Diner	☺"`)
+fmt.Println(s)
+
+

Output:

"\"Fran & Freddie's Diner\t\u263a\""
+

func QuoteToGraphic 1.6

func QuoteToGraphic(s string) string

QuoteToGraphic returns a double-quoted Go string literal representing s. The returned string leaves Unicode graphic characters, as defined by IsGraphic, unchanged and uses Go escape sequences (\t, \n, \xFF, \u0100) for non-graphic characters.

Example +

Code:

s := strconv.QuoteToGraphic("☺")
+fmt.Println(s)
+
+// This string literal contains a tab character.
+s = strconv.QuoteToGraphic("This is a \u263a	\u000a")
+fmt.Println(s)
+
+s = strconv.QuoteToGraphic(`" This is a ☺ \n "`)
+fmt.Println(s)
+
+

Output:

"☺"
+"This is a ☺\t\n"
+"\" This is a ☺ \\n \""
+

func QuotedPrefix 1.17

func QuotedPrefix(s string) (string, error)

QuotedPrefix returns the quoted string (as understood by Unquote) at the prefix of s. If s does not start with a valid quoted string, QuotedPrefix returns an error.

Example +

Code:

s, err := strconv.QuotedPrefix("not a quoted string")
+fmt.Printf("%q, %v\n", s, err)
+s, err = strconv.QuotedPrefix("\"double-quoted string\" with trailing text")
+fmt.Printf("%q, %v\n", s, err)
+s, err = strconv.QuotedPrefix("`or backquoted` with more trailing text")
+fmt.Printf("%q, %v\n", s, err)
+s, err = strconv.QuotedPrefix("'\u263a' is also okay")
+fmt.Printf("%q, %v\n", s, err)
+
+

Output:

"", invalid syntax
+"\"double-quoted string\"", <nil>
+"`or backquoted`", <nil>
+"'☺'", <nil>
+

func Unquote

func Unquote(s string) (string, error)

Unquote interprets s as a single-quoted, double-quoted, or backquoted Go string literal, returning the string value that s quotes. (If s is single-quoted, it would be a Go character literal; Unquote returns the corresponding one-character string.)

Example +

Code:

s, err := strconv.Unquote("You can't unquote a string without quotes")
+fmt.Printf("%q, %v\n", s, err)
+s, err = strconv.Unquote("\"The string must be either double-quoted\"")
+fmt.Printf("%q, %v\n", s, err)
+s, err = strconv.Unquote("`or backquoted.`")
+fmt.Printf("%q, %v\n", s, err)
+s, err = strconv.Unquote("'\u263a'") // single character only allowed in single quotes
+fmt.Printf("%q, %v\n", s, err)
+s, err = strconv.Unquote("'\u2639\u2639'")
+fmt.Printf("%q, %v\n", s, err)
+
+

Output:

"", invalid syntax
+"The string must be either double-quoted", <nil>
+"or backquoted.", <nil>
+"☺", <nil>
+"", invalid syntax
+

func UnquoteChar

func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)

UnquoteChar decodes the first character or byte in the escaped string or character literal represented by the string s. It returns four values:

+
  1. value, the decoded Unicode code point or byte value;
  2. +
  3. multibyte, a boolean indicating whether the decoded character requires a multibyte UTF-8 representation;
  4. +
  5. tail, the remainder of the string after the character; and
  6. +
  7. an error that will be nil if the character is syntactically valid.
  8. +

The second argument, quote, specifies the type of literal being parsed and therefore which escaped quote character is permitted. If set to a single quote, it permits the sequence \' and disallows unescaped '. If set to a double quote, it permits \" and disallows unescaped ". If set to zero, it does not permit either escape and allows both quote characters to appear unescaped.

Example +

Code:

v, mb, t, err := strconv.UnquoteChar(`\"Fran & Freddie's Diner\"`, '"')
+if err != nil {
+    log.Fatal(err)
+}
+
+fmt.Println("value:", string(v))
+fmt.Println("multibyte:", mb)
+fmt.Println("tail:", t)
+
+

Output:

value: "
+multibyte: false
+tail: Fran & Freddie's Diner\"
+

type NumError

A NumError records a failed conversion.

+
type NumError struct {
+    Func string // the failing function (ParseBool, ParseInt, ParseUint, ParseFloat, ParseComplex)
+    Num  string // the input
+    Err  error  // the reason the conversion failed (e.g. ErrRange, ErrSyntax, etc.)
+}
+

Example +

Code:

str := "Not a number"
+if _, err := strconv.ParseFloat(str, 64); err != nil {
+    e := err.(*strconv.NumError)
+    fmt.Println("Func:", e.Func)
+    fmt.Println("Num:", e.Num)
+    fmt.Println("Err:", e.Err)
+    fmt.Println(err)
+}
+
+

Output:

Func: ParseFloat
+Num: Not a number
+Err: invalid syntax
+strconv.ParseFloat: parsing "Not a number": invalid syntax
+

func (*NumError) Error

func (e *NumError) Error() string

func (*NumError) Unwrap 1.14

func (e *NumError) Unwrap() error
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/strconv/ +

+
diff --git a/devdocs/go/strings%2Findex.html b/devdocs/go/strings%2Findex.html new file mode 100644 index 00000000..53dc7feb --- /dev/null +++ b/devdocs/go/strings%2Findex.html @@ -0,0 +1,488 @@ +

Package strings

Overview

Package strings implements simple functions to manipulate UTF-8 encoded strings.

+

For information about UTF-8 strings in Go, see https://blog.golang.org/strings.

Index

Examples

Builder
Clone
Compare
Contains
ContainsAny
ContainsFunc
ContainsRune
Count
Cut
CutPrefix
CutSuffix
EqualFold
Fields
FieldsFunc
HasPrefix
HasSuffix
Index
IndexAny
IndexByte
IndexFunc
IndexRune
Join
LastIndex
LastIndexAny
LastIndexByte
LastIndexFunc
Map
NewReplacer
Repeat
Replace
ReplaceAll
Split
SplitAfter
SplitAfterN
SplitN
Title
ToLower
ToLowerSpecial
ToTitle
ToTitleSpecial
ToUpper
ToUpperSpecial
ToValidUTF8
Trim
TrimFunc
TrimLeft
TrimLeftFunc
TrimPrefix
TrimRight
TrimRightFunc
TrimSpace
TrimSuffix

Package files

builder.go clone.go compare.go reader.go replace.go search.go strings.go

func Clone 1.18

func Clone(s string) string

Clone returns a fresh copy of s. It guarantees to make a copy of s into a new allocation, which can be important when retaining only a small substring of a much larger string. Using Clone can help such programs use less memory. Of course, since using Clone makes a copy, overuse of Clone can make programs use more memory. Clone should typically be used only rarely, and only when profiling indicates that it is needed. For strings of length zero the string "" will be returned and no allocation is made.

Example +

Code:

s := "abc"
+clone := strings.Clone(s)
+fmt.Println(s == clone)
+fmt.Println(unsafe.StringData(s) == unsafe.StringData(clone))
+

Output:

true
+false
+

func Compare 1.5

func Compare(a, b string) int

Compare returns an integer comparing two strings lexicographically. The result will be 0 if a == b, -1 if a < b, and +1 if a > b.

+

Compare is included only for symmetry with package bytes. It is usually clearer and always faster to use the built-in string comparison operators ==, <, >, and so on.

Example +

Code:

fmt.Println(strings.Compare("a", "b"))
+fmt.Println(strings.Compare("a", "a"))
+fmt.Println(strings.Compare("b", "a"))
+

Output:

-1
+0
+1
+

func Contains

func Contains(s, substr string) bool

Contains reports whether substr is within s.

Example +

Code:

fmt.Println(strings.Contains("seafood", "foo"))
+fmt.Println(strings.Contains("seafood", "bar"))
+fmt.Println(strings.Contains("seafood", ""))
+fmt.Println(strings.Contains("", ""))
+

Output:

true
+false
+true
+true
+

func ContainsAny

func ContainsAny(s, chars string) bool

ContainsAny reports whether any Unicode code points in chars are within s.

Example +

Code:

fmt.Println(strings.ContainsAny("team", "i"))
+fmt.Println(strings.ContainsAny("fail", "ui"))
+fmt.Println(strings.ContainsAny("ure", "ui"))
+fmt.Println(strings.ContainsAny("failure", "ui"))
+fmt.Println(strings.ContainsAny("foo", ""))
+fmt.Println(strings.ContainsAny("", ""))
+

Output:

false
+true
+true
+true
+false
+false
+

func ContainsFunc 1.21

func ContainsFunc(s string, f func(rune) bool) bool

ContainsFunc reports whether any Unicode code points r within s satisfy f(r).

Example +

Code:

f := func(r rune) bool {
+    return r == 'a' || r == 'e' || r == 'i' || r == 'o' || r == 'u'
+}
+fmt.Println(strings.ContainsFunc("hello", f))
+fmt.Println(strings.ContainsFunc("rhythms", f))
+

Output:

true
+false
+

func ContainsRune

func ContainsRune(s string, r rune) bool

ContainsRune reports whether the Unicode code point r is within s.

Example +

Code:

// Finds whether a string contains a particular Unicode code point.
+// The code point for the lowercase letter "a", for example, is 97.
+fmt.Println(strings.ContainsRune("aardvark", 97))
+fmt.Println(strings.ContainsRune("timeout", 97))
+

Output:

true
+false
+

func Count

func Count(s, substr string) int

Count counts the number of non-overlapping instances of substr in s. If substr is an empty string, Count returns 1 + the number of Unicode code points in s.

Example +

Code:

fmt.Println(strings.Count("cheese", "e"))
+fmt.Println(strings.Count("five", "")) // before & after each rune
+

Output:

3
+5
+

func Cut 1.18

func Cut(s, sep string) (before, after string, found bool)

Cut slices s around the first instance of sep, returning the text before and after sep. The found result reports whether sep appears in s. If sep does not appear in s, cut returns s, "", false.

Example +

Code:

show := func(s, sep string) {
+    before, after, found := strings.Cut(s, sep)
+    fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
+}
+show("Gopher", "Go")
+show("Gopher", "ph")
+show("Gopher", "er")
+show("Gopher", "Badger")
+

Output:

Cut("Gopher", "Go") = "", "pher", true
+Cut("Gopher", "ph") = "Go", "er", true
+Cut("Gopher", "er") = "Goph", "", true
+Cut("Gopher", "Badger") = "Gopher", "", false
+

func CutPrefix 1.20

func CutPrefix(s, prefix string) (after string, found bool)

CutPrefix returns s without the provided leading prefix string and reports whether it found the prefix. If s doesn't start with prefix, CutPrefix returns s, false. If prefix is the empty string, CutPrefix returns s, true.

Example +

Code:

show := func(s, sep string) {
+    after, found := strings.CutPrefix(s, sep)
+    fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, sep, after, found)
+}
+show("Gopher", "Go")
+show("Gopher", "ph")
+

Output:

CutPrefix("Gopher", "Go") = "pher", true
+CutPrefix("Gopher", "ph") = "Gopher", false
+

func CutSuffix 1.20

func CutSuffix(s, suffix string) (before string, found bool)

CutSuffix returns s without the provided ending suffix string and reports whether it found the suffix. If s doesn't end with suffix, CutSuffix returns s, false. If suffix is the empty string, CutSuffix returns s, true.

Example +

Code:

show := func(s, sep string) {
+    before, found := strings.CutSuffix(s, sep)
+    fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, sep, before, found)
+}
+show("Gopher", "Go")
+show("Gopher", "er")
+

Output:

CutSuffix("Gopher", "Go") = "Gopher", false
+CutSuffix("Gopher", "er") = "Goph", true
+

func EqualFold

func EqualFold(s, t string) bool

EqualFold reports whether s and t, interpreted as UTF-8 strings, are equal under simple Unicode case-folding, which is a more general form of case-insensitivity.

Example +

Code:

fmt.Println(strings.EqualFold("Go", "go"))
+fmt.Println(strings.EqualFold("AB", "ab")) // true because comparison uses simple case-folding
+fmt.Println(strings.EqualFold("ß", "ss"))  // false because comparison does not use full case-folding
+

Output:

true
+true
+false
+

func Fields

func Fields(s string) []string

Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space.

Example +

Code:

fmt.Printf("Fields are: %q", strings.Fields("  foo bar  baz   "))
+

Output:

Fields are: ["foo" "bar" "baz"]
+

func FieldsFunc

func FieldsFunc(s string, f func(rune) bool) []string

FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c) and returns an array of slices of s. If all code points in s satisfy f(c) or the string is empty, an empty slice is returned.

+

FieldsFunc makes no guarantees about the order in which it calls f(c) and assumes that f always returns the same value for a given c.

Example +

Code:

f := func(c rune) bool {
+    return !unicode.IsLetter(c) && !unicode.IsNumber(c)
+}
+fmt.Printf("Fields are: %q", strings.FieldsFunc("  foo1;bar2,baz3...", f))
+

Output:

Fields are: ["foo1" "bar2" "baz3"]
+

func HasPrefix

func HasPrefix(s, prefix string) bool

HasPrefix reports whether the string s begins with prefix.

Example +

Code:

fmt.Println(strings.HasPrefix("Gopher", "Go"))
+fmt.Println(strings.HasPrefix("Gopher", "C"))
+fmt.Println(strings.HasPrefix("Gopher", ""))
+

Output:

true
+false
+true
+

func HasSuffix

func HasSuffix(s, suffix string) bool

HasSuffix reports whether the string s ends with suffix.

Example +

Code:

fmt.Println(strings.HasSuffix("Amigo", "go"))
+fmt.Println(strings.HasSuffix("Amigo", "O"))
+fmt.Println(strings.HasSuffix("Amigo", "Ami"))
+fmt.Println(strings.HasSuffix("Amigo", ""))
+

Output:

true
+false
+false
+true
+

func Index

func Index(s, substr string) int

Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.

Example +

Code:

fmt.Println(strings.Index("chicken", "ken"))
+fmt.Println(strings.Index("chicken", "dmr"))
+

Output:

4
+-1
+

func IndexAny

func IndexAny(s, chars string) int

IndexAny returns the index of the first instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.

Example +

Code:

fmt.Println(strings.IndexAny("chicken", "aeiouy"))
+fmt.Println(strings.IndexAny("crwth", "aeiouy"))
+

Output:

2
+-1
+

func IndexByte 1.2

func IndexByte(s string, c byte) int

IndexByte returns the index of the first instance of c in s, or -1 if c is not present in s.

Example +

Code:

fmt.Println(strings.IndexByte("golang", 'g'))
+fmt.Println(strings.IndexByte("gophers", 'h'))
+fmt.Println(strings.IndexByte("golang", 'x'))
+

Output:

0
+3
+-1
+

func IndexFunc

func IndexFunc(s string, f func(rune) bool) int

IndexFunc returns the index into s of the first Unicode code point satisfying f(c), or -1 if none do.

Example +

Code:

f := func(c rune) bool {
+    return unicode.Is(unicode.Han, c)
+}
+fmt.Println(strings.IndexFunc("Hello, 世界", f))
+fmt.Println(strings.IndexFunc("Hello, world", f))
+

Output:

7
+-1
+

func IndexRune

func IndexRune(s string, r rune) int

IndexRune returns the index of the first instance of the Unicode code point r, or -1 if rune is not present in s. If r is utf8.RuneError, it returns the first instance of any invalid UTF-8 byte sequence.

Example +

Code:

fmt.Println(strings.IndexRune("chicken", 'k'))
+fmt.Println(strings.IndexRune("chicken", 'd'))
+

Output:

4
+-1
+

func Join

func Join(elems []string, sep string) string

Join concatenates the elements of its first argument to create a single string. The separator string sep is placed between elements in the resulting string.

Example +

Code:

s := []string{"foo", "bar", "baz"}
+fmt.Println(strings.Join(s, ", "))
+

Output:

foo, bar, baz
+

func LastIndex

func LastIndex(s, substr string) int

LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present in s.

Example +

Code:

fmt.Println(strings.Index("go gopher", "go"))
+fmt.Println(strings.LastIndex("go gopher", "go"))
+fmt.Println(strings.LastIndex("go gopher", "rodent"))
+

Output:

0
+3
+-1
+

func LastIndexAny

func LastIndexAny(s, chars string) int

LastIndexAny returns the index of the last instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.

Example +

Code:

fmt.Println(strings.LastIndexAny("go gopher", "go"))
+fmt.Println(strings.LastIndexAny("go gopher", "rodent"))
+fmt.Println(strings.LastIndexAny("go gopher", "fail"))
+

Output:

4
+8
+-1
+

func LastIndexByte 1.5

func LastIndexByte(s string, c byte) int

LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s.

Example +

Code:

fmt.Println(strings.LastIndexByte("Hello, world", 'l'))
+fmt.Println(strings.LastIndexByte("Hello, world", 'o'))
+fmt.Println(strings.LastIndexByte("Hello, world", 'x'))
+

Output:

10
+8
+-1
+

func LastIndexFunc

func LastIndexFunc(s string, f func(rune) bool) int

LastIndexFunc returns the index into s of the last Unicode code point satisfying f(c), or -1 if none do.

Example +

Code:

fmt.Println(strings.LastIndexFunc("go 123", unicode.IsNumber))
+fmt.Println(strings.LastIndexFunc("123 go", unicode.IsNumber))
+fmt.Println(strings.LastIndexFunc("go", unicode.IsNumber))
+

Output:

5
+2
+-1
+

func Map

func Map(mapping func(rune) rune, s string) string

Map returns a copy of the string s with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement.

Example +

Code:

rot13 := func(r rune) rune {
+    switch {
+    case r >= 'A' && r <= 'Z':
+        return 'A' + (r-'A'+13)%26
+    case r >= 'a' && r <= 'z':
+        return 'a' + (r-'a'+13)%26
+    }
+    return r
+}
+fmt.Println(strings.Map(rot13, "'Twas brillig and the slithy gopher..."))
+

Output:

'Gjnf oevyyvt naq gur fyvgul tbcure...
+

func Repeat

func Repeat(s string, count int) string

Repeat returns a new string consisting of count copies of the string s.

+

It panics if count is negative or if the result of (len(s) * count) overflows.

Example +

Code:

fmt.Println("ba" + strings.Repeat("na", 2))
+

Output:

banana
+

func Replace

func Replace(s, old, new string, n int) string

Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.

Example +

Code:

fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))
+fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))
+

Output:

oinky oinky oink
+moo moo moo
+

func ReplaceAll 1.12

func ReplaceAll(s, old, new string) string

ReplaceAll returns a copy of the string s with all non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string.

Example +

Code:

fmt.Println(strings.ReplaceAll("oink oink oink", "oink", "moo"))
+

Output:

moo moo moo
+

func Split

func Split(s, sep string) []string

Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.

+

If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s.

+

If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice.

+

It is equivalent to SplitN with a count of -1.

+

To split around the first instance of a separator, see Cut.

Example +

Code:

fmt.Printf("%q\n", strings.Split("a,b,c", ","))
+fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
+fmt.Printf("%q\n", strings.Split(" xyz ", ""))
+fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))
+

Output:

["a" "b" "c"]
+["" "man " "plan " "canal panama"]
+[" " "x" "y" "z" " "]
+[""]
+

func SplitAfter

func SplitAfter(s, sep string) []string

SplitAfter slices s into all substrings after each instance of sep and returns a slice of those substrings.

+

If s does not contain sep and sep is not empty, SplitAfter returns a slice of length 1 whose only element is s.

+

If sep is empty, SplitAfter splits after each UTF-8 sequence. If both s and sep are empty, SplitAfter returns an empty slice.

+

It is equivalent to SplitAfterN with a count of -1.

Example +

Code:

fmt.Printf("%q\n", strings.SplitAfter("a,b,c", ","))
+

Output:

["a," "b," "c"]
+

func SplitAfterN

func SplitAfterN(s, sep string, n int) []string

SplitAfterN slices s into substrings after each instance of sep and returns a slice of those substrings.

+

The count determines the number of substrings to return:

+
n > 0: at most n substrings; the last substring will be the unsplit remainder.
+n == 0: the result is nil (zero substrings)
+n < 0: all substrings
+

Edge cases for s and sep (for example, empty strings) are handled as described in the documentation for SplitAfter.

Example +

Code:

fmt.Printf("%q\n", strings.SplitAfterN("a,b,c", ",", 2))
+

Output:

["a," "b,c"]
+

func SplitN

func SplitN(s, sep string, n int) []string

SplitN slices s into substrings separated by sep and returns a slice of the substrings between those separators.

+

The count determines the number of substrings to return:

+
n > 0: at most n substrings; the last substring will be the unsplit remainder.
+n == 0: the result is nil (zero substrings)
+n < 0: all substrings
+

Edge cases for s and sep (for example, empty strings) are handled as described in the documentation for Split.

+

To split around the first instance of a separator, see Cut.

Example +

Code:

fmt.Printf("%q\n", strings.SplitN("a,b,c", ",", 2))
+z := strings.SplitN("a,b,c", ",", 0)
+fmt.Printf("%q (nil = %v)\n", z, z == nil)
+

Output:

["a" "b,c"]
+[] (nil = true)
+

func Title

func Title(s string) string

Title returns a copy of the string s with all Unicode letters that begin words mapped to their Unicode title case.

+

Deprecated: The rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.

Example +

Code:

// Compare this example to the ToTitle example.
+fmt.Println(strings.Title("her royal highness"))
+fmt.Println(strings.Title("loud noises"))
+fmt.Println(strings.Title("хлеб"))
+

Output:

Her Royal Highness
+Loud Noises
+Хлеб
+

func ToLower

func ToLower(s string) string

ToLower returns s with all Unicode letters mapped to their lower case.

Example +

Code:

fmt.Println(strings.ToLower("Gopher"))
+

Output:

gopher
+

func ToLowerSpecial

func ToLowerSpecial(c unicode.SpecialCase, s string) string

ToLowerSpecial returns a copy of the string s with all Unicode letters mapped to their lower case using the case mapping specified by c.

Example +

Code:

fmt.Println(strings.ToLowerSpecial(unicode.TurkishCase, "Önnek İş"))
+

Output:

önnek iş
+

func ToTitle

func ToTitle(s string) string

ToTitle returns a copy of the string s with all Unicode letters mapped to their Unicode title case.

Example +

Code:

// Compare this example to the Title example.
+fmt.Println(strings.ToTitle("her royal highness"))
+fmt.Println(strings.ToTitle("loud noises"))
+fmt.Println(strings.ToTitle("хлеб"))
+

Output:

HER ROYAL HIGHNESS
+LOUD NOISES
+ХЛЕБ
+

func ToTitleSpecial

func ToTitleSpecial(c unicode.SpecialCase, s string) string

ToTitleSpecial returns a copy of the string s with all Unicode letters mapped to their Unicode title case, giving priority to the special casing rules.

Example +

Code:

fmt.Println(strings.ToTitleSpecial(unicode.TurkishCase, "dünyanın ilk borsa yapısı Aizonai kabul edilir"))
+

Output:

DÜNYANIN İLK BORSA YAPISI AİZONAİ KABUL EDİLİR
+

func ToUpper

func ToUpper(s string) string

ToUpper returns s with all Unicode letters mapped to their upper case.

Example +

Code:

fmt.Println(strings.ToUpper("Gopher"))
+

Output:

GOPHER
+

func ToUpperSpecial

func ToUpperSpecial(c unicode.SpecialCase, s string) string

ToUpperSpecial returns a copy of the string s with all Unicode letters mapped to their upper case using the case mapping specified by c.

Example +

Code:

fmt.Println(strings.ToUpperSpecial(unicode.TurkishCase, "örnek iş"))
+

Output:

ÖRNEK İŞ
+

func ToValidUTF8 1.13

func ToValidUTF8(s, replacement string) string

ToValidUTF8 returns a copy of the string s with each run of invalid UTF-8 byte sequences replaced by the replacement string, which may be empty.

Example +

Code:

fmt.Printf("%s\n", strings.ToValidUTF8("abc", "\uFFFD"))
+fmt.Printf("%s\n", strings.ToValidUTF8("a\xffb\xC0\xAFc\xff", ""))
+fmt.Printf("%s\n", strings.ToValidUTF8("\xed\xa0\x80", "abc"))
+

Output:

abc
+abc
+abc
+

func Trim

func Trim(s, cutset string) string

Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.

Example +

Code:

fmt.Print(strings.Trim("¡¡¡Hello, Gophers!!!", "!¡"))
+

Output:

Hello, Gophers
+

func TrimFunc

func TrimFunc(s string, f func(rune) bool) string

TrimFunc returns a slice of the string s with all leading and trailing Unicode code points c satisfying f(c) removed.

Example +

Code:

fmt.Print(strings.TrimFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
+    return !unicode.IsLetter(r) && !unicode.IsNumber(r)
+}))
+

Output:

Hello, Gophers
+

func TrimLeft

func TrimLeft(s, cutset string) string

TrimLeft returns a slice of the string s with all leading Unicode code points contained in cutset removed.

+

To remove a prefix, use TrimPrefix instead.

Example +

Code:

fmt.Print(strings.TrimLeft("¡¡¡Hello, Gophers!!!", "!¡"))
+

Output:

Hello, Gophers!!!
+

func TrimLeftFunc

func TrimLeftFunc(s string, f func(rune) bool) string

TrimLeftFunc returns a slice of the string s with all leading Unicode code points c satisfying f(c) removed.

Example +

Code:

fmt.Print(strings.TrimLeftFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
+    return !unicode.IsLetter(r) && !unicode.IsNumber(r)
+}))
+

Output:

Hello, Gophers!!!
+

func TrimPrefix 1.1

func TrimPrefix(s, prefix string) string

TrimPrefix returns s without the provided leading prefix string. If s doesn't start with prefix, s is returned unchanged.

Example +

Code:

var s = "¡¡¡Hello, Gophers!!!"
+s = strings.TrimPrefix(s, "¡¡¡Hello, ")
+s = strings.TrimPrefix(s, "¡¡¡Howdy, ")
+fmt.Print(s)
+

Output:

Gophers!!!
+

func TrimRight

func TrimRight(s, cutset string) string

TrimRight returns a slice of the string s, with all trailing Unicode code points contained in cutset removed.

+

To remove a suffix, use TrimSuffix instead.

Example +

Code:

fmt.Print(strings.TrimRight("¡¡¡Hello, Gophers!!!", "!¡"))
+

Output:

¡¡¡Hello, Gophers
+

func TrimRightFunc

func TrimRightFunc(s string, f func(rune) bool) string

TrimRightFunc returns a slice of the string s with all trailing Unicode code points c satisfying f(c) removed.

Example +

Code:

fmt.Print(strings.TrimRightFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
+    return !unicode.IsLetter(r) && !unicode.IsNumber(r)
+}))
+

Output:

¡¡¡Hello, Gophers
+

func TrimSpace

func TrimSpace(s string) string

TrimSpace returns a slice of the string s, with all leading and trailing white space removed, as defined by Unicode.

Example +

Code:

fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
+

Output:

Hello, Gophers
+

func TrimSuffix 1.1

func TrimSuffix(s, suffix string) string

TrimSuffix returns s without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.

Example +

Code:

var s = "¡¡¡Hello, Gophers!!!"
+s = strings.TrimSuffix(s, ", Gophers!!!")
+s = strings.TrimSuffix(s, ", Marmots!!!")
+fmt.Print(s)
+

Output:

¡¡¡Hello
+

type Builder 1.10

A Builder is used to efficiently build a string using Builder.Write methods. It minimizes memory copying. The zero value is ready to use. Do not copy a non-zero Builder.

+
type Builder struct {
+    // contains filtered or unexported fields
+}
+

Example +

Code:

var b strings.Builder
+for i := 3; i >= 1; i-- {
+    fmt.Fprintf(&b, "%d...", i)
+}
+b.WriteString("ignition")
+fmt.Println(b.String())
+
+

Output:

3...2...1...ignition
+

func (*Builder) Cap 1.12

func (b *Builder) Cap() int

Cap returns the capacity of the builder's underlying byte slice. It is the total space allocated for the string being built and includes any bytes already written.

+

func (*Builder) Grow 1.10

func (b *Builder) Grow(n int)

Grow grows b's capacity, if necessary, to guarantee space for another n bytes. After Grow(n), at least n bytes can be written to b without another allocation. If n is negative, Grow panics.

+

func (*Builder) Len 1.10

func (b *Builder) Len() int

Len returns the number of accumulated bytes; b.Len() == len(b.String()).

+

func (*Builder) Reset 1.10

func (b *Builder) Reset()

Reset resets the Builder to be empty.

+

func (*Builder) String 1.10

func (b *Builder) String() string

String returns the accumulated string.

+

func (*Builder) Write 1.10

func (b *Builder) Write(p []byte) (int, error)

Write appends the contents of p to b's buffer. Write always returns len(p), nil.

+

func (*Builder) WriteByte 1.10

func (b *Builder) WriteByte(c byte) error

WriteByte appends the byte c to b's buffer. The returned error is always nil.

+

func (*Builder) WriteRune 1.10

func (b *Builder) WriteRune(r rune) (int, error)

WriteRune appends the UTF-8 encoding of Unicode code point r to b's buffer. It returns the length of r and a nil error.

+

func (*Builder) WriteString 1.10

func (b *Builder) WriteString(s string) (int, error)

WriteString appends the contents of s to b's buffer. It returns the length of s and a nil error.

+

type Reader

A Reader implements the io.Reader, io.ReaderAt, io.ByteReader, io.ByteScanner, io.RuneReader, io.RuneScanner, io.Seeker, and io.WriterTo interfaces by reading from a string. The zero value for Reader operates like a Reader of an empty string.

+
type Reader struct {
+    // contains filtered or unexported fields
+}
+

func NewReader

func NewReader(s string) *Reader

NewReader returns a new Reader reading from s. It is similar to bytes.NewBufferString but more efficient and non-writable.

+

func (*Reader) Len

func (r *Reader) Len() int

Len returns the number of bytes of the unread portion of the string.

+

func (*Reader) Read

func (r *Reader) Read(b []byte) (n int, err error)

Read implements the io.Reader interface.

+

func (*Reader) ReadAt

func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)

ReadAt implements the io.ReaderAt interface.

+

func (*Reader) ReadByte

func (r *Reader) ReadByte() (byte, error)

ReadByte implements the io.ByteReader interface.

+

func (*Reader) ReadRune

func (r *Reader) ReadRune() (ch rune, size int, err error)

ReadRune implements the io.RuneReader interface.

+

func (*Reader) Reset 1.7

func (r *Reader) Reset(s string)

Reset resets the Reader to be reading from s.

+

func (*Reader) Seek

func (r *Reader) Seek(offset int64, whence int) (int64, error)

Seek implements the io.Seeker interface.

+

func (*Reader) Size 1.5

func (r *Reader) Size() int64

Size returns the original length of the underlying string. Size is the number of bytes available for reading via Reader.ReadAt. The returned value is always the same and is not affected by calls to any other method.

+

func (*Reader) UnreadByte

func (r *Reader) UnreadByte() error

UnreadByte implements the io.ByteScanner interface.

+

func (*Reader) UnreadRune

func (r *Reader) UnreadRune() error

UnreadRune implements the io.RuneScanner interface.

+

func (*Reader) WriteTo 1.1

func (r *Reader) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements the io.WriterTo interface.

+

type Replacer

Replacer replaces a list of strings with replacements. It is safe for concurrent use by multiple goroutines.

+
type Replacer struct {
+    // contains filtered or unexported fields
+}
+

func NewReplacer

func NewReplacer(oldnew ...string) *Replacer

NewReplacer returns a new Replacer from a list of old, new string pairs. Replacements are performed in the order they appear in the target string, without overlapping matches. The old string comparisons are done in argument order.

+

NewReplacer panics if given an odd number of arguments.

Example +

Code:

r := strings.NewReplacer("<", "&lt;", ">", "&gt;")
+fmt.Println(r.Replace("This is <b>HTML</b>!"))
+

Output:

This is &lt;b&gt;HTML&lt;/b&gt;!
+

func (*Replacer) Replace

func (r *Replacer) Replace(s string) string

Replace returns a copy of s with all replacements performed.

+

func (*Replacer) WriteString

func (r *Replacer) WriteString(w io.Writer, s string) (n int, err error)

WriteString writes s to w with all replacements performed.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/strings/ +

+
diff --git a/devdocs/go/sync%2Fatomic%2Findex.html b/devdocs/go/sync%2Fatomic%2Findex.html new file mode 100644 index 00000000..f5fd3ba4 --- /dev/null +++ b/devdocs/go/sync%2Fatomic%2Findex.html @@ -0,0 +1,295 @@ +

Package atomic

Overview

Package atomic provides low-level atomic memory primitives useful for implementing synchronization algorithms.

+

These functions require great care to be used correctly. Except for special, low-level applications, synchronization is better done with channels or the facilities of the sync package. Share memory by communicating; don't communicate by sharing memory.

+

The swap operation, implemented by the SwapT functions, is the atomic equivalent of:

+
old = *addr
+*addr = new
+return old
+

The compare-and-swap operation, implemented by the CompareAndSwapT functions, is the atomic equivalent of:

+
if *addr == old {
+	*addr = new
+	return true
+}
+return false
+

The add operation, implemented by the AddT functions, is the atomic equivalent of:

+
*addr += delta
+return *addr
+

The load and store operations, implemented by the LoadT and StoreT functions, are the atomic equivalents of "return *addr" and "*addr = val".

+

In the terminology of the Go memory model, if the effect of an atomic operation A is observed by atomic operation B, then A “synchronizes before” B. Additionally, all the atomic operations executed in a program behave as though executed in some sequentially consistent order. This definition provides the same semantics as C++'s sequentially consistent atomics and Java's volatile variables.

Index

Examples

Value (Config)
Value (ReadMostly)

Package files

doc.go type.go value.go

func AddInt32

func AddInt32(addr *int32, delta int32) (new int32)

AddInt32 atomically adds delta to *addr and returns the new value. Consider using the more ergonomic and less error-prone Int32.Add instead.

+

func AddInt64

func AddInt64(addr *int64, delta int64) (new int64)

AddInt64 atomically adds delta to *addr and returns the new value. Consider using the more ergonomic and less error-prone Int64.Add instead (particularly if you target 32-bit platforms; see the bugs section).

+

func AddUint32

func AddUint32(addr *uint32, delta uint32) (new uint32)

AddUint32 atomically adds delta to *addr and returns the new value. To subtract a signed positive constant value c from x, do AddUint32(&x, ^uint32(c-1)). In particular, to decrement x, do AddUint32(&x, ^uint32(0)). Consider using the more ergonomic and less error-prone Uint32.Add instead.

+

func AddUint64

func AddUint64(addr *uint64, delta uint64) (new uint64)

AddUint64 atomically adds delta to *addr and returns the new value. To subtract a signed positive constant value c from x, do AddUint64(&x, ^uint64(c-1)). In particular, to decrement x, do AddUint64(&x, ^uint64(0)). Consider using the more ergonomic and less error-prone Uint64.Add instead (particularly if you target 32-bit platforms; see the bugs section).

+

func AddUintptr

func AddUintptr(addr *uintptr, delta uintptr) (new uintptr)

AddUintptr atomically adds delta to *addr and returns the new value. Consider using the more ergonomic and less error-prone Uintptr.Add instead.

+

func CompareAndSwapInt32

func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)

CompareAndSwapInt32 executes the compare-and-swap operation for an int32 value. Consider using the more ergonomic and less error-prone Int32.CompareAndSwap instead.

+

func CompareAndSwapInt64

func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)

CompareAndSwapInt64 executes the compare-and-swap operation for an int64 value. Consider using the more ergonomic and less error-prone Int64.CompareAndSwap instead (particularly if you target 32-bit platforms; see the bugs section).

+

func CompareAndSwapPointer

func CompareAndSwapPointer(addr *unsafe.Pointer, old, new unsafe.Pointer) (swapped bool)

CompareAndSwapPointer executes the compare-and-swap operation for a unsafe.Pointer value. Consider using the more ergonomic and less error-prone Pointer.CompareAndSwap instead.

+

func CompareAndSwapUint32

func CompareAndSwapUint32(addr *uint32, old, new uint32) (swapped bool)

CompareAndSwapUint32 executes the compare-and-swap operation for a uint32 value. Consider using the more ergonomic and less error-prone Uint32.CompareAndSwap instead.

+

func CompareAndSwapUint64

func CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool)

CompareAndSwapUint64 executes the compare-and-swap operation for a uint64 value. Consider using the more ergonomic and less error-prone Uint64.CompareAndSwap instead (particularly if you target 32-bit platforms; see the bugs section).

+

func CompareAndSwapUintptr

func CompareAndSwapUintptr(addr *uintptr, old, new uintptr) (swapped bool)

CompareAndSwapUintptr executes the compare-and-swap operation for a uintptr value. Consider using the more ergonomic and less error-prone Uintptr.CompareAndSwap instead.

+

func LoadInt32

func LoadInt32(addr *int32) (val int32)

LoadInt32 atomically loads *addr. Consider using the more ergonomic and less error-prone Int32.Load instead.

+

func LoadInt64

func LoadInt64(addr *int64) (val int64)

LoadInt64 atomically loads *addr. Consider using the more ergonomic and less error-prone Int64.Load instead (particularly if you target 32-bit platforms; see the bugs section).

+

func LoadPointer

func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer)

LoadPointer atomically loads *addr. Consider using the more ergonomic and less error-prone Pointer.Load instead.

+

func LoadUint32

func LoadUint32(addr *uint32) (val uint32)

LoadUint32 atomically loads *addr. Consider using the more ergonomic and less error-prone Uint32.Load instead.

+

func LoadUint64

func LoadUint64(addr *uint64) (val uint64)

LoadUint64 atomically loads *addr. Consider using the more ergonomic and less error-prone Uint64.Load instead (particularly if you target 32-bit platforms; see the bugs section).

+

func LoadUintptr

func LoadUintptr(addr *uintptr) (val uintptr)

LoadUintptr atomically loads *addr. Consider using the more ergonomic and less error-prone Uintptr.Load instead.

+

func StoreInt32

func StoreInt32(addr *int32, val int32)

StoreInt32 atomically stores val into *addr. Consider using the more ergonomic and less error-prone Int32.Store instead.

+

func StoreInt64

func StoreInt64(addr *int64, val int64)

StoreInt64 atomically stores val into *addr. Consider using the more ergonomic and less error-prone Int64.Store instead (particularly if you target 32-bit platforms; see the bugs section).

+

func StorePointer

func StorePointer(addr *unsafe.Pointer, val unsafe.Pointer)

StorePointer atomically stores val into *addr. Consider using the more ergonomic and less error-prone Pointer.Store instead.

+

func StoreUint32

func StoreUint32(addr *uint32, val uint32)

StoreUint32 atomically stores val into *addr. Consider using the more ergonomic and less error-prone Uint32.Store instead.

+

func StoreUint64

func StoreUint64(addr *uint64, val uint64)

StoreUint64 atomically stores val into *addr. Consider using the more ergonomic and less error-prone Uint64.Store instead (particularly if you target 32-bit platforms; see the bugs section).

+

func StoreUintptr

func StoreUintptr(addr *uintptr, val uintptr)

StoreUintptr atomically stores val into *addr. Consider using the more ergonomic and less error-prone Uintptr.Store instead.

+

func SwapInt32 1.2

func SwapInt32(addr *int32, new int32) (old int32)

SwapInt32 atomically stores new into *addr and returns the previous *addr value. Consider using the more ergonomic and less error-prone Int32.Swap instead.

+

func SwapInt64 1.2

func SwapInt64(addr *int64, new int64) (old int64)

SwapInt64 atomically stores new into *addr and returns the previous *addr value. Consider using the more ergonomic and less error-prone Int64.Swap instead (particularly if you target 32-bit platforms; see the bugs section).

+

func SwapPointer 1.2

func SwapPointer(addr *unsafe.Pointer, new unsafe.Pointer) (old unsafe.Pointer)

SwapPointer atomically stores new into *addr and returns the previous *addr value. Consider using the more ergonomic and less error-prone Pointer.Swap instead.

+

func SwapUint32 1.2

func SwapUint32(addr *uint32, new uint32) (old uint32)

SwapUint32 atomically stores new into *addr and returns the previous *addr value. Consider using the more ergonomic and less error-prone Uint32.Swap instead.

+

func SwapUint64 1.2

func SwapUint64(addr *uint64, new uint64) (old uint64)

SwapUint64 atomically stores new into *addr and returns the previous *addr value. Consider using the more ergonomic and less error-prone Uint64.Swap instead (particularly if you target 32-bit platforms; see the bugs section).

+

func SwapUintptr 1.2

func SwapUintptr(addr *uintptr, new uintptr) (old uintptr)

SwapUintptr atomically stores new into *addr and returns the previous *addr value. Consider using the more ergonomic and less error-prone Uintptr.Swap instead.

+

type Bool 1.19

A Bool is an atomic boolean value. The zero value is false.

+
type Bool struct {
+    // contains filtered or unexported fields
+}
+

func (*Bool) CompareAndSwap 1.19

func (x *Bool) CompareAndSwap(old, new bool) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for the boolean value x.

+

func (*Bool) Load 1.19

func (x *Bool) Load() bool

Load atomically loads and returns the value stored in x.

+

func (*Bool) Store 1.19

func (x *Bool) Store(val bool)

Store atomically stores val into x.

+

func (*Bool) Swap 1.19

func (x *Bool) Swap(new bool) (old bool)

Swap atomically stores new into x and returns the previous value.

+

type Int32 1.19

An Int32 is an atomic int32. The zero value is zero.

+
type Int32 struct {
+    // contains filtered or unexported fields
+}
+

func (*Int32) Add 1.19

func (x *Int32) Add(delta int32) (new int32)

Add atomically adds delta to x and returns the new value.

+

func (*Int32) CompareAndSwap 1.19

func (x *Int32) CompareAndSwap(old, new int32) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for x.

+

func (*Int32) Load 1.19

func (x *Int32) Load() int32

Load atomically loads and returns the value stored in x.

+

func (*Int32) Store 1.19

func (x *Int32) Store(val int32)

Store atomically stores val into x.

+

func (*Int32) Swap 1.19

func (x *Int32) Swap(new int32) (old int32)

Swap atomically stores new into x and returns the previous value.

+

type Int64 1.19

An Int64 is an atomic int64. The zero value is zero.

+
type Int64 struct {
+    // contains filtered or unexported fields
+}
+

func (*Int64) Add 1.19

func (x *Int64) Add(delta int64) (new int64)

Add atomically adds delta to x and returns the new value.

+

func (*Int64) CompareAndSwap 1.19

func (x *Int64) CompareAndSwap(old, new int64) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for x.

+

func (*Int64) Load 1.19

func (x *Int64) Load() int64

Load atomically loads and returns the value stored in x.

+

func (*Int64) Store 1.19

func (x *Int64) Store(val int64)

Store atomically stores val into x.

+

func (*Int64) Swap 1.19

func (x *Int64) Swap(new int64) (old int64)

Swap atomically stores new into x and returns the previous value.

+

type Pointer

A Pointer is an atomic pointer of type *T. The zero value is a nil *T.

+
type Pointer[T any] struct {
+    // contains filtered or unexported fields
+}
+

func (*Pointer[T]) CompareAndSwap

func (x *Pointer[T]) CompareAndSwap(old, new *T) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for x.

+

func (*Pointer[T]) Load

func (x *Pointer[T]) Load() *T

Load atomically loads and returns the value stored in x.

+

func (*Pointer[T]) Store

func (x *Pointer[T]) Store(val *T)

Store atomically stores val into x.

+

func (*Pointer[T]) Swap

func (x *Pointer[T]) Swap(new *T) (old *T)

Swap atomically stores new into x and returns the previous value.

+

type Uint32 1.19

A Uint32 is an atomic uint32. The zero value is zero.

+
type Uint32 struct {
+    // contains filtered or unexported fields
+}
+

func (*Uint32) Add 1.19

func (x *Uint32) Add(delta uint32) (new uint32)

Add atomically adds delta to x and returns the new value.

+

func (*Uint32) CompareAndSwap 1.19

func (x *Uint32) CompareAndSwap(old, new uint32) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for x.

+

func (*Uint32) Load 1.19

func (x *Uint32) Load() uint32

Load atomically loads and returns the value stored in x.

+

func (*Uint32) Store 1.19

func (x *Uint32) Store(val uint32)

Store atomically stores val into x.

+

func (*Uint32) Swap 1.19

func (x *Uint32) Swap(new uint32) (old uint32)

Swap atomically stores new into x and returns the previous value.

+

type Uint64 1.19

A Uint64 is an atomic uint64. The zero value is zero.

+
type Uint64 struct {
+    // contains filtered or unexported fields
+}
+

func (*Uint64) Add 1.19

func (x *Uint64) Add(delta uint64) (new uint64)

Add atomically adds delta to x and returns the new value.

+

func (*Uint64) CompareAndSwap 1.19

func (x *Uint64) CompareAndSwap(old, new uint64) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for x.

+

func (*Uint64) Load 1.19

func (x *Uint64) Load() uint64

Load atomically loads and returns the value stored in x.

+

func (*Uint64) Store 1.19

func (x *Uint64) Store(val uint64)

Store atomically stores val into x.

+

func (*Uint64) Swap 1.19

func (x *Uint64) Swap(new uint64) (old uint64)

Swap atomically stores new into x and returns the previous value.

+

type Uintptr 1.19

A Uintptr is an atomic uintptr. The zero value is zero.

+
type Uintptr struct {
+    // contains filtered or unexported fields
+}
+

func (*Uintptr) Add 1.19

func (x *Uintptr) Add(delta uintptr) (new uintptr)

Add atomically adds delta to x and returns the new value.

+

func (*Uintptr) CompareAndSwap 1.19

func (x *Uintptr) CompareAndSwap(old, new uintptr) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for x.

+

func (*Uintptr) Load 1.19

func (x *Uintptr) Load() uintptr

Load atomically loads and returns the value stored in x.

+

func (*Uintptr) Store 1.19

func (x *Uintptr) Store(val uintptr)

Store atomically stores val into x.

+

func (*Uintptr) Swap 1.19

func (x *Uintptr) Swap(new uintptr) (old uintptr)

Swap atomically stores new into x and returns the previous value.

+

type Value 1.4

A Value provides an atomic load and store of a consistently typed value. The zero value for a Value returns nil from Load. Once Store has been called, a Value must not be copied.

+

A Value must not be copied after first use.

+
type Value struct {
+    // contains filtered or unexported fields
+}
+

Example (Config) +

The following example shows how to use Value for periodic program config updates and propagation of the changes to worker goroutines.

Code:

+var config atomic.Value // holds current server configuration
+// Create initial config value and store into config.
+config.Store(loadConfig())
+go func() {
+    // Reload config every 10 seconds
+    // and update config value with the new version.
+    for {
+        time.Sleep(10 * time.Second)
+        config.Store(loadConfig())
+    }
+}()
+// Create worker goroutines that handle incoming requests
+// using the latest config value.
+for i := 0; i < 10; i++ {
+    go func() {
+        for r := range requests() {
+            c := config.Load()
+            // Handle request r using config c.
+            _, _ = r, c
+        }
+    }()
+}
+

Example (ReadMostly) +

The following example shows how to maintain a scalable frequently read, but infrequently updated data structure using copy-on-write idiom.

Code:

+type Map map[string]string
+var m atomic.Value
+m.Store(make(Map))
+var mu sync.Mutex // used only by writers
+// read function can be used to read the data without further synchronization
+read := func(key string) (val string) {
+    m1 := m.Load().(Map)
+    return m1[key]
+}
+// insert function can be used to update the data without further synchronization
+insert := func(key, val string) {
+    mu.Lock() // synchronize with other potential writers
+    defer mu.Unlock()
+    m1 := m.Load().(Map) // load current value of the data structure
+    m2 := make(Map)      // create a new value
+    for k, v := range m1 {
+        m2[k] = v // copy all data from the current object to the new one
+    }
+    m2[key] = val // do the update that we need
+    m.Store(m2)   // atomically replace the current object with the new one
+    // At this point all new readers start working with the new version.
+    // The old version will be garbage collected once the existing readers
+    // (if any) are done with it.
+}
+_, _ = read, insert
+

func (*Value) CompareAndSwap 1.17

func (v *Value) CompareAndSwap(old, new any) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for the Value.

+

All calls to CompareAndSwap for a given Value must use values of the same concrete type. CompareAndSwap of an inconsistent type panics, as does CompareAndSwap(old, nil).

+

func (*Value) Load 1.4

func (v *Value) Load() (val any)

Load returns the value set by the most recent Store. It returns nil if there has been no call to Store for this Value.

+

func (*Value) Store 1.4

func (v *Value) Store(val any)

Store sets the value of the Value v to val. All calls to Store for a given Value must use values of the same concrete type. Store of an inconsistent type panics, as does Store(nil).

+

func (*Value) Swap 1.17

func (v *Value) Swap(new any) (old any)

Swap stores new into Value and returns the previous value. It returns nil if the Value is empty.

+

All calls to Swap for a given Value must use values of the same concrete type. Swap of an inconsistent type panics, as does Swap(nil).

+

Bugs

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/sync/atomic/ +

+
diff --git a/devdocs/go/sync%2Findex.html b/devdocs/go/sync%2Findex.html new file mode 100644 index 00000000..d697bad7 --- /dev/null +++ b/devdocs/go/sync%2Findex.html @@ -0,0 +1,290 @@ +

Package sync

Overview

Package sync provides basic synchronization primitives such as mutual exclusion locks. Other than the Once and WaitGroup types, most are intended for use by low-level library routines. Higher-level synchronization is better done via channels and communication.

+

Values containing the types defined in this package should not be copied.

Index

Examples

Once
Pool
WaitGroup

Package files

cond.go map.go mutex.go once.go oncefunc.go pool.go poolqueue.go runtime.go runtime2.go rwmutex.go waitgroup.go

func OnceFunc 1.21

func OnceFunc(f func()) func()

OnceFunc returns a function that invokes f only once. The returned function may be called concurrently.

+

If f panics, the returned function will panic with the same value on every call.

+

func OnceValue

func OnceValue[T any](f func() T) func() T

OnceValue returns a function that invokes f only once and returns the value returned by f. The returned function may be called concurrently.

+

If f panics, the returned function will panic with the same value on every call.

+

func OnceValues

func OnceValues[T1, T2 any](f func() (T1, T2)) func() (T1, T2)

OnceValues returns a function that invokes f only once and returns the values returned by f. The returned function may be called concurrently.

+

If f panics, the returned function will panic with the same value on every call.

+

type Cond

Cond implements a condition variable, a rendezvous point for goroutines waiting for or announcing the occurrence of an event.

+

Each Cond has an associated Locker L (often a *Mutex or *RWMutex), which must be held when changing the condition and when calling the Wait method.

+

A Cond must not be copied after first use.

+

In the terminology of the Go memory model, Cond arranges that a call to Broadcast or Signal “synchronizes before” any Wait call that it unblocks.

+

For many simple use cases, users will be better off using channels than a Cond (Broadcast corresponds to closing a channel, and Signal corresponds to sending on a channel).

+

For more on replacements for sync.Cond, see Roberto Clapis's series on advanced concurrency patterns, as well as Bryan Mills's talk on concurrency patterns.

+
type Cond struct {
+
+    // L is held while observing or changing the condition
+    L Locker
+    // contains filtered or unexported fields
+}
+

func NewCond

func NewCond(l Locker) *Cond

NewCond returns a new Cond with Locker l.

+

func (*Cond) Broadcast

func (c *Cond) Broadcast()

Broadcast wakes all goroutines waiting on c.

+

It is allowed but not required for the caller to hold c.L during the call.

+

func (*Cond) Signal

func (c *Cond) Signal()

Signal wakes one goroutine waiting on c, if there is any.

+

It is allowed but not required for the caller to hold c.L during the call.

+

Signal() does not affect goroutine scheduling priority; if other goroutines are attempting to lock c.L, they may be awoken before a "waiting" goroutine.

+

func (*Cond) Wait

func (c *Cond) Wait()

Wait atomically unlocks c.L and suspends execution of the calling goroutine. After later resuming execution, Wait locks c.L before returning. Unlike in other systems, Wait cannot return unless awoken by Broadcast or Signal.

+

Because c.L is not locked while Wait is waiting, the caller typically cannot assume that the condition is true when Wait returns. Instead, the caller should Wait in a loop:

+
c.L.Lock()
+for !condition() {
+    c.Wait()
+}
+... make use of condition ...
+c.L.Unlock()
+

type Locker

A Locker represents an object that can be locked and unlocked.

+
type Locker interface {
+    Lock()
+    Unlock()
+}

type Map 1.9

Map is like a Go map[any]any but is safe for concurrent use by multiple goroutines without additional locking or coordination. Loads, stores, and deletes run in amortized constant time.

+

The Map type is specialized. Most code should use a plain Go map instead, with separate locking or coordination, for better type safety and to make it easier to maintain other invariants along with the map content.

+

The Map type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys. In these two cases, use of a Map may significantly reduce lock contention compared to a Go map paired with a separate Mutex or RWMutex.

+

The zero Map is empty and ready for use. A Map must not be copied after first use.

+

In the terminology of the Go memory model, Map arranges that a write operation “synchronizes before” any read operation that observes the effect of the write, where read and write operations are defined as follows. Load, LoadAndDelete, LoadOrStore, Swap, CompareAndSwap, and CompareAndDelete are read operations; Delete, LoadAndDelete, Store, and Swap are write operations; LoadOrStore is a write operation when it returns loaded set to false; CompareAndSwap is a write operation when it returns swapped set to true; and CompareAndDelete is a write operation when it returns deleted set to true.

+
type Map struct {
+    // contains filtered or unexported fields
+}
+

func (*Map) CompareAndDelete 1.20

func (m *Map) CompareAndDelete(key, old any) (deleted bool)

CompareAndDelete deletes the entry for key if its value is equal to old. The old value must be of a comparable type.

+

If there is no current value for key in the map, CompareAndDelete returns false (even if the old value is the nil interface value).

+

func (*Map) CompareAndSwap 1.20

func (m *Map) CompareAndSwap(key, old, new any) bool

CompareAndSwap swaps the old and new values for key if the value stored in the map is equal to old. The old value must be of a comparable type.

+

func (*Map) Delete 1.9

func (m *Map) Delete(key any)

Delete deletes the value for a key.

+

func (*Map) Load 1.9

func (m *Map) Load(key any) (value any, ok bool)

Load returns the value stored in the map for a key, or nil if no value is present. The ok result indicates whether value was found in the map.

+

func (*Map) LoadAndDelete 1.15

func (m *Map) LoadAndDelete(key any) (value any, loaded bool)

LoadAndDelete deletes the value for a key, returning the previous value if any. The loaded result reports whether the key was present.

+

func (*Map) LoadOrStore 1.9

func (m *Map) LoadOrStore(key, value any) (actual any, loaded bool)

LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.

+

func (*Map) Range 1.9

func (m *Map) Range(f func(key, value any) bool)

Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.

+

Range does not necessarily correspond to any consistent snapshot of the Map's contents: no key will be visited more than once, but if the value for any key is stored or deleted concurrently (including by f), Range may reflect any mapping for that key from any point during the Range call. Range does not block other methods on the receiver; even f itself may call any method on m.

+

Range may be O(N) with the number of elements in the map even if f returns false after a constant number of calls.

+

func (*Map) Store 1.9

func (m *Map) Store(key, value any)

Store sets the value for a key.

+

func (*Map) Swap 1.20

func (m *Map) Swap(key, value any) (previous any, loaded bool)

Swap swaps the value for a key and returns the previous value if any. The loaded result reports whether the key was present.

+

type Mutex

A Mutex is a mutual exclusion lock. The zero value for a Mutex is an unlocked mutex.

+

A Mutex must not be copied after first use.

+

In the terminology of the Go memory model, the n'th call to Unlock “synchronizes before” the m'th call to Lock for any n < m. A successful call to TryLock is equivalent to a call to Lock. A failed call to TryLock does not establish any “synchronizes before” relation at all.

+
type Mutex struct {
+    // contains filtered or unexported fields
+}
+

func (*Mutex) Lock

func (m *Mutex) Lock()

Lock locks m. If the lock is already in use, the calling goroutine blocks until the mutex is available.

+

func (*Mutex) TryLock 1.18

func (m *Mutex) TryLock() bool

TryLock tries to lock m and reports whether it succeeded.

+

Note that while correct uses of TryLock do exist, they are rare, and use of TryLock is often a sign of a deeper problem in a particular use of mutexes.

+

func (*Mutex) Unlock

func (m *Mutex) Unlock()

Unlock unlocks m. It is a run-time error if m is not locked on entry to Unlock.

+

A locked Mutex is not associated with a particular goroutine. It is allowed for one goroutine to lock a Mutex and then arrange for another goroutine to unlock it.

+

type Once

Once is an object that will perform exactly one action.

+

A Once must not be copied after first use.

+

In the terminology of the Go memory model, the return from f “synchronizes before” the return from any call of once.Do(f).

+
type Once struct {
+    // contains filtered or unexported fields
+}
+

Example +

Code:

var once sync.Once
+onceBody := func() {
+    fmt.Println("Only once")
+}
+done := make(chan bool)
+for i := 0; i < 10; i++ {
+    go func() {
+        once.Do(onceBody)
+        done <- true
+    }()
+}
+for i := 0; i < 10; i++ {
+    <-done
+}
+

Output:

Only once
+

func (*Once) Do

func (o *Once) Do(f func())

Do calls the function f if and only if Do is being called for the first time for this instance of Once. In other words, given

+
var once Once
+

if once.Do(f) is called multiple times, only the first call will invoke f, even if f has a different value in each invocation. A new instance of Once is required for each function to execute.

+

Do is intended for initialization that must be run exactly once. Since f is niladic, it may be necessary to use a function literal to capture the arguments to a function to be invoked by Do:

+
config.once.Do(func() { config.init(filename) })
+

Because no call to Do returns until the one call to f returns, if f causes Do to be called, it will deadlock.

+

If f panics, Do considers it to have returned; future calls of Do return without calling f.

+

type Pool 1.3

A Pool is a set of temporary objects that may be individually saved and retrieved.

+

Any item stored in the Pool may be removed automatically at any time without notification. If the Pool holds the only reference when this happens, the item might be deallocated.

+

A Pool is safe for use by multiple goroutines simultaneously.

+

Pool's purpose is to cache allocated but unused items for later reuse, relieving pressure on the garbage collector. That is, it makes it easy to build efficient, thread-safe free lists. However, it is not suitable for all free lists.

+

An appropriate use of a Pool is to manage a group of temporary items silently shared among and potentially reused by concurrent independent clients of a package. Pool provides a way to amortize allocation overhead across many clients.

+

An example of good use of a Pool is in the fmt package, which maintains a dynamically-sized store of temporary output buffers. The store scales under load (when many goroutines are actively printing) and shrinks when quiescent.

+

On the other hand, a free list maintained as part of a short-lived object is not a suitable use for a Pool, since the overhead does not amortize well in that scenario. It is more efficient to have such objects implement their own free list.

+

A Pool must not be copied after first use.

+

In the terminology of the Go memory model, a call to Put(x) “synchronizes before” a call to Get returning that same value x. Similarly, a call to New returning x “synchronizes before” a call to Get returning that same value x.

+
type Pool struct {
+
+    // New optionally specifies a function to generate
+    // a value when Get would otherwise return nil.
+    // It may not be changed concurrently with calls to Get.
+    New func() any
+    // contains filtered or unexported fields
+}
+

Example +

Code:

package sync_test
+
+import (
+    "bytes"
+    "io"
+    "os"
+    "sync"
+    "time"
+)
+
+var bufPool = sync.Pool{
+    New: func() any {
+        // The Pool's New function should generally only return pointer
+        // types, since a pointer can be put into the return interface
+        // value without an allocation:
+        return new(bytes.Buffer)
+    },
+}
+
+// timeNow is a fake version of time.Now for tests.
+func timeNow() time.Time {
+    return time.Unix(1136214245, 0)
+}
+
+func Log(w io.Writer, key, val string) {
+    b := bufPool.Get().(*bytes.Buffer)
+    b.Reset()
+    // Replace this with time.Now() in a real logger.
+    b.WriteString(timeNow().UTC().Format(time.RFC3339))
+    b.WriteByte(' ')
+    b.WriteString(key)
+    b.WriteByte('=')
+    b.WriteString(val)
+    w.Write(b.Bytes())
+    bufPool.Put(b)
+}
+
+func ExamplePool() {
+    Log(os.Stdout, "path", "/search?q=flowers")
+    // Output: 2006-01-02T15:04:05Z path=/search?q=flowers
+}
+

func (*Pool) Get 1.3

func (p *Pool) Get() any

Get selects an arbitrary item from the Pool, removes it from the Pool, and returns it to the caller. Get may choose to ignore the pool and treat it as empty. Callers should not assume any relation between values passed to Put and the values returned by Get.

+

If Get would otherwise return nil and p.New is non-nil, Get returns the result of calling p.New.

+

func (*Pool) Put 1.3

func (p *Pool) Put(x any)

Put adds x to the pool.

+

type RWMutex

A RWMutex is a reader/writer mutual exclusion lock. The lock can be held by an arbitrary number of readers or a single writer. The zero value for a RWMutex is an unlocked mutex.

+

A RWMutex must not be copied after first use.

+

If any goroutine calls Lock while the lock is already held by one or more readers, concurrent calls to RLock will block until the writer has acquired (and released) the lock, to ensure that the lock eventually becomes available to the writer. Note that this prohibits recursive read-locking.

+

In the terminology of the Go memory model, the n'th call to Unlock “synchronizes before” the m'th call to Lock for any n < m, just as for Mutex. For any call to RLock, there exists an n such that the n'th call to Unlock “synchronizes before” that call to RLock, and the corresponding call to RUnlock “synchronizes before” the n+1'th call to Lock.

+
type RWMutex struct {
+    // contains filtered or unexported fields
+}
+

func (*RWMutex) Lock

func (rw *RWMutex) Lock()

Lock locks rw for writing. If the lock is already locked for reading or writing, Lock blocks until the lock is available.

+

func (*RWMutex) RLock

func (rw *RWMutex) RLock()

RLock locks rw for reading.

+

It should not be used for recursive read locking; a blocked Lock call excludes new readers from acquiring the lock. See the documentation on the RWMutex type.

+

func (*RWMutex) RLocker

func (rw *RWMutex) RLocker() Locker

RLocker returns a Locker interface that implements the Lock and Unlock methods by calling rw.RLock and rw.RUnlock.

+

func (*RWMutex) RUnlock

func (rw *RWMutex) RUnlock()

RUnlock undoes a single RLock call; it does not affect other simultaneous readers. It is a run-time error if rw is not locked for reading on entry to RUnlock.

+

func (*RWMutex) TryLock 1.18

func (rw *RWMutex) TryLock() bool

TryLock tries to lock rw for writing and reports whether it succeeded.

+

Note that while correct uses of TryLock do exist, they are rare, and use of TryLock is often a sign of a deeper problem in a particular use of mutexes.

+

func (*RWMutex) TryRLock 1.18

func (rw *RWMutex) TryRLock() bool

TryRLock tries to lock rw for reading and reports whether it succeeded.

+

Note that while correct uses of TryRLock do exist, they are rare, and use of TryRLock is often a sign of a deeper problem in a particular use of mutexes.

+

func (*RWMutex) Unlock

func (rw *RWMutex) Unlock()

Unlock unlocks rw for writing. It is a run-time error if rw is not locked for writing on entry to Unlock.

+

As with Mutexes, a locked RWMutex is not associated with a particular goroutine. One goroutine may RLock (Lock) a RWMutex and then arrange for another goroutine to RUnlock (Unlock) it.

+

type WaitGroup

A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.

+

A WaitGroup must not be copied after first use.

+

In the terminology of the Go memory model, a call to Done “synchronizes before” the return of any Wait call that it unblocks.

+
type WaitGroup struct {
+    // contains filtered or unexported fields
+}
+

Example +

This example fetches several URLs concurrently, using a WaitGroup to block until all the fetches are complete.

Code:

+var wg sync.WaitGroup
+var urls = []string{
+    "http://www.golang.org/",
+    "http://www.google.com/",
+    "http://www.example.com/",
+}
+for _, url := range urls {
+    // Increment the WaitGroup counter.
+    wg.Add(1)
+    // Launch a goroutine to fetch the URL.
+    go func(url string) {
+        // Decrement the counter when the goroutine completes.
+        defer wg.Done()
+        // Fetch the URL.
+        http.Get(url)
+    }(url)
+}
+// Wait for all HTTP fetches to complete.
+wg.Wait()
+

func (*WaitGroup) Add

func (wg *WaitGroup) Add(delta int)

Add adds delta, which may be negative, to the WaitGroup counter. If the counter becomes zero, all goroutines blocked on Wait are released. If the counter goes negative, Add panics.

+

Note that calls with a positive delta that occur when the counter is zero must happen before a Wait. Calls with a negative delta, or calls with a positive delta that start when the counter is greater than zero, may happen at any time. Typically this means the calls to Add should execute before the statement creating the goroutine or other event to be waited for. If a WaitGroup is reused to wait for several independent sets of events, new Add calls must happen after all previous Wait calls have returned. See the WaitGroup example.

+

func (*WaitGroup) Done

func (wg *WaitGroup) Done()

Done decrements the WaitGroup counter by one.

+

func (*WaitGroup) Wait

func (wg *WaitGroup) Wait()

Wait blocks until the WaitGroup counter is zero.

+

Subdirectories

Name Synopsis
..
atomic Package atomic provides low-level atomic memory primitives useful for implementing synchronization algorithms.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/sync/ +

+
diff --git a/devdocs/go/syscall%2Findex.html b/devdocs/go/syscall%2Findex.html new file mode 100644 index 00000000..98841565 --- /dev/null +++ b/devdocs/go/syscall%2Findex.html @@ -0,0 +1,2897 @@ +

Package syscall

Overview

Package syscall contains an interface to the low-level operating system primitives. The details vary depending on the underlying system, and by default, godoc will display the syscall documentation for the current system. If you want godoc to display syscall documentation for another system, set $GOOS and $GOARCH to the desired system. For example, if you want to view documentation for freebsd/arm on linux/amd64, set $GOOS to freebsd and $GOARCH to arm. The primary use of syscall is inside other packages that provide a more portable interface to the system, such as "os", "time" and "net". Use those packages rather than this one if you can. For details of the functions and data types in this package consult the manuals for the appropriate operating system. These calls return err == nil to indicate success; otherwise err is an operating system error describing the failure. On most systems, that error has type syscall.Errno.

+

NOTE: Most of the functions, types, and constants defined in this package are also available in the golang.org/x/sys package. That package has more system call support than this one, and most new code should prefer that package where possible. See https://golang.org/s/go1.4-syscall for more information.

Index

Package files

asan0.go dirent.go endian_little.go env_unix.go exec_linux.go exec_unix.go flock_linux.go forkpipe2.go lsf_linux.go msan0.go net.go netlink_linux.go rlimit.go rlimit_stub.go setuidgid_linux.go sockcmsg_linux.go sockcmsg_unix.go sockcmsg_unix_other.go syscall.go syscall_linux.go syscall_linux_accept4.go syscall_linux_amd64.go syscall_unix.go time_nofake.go timestruct.go zerrors_linux_amd64.go zsyscall_linux_amd64.go zsysnum_linux_amd64.go ztypes_linux_amd64.go

Constants

Linux unshare/clone/clone2/clone3 flags, architecture-independent, copied from linux/sched.h.

+
const (
+    CLONE_VM             = 0x00000100 // set if VM shared between processes
+    CLONE_FS             = 0x00000200 // set if fs info shared between processes
+    CLONE_FILES          = 0x00000400 // set if open files shared between processes
+    CLONE_SIGHAND        = 0x00000800 // set if signal handlers and blocked signals shared
+    CLONE_PIDFD          = 0x00001000 // set if a pidfd should be placed in parent
+    CLONE_PTRACE         = 0x00002000 // set if we want to let tracing continue on the child too
+    CLONE_VFORK          = 0x00004000 // set if the parent wants the child to wake it up on mm_release
+    CLONE_PARENT         = 0x00008000 // set if we want to have the same parent as the cloner
+    CLONE_THREAD         = 0x00010000 // Same thread group?
+    CLONE_NEWNS          = 0x00020000 // New mount namespace group
+    CLONE_SYSVSEM        = 0x00040000 // share system V SEM_UNDO semantics
+    CLONE_SETTLS         = 0x00080000 // create a new TLS for the child
+    CLONE_PARENT_SETTID  = 0x00100000 // set the TID in the parent
+    CLONE_CHILD_CLEARTID = 0x00200000 // clear the TID in the child
+    CLONE_DETACHED       = 0x00400000 // Unused, ignored
+    CLONE_UNTRACED       = 0x00800000 // set if the tracing process can't force CLONE_PTRACE on this clone
+    CLONE_CHILD_SETTID   = 0x01000000 // set the TID in the child
+    CLONE_NEWCGROUP      = 0x02000000 // New cgroup namespace
+    CLONE_NEWUTS         = 0x04000000 // New utsname namespace
+    CLONE_NEWIPC         = 0x08000000 // New ipc namespace
+    CLONE_NEWUSER        = 0x10000000 // New user namespace
+    CLONE_NEWPID         = 0x20000000 // New pid namespace
+    CLONE_NEWNET         = 0x40000000 // New network namespace
+    CLONE_IO             = 0x80000000 // Clone io context
+
+    CLONE_CLEAR_SIGHAND = 0x100000000 // Clear any signal handler and reset to SIG_DFL.
+    CLONE_INTO_CGROUP   = 0x200000000 // Clone into a specific cgroup given the right permissions.
+
+    CLONE_NEWTIME = 0x00000080 // New time namespace
+)
const (
+    AF_ALG                           = 0x26
+    AF_APPLETALK                     = 0x5
+    AF_ASH                           = 0x12
+    AF_ATMPVC                        = 0x8
+    AF_ATMSVC                        = 0x14
+    AF_AX25                          = 0x3
+    AF_BLUETOOTH                     = 0x1f
+    AF_BRIDGE                        = 0x7
+    AF_CAIF                          = 0x25
+    AF_CAN                           = 0x1d
+    AF_DECnet                        = 0xc
+    AF_ECONET                        = 0x13
+    AF_FILE                          = 0x1
+    AF_IEEE802154                    = 0x24
+    AF_INET                          = 0x2
+    AF_INET6                         = 0xa
+    AF_IPX                           = 0x4
+    AF_IRDA                          = 0x17
+    AF_ISDN                          = 0x22
+    AF_IUCV                          = 0x20
+    AF_KEY                           = 0xf
+    AF_LLC                           = 0x1a
+    AF_LOCAL                         = 0x1
+    AF_MAX                           = 0x27
+    AF_NETBEUI                       = 0xd
+    AF_NETLINK                       = 0x10
+    AF_NETROM                        = 0x6
+    AF_PACKET                        = 0x11
+    AF_PHONET                        = 0x23
+    AF_PPPOX                         = 0x18
+    AF_RDS                           = 0x15
+    AF_ROSE                          = 0xb
+    AF_ROUTE                         = 0x10
+    AF_RXRPC                         = 0x21
+    AF_SECURITY                      = 0xe
+    AF_SNA                           = 0x16
+    AF_TIPC                          = 0x1e
+    AF_UNIX                          = 0x1
+    AF_UNSPEC                        = 0x0
+    AF_WANPIPE                       = 0x19
+    AF_X25                           = 0x9
+    ARPHRD_ADAPT                     = 0x108
+    ARPHRD_APPLETLK                  = 0x8
+    ARPHRD_ARCNET                    = 0x7
+    ARPHRD_ASH                       = 0x30d
+    ARPHRD_ATM                       = 0x13
+    ARPHRD_AX25                      = 0x3
+    ARPHRD_BIF                       = 0x307
+    ARPHRD_CHAOS                     = 0x5
+    ARPHRD_CISCO                     = 0x201
+    ARPHRD_CSLIP                     = 0x101
+    ARPHRD_CSLIP6                    = 0x103
+    ARPHRD_DDCMP                     = 0x205
+    ARPHRD_DLCI                      = 0xf
+    ARPHRD_ECONET                    = 0x30e
+    ARPHRD_EETHER                    = 0x2
+    ARPHRD_ETHER                     = 0x1
+    ARPHRD_EUI64                     = 0x1b
+    ARPHRD_FCAL                      = 0x311
+    ARPHRD_FCFABRIC                  = 0x313
+    ARPHRD_FCPL                      = 0x312
+    ARPHRD_FCPP                      = 0x310
+    ARPHRD_FDDI                      = 0x306
+    ARPHRD_FRAD                      = 0x302
+    ARPHRD_HDLC                      = 0x201
+    ARPHRD_HIPPI                     = 0x30c
+    ARPHRD_HWX25                     = 0x110
+    ARPHRD_IEEE1394                  = 0x18
+    ARPHRD_IEEE802                   = 0x6
+    ARPHRD_IEEE80211                 = 0x321
+    ARPHRD_IEEE80211_PRISM           = 0x322
+    ARPHRD_IEEE80211_RADIOTAP        = 0x323
+    ARPHRD_IEEE802154                = 0x324
+    ARPHRD_IEEE802154_PHY            = 0x325
+    ARPHRD_IEEE802_TR                = 0x320
+    ARPHRD_INFINIBAND                = 0x20
+    ARPHRD_IPDDP                     = 0x309
+    ARPHRD_IPGRE                     = 0x30a
+    ARPHRD_IRDA                      = 0x30f
+    ARPHRD_LAPB                      = 0x204
+    ARPHRD_LOCALTLK                  = 0x305
+    ARPHRD_LOOPBACK                  = 0x304
+    ARPHRD_METRICOM                  = 0x17
+    ARPHRD_NETROM                    = 0x0
+    ARPHRD_NONE                      = 0xfffe
+    ARPHRD_PIMREG                    = 0x30b
+    ARPHRD_PPP                       = 0x200
+    ARPHRD_PRONET                    = 0x4
+    ARPHRD_RAWHDLC                   = 0x206
+    ARPHRD_ROSE                      = 0x10e
+    ARPHRD_RSRVD                     = 0x104
+    ARPHRD_SIT                       = 0x308
+    ARPHRD_SKIP                      = 0x303
+    ARPHRD_SLIP                      = 0x100
+    ARPHRD_SLIP6                     = 0x102
+    ARPHRD_TUNNEL                    = 0x300
+    ARPHRD_TUNNEL6                   = 0x301
+    ARPHRD_VOID                      = 0xffff
+    ARPHRD_X25                       = 0x10f
+    BPF_A                            = 0x10
+    BPF_ABS                          = 0x20
+    BPF_ADD                          = 0x0
+    BPF_ALU                          = 0x4
+    BPF_AND                          = 0x50
+    BPF_B                            = 0x10
+    BPF_DIV                          = 0x30
+    BPF_H                            = 0x8
+    BPF_IMM                          = 0x0
+    BPF_IND                          = 0x40
+    BPF_JA                           = 0x0
+    BPF_JEQ                          = 0x10
+    BPF_JGE                          = 0x30
+    BPF_JGT                          = 0x20
+    BPF_JMP                          = 0x5
+    BPF_JSET                         = 0x40
+    BPF_K                            = 0x0
+    BPF_LD                           = 0x0
+    BPF_LDX                          = 0x1
+    BPF_LEN                          = 0x80
+    BPF_LSH                          = 0x60
+    BPF_MAJOR_VERSION                = 0x1
+    BPF_MAXINSNS                     = 0x1000
+    BPF_MEM                          = 0x60
+    BPF_MEMWORDS                     = 0x10
+    BPF_MINOR_VERSION                = 0x1
+    BPF_MISC                         = 0x7
+    BPF_MSH                          = 0xa0
+    BPF_MUL                          = 0x20
+    BPF_NEG                          = 0x80
+    BPF_OR                           = 0x40
+    BPF_RET                          = 0x6
+    BPF_RSH                          = 0x70
+    BPF_ST                           = 0x2
+    BPF_STX                          = 0x3
+    BPF_SUB                          = 0x10
+    BPF_TAX                          = 0x0
+    BPF_TXA                          = 0x80
+    BPF_W                            = 0x0
+    BPF_X                            = 0x8
+    DT_BLK                           = 0x6
+    DT_CHR                           = 0x2
+    DT_DIR                           = 0x4
+    DT_FIFO                          = 0x1
+    DT_LNK                           = 0xa
+    DT_REG                           = 0x8
+    DT_SOCK                          = 0xc
+    DT_UNKNOWN                       = 0x0
+    DT_WHT                           = 0xe
+    EPOLLERR                         = 0x8
+    EPOLLET                          = -0x80000000
+    EPOLLHUP                         = 0x10
+    EPOLLIN                          = 0x1
+    EPOLLMSG                         = 0x400
+    EPOLLONESHOT                     = 0x40000000
+    EPOLLOUT                         = 0x4
+    EPOLLPRI                         = 0x2
+    EPOLLRDBAND                      = 0x80
+    EPOLLRDHUP                       = 0x2000
+    EPOLLRDNORM                      = 0x40
+    EPOLLWRBAND                      = 0x200
+    EPOLLWRNORM                      = 0x100
+    EPOLL_CLOEXEC                    = 0x80000
+    EPOLL_CTL_ADD                    = 0x1
+    EPOLL_CTL_DEL                    = 0x2
+    EPOLL_CTL_MOD                    = 0x3
+    EPOLL_NONBLOCK                   = 0x800
+    ETH_P_1588                       = 0x88f7
+    ETH_P_8021Q                      = 0x8100
+    ETH_P_802_2                      = 0x4
+    ETH_P_802_3                      = 0x1
+    ETH_P_AARP                       = 0x80f3
+    ETH_P_ALL                        = 0x3
+    ETH_P_AOE                        = 0x88a2
+    ETH_P_ARCNET                     = 0x1a
+    ETH_P_ARP                        = 0x806
+    ETH_P_ATALK                      = 0x809b
+    ETH_P_ATMFATE                    = 0x8884
+    ETH_P_ATMMPOA                    = 0x884c
+    ETH_P_AX25                       = 0x2
+    ETH_P_BPQ                        = 0x8ff
+    ETH_P_CAIF                       = 0xf7
+    ETH_P_CAN                        = 0xc
+    ETH_P_CONTROL                    = 0x16
+    ETH_P_CUST                       = 0x6006
+    ETH_P_DDCMP                      = 0x6
+    ETH_P_DEC                        = 0x6000
+    ETH_P_DIAG                       = 0x6005
+    ETH_P_DNA_DL                     = 0x6001
+    ETH_P_DNA_RC                     = 0x6002
+    ETH_P_DNA_RT                     = 0x6003
+    ETH_P_DSA                        = 0x1b
+    ETH_P_ECONET                     = 0x18
+    ETH_P_EDSA                       = 0xdada
+    ETH_P_FCOE                       = 0x8906
+    ETH_P_FIP                        = 0x8914
+    ETH_P_HDLC                       = 0x19
+    ETH_P_IEEE802154                 = 0xf6
+    ETH_P_IEEEPUP                    = 0xa00
+    ETH_P_IEEEPUPAT                  = 0xa01
+    ETH_P_IP                         = 0x800
+    ETH_P_IPV6                       = 0x86dd
+    ETH_P_IPX                        = 0x8137
+    ETH_P_IRDA                       = 0x17
+    ETH_P_LAT                        = 0x6004
+    ETH_P_LINK_CTL                   = 0x886c
+    ETH_P_LOCALTALK                  = 0x9
+    ETH_P_LOOP                       = 0x60
+    ETH_P_MOBITEX                    = 0x15
+    ETH_P_MPLS_MC                    = 0x8848
+    ETH_P_MPLS_UC                    = 0x8847
+    ETH_P_PAE                        = 0x888e
+    ETH_P_PAUSE                      = 0x8808
+    ETH_P_PHONET                     = 0xf5
+    ETH_P_PPPTALK                    = 0x10
+    ETH_P_PPP_DISC                   = 0x8863
+    ETH_P_PPP_MP                     = 0x8
+    ETH_P_PPP_SES                    = 0x8864
+    ETH_P_PUP                        = 0x200
+    ETH_P_PUPAT                      = 0x201
+    ETH_P_RARP                       = 0x8035
+    ETH_P_SCA                        = 0x6007
+    ETH_P_SLOW                       = 0x8809
+    ETH_P_SNAP                       = 0x5
+    ETH_P_TEB                        = 0x6558
+    ETH_P_TIPC                       = 0x88ca
+    ETH_P_TRAILER                    = 0x1c
+    ETH_P_TR_802_2                   = 0x11
+    ETH_P_WAN_PPP                    = 0x7
+    ETH_P_WCCP                       = 0x883e
+    ETH_P_X25                        = 0x805
+    FD_CLOEXEC                       = 0x1
+    FD_SETSIZE                       = 0x400
+    F_DUPFD                          = 0x0
+    F_DUPFD_CLOEXEC                  = 0x406
+    F_EXLCK                          = 0x4
+    F_GETFD                          = 0x1
+    F_GETFL                          = 0x3
+    F_GETLEASE                       = 0x401
+    F_GETLK                          = 0x5
+    F_GETLK64                        = 0x5
+    F_GETOWN                         = 0x9
+    F_GETOWN_EX                      = 0x10
+    F_GETPIPE_SZ                     = 0x408
+    F_GETSIG                         = 0xb
+    F_LOCK                           = 0x1
+    F_NOTIFY                         = 0x402
+    F_OK                             = 0x0
+    F_RDLCK                          = 0x0
+    F_SETFD                          = 0x2
+    F_SETFL                          = 0x4
+    F_SETLEASE                       = 0x400
+    F_SETLK                          = 0x6
+    F_SETLK64                        = 0x6
+    F_SETLKW                         = 0x7
+    F_SETLKW64                       = 0x7
+    F_SETOWN                         = 0x8
+    F_SETOWN_EX                      = 0xf
+    F_SETPIPE_SZ                     = 0x407
+    F_SETSIG                         = 0xa
+    F_SHLCK                          = 0x8
+    F_TEST                           = 0x3
+    F_TLOCK                          = 0x2
+    F_ULOCK                          = 0x0
+    F_UNLCK                          = 0x2
+    F_WRLCK                          = 0x1
+    ICMPV6_FILTER                    = 0x1
+    IFA_F_DADFAILED                  = 0x8
+    IFA_F_DEPRECATED                 = 0x20
+    IFA_F_HOMEADDRESS                = 0x10
+    IFA_F_NODAD                      = 0x2
+    IFA_F_OPTIMISTIC                 = 0x4
+    IFA_F_PERMANENT                  = 0x80
+    IFA_F_SECONDARY                  = 0x1
+    IFA_F_TEMPORARY                  = 0x1
+    IFA_F_TENTATIVE                  = 0x40
+    IFA_MAX                          = 0x7
+    IFF_ALLMULTI                     = 0x200
+    IFF_AUTOMEDIA                    = 0x4000
+    IFF_BROADCAST                    = 0x2
+    IFF_DEBUG                        = 0x4
+    IFF_DYNAMIC                      = 0x8000
+    IFF_LOOPBACK                     = 0x8
+    IFF_MASTER                       = 0x400
+    IFF_MULTICAST                    = 0x1000
+    IFF_NOARP                        = 0x80
+    IFF_NOTRAILERS                   = 0x20
+    IFF_NO_PI                        = 0x1000
+    IFF_ONE_QUEUE                    = 0x2000
+    IFF_POINTOPOINT                  = 0x10
+    IFF_PORTSEL                      = 0x2000
+    IFF_PROMISC                      = 0x100
+    IFF_RUNNING                      = 0x40
+    IFF_SLAVE                        = 0x800
+    IFF_TAP                          = 0x2
+    IFF_TUN                          = 0x1
+    IFF_TUN_EXCL                     = 0x8000
+    IFF_UP                           = 0x1
+    IFF_VNET_HDR                     = 0x4000
+    IFNAMSIZ                         = 0x10
+    IN_ACCESS                        = 0x1
+    IN_ALL_EVENTS                    = 0xfff
+    IN_ATTRIB                        = 0x4
+    IN_CLASSA_HOST                   = 0xffffff
+    IN_CLASSA_MAX                    = 0x80
+    IN_CLASSA_NET                    = 0xff000000
+    IN_CLASSA_NSHIFT                 = 0x18
+    IN_CLASSB_HOST                   = 0xffff
+    IN_CLASSB_MAX                    = 0x10000
+    IN_CLASSB_NET                    = 0xffff0000
+    IN_CLASSB_NSHIFT                 = 0x10
+    IN_CLASSC_HOST                   = 0xff
+    IN_CLASSC_NET                    = 0xffffff00
+    IN_CLASSC_NSHIFT                 = 0x8
+    IN_CLOEXEC                       = 0x80000
+    IN_CLOSE                         = 0x18
+    IN_CLOSE_NOWRITE                 = 0x10
+    IN_CLOSE_WRITE                   = 0x8
+    IN_CREATE                        = 0x100
+    IN_DELETE                        = 0x200
+    IN_DELETE_SELF                   = 0x400
+    IN_DONT_FOLLOW                   = 0x2000000
+    IN_EXCL_UNLINK                   = 0x4000000
+    IN_IGNORED                       = 0x8000
+    IN_ISDIR                         = 0x40000000
+    IN_LOOPBACKNET                   = 0x7f
+    IN_MASK_ADD                      = 0x20000000
+    IN_MODIFY                        = 0x2
+    IN_MOVE                          = 0xc0
+    IN_MOVED_FROM                    = 0x40
+    IN_MOVED_TO                      = 0x80
+    IN_MOVE_SELF                     = 0x800
+    IN_NONBLOCK                      = 0x800
+    IN_ONESHOT                       = 0x80000000
+    IN_ONLYDIR                       = 0x1000000
+    IN_OPEN                          = 0x20
+    IN_Q_OVERFLOW                    = 0x4000
+    IN_UNMOUNT                       = 0x2000
+    IPPROTO_AH                       = 0x33
+    IPPROTO_COMP                     = 0x6c
+    IPPROTO_DCCP                     = 0x21
+    IPPROTO_DSTOPTS                  = 0x3c
+    IPPROTO_EGP                      = 0x8
+    IPPROTO_ENCAP                    = 0x62
+    IPPROTO_ESP                      = 0x32
+    IPPROTO_FRAGMENT                 = 0x2c
+    IPPROTO_GRE                      = 0x2f
+    IPPROTO_HOPOPTS                  = 0x0
+    IPPROTO_ICMP                     = 0x1
+    IPPROTO_ICMPV6                   = 0x3a
+    IPPROTO_IDP                      = 0x16
+    IPPROTO_IGMP                     = 0x2
+    IPPROTO_IP                       = 0x0
+    IPPROTO_IPIP                     = 0x4
+    IPPROTO_IPV6                     = 0x29
+    IPPROTO_MTP                      = 0x5c
+    IPPROTO_NONE                     = 0x3b
+    IPPROTO_PIM                      = 0x67
+    IPPROTO_PUP                      = 0xc
+    IPPROTO_RAW                      = 0xff
+    IPPROTO_ROUTING                  = 0x2b
+    IPPROTO_RSVP                     = 0x2e
+    IPPROTO_SCTP                     = 0x84
+    IPPROTO_TCP                      = 0x6
+    IPPROTO_TP                       = 0x1d
+    IPPROTO_UDP                      = 0x11
+    IPPROTO_UDPLITE                  = 0x88
+    IPV6_2292DSTOPTS                 = 0x4
+    IPV6_2292HOPLIMIT                = 0x8
+    IPV6_2292HOPOPTS                 = 0x3
+    IPV6_2292PKTINFO                 = 0x2
+    IPV6_2292PKTOPTIONS              = 0x6
+    IPV6_2292RTHDR                   = 0x5
+    IPV6_ADDRFORM                    = 0x1
+    IPV6_ADD_MEMBERSHIP              = 0x14
+    IPV6_AUTHHDR                     = 0xa
+    IPV6_CHECKSUM                    = 0x7
+    IPV6_DROP_MEMBERSHIP             = 0x15
+    IPV6_DSTOPTS                     = 0x3b
+    IPV6_HOPLIMIT                    = 0x34
+    IPV6_HOPOPTS                     = 0x36
+    IPV6_IPSEC_POLICY                = 0x22
+    IPV6_JOIN_ANYCAST                = 0x1b
+    IPV6_JOIN_GROUP                  = 0x14
+    IPV6_LEAVE_ANYCAST               = 0x1c
+    IPV6_LEAVE_GROUP                 = 0x15
+    IPV6_MTU                         = 0x18
+    IPV6_MTU_DISCOVER                = 0x17
+    IPV6_MULTICAST_HOPS              = 0x12
+    IPV6_MULTICAST_IF                = 0x11
+    IPV6_MULTICAST_LOOP              = 0x13
+    IPV6_NEXTHOP                     = 0x9
+    IPV6_PKTINFO                     = 0x32
+    IPV6_PMTUDISC_DO                 = 0x2
+    IPV6_PMTUDISC_DONT               = 0x0
+    IPV6_PMTUDISC_PROBE              = 0x3
+    IPV6_PMTUDISC_WANT               = 0x1
+    IPV6_RECVDSTOPTS                 = 0x3a
+    IPV6_RECVERR                     = 0x19
+    IPV6_RECVHOPLIMIT                = 0x33
+    IPV6_RECVHOPOPTS                 = 0x35
+    IPV6_RECVPKTINFO                 = 0x31
+    IPV6_RECVRTHDR                   = 0x38
+    IPV6_RECVTCLASS                  = 0x42
+    IPV6_ROUTER_ALERT                = 0x16
+    IPV6_RTHDR                       = 0x39
+    IPV6_RTHDRDSTOPTS                = 0x37
+    IPV6_RTHDR_LOOSE                 = 0x0
+    IPV6_RTHDR_STRICT                = 0x1
+    IPV6_RTHDR_TYPE_0                = 0x0
+    IPV6_RXDSTOPTS                   = 0x3b
+    IPV6_RXHOPOPTS                   = 0x36
+    IPV6_TCLASS                      = 0x43
+    IPV6_UNICAST_HOPS                = 0x10
+    IPV6_V6ONLY                      = 0x1a
+    IPV6_XFRM_POLICY                 = 0x23
+    IP_ADD_MEMBERSHIP                = 0x23
+    IP_ADD_SOURCE_MEMBERSHIP         = 0x27
+    IP_BLOCK_SOURCE                  = 0x26
+    IP_DEFAULT_MULTICAST_LOOP        = 0x1
+    IP_DEFAULT_MULTICAST_TTL         = 0x1
+    IP_DF                            = 0x4000
+    IP_DROP_MEMBERSHIP               = 0x24
+    IP_DROP_SOURCE_MEMBERSHIP        = 0x28
+    IP_FREEBIND                      = 0xf
+    IP_HDRINCL                       = 0x3
+    IP_IPSEC_POLICY                  = 0x10
+    IP_MAXPACKET                     = 0xffff
+    IP_MAX_MEMBERSHIPS               = 0x14
+    IP_MF                            = 0x2000
+    IP_MINTTL                        = 0x15
+    IP_MSFILTER                      = 0x29
+    IP_MSS                           = 0x240
+    IP_MTU                           = 0xe
+    IP_MTU_DISCOVER                  = 0xa
+    IP_MULTICAST_IF                  = 0x20
+    IP_MULTICAST_LOOP                = 0x22
+    IP_MULTICAST_TTL                 = 0x21
+    IP_OFFMASK                       = 0x1fff
+    IP_OPTIONS                       = 0x4
+    IP_ORIGDSTADDR                   = 0x14
+    IP_PASSSEC                       = 0x12
+    IP_PKTINFO                       = 0x8
+    IP_PKTOPTIONS                    = 0x9
+    IP_PMTUDISC                      = 0xa
+    IP_PMTUDISC_DO                   = 0x2
+    IP_PMTUDISC_DONT                 = 0x0
+    IP_PMTUDISC_PROBE                = 0x3
+    IP_PMTUDISC_WANT                 = 0x1
+    IP_RECVERR                       = 0xb
+    IP_RECVOPTS                      = 0x6
+    IP_RECVORIGDSTADDR               = 0x14
+    IP_RECVRETOPTS                   = 0x7
+    IP_RECVTOS                       = 0xd
+    IP_RECVTTL                       = 0xc
+    IP_RETOPTS                       = 0x7
+    IP_RF                            = 0x8000
+    IP_ROUTER_ALERT                  = 0x5
+    IP_TOS                           = 0x1
+    IP_TRANSPARENT                   = 0x13
+    IP_TTL                           = 0x2
+    IP_UNBLOCK_SOURCE                = 0x25
+    IP_XFRM_POLICY                   = 0x11
+    LINUX_REBOOT_CMD_CAD_OFF         = 0x0
+    LINUX_REBOOT_CMD_CAD_ON          = 0x89abcdef
+    LINUX_REBOOT_CMD_HALT            = 0xcdef0123
+    LINUX_REBOOT_CMD_KEXEC           = 0x45584543
+    LINUX_REBOOT_CMD_POWER_OFF       = 0x4321fedc
+    LINUX_REBOOT_CMD_RESTART         = 0x1234567
+    LINUX_REBOOT_CMD_RESTART2        = 0xa1b2c3d4
+    LINUX_REBOOT_CMD_SW_SUSPEND      = 0xd000fce2
+    LINUX_REBOOT_MAGIC1              = 0xfee1dead
+    LINUX_REBOOT_MAGIC2              = 0x28121969
+    LOCK_EX                          = 0x2
+    LOCK_NB                          = 0x4
+    LOCK_SH                          = 0x1
+    LOCK_UN                          = 0x8
+    MADV_DOFORK                      = 0xb
+    MADV_DONTFORK                    = 0xa
+    MADV_DONTNEED                    = 0x4
+    MADV_HUGEPAGE                    = 0xe
+    MADV_HWPOISON                    = 0x64
+    MADV_MERGEABLE                   = 0xc
+    MADV_NOHUGEPAGE                  = 0xf
+    MADV_NORMAL                      = 0x0
+    MADV_RANDOM                      = 0x1
+    MADV_REMOVE                      = 0x9
+    MADV_SEQUENTIAL                  = 0x2
+    MADV_UNMERGEABLE                 = 0xd
+    MADV_WILLNEED                    = 0x3
+    MAP_32BIT                        = 0x40
+    MAP_ANON                         = 0x20
+    MAP_ANONYMOUS                    = 0x20
+    MAP_DENYWRITE                    = 0x800
+    MAP_EXECUTABLE                   = 0x1000
+    MAP_FILE                         = 0x0
+    MAP_FIXED                        = 0x10
+    MAP_GROWSDOWN                    = 0x100
+    MAP_HUGETLB                      = 0x40000
+    MAP_LOCKED                       = 0x2000
+    MAP_NONBLOCK                     = 0x10000
+    MAP_NORESERVE                    = 0x4000
+    MAP_POPULATE                     = 0x8000
+    MAP_PRIVATE                      = 0x2
+    MAP_SHARED                       = 0x1
+    MAP_STACK                        = 0x20000
+    MAP_TYPE                         = 0xf
+    MCL_CURRENT                      = 0x1
+    MCL_FUTURE                       = 0x2
+    MNT_DETACH                       = 0x2
+    MNT_EXPIRE                       = 0x4
+    MNT_FORCE                        = 0x1
+    MSG_CMSG_CLOEXEC                 = 0x40000000
+    MSG_CONFIRM                      = 0x800
+    MSG_CTRUNC                       = 0x8
+    MSG_DONTROUTE                    = 0x4
+    MSG_DONTWAIT                     = 0x40
+    MSG_EOR                          = 0x80
+    MSG_ERRQUEUE                     = 0x2000
+    MSG_FASTOPEN                     = 0x20000000
+    MSG_FIN                          = 0x200
+    MSG_MORE                         = 0x8000
+    MSG_NOSIGNAL                     = 0x4000
+    MSG_OOB                          = 0x1
+    MSG_PEEK                         = 0x2
+    MSG_PROXY                        = 0x10
+    MSG_RST                          = 0x1000
+    MSG_SYN                          = 0x400
+    MSG_TRUNC                        = 0x20
+    MSG_TRYHARD                      = 0x4
+    MSG_WAITALL                      = 0x100
+    MSG_WAITFORONE                   = 0x10000
+    MS_ACTIVE                        = 0x40000000
+    MS_ASYNC                         = 0x1
+    MS_BIND                          = 0x1000
+    MS_DIRSYNC                       = 0x80
+    MS_INVALIDATE                    = 0x2
+    MS_I_VERSION                     = 0x800000
+    MS_KERNMOUNT                     = 0x400000
+    MS_MANDLOCK                      = 0x40
+    MS_MGC_MSK                       = 0xffff0000
+    MS_MGC_VAL                       = 0xc0ed0000
+    MS_MOVE                          = 0x2000
+    MS_NOATIME                       = 0x400
+    MS_NODEV                         = 0x4
+    MS_NODIRATIME                    = 0x800
+    MS_NOEXEC                        = 0x8
+    MS_NOSUID                        = 0x2
+    MS_NOUSER                        = -0x80000000
+    MS_POSIXACL                      = 0x10000
+    MS_PRIVATE                       = 0x40000
+    MS_RDONLY                        = 0x1
+    MS_REC                           = 0x4000
+    MS_RELATIME                      = 0x200000
+    MS_REMOUNT                       = 0x20
+    MS_RMT_MASK                      = 0x800051
+    MS_SHARED                        = 0x100000
+    MS_SILENT                        = 0x8000
+    MS_SLAVE                         = 0x80000
+    MS_STRICTATIME                   = 0x1000000
+    MS_SYNC                          = 0x4
+    MS_SYNCHRONOUS                   = 0x10
+    MS_UNBINDABLE                    = 0x20000
+    NAME_MAX                         = 0xff
+    NETLINK_ADD_MEMBERSHIP           = 0x1
+    NETLINK_AUDIT                    = 0x9
+    NETLINK_BROADCAST_ERROR          = 0x4
+    NETLINK_CONNECTOR                = 0xb
+    NETLINK_DNRTMSG                  = 0xe
+    NETLINK_DROP_MEMBERSHIP          = 0x2
+    NETLINK_ECRYPTFS                 = 0x13
+    NETLINK_FIB_LOOKUP               = 0xa
+    NETLINK_FIREWALL                 = 0x3
+    NETLINK_GENERIC                  = 0x10
+    NETLINK_INET_DIAG                = 0x4
+    NETLINK_IP6_FW                   = 0xd
+    NETLINK_ISCSI                    = 0x8
+    NETLINK_KOBJECT_UEVENT           = 0xf
+    NETLINK_NETFILTER                = 0xc
+    NETLINK_NFLOG                    = 0x5
+    NETLINK_NO_ENOBUFS               = 0x5
+    NETLINK_PKTINFO                  = 0x3
+    NETLINK_ROUTE                    = 0x0
+    NETLINK_SCSITRANSPORT            = 0x12
+    NETLINK_SELINUX                  = 0x7
+    NETLINK_UNUSED                   = 0x1
+    NETLINK_USERSOCK                 = 0x2
+    NETLINK_XFRM                     = 0x6
+    NLA_ALIGNTO                      = 0x4
+    NLA_F_NESTED                     = 0x8000
+    NLA_F_NET_BYTEORDER              = 0x4000
+    NLA_HDRLEN                       = 0x4
+    NLMSG_ALIGNTO                    = 0x4
+    NLMSG_DONE                       = 0x3
+    NLMSG_ERROR                      = 0x2
+    NLMSG_HDRLEN                     = 0x10
+    NLMSG_MIN_TYPE                   = 0x10
+    NLMSG_NOOP                       = 0x1
+    NLMSG_OVERRUN                    = 0x4
+    NLM_F_ACK                        = 0x4
+    NLM_F_APPEND                     = 0x800
+    NLM_F_ATOMIC                     = 0x400
+    NLM_F_CREATE                     = 0x400
+    NLM_F_DUMP                       = 0x300
+    NLM_F_ECHO                       = 0x8
+    NLM_F_EXCL                       = 0x200
+    NLM_F_MATCH                      = 0x200
+    NLM_F_MULTI                      = 0x2
+    NLM_F_REPLACE                    = 0x100
+    NLM_F_REQUEST                    = 0x1
+    NLM_F_ROOT                       = 0x100
+    O_ACCMODE                        = 0x3
+    O_APPEND                         = 0x400
+    O_ASYNC                          = 0x2000
+    O_CLOEXEC                        = 0x80000
+    O_CREAT                          = 0x40
+    O_DIRECT                         = 0x4000
+    O_DIRECTORY                      = 0x10000
+    O_DSYNC                          = 0x1000
+    O_EXCL                           = 0x80
+    O_FSYNC                          = 0x101000
+    O_LARGEFILE                      = 0x0
+    O_NDELAY                         = 0x800
+    O_NOATIME                        = 0x40000
+    O_NOCTTY                         = 0x100
+    O_NOFOLLOW                       = 0x20000
+    O_NONBLOCK                       = 0x800
+    O_RDONLY                         = 0x0
+    O_RDWR                           = 0x2
+    O_RSYNC                          = 0x101000
+    O_SYNC                           = 0x101000
+    O_TRUNC                          = 0x200
+    O_WRONLY                         = 0x1
+    PACKET_ADD_MEMBERSHIP            = 0x1
+    PACKET_BROADCAST                 = 0x1
+    PACKET_DROP_MEMBERSHIP           = 0x2
+    PACKET_FASTROUTE                 = 0x6
+    PACKET_HOST                      = 0x0
+    PACKET_LOOPBACK                  = 0x5
+    PACKET_MR_ALLMULTI               = 0x2
+    PACKET_MR_MULTICAST              = 0x0
+    PACKET_MR_PROMISC                = 0x1
+    PACKET_MULTICAST                 = 0x2
+    PACKET_OTHERHOST                 = 0x3
+    PACKET_OUTGOING                  = 0x4
+    PACKET_RECV_OUTPUT               = 0x3
+    PACKET_RX_RING                   = 0x5
+    PACKET_STATISTICS                = 0x6
+    PRIO_PGRP                        = 0x1
+    PRIO_PROCESS                     = 0x0
+    PRIO_USER                        = 0x2
+    PROT_EXEC                        = 0x4
+    PROT_GROWSDOWN                   = 0x1000000
+    PROT_GROWSUP                     = 0x2000000
+    PROT_NONE                        = 0x0
+    PROT_READ                        = 0x1
+    PROT_WRITE                       = 0x2
+    PR_CAPBSET_DROP                  = 0x18
+    PR_CAPBSET_READ                  = 0x17
+    PR_ENDIAN_BIG                    = 0x0
+    PR_ENDIAN_LITTLE                 = 0x1
+    PR_ENDIAN_PPC_LITTLE             = 0x2
+    PR_FPEMU_NOPRINT                 = 0x1
+    PR_FPEMU_SIGFPE                  = 0x2
+    PR_FP_EXC_ASYNC                  = 0x2
+    PR_FP_EXC_DISABLED               = 0x0
+    PR_FP_EXC_DIV                    = 0x10000
+    PR_FP_EXC_INV                    = 0x100000
+    PR_FP_EXC_NONRECOV               = 0x1
+    PR_FP_EXC_OVF                    = 0x20000
+    PR_FP_EXC_PRECISE                = 0x3
+    PR_FP_EXC_RES                    = 0x80000
+    PR_FP_EXC_SW_ENABLE              = 0x80
+    PR_FP_EXC_UND                    = 0x40000
+    PR_GET_DUMPABLE                  = 0x3
+    PR_GET_ENDIAN                    = 0x13
+    PR_GET_FPEMU                     = 0x9
+    PR_GET_FPEXC                     = 0xb
+    PR_GET_KEEPCAPS                  = 0x7
+    PR_GET_NAME                      = 0x10
+    PR_GET_PDEATHSIG                 = 0x2
+    PR_GET_SECCOMP                   = 0x15
+    PR_GET_SECUREBITS                = 0x1b
+    PR_GET_TIMERSLACK                = 0x1e
+    PR_GET_TIMING                    = 0xd
+    PR_GET_TSC                       = 0x19
+    PR_GET_UNALIGN                   = 0x5
+    PR_MCE_KILL                      = 0x21
+    PR_MCE_KILL_CLEAR                = 0x0
+    PR_MCE_KILL_DEFAULT              = 0x2
+    PR_MCE_KILL_EARLY                = 0x1
+    PR_MCE_KILL_GET                  = 0x22
+    PR_MCE_KILL_LATE                 = 0x0
+    PR_MCE_KILL_SET                  = 0x1
+    PR_SET_DUMPABLE                  = 0x4
+    PR_SET_ENDIAN                    = 0x14
+    PR_SET_FPEMU                     = 0xa
+    PR_SET_FPEXC                     = 0xc
+    PR_SET_KEEPCAPS                  = 0x8
+    PR_SET_NAME                      = 0xf
+    PR_SET_PDEATHSIG                 = 0x1
+    PR_SET_PTRACER                   = 0x59616d61
+    PR_SET_SECCOMP                   = 0x16
+    PR_SET_SECUREBITS                = 0x1c
+    PR_SET_TIMERSLACK                = 0x1d
+    PR_SET_TIMING                    = 0xe
+    PR_SET_TSC                       = 0x1a
+    PR_SET_UNALIGN                   = 0x6
+    PR_TASK_PERF_EVENTS_DISABLE      = 0x1f
+    PR_TASK_PERF_EVENTS_ENABLE       = 0x20
+    PR_TIMING_STATISTICAL            = 0x0
+    PR_TIMING_TIMESTAMP              = 0x1
+    PR_TSC_ENABLE                    = 0x1
+    PR_TSC_SIGSEGV                   = 0x2
+    PR_UNALIGN_NOPRINT               = 0x1
+    PR_UNALIGN_SIGBUS                = 0x2
+    PTRACE_ARCH_PRCTL                = 0x1e
+    PTRACE_ATTACH                    = 0x10
+    PTRACE_CONT                      = 0x7
+    PTRACE_DETACH                    = 0x11
+    PTRACE_EVENT_CLONE               = 0x3
+    PTRACE_EVENT_EXEC                = 0x4
+    PTRACE_EVENT_EXIT                = 0x6
+    PTRACE_EVENT_FORK                = 0x1
+    PTRACE_EVENT_VFORK               = 0x2
+    PTRACE_EVENT_VFORK_DONE          = 0x5
+    PTRACE_GETEVENTMSG               = 0x4201
+    PTRACE_GETFPREGS                 = 0xe
+    PTRACE_GETFPXREGS                = 0x12
+    PTRACE_GETREGS                   = 0xc
+    PTRACE_GETREGSET                 = 0x4204
+    PTRACE_GETSIGINFO                = 0x4202
+    PTRACE_GET_THREAD_AREA           = 0x19
+    PTRACE_KILL                      = 0x8
+    PTRACE_OLDSETOPTIONS             = 0x15
+    PTRACE_O_MASK                    = 0x7f
+    PTRACE_O_TRACECLONE              = 0x8
+    PTRACE_O_TRACEEXEC               = 0x10
+    PTRACE_O_TRACEEXIT               = 0x40
+    PTRACE_O_TRACEFORK               = 0x2
+    PTRACE_O_TRACESYSGOOD            = 0x1
+    PTRACE_O_TRACEVFORK              = 0x4
+    PTRACE_O_TRACEVFORKDONE          = 0x20
+    PTRACE_PEEKDATA                  = 0x2
+    PTRACE_PEEKTEXT                  = 0x1
+    PTRACE_PEEKUSR                   = 0x3
+    PTRACE_POKEDATA                  = 0x5
+    PTRACE_POKETEXT                  = 0x4
+    PTRACE_POKEUSR                   = 0x6
+    PTRACE_SETFPREGS                 = 0xf
+    PTRACE_SETFPXREGS                = 0x13
+    PTRACE_SETOPTIONS                = 0x4200
+    PTRACE_SETREGS                   = 0xd
+    PTRACE_SETREGSET                 = 0x4205
+    PTRACE_SETSIGINFO                = 0x4203
+    PTRACE_SET_THREAD_AREA           = 0x1a
+    PTRACE_SINGLEBLOCK               = 0x21
+    PTRACE_SINGLESTEP                = 0x9
+    PTRACE_SYSCALL                   = 0x18
+    PTRACE_SYSEMU                    = 0x1f
+    PTRACE_SYSEMU_SINGLESTEP         = 0x20
+    PTRACE_TRACEME                   = 0x0
+    RLIMIT_AS                        = 0x9
+    RLIMIT_CORE                      = 0x4
+    RLIMIT_CPU                       = 0x0
+    RLIMIT_DATA                      = 0x2
+    RLIMIT_FSIZE                     = 0x1
+    RLIMIT_NOFILE                    = 0x7
+    RLIMIT_STACK                     = 0x3
+    RLIM_INFINITY                    = -0x1
+    RTAX_ADVMSS                      = 0x8
+    RTAX_CWND                        = 0x7
+    RTAX_FEATURES                    = 0xc
+    RTAX_FEATURE_ALLFRAG             = 0x8
+    RTAX_FEATURE_ECN                 = 0x1
+    RTAX_FEATURE_SACK                = 0x2
+    RTAX_FEATURE_TIMESTAMP           = 0x4
+    RTAX_HOPLIMIT                    = 0xa
+    RTAX_INITCWND                    = 0xb
+    RTAX_INITRWND                    = 0xe
+    RTAX_LOCK                        = 0x1
+    RTAX_MAX                         = 0xe
+    RTAX_MTU                         = 0x2
+    RTAX_REORDERING                  = 0x9
+    RTAX_RTO_MIN                     = 0xd
+    RTAX_RTT                         = 0x4
+    RTAX_RTTVAR                      = 0x5
+    RTAX_SSTHRESH                    = 0x6
+    RTAX_UNSPEC                      = 0x0
+    RTAX_WINDOW                      = 0x3
+    RTA_ALIGNTO                      = 0x4
+    RTA_MAX                          = 0x10
+    RTCF_DIRECTSRC                   = 0x4000000
+    RTCF_DOREDIRECT                  = 0x1000000
+    RTCF_LOG                         = 0x2000000
+    RTCF_MASQ                        = 0x400000
+    RTCF_NAT                         = 0x800000
+    RTCF_VALVE                       = 0x200000
+    RTF_ADDRCLASSMASK                = 0xf8000000
+    RTF_ADDRCONF                     = 0x40000
+    RTF_ALLONLINK                    = 0x20000
+    RTF_BROADCAST                    = 0x10000000
+    RTF_CACHE                        = 0x1000000
+    RTF_DEFAULT                      = 0x10000
+    RTF_DYNAMIC                      = 0x10
+    RTF_FLOW                         = 0x2000000
+    RTF_GATEWAY                      = 0x2
+    RTF_HOST                         = 0x4
+    RTF_INTERFACE                    = 0x40000000
+    RTF_IRTT                         = 0x100
+    RTF_LINKRT                       = 0x100000
+    RTF_LOCAL                        = 0x80000000
+    RTF_MODIFIED                     = 0x20
+    RTF_MSS                          = 0x40
+    RTF_MTU                          = 0x40
+    RTF_MULTICAST                    = 0x20000000
+    RTF_NAT                          = 0x8000000
+    RTF_NOFORWARD                    = 0x1000
+    RTF_NONEXTHOP                    = 0x200000
+    RTF_NOPMTUDISC                   = 0x4000
+    RTF_POLICY                       = 0x4000000
+    RTF_REINSTATE                    = 0x8
+    RTF_REJECT                       = 0x200
+    RTF_STATIC                       = 0x400
+    RTF_THROW                        = 0x2000
+    RTF_UP                           = 0x1
+    RTF_WINDOW                       = 0x80
+    RTF_XRESOLVE                     = 0x800
+    RTM_BASE                         = 0x10
+    RTM_DELACTION                    = 0x31
+    RTM_DELADDR                      = 0x15
+    RTM_DELADDRLABEL                 = 0x49
+    RTM_DELLINK                      = 0x11
+    RTM_DELNEIGH                     = 0x1d
+    RTM_DELQDISC                     = 0x25
+    RTM_DELROUTE                     = 0x19
+    RTM_DELRULE                      = 0x21
+    RTM_DELTCLASS                    = 0x29
+    RTM_DELTFILTER                   = 0x2d
+    RTM_F_CLONED                     = 0x200
+    RTM_F_EQUALIZE                   = 0x400
+    RTM_F_NOTIFY                     = 0x100
+    RTM_F_PREFIX                     = 0x800
+    RTM_GETACTION                    = 0x32
+    RTM_GETADDR                      = 0x16
+    RTM_GETADDRLABEL                 = 0x4a
+    RTM_GETANYCAST                   = 0x3e
+    RTM_GETDCB                       = 0x4e
+    RTM_GETLINK                      = 0x12
+    RTM_GETMULTICAST                 = 0x3a
+    RTM_GETNEIGH                     = 0x1e
+    RTM_GETNEIGHTBL                  = 0x42
+    RTM_GETQDISC                     = 0x26
+    RTM_GETROUTE                     = 0x1a
+    RTM_GETRULE                      = 0x22
+    RTM_GETTCLASS                    = 0x2a
+    RTM_GETTFILTER                   = 0x2e
+    RTM_MAX                          = 0x4f
+    RTM_NEWACTION                    = 0x30
+    RTM_NEWADDR                      = 0x14
+    RTM_NEWADDRLABEL                 = 0x48
+    RTM_NEWLINK                      = 0x10
+    RTM_NEWNDUSEROPT                 = 0x44
+    RTM_NEWNEIGH                     = 0x1c
+    RTM_NEWNEIGHTBL                  = 0x40
+    RTM_NEWPREFIX                    = 0x34
+    RTM_NEWQDISC                     = 0x24
+    RTM_NEWROUTE                     = 0x18
+    RTM_NEWRULE                      = 0x20
+    RTM_NEWTCLASS                    = 0x28
+    RTM_NEWTFILTER                   = 0x2c
+    RTM_NR_FAMILIES                  = 0x10
+    RTM_NR_MSGTYPES                  = 0x40
+    RTM_SETDCB                       = 0x4f
+    RTM_SETLINK                      = 0x13
+    RTM_SETNEIGHTBL                  = 0x43
+    RTNH_ALIGNTO                     = 0x4
+    RTNH_F_DEAD                      = 0x1
+    RTNH_F_ONLINK                    = 0x4
+    RTNH_F_PERVASIVE                 = 0x2
+    RTN_MAX                          = 0xb
+    RTPROT_BIRD                      = 0xc
+    RTPROT_BOOT                      = 0x3
+    RTPROT_DHCP                      = 0x10
+    RTPROT_DNROUTED                  = 0xd
+    RTPROT_GATED                     = 0x8
+    RTPROT_KERNEL                    = 0x2
+    RTPROT_MRT                       = 0xa
+    RTPROT_NTK                       = 0xf
+    RTPROT_RA                        = 0x9
+    RTPROT_REDIRECT                  = 0x1
+    RTPROT_STATIC                    = 0x4
+    RTPROT_UNSPEC                    = 0x0
+    RTPROT_XORP                      = 0xe
+    RTPROT_ZEBRA                     = 0xb
+    RT_CLASS_DEFAULT                 = 0xfd
+    RT_CLASS_LOCAL                   = 0xff
+    RT_CLASS_MAIN                    = 0xfe
+    RT_CLASS_MAX                     = 0xff
+    RT_CLASS_UNSPEC                  = 0x0
+    RUSAGE_CHILDREN                  = -0x1
+    RUSAGE_SELF                      = 0x0
+    RUSAGE_THREAD                    = 0x1
+    SCM_CREDENTIALS                  = 0x2
+    SCM_RIGHTS                       = 0x1
+    SCM_TIMESTAMP                    = 0x1d
+    SCM_TIMESTAMPING                 = 0x25
+    SCM_TIMESTAMPNS                  = 0x23
+    SHUT_RD                          = 0x0
+    SHUT_RDWR                        = 0x2
+    SHUT_WR                          = 0x1
+    SIOCADDDLCI                      = 0x8980
+    SIOCADDMULTI                     = 0x8931
+    SIOCADDRT                        = 0x890b
+    SIOCATMARK                       = 0x8905
+    SIOCDARP                         = 0x8953
+    SIOCDELDLCI                      = 0x8981
+    SIOCDELMULTI                     = 0x8932
+    SIOCDELRT                        = 0x890c
+    SIOCDEVPRIVATE                   = 0x89f0
+    SIOCDIFADDR                      = 0x8936
+    SIOCDRARP                        = 0x8960
+    SIOCGARP                         = 0x8954
+    SIOCGIFADDR                      = 0x8915
+    SIOCGIFBR                        = 0x8940
+    SIOCGIFBRDADDR                   = 0x8919
+    SIOCGIFCONF                      = 0x8912
+    SIOCGIFCOUNT                     = 0x8938
+    SIOCGIFDSTADDR                   = 0x8917
+    SIOCGIFENCAP                     = 0x8925
+    SIOCGIFFLAGS                     = 0x8913
+    SIOCGIFHWADDR                    = 0x8927
+    SIOCGIFINDEX                     = 0x8933
+    SIOCGIFMAP                       = 0x8970
+    SIOCGIFMEM                       = 0x891f
+    SIOCGIFMETRIC                    = 0x891d
+    SIOCGIFMTU                       = 0x8921
+    SIOCGIFNAME                      = 0x8910
+    SIOCGIFNETMASK                   = 0x891b
+    SIOCGIFPFLAGS                    = 0x8935
+    SIOCGIFSLAVE                     = 0x8929
+    SIOCGIFTXQLEN                    = 0x8942
+    SIOCGPGRP                        = 0x8904
+    SIOCGRARP                        = 0x8961
+    SIOCGSTAMP                       = 0x8906
+    SIOCGSTAMPNS                     = 0x8907
+    SIOCPROTOPRIVATE                 = 0x89e0
+    SIOCRTMSG                        = 0x890d
+    SIOCSARP                         = 0x8955
+    SIOCSIFADDR                      = 0x8916
+    SIOCSIFBR                        = 0x8941
+    SIOCSIFBRDADDR                   = 0x891a
+    SIOCSIFDSTADDR                   = 0x8918
+    SIOCSIFENCAP                     = 0x8926
+    SIOCSIFFLAGS                     = 0x8914
+    SIOCSIFHWADDR                    = 0x8924
+    SIOCSIFHWBROADCAST               = 0x8937
+    SIOCSIFLINK                      = 0x8911
+    SIOCSIFMAP                       = 0x8971
+    SIOCSIFMEM                       = 0x8920
+    SIOCSIFMETRIC                    = 0x891e
+    SIOCSIFMTU                       = 0x8922
+    SIOCSIFNAME                      = 0x8923
+    SIOCSIFNETMASK                   = 0x891c
+    SIOCSIFPFLAGS                    = 0x8934
+    SIOCSIFSLAVE                     = 0x8930
+    SIOCSIFTXQLEN                    = 0x8943
+    SIOCSPGRP                        = 0x8902
+    SIOCSRARP                        = 0x8962
+    SOCK_CLOEXEC                     = 0x80000
+    SOCK_DCCP                        = 0x6
+    SOCK_DGRAM                       = 0x2
+    SOCK_NONBLOCK                    = 0x800
+    SOCK_PACKET                      = 0xa
+    SOCK_RAW                         = 0x3
+    SOCK_RDM                         = 0x4
+    SOCK_SEQPACKET                   = 0x5
+    SOCK_STREAM                      = 0x1
+    SOL_AAL                          = 0x109
+    SOL_ATM                          = 0x108
+    SOL_DECNET                       = 0x105
+    SOL_ICMPV6                       = 0x3a
+    SOL_IP                           = 0x0
+    SOL_IPV6                         = 0x29
+    SOL_IRDA                         = 0x10a
+    SOL_PACKET                       = 0x107
+    SOL_RAW                          = 0xff
+    SOL_SOCKET                       = 0x1
+    SOL_TCP                          = 0x6
+    SOL_X25                          = 0x106
+    SOMAXCONN                        = 0x80
+    SO_ACCEPTCONN                    = 0x1e
+    SO_ATTACH_FILTER                 = 0x1a
+    SO_BINDTODEVICE                  = 0x19
+    SO_BROADCAST                     = 0x6
+    SO_BSDCOMPAT                     = 0xe
+    SO_DEBUG                         = 0x1
+    SO_DETACH_FILTER                 = 0x1b
+    SO_DOMAIN                        = 0x27
+    SO_DONTROUTE                     = 0x5
+    SO_ERROR                         = 0x4
+    SO_KEEPALIVE                     = 0x9
+    SO_LINGER                        = 0xd
+    SO_MARK                          = 0x24
+    SO_NO_CHECK                      = 0xb
+    SO_OOBINLINE                     = 0xa
+    SO_PASSCRED                      = 0x10
+    SO_PASSSEC                       = 0x22
+    SO_PEERCRED                      = 0x11
+    SO_PEERNAME                      = 0x1c
+    SO_PEERSEC                       = 0x1f
+    SO_PRIORITY                      = 0xc
+    SO_PROTOCOL                      = 0x26
+    SO_RCVBUF                        = 0x8
+    SO_RCVBUFFORCE                   = 0x21
+    SO_RCVLOWAT                      = 0x12
+    SO_RCVTIMEO                      = 0x14
+    SO_REUSEADDR                     = 0x2
+    SO_RXQ_OVFL                      = 0x28
+    SO_SECURITY_AUTHENTICATION       = 0x16
+    SO_SECURITY_ENCRYPTION_NETWORK   = 0x18
+    SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17
+    SO_SNDBUF                        = 0x7
+    SO_SNDBUFFORCE                   = 0x20
+    SO_SNDLOWAT                      = 0x13
+    SO_SNDTIMEO                      = 0x15
+    SO_TIMESTAMP                     = 0x1d
+    SO_TIMESTAMPING                  = 0x25
+    SO_TIMESTAMPNS                   = 0x23
+    SO_TYPE                          = 0x3
+    S_BLKSIZE                        = 0x200
+    S_IEXEC                          = 0x40
+    S_IFBLK                          = 0x6000
+    S_IFCHR                          = 0x2000
+    S_IFDIR                          = 0x4000
+    S_IFIFO                          = 0x1000
+    S_IFLNK                          = 0xa000
+    S_IFMT                           = 0xf000
+    S_IFREG                          = 0x8000
+    S_IFSOCK                         = 0xc000
+    S_IREAD                          = 0x100
+    S_IRGRP                          = 0x20
+    S_IROTH                          = 0x4
+    S_IRUSR                          = 0x100
+    S_IRWXG                          = 0x38
+    S_IRWXO                          = 0x7
+    S_IRWXU                          = 0x1c0
+    S_ISGID                          = 0x400
+    S_ISUID                          = 0x800
+    S_ISVTX                          = 0x200
+    S_IWGRP                          = 0x10
+    S_IWOTH                          = 0x2
+    S_IWRITE                         = 0x80
+    S_IWUSR                          = 0x80
+    S_IXGRP                          = 0x8
+    S_IXOTH                          = 0x1
+    S_IXUSR                          = 0x40
+    TCIFLUSH                         = 0x0
+    TCIOFLUSH                        = 0x2
+    TCOFLUSH                         = 0x1
+    TCP_CONGESTION                   = 0xd
+    TCP_CORK                         = 0x3
+    TCP_DEFER_ACCEPT                 = 0x9
+    TCP_INFO                         = 0xb
+    TCP_KEEPCNT                      = 0x6
+    TCP_KEEPIDLE                     = 0x4
+    TCP_KEEPINTVL                    = 0x5
+    TCP_LINGER2                      = 0x8
+    TCP_MAXSEG                       = 0x2
+    TCP_MAXWIN                       = 0xffff
+    TCP_MAX_WINSHIFT                 = 0xe
+    TCP_MD5SIG                       = 0xe
+    TCP_MD5SIG_MAXKEYLEN             = 0x50
+    TCP_MSS                          = 0x200
+    TCP_NODELAY                      = 0x1
+    TCP_QUICKACK                     = 0xc
+    TCP_SYNCNT                       = 0x7
+    TCP_WINDOW_CLAMP                 = 0xa
+    TIOCCBRK                         = 0x5428
+    TIOCCONS                         = 0x541d
+    TIOCEXCL                         = 0x540c
+    TIOCGDEV                         = 0x80045432
+    TIOCGETD                         = 0x5424
+    TIOCGICOUNT                      = 0x545d
+    TIOCGLCKTRMIOS                   = 0x5456
+    TIOCGPGRP                        = 0x540f
+    TIOCGPTN                         = 0x80045430
+    TIOCGRS485                       = 0x542e
+    TIOCGSERIAL                      = 0x541e
+    TIOCGSID                         = 0x5429
+    TIOCGSOFTCAR                     = 0x5419
+    TIOCGWINSZ                       = 0x5413
+    TIOCINQ                          = 0x541b
+    TIOCLINUX                        = 0x541c
+    TIOCMBIC                         = 0x5417
+    TIOCMBIS                         = 0x5416
+    TIOCMGET                         = 0x5415
+    TIOCMIWAIT                       = 0x545c
+    TIOCMSET                         = 0x5418
+    TIOCM_CAR                        = 0x40
+    TIOCM_CD                         = 0x40
+    TIOCM_CTS                        = 0x20
+    TIOCM_DSR                        = 0x100
+    TIOCM_DTR                        = 0x2
+    TIOCM_LE                         = 0x1
+    TIOCM_RI                         = 0x80
+    TIOCM_RNG                        = 0x80
+    TIOCM_RTS                        = 0x4
+    TIOCM_SR                         = 0x10
+    TIOCM_ST                         = 0x8
+    TIOCNOTTY                        = 0x5422
+    TIOCNXCL                         = 0x540d
+    TIOCOUTQ                         = 0x5411
+    TIOCPKT                          = 0x5420
+    TIOCPKT_DATA                     = 0x0
+    TIOCPKT_DOSTOP                   = 0x20
+    TIOCPKT_FLUSHREAD                = 0x1
+    TIOCPKT_FLUSHWRITE               = 0x2
+    TIOCPKT_IOCTL                    = 0x40
+    TIOCPKT_NOSTOP                   = 0x10
+    TIOCPKT_START                    = 0x8
+    TIOCPKT_STOP                     = 0x4
+    TIOCSBRK                         = 0x5427
+    TIOCSCTTY                        = 0x540e
+    TIOCSERCONFIG                    = 0x5453
+    TIOCSERGETLSR                    = 0x5459
+    TIOCSERGETMULTI                  = 0x545a
+    TIOCSERGSTRUCT                   = 0x5458
+    TIOCSERGWILD                     = 0x5454
+    TIOCSERSETMULTI                  = 0x545b
+    TIOCSERSWILD                     = 0x5455
+    TIOCSER_TEMT                     = 0x1
+    TIOCSETD                         = 0x5423
+    TIOCSIG                          = 0x40045436
+    TIOCSLCKTRMIOS                   = 0x5457
+    TIOCSPGRP                        = 0x5410
+    TIOCSPTLCK                       = 0x40045431
+    TIOCSRS485                       = 0x542f
+    TIOCSSERIAL                      = 0x541f
+    TIOCSSOFTCAR                     = 0x541a
+    TIOCSTI                          = 0x5412
+    TIOCSWINSZ                       = 0x5414
+    TUNATTACHFILTER                  = 0x401054d5
+    TUNDETACHFILTER                  = 0x401054d6
+    TUNGETFEATURES                   = 0x800454cf
+    TUNGETIFF                        = 0x800454d2
+    TUNGETSNDBUF                     = 0x800454d3
+    TUNGETVNETHDRSZ                  = 0x800454d7
+    TUNSETDEBUG                      = 0x400454c9
+    TUNSETGROUP                      = 0x400454ce
+    TUNSETIFF                        = 0x400454ca
+    TUNSETLINK                       = 0x400454cd
+    TUNSETNOCSUM                     = 0x400454c8
+    TUNSETOFFLOAD                    = 0x400454d0
+    TUNSETOWNER                      = 0x400454cc
+    TUNSETPERSIST                    = 0x400454cb
+    TUNSETSNDBUF                     = 0x400454d4
+    TUNSETTXFILTER                   = 0x400454d1
+    TUNSETVNETHDRSZ                  = 0x400454d8
+    WALL                             = 0x40000000
+    WCLONE                           = 0x80000000
+    WCONTINUED                       = 0x8
+    WEXITED                          = 0x4
+    WNOHANG                          = 0x1
+    WNOTHREAD                        = 0x20000000
+    WNOWAIT                          = 0x1000000
+    WORDSIZE                         = 0x40
+    WSTOPPED                         = 0x2
+    WUNTRACED                        = 0x2
+)

Errors

+
const (
+    E2BIG           = Errno(0x7)
+    EACCES          = Errno(0xd)
+    EADDRINUSE      = Errno(0x62)
+    EADDRNOTAVAIL   = Errno(0x63)
+    EADV            = Errno(0x44)
+    EAFNOSUPPORT    = Errno(0x61)
+    EAGAIN          = Errno(0xb)
+    EALREADY        = Errno(0x72)
+    EBADE           = Errno(0x34)
+    EBADF           = Errno(0x9)
+    EBADFD          = Errno(0x4d)
+    EBADMSG         = Errno(0x4a)
+    EBADR           = Errno(0x35)
+    EBADRQC         = Errno(0x38)
+    EBADSLT         = Errno(0x39)
+    EBFONT          = Errno(0x3b)
+    EBUSY           = Errno(0x10)
+    ECANCELED       = Errno(0x7d)
+    ECHILD          = Errno(0xa)
+    ECHRNG          = Errno(0x2c)
+    ECOMM           = Errno(0x46)
+    ECONNABORTED    = Errno(0x67)
+    ECONNREFUSED    = Errno(0x6f)
+    ECONNRESET      = Errno(0x68)
+    EDEADLK         = Errno(0x23)
+    EDEADLOCK       = Errno(0x23)
+    EDESTADDRREQ    = Errno(0x59)
+    EDOM            = Errno(0x21)
+    EDOTDOT         = Errno(0x49)
+    EDQUOT          = Errno(0x7a)
+    EEXIST          = Errno(0x11)
+    EFAULT          = Errno(0xe)
+    EFBIG           = Errno(0x1b)
+    EHOSTDOWN       = Errno(0x70)
+    EHOSTUNREACH    = Errno(0x71)
+    EIDRM           = Errno(0x2b)
+    EILSEQ          = Errno(0x54)
+    EINPROGRESS     = Errno(0x73)
+    EINTR           = Errno(0x4)
+    EINVAL          = Errno(0x16)
+    EIO             = Errno(0x5)
+    EISCONN         = Errno(0x6a)
+    EISDIR          = Errno(0x15)
+    EISNAM          = Errno(0x78)
+    EKEYEXPIRED     = Errno(0x7f)
+    EKEYREJECTED    = Errno(0x81)
+    EKEYREVOKED     = Errno(0x80)
+    EL2HLT          = Errno(0x33)
+    EL2NSYNC        = Errno(0x2d)
+    EL3HLT          = Errno(0x2e)
+    EL3RST          = Errno(0x2f)
+    ELIBACC         = Errno(0x4f)
+    ELIBBAD         = Errno(0x50)
+    ELIBEXEC        = Errno(0x53)
+    ELIBMAX         = Errno(0x52)
+    ELIBSCN         = Errno(0x51)
+    ELNRNG          = Errno(0x30)
+    ELOOP           = Errno(0x28)
+    EMEDIUMTYPE     = Errno(0x7c)
+    EMFILE          = Errno(0x18)
+    EMLINK          = Errno(0x1f)
+    EMSGSIZE        = Errno(0x5a)
+    EMULTIHOP       = Errno(0x48)
+    ENAMETOOLONG    = Errno(0x24)
+    ENAVAIL         = Errno(0x77)
+    ENETDOWN        = Errno(0x64)
+    ENETRESET       = Errno(0x66)
+    ENETUNREACH     = Errno(0x65)
+    ENFILE          = Errno(0x17)
+    ENOANO          = Errno(0x37)
+    ENOBUFS         = Errno(0x69)
+    ENOCSI          = Errno(0x32)
+    ENODATA         = Errno(0x3d)
+    ENODEV          = Errno(0x13)
+    ENOENT          = Errno(0x2)
+    ENOEXEC         = Errno(0x8)
+    ENOKEY          = Errno(0x7e)
+    ENOLCK          = Errno(0x25)
+    ENOLINK         = Errno(0x43)
+    ENOMEDIUM       = Errno(0x7b)
+    ENOMEM          = Errno(0xc)
+    ENOMSG          = Errno(0x2a)
+    ENONET          = Errno(0x40)
+    ENOPKG          = Errno(0x41)
+    ENOPROTOOPT     = Errno(0x5c)
+    ENOSPC          = Errno(0x1c)
+    ENOSR           = Errno(0x3f)
+    ENOSTR          = Errno(0x3c)
+    ENOSYS          = Errno(0x26)
+    ENOTBLK         = Errno(0xf)
+    ENOTCONN        = Errno(0x6b)
+    ENOTDIR         = Errno(0x14)
+    ENOTEMPTY       = Errno(0x27)
+    ENOTNAM         = Errno(0x76)
+    ENOTRECOVERABLE = Errno(0x83)
+    ENOTSOCK        = Errno(0x58)
+    ENOTSUP         = Errno(0x5f)
+    ENOTTY          = Errno(0x19)
+    ENOTUNIQ        = Errno(0x4c)
+    ENXIO           = Errno(0x6)
+    EOPNOTSUPP      = Errno(0x5f)
+    EOVERFLOW       = Errno(0x4b)
+    EOWNERDEAD      = Errno(0x82)
+    EPERM           = Errno(0x1)
+    EPFNOSUPPORT    = Errno(0x60)
+    EPIPE           = Errno(0x20)
+    EPROTO          = Errno(0x47)
+    EPROTONOSUPPORT = Errno(0x5d)
+    EPROTOTYPE      = Errno(0x5b)
+    ERANGE          = Errno(0x22)
+    EREMCHG         = Errno(0x4e)
+    EREMOTE         = Errno(0x42)
+    EREMOTEIO       = Errno(0x79)
+    ERESTART        = Errno(0x55)
+    ERFKILL         = Errno(0x84)
+    EROFS           = Errno(0x1e)
+    ESHUTDOWN       = Errno(0x6c)
+    ESOCKTNOSUPPORT = Errno(0x5e)
+    ESPIPE          = Errno(0x1d)
+    ESRCH           = Errno(0x3)
+    ESRMNT          = Errno(0x45)
+    ESTALE          = Errno(0x74)
+    ESTRPIPE        = Errno(0x56)
+    ETIME           = Errno(0x3e)
+    ETIMEDOUT       = Errno(0x6e)
+    ETOOMANYREFS    = Errno(0x6d)
+    ETXTBSY         = Errno(0x1a)
+    EUCLEAN         = Errno(0x75)
+    EUNATCH         = Errno(0x31)
+    EUSERS          = Errno(0x57)
+    EWOULDBLOCK     = Errno(0xb)
+    EXDEV           = Errno(0x12)
+    EXFULL          = Errno(0x36)
+)

Signals

+
const (
+    SIGABRT   = Signal(0x6)
+    SIGALRM   = Signal(0xe)
+    SIGBUS    = Signal(0x7)
+    SIGCHLD   = Signal(0x11)
+    SIGCLD    = Signal(0x11)
+    SIGCONT   = Signal(0x12)
+    SIGFPE    = Signal(0x8)
+    SIGHUP    = Signal(0x1)
+    SIGILL    = Signal(0x4)
+    SIGINT    = Signal(0x2)
+    SIGIO     = Signal(0x1d)
+    SIGIOT    = Signal(0x6)
+    SIGKILL   = Signal(0x9)
+    SIGPIPE   = Signal(0xd)
+    SIGPOLL   = Signal(0x1d)
+    SIGPROF   = Signal(0x1b)
+    SIGPWR    = Signal(0x1e)
+    SIGQUIT   = Signal(0x3)
+    SIGSEGV   = Signal(0xb)
+    SIGSTKFLT = Signal(0x10)
+    SIGSTOP   = Signal(0x13)
+    SIGSYS    = Signal(0x1f)
+    SIGTERM   = Signal(0xf)
+    SIGTRAP   = Signal(0x5)
+    SIGTSTP   = Signal(0x14)
+    SIGTTIN   = Signal(0x15)
+    SIGTTOU   = Signal(0x16)
+    SIGUNUSED = Signal(0x1f)
+    SIGURG    = Signal(0x17)
+    SIGUSR1   = Signal(0xa)
+    SIGUSR2   = Signal(0xc)
+    SIGVTALRM = Signal(0x1a)
+    SIGWINCH  = Signal(0x1c)
+    SIGXCPU   = Signal(0x18)
+    SIGXFSZ   = Signal(0x19)
+)
const (
+    SYS_READ                   = 0
+    SYS_WRITE                  = 1
+    SYS_OPEN                   = 2
+    SYS_CLOSE                  = 3
+    SYS_STAT                   = 4
+    SYS_FSTAT                  = 5
+    SYS_LSTAT                  = 6
+    SYS_POLL                   = 7
+    SYS_LSEEK                  = 8
+    SYS_MMAP                   = 9
+    SYS_MPROTECT               = 10
+    SYS_MUNMAP                 = 11
+    SYS_BRK                    = 12
+    SYS_RT_SIGACTION           = 13
+    SYS_RT_SIGPROCMASK         = 14
+    SYS_RT_SIGRETURN           = 15
+    SYS_IOCTL                  = 16
+    SYS_PREAD64                = 17
+    SYS_PWRITE64               = 18
+    SYS_READV                  = 19
+    SYS_WRITEV                 = 20
+    SYS_ACCESS                 = 21
+    SYS_PIPE                   = 22
+    SYS_SELECT                 = 23
+    SYS_SCHED_YIELD            = 24
+    SYS_MREMAP                 = 25
+    SYS_MSYNC                  = 26
+    SYS_MINCORE                = 27
+    SYS_MADVISE                = 28
+    SYS_SHMGET                 = 29
+    SYS_SHMAT                  = 30
+    SYS_SHMCTL                 = 31
+    SYS_DUP                    = 32
+    SYS_DUP2                   = 33
+    SYS_PAUSE                  = 34
+    SYS_NANOSLEEP              = 35
+    SYS_GETITIMER              = 36
+    SYS_ALARM                  = 37
+    SYS_SETITIMER              = 38
+    SYS_GETPID                 = 39
+    SYS_SENDFILE               = 40
+    SYS_SOCKET                 = 41
+    SYS_CONNECT                = 42
+    SYS_ACCEPT                 = 43
+    SYS_SENDTO                 = 44
+    SYS_RECVFROM               = 45
+    SYS_SENDMSG                = 46
+    SYS_RECVMSG                = 47
+    SYS_SHUTDOWN               = 48
+    SYS_BIND                   = 49
+    SYS_LISTEN                 = 50
+    SYS_GETSOCKNAME            = 51
+    SYS_GETPEERNAME            = 52
+    SYS_SOCKETPAIR             = 53
+    SYS_SETSOCKOPT             = 54
+    SYS_GETSOCKOPT             = 55
+    SYS_CLONE                  = 56
+    SYS_FORK                   = 57
+    SYS_VFORK                  = 58
+    SYS_EXECVE                 = 59
+    SYS_EXIT                   = 60
+    SYS_WAIT4                  = 61
+    SYS_KILL                   = 62
+    SYS_UNAME                  = 63
+    SYS_SEMGET                 = 64
+    SYS_SEMOP                  = 65
+    SYS_SEMCTL                 = 66
+    SYS_SHMDT                  = 67
+    SYS_MSGGET                 = 68
+    SYS_MSGSND                 = 69
+    SYS_MSGRCV                 = 70
+    SYS_MSGCTL                 = 71
+    SYS_FCNTL                  = 72
+    SYS_FLOCK                  = 73
+    SYS_FSYNC                  = 74
+    SYS_FDATASYNC              = 75
+    SYS_TRUNCATE               = 76
+    SYS_FTRUNCATE              = 77
+    SYS_GETDENTS               = 78
+    SYS_GETCWD                 = 79
+    SYS_CHDIR                  = 80
+    SYS_FCHDIR                 = 81
+    SYS_RENAME                 = 82
+    SYS_MKDIR                  = 83
+    SYS_RMDIR                  = 84
+    SYS_CREAT                  = 85
+    SYS_LINK                   = 86
+    SYS_UNLINK                 = 87
+    SYS_SYMLINK                = 88
+    SYS_READLINK               = 89
+    SYS_CHMOD                  = 90
+    SYS_FCHMOD                 = 91
+    SYS_CHOWN                  = 92
+    SYS_FCHOWN                 = 93
+    SYS_LCHOWN                 = 94
+    SYS_UMASK                  = 95
+    SYS_GETTIMEOFDAY           = 96
+    SYS_GETRLIMIT              = 97
+    SYS_GETRUSAGE              = 98
+    SYS_SYSINFO                = 99
+    SYS_TIMES                  = 100
+    SYS_PTRACE                 = 101
+    SYS_GETUID                 = 102
+    SYS_SYSLOG                 = 103
+    SYS_GETGID                 = 104
+    SYS_SETUID                 = 105
+    SYS_SETGID                 = 106
+    SYS_GETEUID                = 107
+    SYS_GETEGID                = 108
+    SYS_SETPGID                = 109
+    SYS_GETPPID                = 110
+    SYS_GETPGRP                = 111
+    SYS_SETSID                 = 112
+    SYS_SETREUID               = 113
+    SYS_SETREGID               = 114
+    SYS_GETGROUPS              = 115
+    SYS_SETGROUPS              = 116
+    SYS_SETRESUID              = 117
+    SYS_GETRESUID              = 118
+    SYS_SETRESGID              = 119
+    SYS_GETRESGID              = 120
+    SYS_GETPGID                = 121
+    SYS_SETFSUID               = 122
+    SYS_SETFSGID               = 123
+    SYS_GETSID                 = 124
+    SYS_CAPGET                 = 125
+    SYS_CAPSET                 = 126
+    SYS_RT_SIGPENDING          = 127
+    SYS_RT_SIGTIMEDWAIT        = 128
+    SYS_RT_SIGQUEUEINFO        = 129
+    SYS_RT_SIGSUSPEND          = 130
+    SYS_SIGALTSTACK            = 131
+    SYS_UTIME                  = 132
+    SYS_MKNOD                  = 133
+    SYS_USELIB                 = 134
+    SYS_PERSONALITY            = 135
+    SYS_USTAT                  = 136
+    SYS_STATFS                 = 137
+    SYS_FSTATFS                = 138
+    SYS_SYSFS                  = 139
+    SYS_GETPRIORITY            = 140
+    SYS_SETPRIORITY            = 141
+    SYS_SCHED_SETPARAM         = 142
+    SYS_SCHED_GETPARAM         = 143
+    SYS_SCHED_SETSCHEDULER     = 144
+    SYS_SCHED_GETSCHEDULER     = 145
+    SYS_SCHED_GET_PRIORITY_MAX = 146
+    SYS_SCHED_GET_PRIORITY_MIN = 147
+    SYS_SCHED_RR_GET_INTERVAL  = 148
+    SYS_MLOCK                  = 149
+    SYS_MUNLOCK                = 150
+    SYS_MLOCKALL               = 151
+    SYS_MUNLOCKALL             = 152
+    SYS_VHANGUP                = 153
+    SYS_MODIFY_LDT             = 154
+    SYS_PIVOT_ROOT             = 155
+    SYS__SYSCTL                = 156
+    SYS_PRCTL                  = 157
+    SYS_ARCH_PRCTL             = 158
+    SYS_ADJTIMEX               = 159
+    SYS_SETRLIMIT              = 160
+    SYS_CHROOT                 = 161
+    SYS_SYNC                   = 162
+    SYS_ACCT                   = 163
+    SYS_SETTIMEOFDAY           = 164
+    SYS_MOUNT                  = 165
+    SYS_UMOUNT2                = 166
+    SYS_SWAPON                 = 167
+    SYS_SWAPOFF                = 168
+    SYS_REBOOT                 = 169
+    SYS_SETHOSTNAME            = 170
+    SYS_SETDOMAINNAME          = 171
+    SYS_IOPL                   = 172
+    SYS_IOPERM                 = 173
+    SYS_CREATE_MODULE          = 174
+    SYS_INIT_MODULE            = 175
+    SYS_DELETE_MODULE          = 176
+    SYS_GET_KERNEL_SYMS        = 177
+    SYS_QUERY_MODULE           = 178
+    SYS_QUOTACTL               = 179
+    SYS_NFSSERVCTL             = 180
+    SYS_GETPMSG                = 181
+    SYS_PUTPMSG                = 182
+    SYS_AFS_SYSCALL            = 183
+    SYS_TUXCALL                = 184
+    SYS_SECURITY               = 185
+    SYS_GETTID                 = 186
+    SYS_READAHEAD              = 187
+    SYS_SETXATTR               = 188
+    SYS_LSETXATTR              = 189
+    SYS_FSETXATTR              = 190
+    SYS_GETXATTR               = 191
+    SYS_LGETXATTR              = 192
+    SYS_FGETXATTR              = 193
+    SYS_LISTXATTR              = 194
+    SYS_LLISTXATTR             = 195
+    SYS_FLISTXATTR             = 196
+    SYS_REMOVEXATTR            = 197
+    SYS_LREMOVEXATTR           = 198
+    SYS_FREMOVEXATTR           = 199
+    SYS_TKILL                  = 200
+    SYS_TIME                   = 201
+    SYS_FUTEX                  = 202
+    SYS_SCHED_SETAFFINITY      = 203
+    SYS_SCHED_GETAFFINITY      = 204
+    SYS_SET_THREAD_AREA        = 205
+    SYS_IO_SETUP               = 206
+    SYS_IO_DESTROY             = 207
+    SYS_IO_GETEVENTS           = 208
+    SYS_IO_SUBMIT              = 209
+    SYS_IO_CANCEL              = 210
+    SYS_GET_THREAD_AREA        = 211
+    SYS_LOOKUP_DCOOKIE         = 212
+    SYS_EPOLL_CREATE           = 213
+    SYS_EPOLL_CTL_OLD          = 214
+    SYS_EPOLL_WAIT_OLD         = 215
+    SYS_REMAP_FILE_PAGES       = 216
+    SYS_GETDENTS64             = 217
+    SYS_SET_TID_ADDRESS        = 218
+    SYS_RESTART_SYSCALL        = 219
+    SYS_SEMTIMEDOP             = 220
+    SYS_FADVISE64              = 221
+    SYS_TIMER_CREATE           = 222
+    SYS_TIMER_SETTIME          = 223
+    SYS_TIMER_GETTIME          = 224
+    SYS_TIMER_GETOVERRUN       = 225
+    SYS_TIMER_DELETE           = 226
+    SYS_CLOCK_SETTIME          = 227
+    SYS_CLOCK_GETTIME          = 228
+    SYS_CLOCK_GETRES           = 229
+    SYS_CLOCK_NANOSLEEP        = 230
+    SYS_EXIT_GROUP             = 231
+    SYS_EPOLL_WAIT             = 232
+    SYS_EPOLL_CTL              = 233
+    SYS_TGKILL                 = 234
+    SYS_UTIMES                 = 235
+    SYS_VSERVER                = 236
+    SYS_MBIND                  = 237
+    SYS_SET_MEMPOLICY          = 238
+    SYS_GET_MEMPOLICY          = 239
+    SYS_MQ_OPEN                = 240
+    SYS_MQ_UNLINK              = 241
+    SYS_MQ_TIMEDSEND           = 242
+    SYS_MQ_TIMEDRECEIVE        = 243
+    SYS_MQ_NOTIFY              = 244
+    SYS_MQ_GETSETATTR          = 245
+    SYS_KEXEC_LOAD             = 246
+    SYS_WAITID                 = 247
+    SYS_ADD_KEY                = 248
+    SYS_REQUEST_KEY            = 249
+    SYS_KEYCTL                 = 250
+    SYS_IOPRIO_SET             = 251
+    SYS_IOPRIO_GET             = 252
+    SYS_INOTIFY_INIT           = 253
+    SYS_INOTIFY_ADD_WATCH      = 254
+    SYS_INOTIFY_RM_WATCH       = 255
+    SYS_MIGRATE_PAGES          = 256
+    SYS_OPENAT                 = 257
+    SYS_MKDIRAT                = 258
+    SYS_MKNODAT                = 259
+    SYS_FCHOWNAT               = 260
+    SYS_FUTIMESAT              = 261
+    SYS_NEWFSTATAT             = 262
+    SYS_UNLINKAT               = 263
+    SYS_RENAMEAT               = 264
+    SYS_LINKAT                 = 265
+    SYS_SYMLINKAT              = 266
+    SYS_READLINKAT             = 267
+    SYS_FCHMODAT               = 268
+    SYS_FACCESSAT              = 269
+    SYS_PSELECT6               = 270
+    SYS_PPOLL                  = 271
+    SYS_UNSHARE                = 272
+    SYS_SET_ROBUST_LIST        = 273
+    SYS_GET_ROBUST_LIST        = 274
+    SYS_SPLICE                 = 275
+    SYS_TEE                    = 276
+    SYS_SYNC_FILE_RANGE        = 277
+    SYS_VMSPLICE               = 278
+    SYS_MOVE_PAGES             = 279
+    SYS_UTIMENSAT              = 280
+    SYS_EPOLL_PWAIT            = 281
+    SYS_SIGNALFD               = 282
+    SYS_TIMERFD_CREATE         = 283
+    SYS_EVENTFD                = 284
+    SYS_FALLOCATE              = 285
+    SYS_TIMERFD_SETTIME        = 286
+    SYS_TIMERFD_GETTIME        = 287
+    SYS_ACCEPT4                = 288
+    SYS_SIGNALFD4              = 289
+    SYS_EVENTFD2               = 290
+    SYS_EPOLL_CREATE1          = 291
+    SYS_DUP3                   = 292
+    SYS_PIPE2                  = 293
+    SYS_INOTIFY_INIT1          = 294
+    SYS_PREADV                 = 295
+    SYS_PWRITEV                = 296
+    SYS_RT_TGSIGQUEUEINFO      = 297
+    SYS_PERF_EVENT_OPEN        = 298
+    SYS_RECVMMSG               = 299
+    SYS_FANOTIFY_INIT          = 300
+    SYS_FANOTIFY_MARK          = 301
+    SYS_PRLIMIT64              = 302
+)
const (
+    SizeofSockaddrInet4     = 0x10
+    SizeofSockaddrInet6     = 0x1c
+    SizeofSockaddrAny       = 0x70
+    SizeofSockaddrUnix      = 0x6e
+    SizeofSockaddrLinklayer = 0x14
+    SizeofSockaddrNetlink   = 0xc
+    SizeofLinger            = 0x8
+    SizeofIPMreq            = 0x8
+    SizeofIPMreqn           = 0xc
+    SizeofIPv6Mreq          = 0x14
+    SizeofMsghdr            = 0x38
+    SizeofCmsghdr           = 0x10
+    SizeofInet4Pktinfo      = 0xc
+    SizeofInet6Pktinfo      = 0x14
+    SizeofIPv6MTUInfo       = 0x20
+    SizeofICMPv6Filter      = 0x20
+    SizeofUcred             = 0xc
+    SizeofTCPInfo           = 0x68
+)
const (
+    IFA_UNSPEC          = 0x0
+    IFA_ADDRESS         = 0x1
+    IFA_LOCAL           = 0x2
+    IFA_LABEL           = 0x3
+    IFA_BROADCAST       = 0x4
+    IFA_ANYCAST         = 0x5
+    IFA_CACHEINFO       = 0x6
+    IFA_MULTICAST       = 0x7
+    IFLA_UNSPEC         = 0x0
+    IFLA_ADDRESS        = 0x1
+    IFLA_BROADCAST      = 0x2
+    IFLA_IFNAME         = 0x3
+    IFLA_MTU            = 0x4
+    IFLA_LINK           = 0x5
+    IFLA_QDISC          = 0x6
+    IFLA_STATS          = 0x7
+    IFLA_COST           = 0x8
+    IFLA_PRIORITY       = 0x9
+    IFLA_MASTER         = 0xa
+    IFLA_WIRELESS       = 0xb
+    IFLA_PROTINFO       = 0xc
+    IFLA_TXQLEN         = 0xd
+    IFLA_MAP            = 0xe
+    IFLA_WEIGHT         = 0xf
+    IFLA_OPERSTATE      = 0x10
+    IFLA_LINKMODE       = 0x11
+    IFLA_LINKINFO       = 0x12
+    IFLA_NET_NS_PID     = 0x13
+    IFLA_IFALIAS        = 0x14
+    IFLA_MAX            = 0x1d
+    RT_SCOPE_UNIVERSE   = 0x0
+    RT_SCOPE_SITE       = 0xc8
+    RT_SCOPE_LINK       = 0xfd
+    RT_SCOPE_HOST       = 0xfe
+    RT_SCOPE_NOWHERE    = 0xff
+    RT_TABLE_UNSPEC     = 0x0
+    RT_TABLE_COMPAT     = 0xfc
+    RT_TABLE_DEFAULT    = 0xfd
+    RT_TABLE_MAIN       = 0xfe
+    RT_TABLE_LOCAL      = 0xff
+    RT_TABLE_MAX        = 0xffffffff
+    RTA_UNSPEC          = 0x0
+    RTA_DST             = 0x1
+    RTA_SRC             = 0x2
+    RTA_IIF             = 0x3
+    RTA_OIF             = 0x4
+    RTA_GATEWAY         = 0x5
+    RTA_PRIORITY        = 0x6
+    RTA_PREFSRC         = 0x7
+    RTA_METRICS         = 0x8
+    RTA_MULTIPATH       = 0x9
+    RTA_FLOW            = 0xb
+    RTA_CACHEINFO       = 0xc
+    RTA_TABLE           = 0xf
+    RTN_UNSPEC          = 0x0
+    RTN_UNICAST         = 0x1
+    RTN_LOCAL           = 0x2
+    RTN_BROADCAST       = 0x3
+    RTN_ANYCAST         = 0x4
+    RTN_MULTICAST       = 0x5
+    RTN_BLACKHOLE       = 0x6
+    RTN_UNREACHABLE     = 0x7
+    RTN_PROHIBIT        = 0x8
+    RTN_THROW           = 0x9
+    RTN_NAT             = 0xa
+    RTN_XRESOLVE        = 0xb
+    RTNLGRP_NONE        = 0x0
+    RTNLGRP_LINK        = 0x1
+    RTNLGRP_NOTIFY      = 0x2
+    RTNLGRP_NEIGH       = 0x3
+    RTNLGRP_TC          = 0x4
+    RTNLGRP_IPV4_IFADDR = 0x5
+    RTNLGRP_IPV4_MROUTE = 0x6
+    RTNLGRP_IPV4_ROUTE  = 0x7
+    RTNLGRP_IPV4_RULE   = 0x8
+    RTNLGRP_IPV6_IFADDR = 0x9
+    RTNLGRP_IPV6_MROUTE = 0xa
+    RTNLGRP_IPV6_ROUTE  = 0xb
+    RTNLGRP_IPV6_IFINFO = 0xc
+    RTNLGRP_IPV6_PREFIX = 0x12
+    RTNLGRP_IPV6_RULE   = 0x13
+    RTNLGRP_ND_USEROPT  = 0x14
+    SizeofNlMsghdr      = 0x10
+    SizeofNlMsgerr      = 0x14
+    SizeofRtGenmsg      = 0x1
+    SizeofNlAttr        = 0x4
+    SizeofRtAttr        = 0x4
+    SizeofIfInfomsg     = 0x10
+    SizeofIfAddrmsg     = 0x8
+    SizeofRtMsg         = 0xc
+    SizeofRtNexthop     = 0x8
+)
const (
+    SizeofSockFilter = 0x8
+    SizeofSockFprog  = 0x10
+)
const (
+    VINTR    = 0x0
+    VQUIT    = 0x1
+    VERASE   = 0x2
+    VKILL    = 0x3
+    VEOF     = 0x4
+    VTIME    = 0x5
+    VMIN     = 0x6
+    VSWTC    = 0x7
+    VSTART   = 0x8
+    VSTOP    = 0x9
+    VSUSP    = 0xa
+    VEOL     = 0xb
+    VREPRINT = 0xc
+    VDISCARD = 0xd
+    VWERASE  = 0xe
+    VLNEXT   = 0xf
+    VEOL2    = 0x10
+    IGNBRK   = 0x1
+    BRKINT   = 0x2
+    IGNPAR   = 0x4
+    PARMRK   = 0x8
+    INPCK    = 0x10
+    ISTRIP   = 0x20
+    INLCR    = 0x40
+    IGNCR    = 0x80
+    ICRNL    = 0x100
+    IUCLC    = 0x200
+    IXON     = 0x400
+    IXANY    = 0x800
+    IXOFF    = 0x1000
+    IMAXBEL  = 0x2000
+    IUTF8    = 0x4000
+    OPOST    = 0x1
+    OLCUC    = 0x2
+    ONLCR    = 0x4
+    OCRNL    = 0x8
+    ONOCR    = 0x10
+    ONLRET   = 0x20
+    OFILL    = 0x40
+    OFDEL    = 0x80
+    B0       = 0x0
+    B50      = 0x1
+    B75      = 0x2
+    B110     = 0x3
+    B134     = 0x4
+    B150     = 0x5
+    B200     = 0x6
+    B300     = 0x7
+    B600     = 0x8
+    B1200    = 0x9
+    B1800    = 0xa
+    B2400    = 0xb
+    B4800    = 0xc
+    B9600    = 0xd
+    B19200   = 0xe
+    B38400   = 0xf
+    CSIZE    = 0x30
+    CS5      = 0x0
+    CS6      = 0x10
+    CS7      = 0x20
+    CS8      = 0x30
+    CSTOPB   = 0x40
+    CREAD    = 0x80
+    PARENB   = 0x100
+    PARODD   = 0x200
+    HUPCL    = 0x400
+    CLOCAL   = 0x800
+    B57600   = 0x1001
+    B115200  = 0x1002
+    B230400  = 0x1003
+    B460800  = 0x1004
+    B500000  = 0x1005
+    B576000  = 0x1006
+    B921600  = 0x1007
+    B1000000 = 0x1008
+    B1152000 = 0x1009
+    B1500000 = 0x100a
+    B2000000 = 0x100b
+    B2500000 = 0x100c
+    B3000000 = 0x100d
+    B3500000 = 0x100e
+    B4000000 = 0x100f
+    ISIG     = 0x1
+    ICANON   = 0x2
+    XCASE    = 0x4
+    ECHO     = 0x8
+    ECHOE    = 0x10
+    ECHOK    = 0x20
+    ECHONL   = 0x40
+    NOFLSH   = 0x80
+    TOSTOP   = 0x100
+    ECHOCTL  = 0x200
+    ECHOPRT  = 0x400
+    ECHOKE   = 0x800
+    FLUSHO   = 0x1000
+    PENDIN   = 0x4000
+    IEXTEN   = 0x8000
+    TCGETS   = 0x5401
+    TCSETS   = 0x5402
+)
const ImplementsGetwd = true
const (
+    PathMax = 0x1000
+)
const SizeofInotifyEvent = 0x10

Variables

var (
+    Stdin  = 0
+    Stdout = 1
+    Stderr = 2
+)

ForkLock is used to synchronize creation of new file descriptors with fork.

+

We want the child in a fork/exec sequence to inherit only the file descriptors we intend. To do that, we mark all file descriptors close-on-exec and then, in the child, explicitly unmark the ones we want the exec'ed program to keep. Unix doesn't make this easy: there is, in general, no way to allocate a new file descriptor close-on-exec. Instead you have to allocate the descriptor and then mark it close-on-exec. If a fork happens between those two events, the child's exec will inherit an unwanted file descriptor.

+

This lock solves that race: the create new fd/mark close-on-exec operation is done holding ForkLock for reading, and the fork itself is done holding ForkLock for writing. At least, that's the idea. There are some complications.

+

Some system calls that create new file descriptors can block for arbitrarily long times: open on a hung NFS server or named pipe, accept on a socket, and so on. We can't reasonably grab the lock across those operations.

+

It is worse to inherit some file descriptors than others. If a non-malicious child accidentally inherits an open ordinary file, that's not a big deal. On the other hand, if a long-lived child accidentally inherits the write end of a pipe, then the reader of that pipe will not see EOF until that child exits, potentially causing the parent program to hang. This is a common problem in threaded C programs that use popen.

+

Luckily, the file descriptors that are most important not to inherit are not the ones that can take an arbitrarily long time to create: pipe returns instantly, and the net package uses non-blocking I/O to accept on a listening socket. The rules for which file descriptor-creating operations use the ForkLock are as follows:

+
var ForkLock sync.RWMutex

For testing: clients can set this flag to force creation of IPv6 sockets to return EAFNOSUPPORT.

+
var SocketDisableIPv6 bool

func Access

func Access(path string, mode uint32) (err error)

func Acct

func Acct(path string) (err error)

func Adjtimex

func Adjtimex(buf *Timex) (state int, err error)

func AttachLsf

func AttachLsf(fd int, i []SockFilter) error

Deprecated: Use golang.org/x/net/bpf instead.

+

func Bind

func Bind(fd int, sa Sockaddr) (err error)

func BindToDevice

func BindToDevice(fd int, device string) (err error)

BindToDevice binds the socket associated with fd to device.

+

func BytePtrFromString 1.1

func BytePtrFromString(s string) (*byte, error)

BytePtrFromString returns a pointer to a NUL-terminated array of bytes containing the text of s. If s contains a NUL byte at any location, it returns (nil, EINVAL).

+

func ByteSliceFromString 1.1

func ByteSliceFromString(s string) ([]byte, error)

ByteSliceFromString returns a NUL-terminated slice of bytes containing the text of s. If s contains a NUL byte at any location, it returns (nil, EINVAL).

+

func Chdir

func Chdir(path string) (err error)

func Chmod

func Chmod(path string, mode uint32) (err error)

func Chown

func Chown(path string, uid int, gid int) (err error)

func Chroot

func Chroot(path string) (err error)

func Clearenv

func Clearenv()

func Close

func Close(fd int) (err error)

func CloseOnExec

func CloseOnExec(fd int)

func CmsgLen

func CmsgLen(datalen int) int

CmsgLen returns the value to store in the Len field of the Cmsghdr structure, taking into account any necessary alignment.

+

func CmsgSpace

func CmsgSpace(datalen int) int

CmsgSpace returns the number of bytes an ancillary element with payload of the passed data length occupies.

+

func Connect

func Connect(fd int, sa Sockaddr) (err error)

func Creat

func Creat(path string, mode uint32) (fd int, err error)

func DetachLsf

func DetachLsf(fd int) error

Deprecated: Use golang.org/x/net/bpf instead.

+

func Dup

func Dup(oldfd int) (fd int, err error)

func Dup2

func Dup2(oldfd int, newfd int) (err error)

func Dup3

func Dup3(oldfd int, newfd int, flags int) (err error)

func Environ

func Environ() []string

func EpollCreate

func EpollCreate(size int) (fd int, err error)

func EpollCreate1

func EpollCreate1(flag int) (fd int, err error)

func EpollCtl

func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)

func EpollWait

func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)

func Exec

func Exec(argv0 string, argv []string, envv []string) (err error)

Exec invokes the execve(2) system call.

+

func Exit

func Exit(code int)

func Faccessat

func Faccessat(dirfd int, path string, mode uint32, flags int) (err error)

func Fallocate

func Fallocate(fd int, mode uint32, off int64, len int64) (err error)

func Fchdir

func Fchdir(fd int) (err error)

func Fchmod

func Fchmod(fd int, mode uint32) (err error)

func Fchmodat

func Fchmodat(dirfd int, path string, mode uint32, flags int) error

func Fchown

func Fchown(fd int, uid int, gid int) (err error)

func Fchownat

func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)

func FcntlFlock

func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error

FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command.

+

func Fdatasync

func Fdatasync(fd int) (err error)

func Flock

func Flock(fd int, how int) (err error)

func ForkExec

func ForkExec(argv0 string, argv []string, attr *ProcAttr) (pid int, err error)

Combination of fork and exec, careful to be thread safe.

+

func Fstat

func Fstat(fd int, stat *Stat_t) (err error)

func Fstatfs

func Fstatfs(fd int, buf *Statfs_t) (err error)

func Fsync

func Fsync(fd int) (err error)

func Ftruncate

func Ftruncate(fd int, length int64) (err error)

func Futimes

func Futimes(fd int, tv []Timeval) (err error)

func Futimesat

func Futimesat(dirfd int, path string, tv []Timeval) (err error)

func Getcwd

func Getcwd(buf []byte) (n int, err error)

func Getdents

func Getdents(fd int, buf []byte) (n int, err error)

func Getegid

func Getegid() (egid int)

func Getenv

func Getenv(key string) (value string, found bool)

func Geteuid

func Geteuid() (euid int)

func Getgid

func Getgid() (gid int)

func Getgroups

func Getgroups() (gids []int, err error)

func Getpagesize

func Getpagesize() int

func Getpgid

func Getpgid(pid int) (pgid int, err error)

func Getpgrp

func Getpgrp() (pid int)

func Getpid

func Getpid() (pid int)

func Getppid

func Getppid() (ppid int)

func Getpriority

func Getpriority(which int, who int) (prio int, err error)

func Getrlimit

func Getrlimit(resource int, rlim *Rlimit) (err error)

func Getrusage

func Getrusage(who int, rusage *Rusage) (err error)

func GetsockoptInet4Addr

func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error)

func GetsockoptInt

func GetsockoptInt(fd, level, opt int) (value int, err error)

func Gettid

func Gettid() (tid int)

func Gettimeofday

func Gettimeofday(tv *Timeval) (err error)

func Getuid

func Getuid() (uid int)

func Getwd

func Getwd() (wd string, err error)

func Getxattr

func Getxattr(path string, attr string, dest []byte) (sz int, err error)

func InotifyAddWatch

func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)

func InotifyInit

func InotifyInit() (fd int, err error)

func InotifyInit1

func InotifyInit1(flags int) (fd int, err error)

func InotifyRmWatch

func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)

func Ioperm

func Ioperm(from int, num int, on int) (err error)

func Iopl

func Iopl(level int) (err error)

func Kill

func Kill(pid int, sig Signal) (err error)

func Klogctl

func Klogctl(typ int, buf []byte) (n int, err error)

func Lchown

func Lchown(path string, uid int, gid int) (err error)
func Link(oldpath string, newpath string) (err error)

func Listen

func Listen(s int, n int) (err error)

func Listxattr

func Listxattr(path string, dest []byte) (sz int, err error)

func LsfSocket

func LsfSocket(ifindex, proto int) (int, error)

Deprecated: Use golang.org/x/net/bpf instead.

+

func Lstat

func Lstat(path string, stat *Stat_t) (err error)

func Madvise

func Madvise(b []byte, advice int) (err error)

func Mkdir

func Mkdir(path string, mode uint32) (err error)

func Mkdirat

func Mkdirat(dirfd int, path string, mode uint32) (err error)

func Mkfifo

func Mkfifo(path string, mode uint32) (err error)

func Mknod

func Mknod(path string, mode uint32, dev int) (err error)

func Mknodat

func Mknodat(dirfd int, path string, mode uint32, dev int) (err error)

func Mlock

func Mlock(b []byte) (err error)

func Mlockall

func Mlockall(flags int) (err error)

func Mmap

func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error)

func Mount

func Mount(source string, target string, fstype string, flags uintptr, data string) (err error)

func Mprotect

func Mprotect(b []byte, prot int) (err error)

func Munlock

func Munlock(b []byte) (err error)

func Munlockall

func Munlockall() (err error)

func Munmap

func Munmap(b []byte) (err error)

func Nanosleep

func Nanosleep(time *Timespec, leftover *Timespec) (err error)

func NetlinkRIB

func NetlinkRIB(proto, family int) ([]byte, error)

NetlinkRIB returns routing information base, as known as RIB, which consists of network facility information, states and parameters.

+

func Open

func Open(path string, mode int, perm uint32) (fd int, err error)

func Openat

func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)

func ParseDirent

func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string)

ParseDirent parses up to max directory entries in buf, appending the names to names. It returns the number of bytes consumed from buf, the number of entries added to names, and the new names slice.

+

func ParseUnixRights

func ParseUnixRights(m *SocketControlMessage) ([]int, error)

ParseUnixRights decodes a socket control message that contains an integer array of open file descriptors from another process.

+

func Pause

func Pause() (err error)

func Pipe

func Pipe(p []int) error

func Pipe2

func Pipe2(p []int, flags int) error

func PivotRoot

func PivotRoot(newroot string, putold string) (err error)

func Pread

func Pread(fd int, p []byte, offset int64) (n int, err error)

func PtraceAttach

func PtraceAttach(pid int) (err error)

func PtraceCont

func PtraceCont(pid int, signal int) (err error)

func PtraceDetach

func PtraceDetach(pid int) (err error)

func PtraceGetEventMsg

func PtraceGetEventMsg(pid int) (msg uint, err error)

func PtraceGetRegs

func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error)

func PtracePeekData

func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error)

func PtracePeekText

func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error)

func PtracePokeData

func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error)

func PtracePokeText

func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error)

func PtraceSetOptions

func PtraceSetOptions(pid int, options int) (err error)

func PtraceSetRegs

func PtraceSetRegs(pid int, regs *PtraceRegs) (err error)

func PtraceSingleStep

func PtraceSingleStep(pid int) (err error)

func PtraceSyscall

func PtraceSyscall(pid int, signal int) (err error)

func Pwrite

func Pwrite(fd int, p []byte, offset int64) (n int, err error)

func Read

func Read(fd int, p []byte) (n int, err error)

func ReadDirent

func ReadDirent(fd int, buf []byte) (n int, err error)
func Readlink(path string, buf []byte) (n int, err error)

func Reboot

func Reboot(cmd int) (err error)

func Removexattr

func Removexattr(path string, attr string) (err error)

func Rename

func Rename(oldpath string, newpath string) (err error)

func Renameat

func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)

func Rmdir

func Rmdir(path string) error

func Seek

func Seek(fd int, offset int64, whence int) (off int64, err error)

func Select

func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)

func Sendfile

func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)

func Sendmsg

func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error)

func SendmsgN

func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error)

func Sendto

func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error)

func SetLsfPromisc

func SetLsfPromisc(name string, m bool) error

Deprecated: Use golang.org/x/net/bpf instead.

+

func SetNonblock

func SetNonblock(fd int, nonblocking bool) (err error)

func Setdomainname

func Setdomainname(p []byte) (err error)

func Setegid

func Setegid(egid int) (err error)

func Setenv

func Setenv(key, value string) error

func Seteuid

func Seteuid(euid int) (err error)

func Setfsgid

func Setfsgid(gid int) (err error)

func Setfsuid

func Setfsuid(uid int) (err error)

func Setgid

func Setgid(gid int) (err error)

func Setgroups

func Setgroups(gids []int) (err error)

func Sethostname

func Sethostname(p []byte) (err error)

func Setpgid

func Setpgid(pid int, pgid int) (err error)

func Setpriority

func Setpriority(which int, who int, prio int) (err error)

func Setregid

func Setregid(rgid, egid int) (err error)

func Setresgid

func Setresgid(rgid, egid, sgid int) (err error)

func Setresuid

func Setresuid(ruid, euid, suid int) (err error)

func Setreuid

func Setreuid(ruid, euid int) (err error)

func Setrlimit

func Setrlimit(resource int, rlim *Rlimit) error

func Setsid

func Setsid() (pid int, err error)

func SetsockoptByte

func SetsockoptByte(fd, level, opt int, value byte) (err error)

func SetsockoptICMPv6Filter

func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error

func SetsockoptIPMreq

func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) (err error)

func SetsockoptIPMreqn

func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error)

func SetsockoptIPv6Mreq

func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) (err error)

func SetsockoptInet4Addr

func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) (err error)

func SetsockoptInt

func SetsockoptInt(fd, level, opt int, value int) (err error)

func SetsockoptLinger

func SetsockoptLinger(fd, level, opt int, l *Linger) (err error)

func SetsockoptString

func SetsockoptString(fd, level, opt int, s string) (err error)

func SetsockoptTimeval

func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error)

func Settimeofday

func Settimeofday(tv *Timeval) (err error)

func Setuid

func Setuid(uid int) (err error)

func Setxattr

func Setxattr(path string, attr string, data []byte, flags int) (err error)

func Shutdown

func Shutdown(fd int, how int) (err error)

func SlicePtrFromStrings

func SlicePtrFromStrings(ss []string) ([]*byte, error)

SlicePtrFromStrings converts a slice of strings to a slice of pointers to NUL-terminated byte arrays. If any string contains a NUL byte, it returns (nil, EINVAL).

+

func Socket

func Socket(domain, typ, proto int) (fd int, err error)

func Socketpair

func Socketpair(domain, typ, proto int) (fd [2]int, err error)

func Splice

func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)

func StartProcess

func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error)

StartProcess wraps ForkExec for package os.

+

func Stat

func Stat(path string, stat *Stat_t) (err error)

func Statfs

func Statfs(path string, buf *Statfs_t) (err error)

func StringBytePtr

func StringBytePtr(s string) *byte

StringBytePtr returns a pointer to a NUL-terminated array of bytes. If s contains a NUL byte this function panics instead of returning an error.

+

Deprecated: Use BytePtrFromString instead.

+

func StringByteSlice

func StringByteSlice(s string) []byte

StringByteSlice converts a string to a NUL-terminated []byte, If s contains a NUL byte this function panics instead of returning an error.

+

Deprecated: Use ByteSliceFromString instead.

+

func StringSlicePtr

func StringSlicePtr(ss []string) []*byte

StringSlicePtr converts a slice of strings to a slice of pointers to NUL-terminated byte arrays. If any string contains a NUL byte this function panics instead of returning an error.

+

Deprecated: Use SlicePtrFromStrings instead.

+
func Symlink(oldpath string, newpath string) (err error)

func Sync

func Sync()

func SyncFileRange

func SyncFileRange(fd int, off int64, n int64, flags int) (err error)

func Sysinfo

func Sysinfo(info *Sysinfo_t) (err error)

func Tee

func Tee(rfd int, wfd int, len int, flags int) (n int64, err error)

func Tgkill

func Tgkill(tgid int, tid int, sig Signal) (err error)

func Times

func Times(tms *Tms) (ticks uintptr, err error)

func TimespecToNsec 1.1

func TimespecToNsec(ts Timespec) int64

TimespecToNsec returns the time stored in ts as nanoseconds.

+

func TimevalToNsec

func TimevalToNsec(tv Timeval) int64

TimevalToNsec returns the time stored in tv as nanoseconds.

+

func Truncate

func Truncate(path string, length int64) (err error)

func Umask

func Umask(mask int) (oldmask int)

func Uname

func Uname(buf *Utsname) (err error)

func UnixCredentials

func UnixCredentials(ucred *Ucred) []byte

UnixCredentials encodes credentials into a socket control message for sending to another process. This can be used for authentication.

+

func UnixRights

func UnixRights(fds ...int) []byte

UnixRights encodes a set of open file descriptors into a socket control message for sending to another process.

+
func Unlink(path string) error

func Unlinkat

func Unlinkat(dirfd int, path string) error

func Unmount

func Unmount(target string, flags int) (err error)

func Unsetenv 1.4

func Unsetenv(key string) error

func Unshare

func Unshare(flags int) (err error)

func Ustat

func Ustat(dev int, ubuf *Ustat_t) (err error)

func Utime

func Utime(path string, buf *Utimbuf) (err error)

func Utimes

func Utimes(path string, tv []Timeval) (err error)

func UtimesNano 1.1

func UtimesNano(path string, ts []Timespec) (err error)

func Wait4

func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error)

func Write

func Write(fd int, p []byte) (n int, err error)

type Cmsghdr

type Cmsghdr struct {
+    Len   uint64
+    Level int32
+    Type  int32
+}
+

func (*Cmsghdr) SetLen

func (cmsg *Cmsghdr) SetLen(length int)

type Conn 1.9

Conn is implemented by some types in the net and os packages to provide access to the underlying file descriptor or handle.

+
type Conn interface {
+    // SyscallConn returns a raw network connection.
+    SyscallConn() (RawConn, error)
+}

type Credential

Credential holds user and group identities to be assumed by a child process started by StartProcess.

+
type Credential struct {
+    Uid         uint32   // User ID.
+    Gid         uint32   // Group ID.
+    Groups      []uint32 // Supplementary group IDs.
+    NoSetGroups bool     // If true, don't set supplementary groups
+}
+

type Dirent

type Dirent struct {
+    Ino       uint64
+    Off       int64
+    Reclen    uint16
+    Type      uint8
+    Name      [256]int8
+    Pad_cgo_0 [5]byte
+}
+

type EpollEvent

type EpollEvent struct {
+    Events uint32
+    Fd     int32
+    Pad    int32
+}
+

type Errno

An Errno is an unsigned number describing an error condition. It implements the error interface. The zero Errno is by convention a non-error, so code to convert from Errno to error should use:

+
err = nil
+if errno != 0 {
+	err = errno
+}
+

Errno values can be tested against error values using errors.Is. For example:

+
_, _, err := syscall.Syscall(...)
+if errors.Is(err, fs.ErrNotExist) ...
+
type Errno uintptr

func AllThreadsSyscall

func AllThreadsSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)

AllThreadsSyscall performs a syscall on each OS thread of the Go runtime. It first invokes the syscall on one thread. Should that invocation fail, it returns immediately with the error status. Otherwise, it invokes the syscall on all of the remaining threads in parallel. It will terminate the program if it observes any invoked syscall's return value differs from that of the first invocation.

+

AllThreadsSyscall is intended for emulating simultaneous process-wide state changes that require consistently modifying per-thread state of the Go runtime.

+

AllThreadsSyscall is unaware of any threads that are launched explicitly by cgo linked code, so the function always returns ENOTSUP in binaries that use cgo.

+

func AllThreadsSyscall6

func AllThreadsSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)

AllThreadsSyscall6 is like AllThreadsSyscall, but extended to six arguments.

+

func RawSyscall

func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)

func RawSyscall6

func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)

func Syscall

func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)

func Syscall6

func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)

func (Errno) Error

func (e Errno) Error() string

func (Errno) Is 1.13

func (e Errno) Is(target error) bool

func (Errno) Temporary

func (e Errno) Temporary() bool

func (Errno) Timeout

func (e Errno) Timeout() bool

type FdSet

type FdSet struct {
+    Bits [16]int64
+}
+

type Flock_t

type Flock_t struct {
+    Type      int16
+    Whence    int16
+    Pad_cgo_0 [4]byte
+    Start     int64
+    Len       int64
+    Pid       int32
+    Pad_cgo_1 [4]byte
+}
+

type Fsid

type Fsid struct {
+    X__val [2]int32
+}
+

type ICMPv6Filter

type ICMPv6Filter struct {
+    Data [8]uint32
+}
+

func GetsockoptICMPv6Filter

func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error)

type IPMreq

type IPMreq struct {
+    Multiaddr [4]byte /* in_addr */
+    Interface [4]byte /* in_addr */
+}
+

func GetsockoptIPMreq

func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error)

type IPMreqn

type IPMreqn struct {
+    Multiaddr [4]byte /* in_addr */
+    Address   [4]byte /* in_addr */
+    Ifindex   int32
+}
+

func GetsockoptIPMreqn

func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error)

type IPv6MTUInfo

type IPv6MTUInfo struct {
+    Addr RawSockaddrInet6
+    Mtu  uint32
+}
+

func GetsockoptIPv6MTUInfo

func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error)

type IPv6Mreq

type IPv6Mreq struct {
+    Multiaddr [16]byte /* in6_addr */
+    Interface uint32
+}
+

func GetsockoptIPv6Mreq

func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error)

type IfAddrmsg

type IfAddrmsg struct {
+    Family    uint8
+    Prefixlen uint8
+    Flags     uint8
+    Scope     uint8
+    Index     uint32
+}
+

type IfInfomsg

type IfInfomsg struct {
+    Family     uint8
+    X__ifi_pad uint8
+    Type       uint16
+    Index      int32
+    Flags      uint32
+    Change     uint32
+}
+

type Inet4Pktinfo

type Inet4Pktinfo struct {
+    Ifindex  int32
+    Spec_dst [4]byte /* in_addr */
+    Addr     [4]byte /* in_addr */
+}
+

type Inet6Pktinfo

type Inet6Pktinfo struct {
+    Addr    [16]byte /* in6_addr */
+    Ifindex uint32
+}
+

type InotifyEvent

type InotifyEvent struct {
+    Wd     int32
+    Mask   uint32
+    Cookie uint32
+    Len    uint32
+    Name   [0]uint8
+}
+

type Iovec

type Iovec struct {
+    Base *byte
+    Len  uint64
+}
+

func (*Iovec) SetLen

func (iov *Iovec) SetLen(length int)

type Linger

type Linger struct {
+    Onoff  int32
+    Linger int32
+}
+

type Msghdr

type Msghdr struct {
+    Name       *byte
+    Namelen    uint32
+    Pad_cgo_0  [4]byte
+    Iov        *Iovec
+    Iovlen     uint64
+    Control    *byte
+    Controllen uint64
+    Flags      int32
+    Pad_cgo_1  [4]byte
+}
+

func (*Msghdr) SetControllen

func (msghdr *Msghdr) SetControllen(length int)

type NetlinkMessage

NetlinkMessage represents a netlink message.

+
type NetlinkMessage struct {
+    Header NlMsghdr
+    Data   []byte
+}
+

func ParseNetlinkMessage

func ParseNetlinkMessage(b []byte) ([]NetlinkMessage, error)

ParseNetlinkMessage parses b as an array of netlink messages and returns the slice containing the NetlinkMessage structures.

+

type NetlinkRouteAttr

NetlinkRouteAttr represents a netlink route attribute.

+
type NetlinkRouteAttr struct {
+    Attr  RtAttr
+    Value []byte
+}
+

func ParseNetlinkRouteAttr

func ParseNetlinkRouteAttr(m *NetlinkMessage) ([]NetlinkRouteAttr, error)

ParseNetlinkRouteAttr parses m's payload as an array of netlink route attributes and returns the slice containing the NetlinkRouteAttr structures.

+

type NetlinkRouteRequest

NetlinkRouteRequest represents a request message to receive routing and link states from the kernel.

+
type NetlinkRouteRequest struct {
+    Header NlMsghdr
+    Data   RtGenmsg
+}
+

type NlAttr

type NlAttr struct {
+    Len  uint16
+    Type uint16
+}
+

type NlMsgerr

type NlMsgerr struct {
+    Error int32
+    Msg   NlMsghdr
+}
+

type NlMsghdr

type NlMsghdr struct {
+    Len   uint32
+    Type  uint16
+    Flags uint16
+    Seq   uint32
+    Pid   uint32
+}
+

type ProcAttr

ProcAttr holds attributes that will be applied to a new process started by StartProcess.

+
type ProcAttr struct {
+    Dir   string    // Current working directory.
+    Env   []string  // Environment.
+    Files []uintptr // File descriptors.
+    Sys   *SysProcAttr
+}
+

type PtraceRegs

type PtraceRegs struct {
+    R15      uint64
+    R14      uint64
+    R13      uint64
+    R12      uint64
+    Rbp      uint64
+    Rbx      uint64
+    R11      uint64
+    R10      uint64
+    R9       uint64
+    R8       uint64
+    Rax      uint64
+    Rcx      uint64
+    Rdx      uint64
+    Rsi      uint64
+    Rdi      uint64
+    Orig_rax uint64
+    Rip      uint64
+    Cs       uint64
+    Eflags   uint64
+    Rsp      uint64
+    Ss       uint64
+    Fs_base  uint64
+    Gs_base  uint64
+    Ds       uint64
+    Es       uint64
+    Fs       uint64
+    Gs       uint64
+}
+

func (*PtraceRegs) PC

func (r *PtraceRegs) PC() uint64

func (*PtraceRegs) SetPC

func (r *PtraceRegs) SetPC(pc uint64)

type RawConn 1.9

A RawConn is a raw network connection.

+
type RawConn interface {
+    // Control invokes f on the underlying connection's file
+    // descriptor or handle.
+    // The file descriptor fd is guaranteed to remain valid while
+    // f executes but not after f returns.
+    Control(f func(fd uintptr)) error
+
+    // Read invokes f on the underlying connection's file
+    // descriptor or handle; f is expected to try to read from the
+    // file descriptor.
+    // If f returns true, Read returns. Otherwise Read blocks
+    // waiting for the connection to be ready for reading and
+    // tries again repeatedly.
+    // The file descriptor is guaranteed to remain valid while f
+    // executes but not after f returns.
+    Read(f func(fd uintptr) (done bool)) error
+
+    // Write is like Read but for writing.
+    Write(f func(fd uintptr) (done bool)) error
+}

type RawSockaddr

type RawSockaddr struct {
+    Family uint16
+    Data   [14]int8
+}
+

type RawSockaddrAny

type RawSockaddrAny struct {
+    Addr RawSockaddr
+    Pad  [96]int8
+}
+

type RawSockaddrInet4

type RawSockaddrInet4 struct {
+    Family uint16
+    Port   uint16
+    Addr   [4]byte /* in_addr */
+    Zero   [8]uint8
+}
+

type RawSockaddrInet6 1.1

type RawSockaddrInet6 struct {
+    Family   uint16
+    Port     uint16
+    Flowinfo uint32
+    Addr     [16]byte /* in6_addr */
+    Scope_id uint32
+}
+

type RawSockaddrLinklayer

type RawSockaddrLinklayer struct {
+    Family   uint16
+    Protocol uint16
+    Ifindex  int32
+    Hatype   uint16
+    Pkttype  uint8
+    Halen    uint8
+    Addr     [8]uint8
+}
+
type RawSockaddrNetlink struct {
+    Family uint16
+    Pad    uint16
+    Pid    uint32
+    Groups uint32
+}
+

type RawSockaddrUnix 1.12

type RawSockaddrUnix struct {
+    Family uint16
+    Path   [108]int8
+}
+

type Rlimit

type Rlimit struct {
+    Cur uint64
+    Max uint64
+}
+

type RtAttr

type RtAttr struct {
+    Len  uint16
+    Type uint16
+}
+

type RtGenmsg

type RtGenmsg struct {
+    Family uint8
+}
+

type RtMsg

type RtMsg struct {
+    Family   uint8
+    Dst_len  uint8
+    Src_len  uint8
+    Tos      uint8
+    Table    uint8
+    Protocol uint8
+    Scope    uint8
+    Type     uint8
+    Flags    uint32
+}
+

type RtNexthop

type RtNexthop struct {
+    Len     uint16
+    Flags   uint8
+    Hops    uint8
+    Ifindex int32
+}
+

type Rusage

type Rusage struct {
+    Utime    Timeval
+    Stime    Timeval
+    Maxrss   int64
+    Ixrss    int64
+    Idrss    int64
+    Isrss    int64
+    Minflt   int64
+    Majflt   int64
+    Nswap    int64
+    Inblock  int64
+    Oublock  int64
+    Msgsnd   int64
+    Msgrcv   int64
+    Nsignals int64
+    Nvcsw    int64
+    Nivcsw   int64
+}
+

type Signal

A Signal is a number describing a process signal. It implements the os.Signal interface.

+
type Signal int

func (Signal) Signal

func (s Signal) Signal()

func (Signal) String

func (s Signal) String() string

type SockFilter

type SockFilter struct {
+    Code uint16
+    Jt   uint8
+    Jf   uint8
+    K    uint32
+}
+

func LsfJump

func LsfJump(code, k, jt, jf int) *SockFilter

Deprecated: Use golang.org/x/net/bpf instead.

+

func LsfStmt

func LsfStmt(code, k int) *SockFilter

Deprecated: Use golang.org/x/net/bpf instead.

+

type SockFprog

type SockFprog struct {
+    Len       uint16
+    Pad_cgo_0 [6]byte
+    Filter    *SockFilter
+}
+

type Sockaddr

type Sockaddr interface {
+    // contains filtered or unexported methods
+}

func Accept

func Accept(fd int) (nfd int, sa Sockaddr, err error)

func Accept4

func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error)

func Getpeername

func Getpeername(fd int) (sa Sockaddr, err error)

func Getsockname

func Getsockname(fd int) (sa Sockaddr, err error)

func Recvfrom

func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error)

func Recvmsg

func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error)

type SockaddrInet4

type SockaddrInet4 struct {
+    Port int
+    Addr [4]byte
+    // contains filtered or unexported fields
+}
+

type SockaddrInet6

type SockaddrInet6 struct {
+    Port   int
+    ZoneId uint32
+    Addr   [16]byte
+    // contains filtered or unexported fields
+}
+

type SockaddrLinklayer

type SockaddrLinklayer struct {
+    Protocol uint16
+    Ifindex  int
+    Hatype   uint16
+    Pkttype  uint8
+    Halen    uint8
+    Addr     [8]byte
+    // contains filtered or unexported fields
+}
+
type SockaddrNetlink struct {
+    Family uint16
+    Pad    uint16
+    Pid    uint32
+    Groups uint32
+    // contains filtered or unexported fields
+}
+

type SockaddrUnix

type SockaddrUnix struct {
+    Name string
+    // contains filtered or unexported fields
+}
+

type SocketControlMessage

SocketControlMessage represents a socket control message.

+
type SocketControlMessage struct {
+    Header Cmsghdr
+    Data   []byte
+}
+

func ParseSocketControlMessage

func ParseSocketControlMessage(b []byte) ([]SocketControlMessage, error)

ParseSocketControlMessage parses b as an array of socket control messages.

+

type Stat_t

type Stat_t struct {
+    Dev       uint64
+    Ino       uint64
+    Nlink     uint64
+    Mode      uint32
+    Uid       uint32
+    Gid       uint32
+    X__pad0   int32
+    Rdev      uint64
+    Size      int64
+    Blksize   int64
+    Blocks    int64
+    Atim      Timespec
+    Mtim      Timespec
+    Ctim      Timespec
+    X__unused [3]int64
+}
+

type Statfs_t

type Statfs_t struct {
+    Type    int64
+    Bsize   int64
+    Blocks  uint64
+    Bfree   uint64
+    Bavail  uint64
+    Files   uint64
+    Ffree   uint64
+    Fsid    Fsid
+    Namelen int64
+    Frsize  int64
+    Flags   int64
+    Spare   [4]int64
+}
+

type SysProcAttr

type SysProcAttr struct {
+    Chroot     string      // Chroot.
+    Credential *Credential // Credential.
+    // Ptrace tells the child to call ptrace(PTRACE_TRACEME).
+    // Call runtime.LockOSThread before starting a process with this set,
+    // and don't call UnlockOSThread until done with PtraceSyscall calls.
+    Ptrace bool
+    Setsid bool // Create session.
+    // Setpgid sets the process group ID of the child to Pgid,
+    // or, if Pgid == 0, to the new child's process ID.
+    Setpgid bool
+    // Setctty sets the controlling terminal of the child to
+    // file descriptor Ctty. Ctty must be a descriptor number
+    // in the child process: an index into ProcAttr.Files.
+    // This is only meaningful if Setsid is true.
+    Setctty bool
+    Noctty  bool // Detach fd 0 from controlling terminal.
+    Ctty    int  // Controlling TTY fd.
+    // Foreground places the child process group in the foreground.
+    // This implies Setpgid. The Ctty field must be set to
+    // the descriptor of the controlling TTY.
+    // Unlike Setctty, in this case Ctty must be a descriptor
+    // number in the parent process.
+    Foreground bool
+    Pgid       int // Child's process group ID if Setpgid.
+    // Pdeathsig, if non-zero, is a signal that the kernel will send to
+    // the child process when the creating thread dies. Note that the signal
+    // is sent on thread termination, which may happen before process termination.
+    // There are more details at https://go.dev/issue/27505.
+    Pdeathsig    Signal
+    Cloneflags   uintptr        // Flags for clone calls.
+    Unshareflags uintptr        // Flags for unshare calls.
+    UidMappings  []SysProcIDMap // User ID mappings for user namespaces.
+    GidMappings  []SysProcIDMap // Group ID mappings for user namespaces.
+    // GidMappingsEnableSetgroups enabling setgroups syscall.
+    // If false, then setgroups syscall will be disabled for the child process.
+    // This parameter is no-op if GidMappings == nil. Otherwise for unprivileged
+    // users this should be set to false for mappings work.
+    GidMappingsEnableSetgroups bool
+    AmbientCaps                []uintptr // Ambient capabilities.
+    UseCgroupFD                bool      // Whether to make use of the CgroupFD field.
+    CgroupFD                   int       // File descriptor of a cgroup to put the new process into.
+    // PidFD, if not nil, is used to store the pidfd of a child, if the
+    // functionality is supported by the kernel, or -1. Note *PidFD is
+    // changed only if the process starts successfully.
+    PidFD *int
+}
+

type SysProcIDMap

SysProcIDMap holds Container ID to Host ID mappings used for User Namespaces in Linux. See user_namespaces(7).

+
type SysProcIDMap struct {
+    ContainerID int // Container ID.
+    HostID      int // Host ID.
+    Size        int // Size.
+}
+

type Sysinfo_t

type Sysinfo_t struct {
+    Uptime    int64
+    Loads     [3]uint64
+    Totalram  uint64
+    Freeram   uint64
+    Sharedram uint64
+    Bufferram uint64
+    Totalswap uint64
+    Freeswap  uint64
+    Procs     uint16
+    Pad       uint16
+    Pad_cgo_0 [4]byte
+    Totalhigh uint64
+    Freehigh  uint64
+    Unit      uint32
+    X_f       [0]byte
+    Pad_cgo_1 [4]byte
+}
+

type TCPInfo

type TCPInfo struct {
+    State          uint8
+    Ca_state       uint8
+    Retransmits    uint8
+    Probes         uint8
+    Backoff        uint8
+    Options        uint8
+    Pad_cgo_0      [2]byte
+    Rto            uint32
+    Ato            uint32
+    Snd_mss        uint32
+    Rcv_mss        uint32
+    Unacked        uint32
+    Sacked         uint32
+    Lost           uint32
+    Retrans        uint32
+    Fackets        uint32
+    Last_data_sent uint32
+    Last_ack_sent  uint32
+    Last_data_recv uint32
+    Last_ack_recv  uint32
+    Pmtu           uint32
+    Rcv_ssthresh   uint32
+    Rtt            uint32
+    Rttvar         uint32
+    Snd_ssthresh   uint32
+    Snd_cwnd       uint32
+    Advmss         uint32
+    Reordering     uint32
+    Rcv_rtt        uint32
+    Rcv_space      uint32
+    Total_retrans  uint32
+}
+

type Termios

type Termios struct {
+    Iflag     uint32
+    Oflag     uint32
+    Cflag     uint32
+    Lflag     uint32
+    Line      uint8
+    Cc        [32]uint8
+    Pad_cgo_0 [3]byte
+    Ispeed    uint32
+    Ospeed    uint32
+}
+

type Time_t

type Time_t int64

func Time

func Time(t *Time_t) (tt Time_t, err error)

type Timespec

type Timespec struct {
+    Sec  int64
+    Nsec int64
+}
+

func NsecToTimespec 1.1

func NsecToTimespec(nsec int64) Timespec

NsecToTimespec converts a number of nanoseconds into a Timespec.

+

func (*Timespec) Nano

func (ts *Timespec) Nano() int64

Nano returns the time stored in ts as nanoseconds.

+

func (*Timespec) Unix

func (ts *Timespec) Unix() (sec int64, nsec int64)

Unix returns the time stored in ts as seconds plus nanoseconds.

+

type Timeval

type Timeval struct {
+    Sec  int64
+    Usec int64
+}
+

func NsecToTimeval

func NsecToTimeval(nsec int64) Timeval

NsecToTimeval converts a number of nanoseconds into a Timeval.

+

func (*Timeval) Nano

func (tv *Timeval) Nano() int64

Nano returns the time stored in tv as nanoseconds.

+

func (*Timeval) Unix

func (tv *Timeval) Unix() (sec int64, nsec int64)

Unix returns the time stored in tv as seconds plus nanoseconds.

+

type Timex

type Timex struct {
+    Modes     uint32
+    Pad_cgo_0 [4]byte
+    Offset    int64
+    Freq      int64
+    Maxerror  int64
+    Esterror  int64
+    Status    int32
+    Pad_cgo_1 [4]byte
+    Constant  int64
+    Precision int64
+    Tolerance int64
+    Time      Timeval
+    Tick      int64
+    Ppsfreq   int64
+    Jitter    int64
+    Shift     int32
+    Pad_cgo_2 [4]byte
+    Stabil    int64
+    Jitcnt    int64
+    Calcnt    int64
+    Errcnt    int64
+    Stbcnt    int64
+    Tai       int32
+    Pad_cgo_3 [44]byte
+}
+

type Tms

type Tms struct {
+    Utime  int64
+    Stime  int64
+    Cutime int64
+    Cstime int64
+}
+

type Ucred

type Ucred struct {
+    Pid int32
+    Uid uint32
+    Gid uint32
+}
+

func GetsockoptUcred

func GetsockoptUcred(fd, level, opt int) (*Ucred, error)

func ParseUnixCredentials

func ParseUnixCredentials(m *SocketControlMessage) (*Ucred, error)

ParseUnixCredentials decodes a socket control message that contains credentials in a Ucred structure. To receive such a message, the SO_PASSCRED option must be enabled on the socket.

+

type Ustat_t

type Ustat_t struct {
+    Tfree     int32
+    Pad_cgo_0 [4]byte
+    Tinode    uint64
+    Fname     [6]int8
+    Fpack     [6]int8
+    Pad_cgo_1 [4]byte
+}
+

type Utimbuf

type Utimbuf struct {
+    Actime  int64
+    Modtime int64
+}
+

type Utsname

type Utsname struct {
+    Sysname    [65]int8
+    Nodename   [65]int8
+    Release    [65]int8
+    Version    [65]int8
+    Machine    [65]int8
+    Domainname [65]int8
+}
+

type WaitStatus

type WaitStatus uint32

func (WaitStatus) Continued

func (w WaitStatus) Continued() bool

func (WaitStatus) CoreDump

func (w WaitStatus) CoreDump() bool

func (WaitStatus) ExitStatus

func (w WaitStatus) ExitStatus() int

func (WaitStatus) Exited

func (w WaitStatus) Exited() bool

func (WaitStatus) Signal

func (w WaitStatus) Signal() Signal

func (WaitStatus) Signaled

func (w WaitStatus) Signaled() bool

func (WaitStatus) StopSignal

func (w WaitStatus) StopSignal() Signal

func (WaitStatus) Stopped

func (w WaitStatus) Stopped() bool

func (WaitStatus) TrapCause

func (w WaitStatus) TrapCause() int

Subdirectories

Name Synopsis
..
js Package js gives access to the WebAssembly host environment when using the js/wasm architecture.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/syscall/ +

+
diff --git a/devdocs/go/syscall%2Fjs%2Findex.html b/devdocs/go/syscall%2Fjs%2Findex.html new file mode 100644 index 00000000..c82ff5a6 --- /dev/null +++ b/devdocs/go/syscall%2Fjs%2Findex.html @@ -0,0 +1,159 @@ +

Package js

Overview

Package js gives access to the WebAssembly host environment when using the js/wasm architecture. Its API is based on JavaScript semantics.

+

This package is EXPERIMENTAL. Its current scope is only to allow tests to run, but not yet to provide a comprehensive API for users. It is exempt from the Go compatibility promise.

Index

Examples

FuncOf

Package files

func.go js.go

func CopyBytesToGo

func CopyBytesToGo(dst []byte, src Value) int

CopyBytesToGo copies bytes from src to dst. It panics if src is not a Uint8Array or Uint8ClampedArray. It returns the number of bytes copied, which will be the minimum of the lengths of src and dst.

+

func CopyBytesToJS

func CopyBytesToJS(dst Value, src []byte) int

CopyBytesToJS copies bytes from src to dst. It panics if dst is not a Uint8Array or Uint8ClampedArray. It returns the number of bytes copied, which will be the minimum of the lengths of src and dst.

+

type Error

Error wraps a JavaScript error.

+
type Error struct {
+    // Value is the underlying JavaScript error value.
+    Value
+}
+

func (Error) Error

func (e Error) Error() string

Error implements the error interface.

+

type Func

Func is a wrapped Go function to be called by JavaScript.

+
type Func struct {
+    Value // the JavaScript function that invokes the Go function
+    // contains filtered or unexported fields
+}
+

func FuncOf

func FuncOf(fn func(this Value, args []Value) any) Func

FuncOf returns a function to be used by JavaScript.

+

The Go function fn is called with the value of JavaScript's "this" keyword and the arguments of the invocation. The return value of the invocation is the result of the Go function mapped back to JavaScript according to ValueOf.

+

Invoking the wrapped Go function from JavaScript will pause the event loop and spawn a new goroutine. Other wrapped functions which are triggered during a call from Go to JavaScript get executed on the same goroutine.

+

As a consequence, if one wrapped function blocks, JavaScript's event loop is blocked until that function returns. Hence, calling any async JavaScript API, which requires the event loop, like fetch (http.Client), will cause an immediate deadlock. Therefore a blocking function should explicitly start a new goroutine.

+

Func.Release must be called to free up resources when the function will not be invoked any more.

Example +

Code:

+var cb js.Func
+cb = js.FuncOf(func(this js.Value, args []js.Value) any {
+    fmt.Println("button clicked")
+    cb.Release() // release the function if the button will not be clicked again
+    return nil
+})
+js.Global().Get("document").Call("getElementById", "myButton").Call("addEventListener", "click", cb)
+

func (Func) Release

func (c Func) Release()

Release frees up resources allocated for the function. The function must not be invoked after calling Release. It is allowed to call Release while the function is still running.

+

type Type

Type represents the JavaScript type of a Value.

+
type Type int
const (
+    TypeUndefined Type = iota
+    TypeNull
+    TypeBoolean
+    TypeNumber
+    TypeString
+    TypeSymbol
+    TypeObject
+    TypeFunction
+)

func (Type) String

func (t Type) String() string

type Value

Value represents a JavaScript value. The zero value is the JavaScript value "undefined". Values can be checked for equality with the Equal method.

+
type Value struct {
+    // contains filtered or unexported fields
+}
+

func Global

func Global() Value

Global returns the JavaScript global object, usually "window" or "global".

+

func Null

func Null() Value

Null returns the JavaScript value "null".

+

func Undefined

func Undefined() Value

Undefined returns the JavaScript value "undefined".

+

func ValueOf

func ValueOf(x any) Value

ValueOf returns x as a JavaScript value:

+
| Go                     | JavaScript             |
+| ---------------------- | ---------------------- |
+| js.Value               | [its value]            |
+| js.Func                | function               |
+| nil                    | null                   |
+| bool                   | boolean                |
+| integers and floats    | number                 |
+| string                 | string                 |
+| []interface{}          | new array              |
+| map[string]interface{} | new object             |
+

Panics if x is not one of the expected types.

+

func (Value) Bool

func (v Value) Bool() bool

Bool returns the value v as a bool. It panics if v is not a JavaScript boolean.

+

func (Value) Call

func (v Value) Call(m string, args ...any) Value

Call does a JavaScript call to the method m of value v with the given arguments. It panics if v has no method m. The arguments get mapped to JavaScript values according to the ValueOf function.

+

func (Value) Delete

func (v Value) Delete(p string)

Delete deletes the JavaScript property p of value v. It panics if v is not a JavaScript object.

+

func (Value) Equal

func (v Value) Equal(w Value) bool

Equal reports whether v and w are equal according to JavaScript's === operator.

+

func (Value) Float

func (v Value) Float() float64

Float returns the value v as a float64. It panics if v is not a JavaScript number.

+

func (Value) Get

func (v Value) Get(p string) Value

Get returns the JavaScript property p of value v. It panics if v is not a JavaScript object.

+

func (Value) Index

func (v Value) Index(i int) Value

Index returns JavaScript index i of value v. It panics if v is not a JavaScript object.

+

func (Value) InstanceOf

func (v Value) InstanceOf(t Value) bool

InstanceOf reports whether v is an instance of type t according to JavaScript's instanceof operator.

+

func (Value) Int

func (v Value) Int() int

Int returns the value v truncated to an int. It panics if v is not a JavaScript number.

+

func (Value) Invoke

func (v Value) Invoke(args ...any) Value

Invoke does a JavaScript call of the value v with the given arguments. It panics if v is not a JavaScript function. The arguments get mapped to JavaScript values according to the ValueOf function.

+

func (Value) IsNaN

func (v Value) IsNaN() bool

IsNaN reports whether v is the JavaScript value "NaN".

+

func (Value) IsNull

func (v Value) IsNull() bool

IsNull reports whether v is the JavaScript value "null".

+

func (Value) IsUndefined

func (v Value) IsUndefined() bool

IsUndefined reports whether v is the JavaScript value "undefined".

+

func (Value) Length

func (v Value) Length() int

Length returns the JavaScript property "length" of v. It panics if v is not a JavaScript object.

+

func (Value) New

func (v Value) New(args ...any) Value

New uses JavaScript's "new" operator with value v as constructor and the given arguments. It panics if v is not a JavaScript function. The arguments get mapped to JavaScript values according to the ValueOf function.

+

func (Value) Set

func (v Value) Set(p string, x any)

Set sets the JavaScript property p of value v to ValueOf(x). It panics if v is not a JavaScript object.

+

func (Value) SetIndex

func (v Value) SetIndex(i int, x any)

SetIndex sets the JavaScript index i of value v to ValueOf(x). It panics if v is not a JavaScript object.

+

func (Value) String

func (v Value) String() string

String returns the value v as a string. String is a special case because of Go's String method convention. Unlike the other getters, it does not panic if v's Type is not TypeString. Instead, it returns a string of the form "<T>" or "<T: V>" where T is v's type and V is a string representation of v's value.

+

func (Value) Truthy

func (v Value) Truthy() bool

Truthy returns the JavaScript "truthiness" of the value v. In JavaScript, false, 0, "", null, undefined, and NaN are "falsy", and everything else is "truthy". See https://developer.mozilla.org/en-US/docs/Glossary/Truthy.

+

func (Value) Type

func (v Value) Type() Type

Type returns the JavaScript type of the value v. It is similar to JavaScript's typeof operator, except that it returns TypeNull instead of TypeObject for null.

+

type ValueError

A ValueError occurs when a Value method is invoked on a Value that does not support it. Such cases are documented in the description of each method.

+
type ValueError struct {
+    Method string
+    Type   Type
+}
+

func (*ValueError) Error

func (e *ValueError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/syscall/js/ +

+
diff --git a/devdocs/go/testing%2Ffstest%2Findex.html b/devdocs/go/testing%2Ffstest%2Findex.html new file mode 100644 index 00000000..3fb1d250 --- /dev/null +++ b/devdocs/go/testing%2Ffstest%2Findex.html @@ -0,0 +1,43 @@ +

Package fstest

Overview

Package fstest implements support for testing implementations and users of file systems.

Index

Package files

mapfs.go testfs.go

func TestFS 1.16

func TestFS(fsys fs.FS, expected ...string) error

TestFS tests a file system implementation. It walks the entire tree of files in fsys, opening and checking that each file behaves correctly. It also checks that the file system contains at least the expected files. As a special case, if no expected files are listed, fsys must be empty. Otherwise, fsys must contain at least the listed files; it can also contain others. The contents of fsys must not change concurrently with TestFS.

+

If TestFS finds any misbehaviors, it returns an error reporting all of them. The error text spans multiple lines, one per detected misbehavior.

+

Typical usage inside a test is:

+
if err := fstest.TestFS(myFS, "file/that/should/be/present"); err != nil {
+	t.Fatal(err)
+}
+

type MapFS 1.16

A MapFS is a simple in-memory file system for use in tests, represented as a map from path names (arguments to Open) to information about the files or directories they represent.

+

The map need not include parent directories for files contained in the map; those will be synthesized if needed. But a directory can still be included by setting the [MapFile.Mode]'s fs.ModeDir bit; this may be necessary for detailed control over the directory's fs.FileInfo or to create an empty directory.

+

File system operations read directly from the map, so that the file system can be changed by editing the map as needed. An implication is that file system operations must not run concurrently with changes to the map, which would be a race. Another implication is that opening or reading a directory requires iterating over the entire map, so a MapFS should typically be used with not more than a few hundred entries or directory reads.

+
type MapFS map[string]*MapFile

func (MapFS) Glob 1.16

func (fsys MapFS) Glob(pattern string) ([]string, error)

func (MapFS) Open 1.16

func (fsys MapFS) Open(name string) (fs.File, error)

Open opens the named file.

+

func (MapFS) ReadDir 1.16

func (fsys MapFS) ReadDir(name string) ([]fs.DirEntry, error)

func (MapFS) ReadFile 1.16

func (fsys MapFS) ReadFile(name string) ([]byte, error)

func (MapFS) Stat 1.16

func (fsys MapFS) Stat(name string) (fs.FileInfo, error)

func (MapFS) Sub 1.16

func (fsys MapFS) Sub(dir string) (fs.FS, error)

type MapFile 1.16

A MapFile describes a single file in a MapFS.

+
type MapFile struct {
+    Data    []byte      // file content
+    Mode    fs.FileMode // fs.FileInfo.Mode
+    ModTime time.Time   // fs.FileInfo.ModTime
+    Sys     any         // fs.FileInfo.Sys
+}
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/testing/fstest/ +

+
diff --git a/devdocs/go/testing%2Findex.html b/devdocs/go/testing%2Findex.html new file mode 100644 index 00000000..15c0b37c --- /dev/null +++ b/devdocs/go/testing%2Findex.html @@ -0,0 +1,661 @@ +

Package testing

Overview

Package testing provides support for automated testing of Go packages. It is intended to be used in concert with the "go test" command, which automates execution of any function of the form

+
func TestXxx(*testing.T)
+

where Xxx does not start with a lowercase letter. The function name serves to identify the test routine.

+

Within these functions, use the Error, Fail or related methods to signal failure.

+

To write a new test suite, create a file that contains the TestXxx functions as described here, and give that file a name ending in "_test.go". The file will be excluded from regular package builds but will be included when the "go test" command is run.

+

The test file can be in the same package as the one being tested, or in a corresponding package with the suffix "_test".

+

If the test file is in the same package, it may refer to unexported identifiers within the package, as in this example:

+
package abs
+
+import "testing"
+
+func TestAbs(t *testing.T) {
+    got := Abs(-1)
+    if got != 1 {
+        t.Errorf("Abs(-1) = %d; want 1", got)
+    }
+}
+

If the file is in a separate "_test" package, the package being tested must be imported explicitly and only its exported identifiers may be used. This is known as "black box" testing.

+
package abs_test
+
+import (
+	"testing"
+
+	"path_to_pkg/abs"
+)
+
+func TestAbs(t *testing.T) {
+    got := abs.Abs(-1)
+    if got != 1 {
+        t.Errorf("Abs(-1) = %d; want 1", got)
+    }
+}
+

For more detail, run "go help test" and "go help testflag".

+

Benchmarks

Functions of the form

+
func BenchmarkXxx(*testing.B)
+

are considered benchmarks, and are executed by the "go test" command when its -bench flag is provided. Benchmarks are run sequentially.

+

For a description of the testing flags, see https://golang.org/cmd/go/#hdr-Testing_flags.

+

A sample benchmark function looks like this:

+
func BenchmarkRandInt(b *testing.B) {
+    for i := 0; i < b.N; i++ {
+        rand.Int()
+    }
+}
+

The benchmark function must run the target code b.N times. During benchmark execution, b.N is adjusted until the benchmark function lasts long enough to be timed reliably. The output

+
BenchmarkRandInt-8   	68453040	        17.8 ns/op
+

means that the loop ran 68453040 times at a speed of 17.8 ns per loop.

+

If a benchmark needs some expensive setup before running, the timer may be reset:

+
func BenchmarkBigLen(b *testing.B) {
+    big := NewBig()
+    b.ResetTimer()
+    for i := 0; i < b.N; i++ {
+        big.Len()
+    }
+}
+

If a benchmark needs to test performance in a parallel setting, it may use the RunParallel helper function; such benchmarks are intended to be used with the go test -cpu flag:

+
func BenchmarkTemplateParallel(b *testing.B) {
+    templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
+    b.RunParallel(func(pb *testing.PB) {
+        var buf bytes.Buffer
+        for pb.Next() {
+            buf.Reset()
+            templ.Execute(&buf, "World")
+        }
+    })
+}
+

A detailed specification of the benchmark results format is given in https://golang.org/design/14313-benchmark-format.

+

There are standard tools for working with benchmark results at https://golang.org/x/perf/cmd. In particular, https://golang.org/x/perf/cmd/benchstat performs statistically robust A/B comparisons.

+

Examples

The package also runs and verifies example code. Example functions may include a concluding line comment that begins with "Output:" and is compared with the standard output of the function when the tests are run. (The comparison ignores leading and trailing space.) These are examples of an example:

+
func ExampleHello() {
+    fmt.Println("hello")
+    // Output: hello
+}
+
+func ExampleSalutations() {
+    fmt.Println("hello, and")
+    fmt.Println("goodbye")
+    // Output:
+    // hello, and
+    // goodbye
+}
+

The comment prefix "Unordered output:" is like "Output:", but matches any line order:

+
func ExamplePerm() {
+    for _, value := range Perm(5) {
+        fmt.Println(value)
+    }
+    // Unordered output: 4
+    // 2
+    // 1
+    // 3
+    // 0
+}
+

Example functions without output comments are compiled but not executed.

+

The naming convention to declare examples for the package, a function F, a type T and method M on type T are:

+
func Example() { ... }
+func ExampleF() { ... }
+func ExampleT() { ... }
+func ExampleT_M() { ... }
+

Multiple example functions for a package/type/function/method may be provided by appending a distinct suffix to the name. The suffix must start with a lower-case letter.

+
func Example_suffix() { ... }
+func ExampleF_suffix() { ... }
+func ExampleT_suffix() { ... }
+func ExampleT_M_suffix() { ... }
+

The entire test file is presented as the example when it contains a single example function, at least one other function, type, variable, or constant declaration, and no test or benchmark functions.

+

Fuzzing

'go test' and the testing package support fuzzing, a testing technique where a function is called with randomly generated inputs to find bugs not anticipated by unit tests.

+

Functions of the form

+
func FuzzXxx(*testing.F)
+

are considered fuzz tests.

+

For example:

+
func FuzzHex(f *testing.F) {
+  for _, seed := range [][]byte{{}, {0}, {9}, {0xa}, {0xf}, {1, 2, 3, 4}} {
+    f.Add(seed)
+  }
+  f.Fuzz(func(t *testing.T, in []byte) {
+    enc := hex.EncodeToString(in)
+    out, err := hex.DecodeString(enc)
+    if err != nil {
+      t.Fatalf("%v: decode: %v", in, err)
+    }
+    if !bytes.Equal(in, out) {
+      t.Fatalf("%v: not equal after round trip: %v", in, out)
+    }
+  })
+}
+

A fuzz test maintains a seed corpus, or a set of inputs which are run by default, and can seed input generation. Seed inputs may be registered by calling (*F).Add or by storing files in the directory testdata/fuzz/<Name> (where <Name> is the name of the fuzz test) within the package containing the fuzz test. Seed inputs are optional, but the fuzzing engine may find bugs more efficiently when provided with a set of small seed inputs with good code coverage. These seed inputs can also serve as regression tests for bugs identified through fuzzing.

+

The function passed to (*F).Fuzz within the fuzz test is considered the fuzz target. A fuzz target must accept a *T parameter, followed by one or more parameters for random inputs. The types of arguments passed to (*F).Add must be identical to the types of these parameters. The fuzz target may signal that it's found a problem the same way tests do: by calling T.Fail (or any method that calls it like T.Error or T.Fatal) or by panicking.

+

When fuzzing is enabled (by setting the -fuzz flag to a regular expression that matches a specific fuzz test), the fuzz target is called with arguments generated by repeatedly making random changes to the seed inputs. On supported platforms, 'go test' compiles the test executable with fuzzing coverage instrumentation. The fuzzing engine uses that instrumentation to find and cache inputs that expand coverage, increasing the likelihood of finding bugs. If the fuzz target fails for a given input, the fuzzing engine writes the inputs that caused the failure to a file in the directory testdata/fuzz/<Name> within the package directory. This file later serves as a seed input. If the file can't be written at that location (for example, because the directory is read-only), the fuzzing engine writes the file to the fuzz cache directory within the build cache instead.

+

When fuzzing is disabled, the fuzz target is called with the seed inputs registered with F.Add and seed inputs from testdata/fuzz/<Name>. In this mode, the fuzz test acts much like a regular test, with subtests started with F.Fuzz instead of T.Run.

+

See https://go.dev/doc/fuzz for documentation about fuzzing.

+

Skipping

Tests or benchmarks may be skipped at run time with a call to the Skip method of *T or *B:

+
func TestTimeConsuming(t *testing.T) {
+    if testing.Short() {
+        t.Skip("skipping test in short mode.")
+    }
+    ...
+}
+

The Skip method of *T can be used in a fuzz target if the input is invalid, but should not be considered a failing input. For example:

+
func FuzzJSONMarshaling(f *testing.F) {
+    f.Fuzz(func(t *testing.T, b []byte) {
+        var v interface{}
+        if err := json.Unmarshal(b, &v); err != nil {
+            t.Skip()
+        }
+        if _, err := json.Marshal(v); err != nil {
+            t.Errorf("Marshal: %v", err)
+        }
+    })
+}
+

Subtests and Sub-benchmarks

The Run methods of T and B allow defining subtests and sub-benchmarks, without having to define separate functions for each. This enables uses like table-driven benchmarks and creating hierarchical tests. It also provides a way to share common setup and tear-down code:

+
func TestFoo(t *testing.T) {
+    // <setup code>
+    t.Run("A=1", func(t *testing.T) { ... })
+    t.Run("A=2", func(t *testing.T) { ... })
+    t.Run("B=1", func(t *testing.T) { ... })
+    // <tear-down code>
+}
+

Each subtest and sub-benchmark has a unique name: the combination of the name of the top-level test and the sequence of names passed to Run, separated by slashes, with an optional trailing sequence number for disambiguation.

+

The argument to the -run, -bench, and -fuzz command-line flags is an unanchored regular expression that matches the test's name. For tests with multiple slash-separated elements, such as subtests, the argument is itself slash-separated, with expressions matching each name element in turn. Because it is unanchored, an empty expression matches any string. For example, using "matching" to mean "whose name contains":

+
go test -run ''        # Run all tests.
+go test -run Foo       # Run top-level tests matching "Foo", such as "TestFooBar".
+go test -run Foo/A=    # For top-level tests matching "Foo", run subtests matching "A=".
+go test -run /A=1      # For all top-level tests, run subtests matching "A=1".
+go test -fuzz FuzzFoo  # Fuzz the target matching "FuzzFoo"
+

The -run argument can also be used to run a specific value in the seed corpus, for debugging. For example:

+
go test -run=FuzzFoo/9ddb952d9814
+

The -fuzz and -run flags can both be set, in order to fuzz a target but skip the execution of all other tests.

+

Subtests can also be used to control parallelism. A parent test will only complete once all of its subtests complete. In this example, all tests are run in parallel with each other, and only with each other, regardless of other top-level tests that may be defined:

+
func TestGroupedParallel(t *testing.T) {
+    for _, tc := range tests {
+        tc := tc // capture range variable
+        t.Run(tc.Name, func(t *testing.T) {
+            t.Parallel()
+            ...
+        })
+    }
+}
+

Run does not return until parallel subtests have completed, providing a way to clean up after a group of parallel tests:

+
func TestTeardownParallel(t *testing.T) {
+    // This Run will not return until the parallel tests finish.
+    t.Run("group", func(t *testing.T) {
+        t.Run("Test1", parallelTest1)
+        t.Run("Test2", parallelTest2)
+        t.Run("Test3", parallelTest3)
+    })
+    // <tear-down code>
+}
+

Main

It is sometimes necessary for a test or benchmark program to do extra setup or teardown before or after it executes. It is also sometimes necessary to control which code runs on the main thread. To support these and other cases, if a test file contains a function:

+
func TestMain(m *testing.M)
+

then the generated test will call TestMain(m) instead of running the tests or benchmarks directly. TestMain runs in the main goroutine and can do whatever setup and teardown is necessary around a call to m.Run. m.Run will return an exit code that may be passed to os.Exit. If TestMain returns, the test wrapper will pass the result of m.Run to os.Exit itself.

+

When TestMain is called, flag.Parse has not been run. If TestMain depends on command-line flags, including those of the testing package, it should call flag.Parse explicitly. Command line flags are always parsed by the time test or benchmark functions run.

+

A simple implementation of TestMain is:

+
func TestMain(m *testing.M) {
+	// call flag.Parse() here if TestMain uses flags
+	os.Exit(m.Run())
+}
+

TestMain is a low-level primitive and should not be necessary for casual testing needs, where ordinary test functions suffice.

Index

Examples

B.ReportMetric
B.ReportMetric (Parallel)
B.RunParallel

Package files

allocs.go benchmark.go cover.go example.go fuzz.go match.go newcover.go run_example.go testing.go testing_other.go

func AllocsPerRun 1.1

func AllocsPerRun(runs int, f func()) (avg float64)

AllocsPerRun returns the average number of allocations during calls to f. Although the return value has type float64, it will always be an integral value.

+

To compute the number of allocations, the function will first be run once as a warm-up. The average number of allocations over the specified number of runs will then be measured and returned.

+

AllocsPerRun sets GOMAXPROCS to 1 during its measurement and will restore it before returning.

+

func CoverMode 1.8

func CoverMode() string

CoverMode reports what the test coverage mode is set to. The values are "set", "count", or "atomic". The return value will be empty if test coverage is not enabled.

+

func Coverage 1.4

func Coverage() float64

Coverage reports the current code coverage as a fraction in the range [0, 1]. If coverage is not enabled, Coverage returns 0.

+

When running a large set of sequential test cases, checking Coverage after each one can be useful for identifying which test cases exercise new code paths. It is not a replacement for the reports generated by 'go test -cover' and 'go tool cover'.

+

func Init 1.13

func Init()

Init registers testing flags. These flags are automatically registered by the "go test" command before running test functions, so Init is only needed when calling functions such as Benchmark without using "go test".

+

Init is not safe to call concurrently. It has no effect if it was already called.

+

func Main

func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample)

Main is an internal function, part of the implementation of the "go test" command. It was exported because it is cross-package and predates "internal" packages. It is no longer used by "go test" but preserved, as much as possible, for other systems that simulate "go test" using Main, but Main sometimes cannot be updated as new functionality is added to the testing package. Systems simulating "go test" should be updated to use MainStart.

+

func RegisterCover 1.2

func RegisterCover(c Cover)

RegisterCover records the coverage data accumulators for the tests. NOTE: This function is internal to the testing infrastructure and may change. It is not covered (yet) by the Go 1 compatibility guidelines.

+

func RunBenchmarks

func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark)

RunBenchmarks is an internal function but exported because it is cross-package; it is part of the implementation of the "go test" command.

+

func RunExamples

func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool)

RunExamples is an internal function but exported because it is cross-package; it is part of the implementation of the "go test" command.

+

func RunTests

func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool)

RunTests is an internal function but exported because it is cross-package; it is part of the implementation of the "go test" command.

+

func Short

func Short() bool

Short reports whether the -test.short flag is set.

+

func Testing 1.21

func Testing() bool

Testing reports whether the current code is being run in a test. This will report true in programs created by "go test", false in programs created by "go build".

+

func Verbose 1.1

func Verbose() bool

Verbose reports whether the -test.v flag is set.

+

type B

B is a type passed to Benchmark functions to manage benchmark timing and to specify the number of iterations to run.

+

A benchmark ends when its Benchmark function returns or calls any of the methods FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods must be called only from the goroutine running the Benchmark function. The other reporting methods, such as the variations of Log and Error, may be called simultaneously from multiple goroutines.

+

Like in tests, benchmark logs are accumulated during execution and dumped to standard output when done. Unlike in tests, benchmark logs are always printed, so as not to hide output whose existence may be affecting benchmark results.

+
type B struct {
+    N int
+    // contains filtered or unexported fields
+}
+

func (*B) Cleanup 1.14

func (c *B) Cleanup(f func())

Cleanup registers a function to be called when the test (or subtest) and all its subtests complete. Cleanup functions will be called in last added, first called order.

+

func (*B) Elapsed 1.20

func (b *B) Elapsed() time.Duration

Elapsed returns the measured elapsed time of the benchmark. The duration reported by Elapsed matches the one measured by B.StartTimer, B.StopTimer, and B.ResetTimer.

+

func (*B) Error

func (c *B) Error(args ...any)

Error is equivalent to Log followed by Fail.

+

func (*B) Errorf

func (c *B) Errorf(format string, args ...any)

Errorf is equivalent to Logf followed by Fail.

+

func (*B) Fail

func (c *B) Fail()

Fail marks the function as having failed but continues execution.

+

func (*B) FailNow

func (c *B) FailNow()

FailNow marks the function as having failed and stops its execution by calling runtime.Goexit (which then runs all deferred calls in the current goroutine). Execution will continue at the next test or benchmark. FailNow must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test. Calling FailNow does not stop those other goroutines.

+

func (*B) Failed

func (c *B) Failed() bool

Failed reports whether the function has failed.

+

func (*B) Fatal

func (c *B) Fatal(args ...any)

Fatal is equivalent to Log followed by FailNow.

+

func (*B) Fatalf

func (c *B) Fatalf(format string, args ...any)

Fatalf is equivalent to Logf followed by FailNow.

+

func (*B) Helper 1.9

func (c *B) Helper()

Helper marks the calling function as a test helper function. When printing file and line information, that function will be skipped. Helper may be called simultaneously from multiple goroutines.

+

func (*B) Log

func (c *B) Log(args ...any)

Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag.

+

func (*B) Logf

func (c *B) Logf(format string, args ...any)

Logf formats its arguments according to the format, analogous to Printf, and records the text in the error log. A final newline is added if not provided. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag.

+

func (*B) Name 1.8

func (c *B) Name() string

Name returns the name of the running (sub-) test or benchmark.

+

The name will include the name of the test along with the names of any nested sub-tests. If two sibling sub-tests have the same name, Name will append a suffix to guarantee the returned name is unique.

+

func (*B) ReportAllocs 1.1

func (b *B) ReportAllocs()

ReportAllocs enables malloc statistics for this benchmark. It is equivalent to setting -test.benchmem, but it only affects the benchmark function that calls ReportAllocs.

+

func (*B) ReportMetric 1.13

func (b *B) ReportMetric(n float64, unit string)

ReportMetric adds "n unit" to the reported benchmark results. If the metric is per-iteration, the caller should divide by b.N, and by convention units should end in "/op". ReportMetric overrides any previously reported value for the same unit. ReportMetric panics if unit is the empty string or if unit contains any whitespace. If unit is a unit normally reported by the benchmark framework itself (such as "allocs/op"), ReportMetric will override that metric. Setting "ns/op" to 0 will suppress that built-in metric.

Example +

Code:

+// This reports a custom benchmark metric relevant to a
+// specific algorithm (in this case, sorting).
+testing.Benchmark(func(b *testing.B) {
+    var compares int64
+    for i := 0; i < b.N; i++ {
+        s := []int{5, 4, 3, 2, 1}
+        sort.Slice(s, func(i, j int) bool {
+            compares++
+            return s[i] < s[j]
+        })
+    }
+    // This metric is per-operation, so divide by b.N and
+    // report it as a "/op" unit.
+    b.ReportMetric(float64(compares)/float64(b.N), "compares/op")
+    // This metric is per-time, so divide by b.Elapsed and
+    // report it as a "/ns" unit.
+    b.ReportMetric(float64(compares)/float64(b.Elapsed().Nanoseconds()), "compares/ns")
+})
+

Example (Parallel) +

Code:

+// This reports a custom benchmark metric relevant to a
+// specific algorithm (in this case, sorting) in parallel.
+testing.Benchmark(func(b *testing.B) {
+    var compares atomic.Int64
+    b.RunParallel(func(pb *testing.PB) {
+        for pb.Next() {
+            s := []int{5, 4, 3, 2, 1}
+            sort.Slice(s, func(i, j int) bool {
+                // Because RunParallel runs the function many
+                // times in parallel, we must increment the
+                // counter atomically to avoid racing writes.
+                compares.Add(1)
+                return s[i] < s[j]
+            })
+        }
+    })
+
+    // NOTE: Report each metric once, after all of the parallel
+    // calls have completed.
+
+    // This metric is per-operation, so divide by b.N and
+    // report it as a "/op" unit.
+    b.ReportMetric(float64(compares.Load())/float64(b.N), "compares/op")
+    // This metric is per-time, so divide by b.Elapsed and
+    // report it as a "/ns" unit.
+    b.ReportMetric(float64(compares.Load())/float64(b.Elapsed().Nanoseconds()), "compares/ns")
+})
+

func (*B) ResetTimer

func (b *B) ResetTimer()

ResetTimer zeroes the elapsed benchmark time and memory allocation counters and deletes user-reported metrics. It does not affect whether the timer is running.

+

func (*B) Run 1.7

func (b *B) Run(name string, f func(b *B)) bool

Run benchmarks f as a subbenchmark with the given name. It reports whether there were any failures.

+

A subbenchmark is like any other benchmark. A benchmark that calls Run at least once will not be measured itself and will be called once with N=1.

+

func (*B) RunParallel 1.3

func (b *B) RunParallel(body func(*PB))

RunParallel runs a benchmark in parallel. It creates multiple goroutines and distributes b.N iterations among them. The number of goroutines defaults to GOMAXPROCS. To increase parallelism for non-CPU-bound benchmarks, call B.SetParallelism before RunParallel. RunParallel is usually used with the go test -cpu flag.

+

The body function will be run in each goroutine. It should set up any goroutine-local state and then iterate until pb.Next returns false. It should not use the B.StartTimer, B.StopTimer, or B.ResetTimer functions, because they have global effect. It should also not call B.Run.

+

RunParallel reports ns/op values as wall time for the benchmark as a whole, not the sum of wall time or CPU time over each parallel goroutine.

Example +

Code:

+// Parallel benchmark for text/template.Template.Execute on a single object.
+testing.Benchmark(func(b *testing.B) {
+    templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
+    // RunParallel will create GOMAXPROCS goroutines
+    // and distribute work among them.
+    b.RunParallel(func(pb *testing.PB) {
+        // Each goroutine has its own bytes.Buffer.
+        var buf bytes.Buffer
+        for pb.Next() {
+            // The loop body is executed b.N times total across all goroutines.
+            buf.Reset()
+            templ.Execute(&buf, "World")
+        }
+    })
+})
+

func (*B) SetBytes

func (b *B) SetBytes(n int64)

SetBytes records the number of bytes processed in a single operation. If this is called, the benchmark will report ns/op and MB/s.

+

func (*B) SetParallelism 1.3

func (b *B) SetParallelism(p int)

SetParallelism sets the number of goroutines used by B.RunParallel to p*GOMAXPROCS. There is usually no need to call SetParallelism for CPU-bound benchmarks. If p is less than 1, this call will have no effect.

+

func (*B) Setenv 1.17

func (c *B) Setenv(key, value string)

Setenv calls os.Setenv(key, value) and uses Cleanup to restore the environment variable to its original value after the test.

+

Because Setenv affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors.

+

func (*B) Skip 1.1

func (c *B) Skip(args ...any)

Skip is equivalent to Log followed by SkipNow.

+

func (*B) SkipNow 1.1

func (c *B) SkipNow()

SkipNow marks the test as having been skipped and stops its execution by calling runtime.Goexit. If a test fails (see Error, Errorf, Fail) and is then skipped, it is still considered to have failed. Execution will continue at the next test or benchmark. See also FailNow. SkipNow must be called from the goroutine running the test, not from other goroutines created during the test. Calling SkipNow does not stop those other goroutines.

+

func (*B) Skipf 1.1

func (c *B) Skipf(format string, args ...any)

Skipf is equivalent to Logf followed by SkipNow.

+

func (*B) Skipped 1.1

func (c *B) Skipped() bool

Skipped reports whether the test was skipped.

+

func (*B) StartTimer

func (b *B) StartTimer()

StartTimer starts timing a test. This function is called automatically before a benchmark starts, but it can also be used to resume timing after a call to B.StopTimer.

+

func (*B) StopTimer

func (b *B) StopTimer()

StopTimer stops timing a test. This can be used to pause the timer while performing complex initialization that you don't want to measure.

+

func (*B) TempDir 1.15

func (c *B) TempDir() string

TempDir returns a temporary directory for the test to use. The directory is automatically removed when the test and all its subtests complete. Each subsequent call to t.TempDir returns a unique directory; if the directory creation fails, TempDir terminates the test by calling Fatal.

+

type BenchmarkResult

BenchmarkResult contains the results of a benchmark run.

+
type BenchmarkResult struct {
+    N         int           // The number of iterations.
+    T         time.Duration // The total time taken.
+    Bytes     int64         // Bytes processed in one iteration.
+    MemAllocs uint64        // The total number of memory allocations; added in Go 1.1
+    MemBytes  uint64        // The total number of bytes allocated; added in Go 1.1
+
+    // Extra records additional metrics reported by ReportMetric.
+    Extra map[string]float64 // Go 1.13
+}
+

func Benchmark

func Benchmark(f func(b *B)) BenchmarkResult

Benchmark benchmarks a single function. It is useful for creating custom benchmarks that do not use the "go test" command.

+

If f depends on testing flags, then Init must be used to register those flags before calling Benchmark and before calling flag.Parse.

+

If f calls Run, the result will be an estimate of running all its subbenchmarks that don't call Run in sequence in a single benchmark.

+

func (BenchmarkResult) AllocedBytesPerOp 1.1

func (r BenchmarkResult) AllocedBytesPerOp() int64

AllocedBytesPerOp returns the "B/op" metric, which is calculated as r.MemBytes / r.N.

+

func (BenchmarkResult) AllocsPerOp 1.1

func (r BenchmarkResult) AllocsPerOp() int64

AllocsPerOp returns the "allocs/op" metric, which is calculated as r.MemAllocs / r.N.

+

func (BenchmarkResult) MemString 1.1

func (r BenchmarkResult) MemString() string

MemString returns r.AllocedBytesPerOp and r.AllocsPerOp in the same format as 'go test'.

+

func (BenchmarkResult) NsPerOp

func (r BenchmarkResult) NsPerOp() int64

NsPerOp returns the "ns/op" metric.

+

func (BenchmarkResult) String

func (r BenchmarkResult) String() string

String returns a summary of the benchmark results. It follows the benchmark result line format from https://golang.org/design/14313-benchmark-format, not including the benchmark name. Extra metrics override built-in metrics of the same name. String does not include allocs/op or B/op, since those are reported by BenchmarkResult.MemString.

+

type Cover 1.2

Cover records information about test coverage checking. NOTE: This struct is internal to the testing infrastructure and may change. It is not covered (yet) by the Go 1 compatibility guidelines.

+
type Cover struct {
+    Mode            string
+    Counters        map[string][]uint32
+    Blocks          map[string][]CoverBlock
+    CoveredPackages string
+}
+

type CoverBlock 1.2

CoverBlock records the coverage data for a single basic block. The fields are 1-indexed, as in an editor: The opening line of the file is number 1, for example. Columns are measured in bytes. NOTE: This struct is internal to the testing infrastructure and may change. It is not covered (yet) by the Go 1 compatibility guidelines.

+
type CoverBlock struct {
+    Line0 uint32 // Line number for block start.
+    Col0  uint16 // Column number for block start.
+    Line1 uint32 // Line number for block end.
+    Col1  uint16 // Column number for block end.
+    Stmts uint16 // Number of statements included in this block.
+}
+

type F 1.18

F is a type passed to fuzz tests.

+

Fuzz tests run generated inputs against a provided fuzz target, which can find and report potential bugs in the code being tested.

+

A fuzz test runs the seed corpus by default, which includes entries provided by (*F).Add and entries in the testdata/fuzz/<FuzzTestName> directory. After any necessary setup and calls to (*F).Add, the fuzz test must then call (*F).Fuzz to provide the fuzz target. See the testing package documentation for an example, and see the F.Fuzz and F.Add method documentation for details.

+

*F methods can only be called before (*F).Fuzz. Once the test is executing the fuzz target, only (*T) methods can be used. The only *F methods that are allowed in the (*F).Fuzz function are (*F).Failed and (*F).Name.

+
type F struct {
+    // contains filtered or unexported fields
+}
+

func (*F) Add 1.18

func (f *F) Add(args ...any)

Add will add the arguments to the seed corpus for the fuzz test. This will be a no-op if called after or within the fuzz target, and args must match the arguments for the fuzz target.

+

func (*F) Cleanup 1.18

func (c *F) Cleanup(f func())

Cleanup registers a function to be called when the test (or subtest) and all its subtests complete. Cleanup functions will be called in last added, first called order.

+

func (*F) Error 1.18

func (c *F) Error(args ...any)

Error is equivalent to Log followed by Fail.

+

func (*F) Errorf 1.18

func (c *F) Errorf(format string, args ...any)

Errorf is equivalent to Logf followed by Fail.

+

func (*F) Fail 1.18

func (f *F) Fail()

Fail marks the function as having failed but continues execution.

+

func (*F) FailNow 1.18

func (c *F) FailNow()

FailNow marks the function as having failed and stops its execution by calling runtime.Goexit (which then runs all deferred calls in the current goroutine). Execution will continue at the next test or benchmark. FailNow must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test. Calling FailNow does not stop those other goroutines.

+

func (*F) Failed 1.18

func (c *F) Failed() bool

Failed reports whether the function has failed.

+

func (*F) Fatal 1.18

func (c *F) Fatal(args ...any)

Fatal is equivalent to Log followed by FailNow.

+

func (*F) Fatalf 1.18

func (c *F) Fatalf(format string, args ...any)

Fatalf is equivalent to Logf followed by FailNow.

+

func (*F) Fuzz 1.18

func (f *F) Fuzz(ff any)

Fuzz runs the fuzz function, ff, for fuzz testing. If ff fails for a set of arguments, those arguments will be added to the seed corpus.

+

ff must be a function with no return value whose first argument is *T and whose remaining arguments are the types to be fuzzed. For example:

+
f.Fuzz(func(t *testing.T, b []byte, i int) { ... })
+

The following types are allowed: []byte, string, bool, byte, rune, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64. More types may be supported in the future.

+

ff must not call any *F methods, e.g. (*F).Log, (*F).Error, (*F).Skip. Use the corresponding *T method instead. The only *F methods that are allowed in the (*F).Fuzz function are (*F).Failed and (*F).Name.

+

This function should be fast and deterministic, and its behavior should not depend on shared state. No mutatable input arguments, or pointers to them, should be retained between executions of the fuzz function, as the memory backing them may be mutated during a subsequent invocation. ff must not modify the underlying data of the arguments provided by the fuzzing engine.

+

When fuzzing, F.Fuzz does not return until a problem is found, time runs out (set with -fuzztime), or the test process is interrupted by a signal. F.Fuzz should be called exactly once, unless F.Skip or F.Fail is called beforehand.

+

func (*F) Helper 1.18

func (f *F) Helper()

Helper marks the calling function as a test helper function. When printing file and line information, that function will be skipped. Helper may be called simultaneously from multiple goroutines.

+

func (*F) Log 1.18

func (c *F) Log(args ...any)

Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag.

+

func (*F) Logf 1.18

func (c *F) Logf(format string, args ...any)

Logf formats its arguments according to the format, analogous to Printf, and records the text in the error log. A final newline is added if not provided. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag.

+

func (*F) Name 1.18

func (c *F) Name() string

Name returns the name of the running (sub-) test or benchmark.

+

The name will include the name of the test along with the names of any nested sub-tests. If two sibling sub-tests have the same name, Name will append a suffix to guarantee the returned name is unique.

+

func (*F) Setenv 1.18

func (c *F) Setenv(key, value string)

Setenv calls os.Setenv(key, value) and uses Cleanup to restore the environment variable to its original value after the test.

+

Because Setenv affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors.

+

func (*F) Skip 1.18

func (c *F) Skip(args ...any)

Skip is equivalent to Log followed by SkipNow.

+

func (*F) SkipNow 1.18

func (c *F) SkipNow()

SkipNow marks the test as having been skipped and stops its execution by calling runtime.Goexit. If a test fails (see Error, Errorf, Fail) and is then skipped, it is still considered to have failed. Execution will continue at the next test or benchmark. See also FailNow. SkipNow must be called from the goroutine running the test, not from other goroutines created during the test. Calling SkipNow does not stop those other goroutines.

+

func (*F) Skipf 1.18

func (c *F) Skipf(format string, args ...any)

Skipf is equivalent to Logf followed by SkipNow.

+

func (*F) Skipped 1.18

func (f *F) Skipped() bool

Skipped reports whether the test was skipped.

+

func (*F) TempDir 1.18

func (c *F) TempDir() string

TempDir returns a temporary directory for the test to use. The directory is automatically removed when the test and all its subtests complete. Each subsequent call to t.TempDir returns a unique directory; if the directory creation fails, TempDir terminates the test by calling Fatal.

+

type InternalBenchmark

InternalBenchmark is an internal type but exported because it is cross-package; it is part of the implementation of the "go test" command.

+
type InternalBenchmark struct {
+    Name string
+    F    func(b *B)
+}
+

type InternalExample

type InternalExample struct {
+    Name      string
+    F         func()
+    Output    string
+    Unordered bool // Go 1.7
+}
+

type InternalFuzzTarget 1.18

InternalFuzzTarget is an internal type but exported because it is cross-package; it is part of the implementation of the "go test" command.

+
type InternalFuzzTarget struct {
+    Name string
+    Fn   func(f *F)
+}
+

type InternalTest

InternalTest is an internal type but exported because it is cross-package; it is part of the implementation of the "go test" command.

+
type InternalTest struct {
+    Name string
+    F    func(*T)
+}
+

type M 1.4

M is a type passed to a TestMain function to run the actual tests.

+
type M struct {
+    // contains filtered or unexported fields
+}
+

func MainStart 1.4

func MainStart(deps testDeps, tests []InternalTest, benchmarks []InternalBenchmark, fuzzTargets []InternalFuzzTarget, examples []InternalExample) *M

MainStart is meant for use by tests generated by 'go test'. It is not meant to be called directly and is not subject to the Go 1 compatibility document. It may change signature from release to release.

+

func (*M) Run 1.4

func (m *M) Run() (code int)

Run runs the tests. It returns an exit code to pass to os.Exit.

+

type PB 1.3

A PB is used by RunParallel for running parallel benchmarks.

+
type PB struct {
+    // contains filtered or unexported fields
+}
+

func (*PB) Next 1.3

func (pb *PB) Next() bool

Next reports whether there are more iterations to execute.

+

type T

T is a type passed to Test functions to manage test state and support formatted test logs.

+

A test ends when its Test function returns or calls any of the methods FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods, as well as the Parallel method, must be called only from the goroutine running the Test function.

+

The other reporting methods, such as the variations of Log and Error, may be called simultaneously from multiple goroutines.

+
type T struct {
+    // contains filtered or unexported fields
+}
+

func (*T) Cleanup 1.14

func (c *T) Cleanup(f func())

Cleanup registers a function to be called when the test (or subtest) and all its subtests complete. Cleanup functions will be called in last added, first called order.

+

func (*T) Deadline 1.15

func (t *T) Deadline() (deadline time.Time, ok bool)

Deadline reports the time at which the test binary will have exceeded the timeout specified by the -timeout flag.

+

The ok result is false if the -timeout flag indicates “no timeout” (0).

+

func (*T) Error

func (c *T) Error(args ...any)

Error is equivalent to Log followed by Fail.

+

func (*T) Errorf

func (c *T) Errorf(format string, args ...any)

Errorf is equivalent to Logf followed by Fail.

+

func (*T) Fail

func (c *T) Fail()

Fail marks the function as having failed but continues execution.

+

func (*T) FailNow

func (c *T) FailNow()

FailNow marks the function as having failed and stops its execution by calling runtime.Goexit (which then runs all deferred calls in the current goroutine). Execution will continue at the next test or benchmark. FailNow must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test. Calling FailNow does not stop those other goroutines.

+

func (*T) Failed

func (c *T) Failed() bool

Failed reports whether the function has failed.

+

func (*T) Fatal

func (c *T) Fatal(args ...any)

Fatal is equivalent to Log followed by FailNow.

+

func (*T) Fatalf

func (c *T) Fatalf(format string, args ...any)

Fatalf is equivalent to Logf followed by FailNow.

+

func (*T) Helper 1.9

func (c *T) Helper()

Helper marks the calling function as a test helper function. When printing file and line information, that function will be skipped. Helper may be called simultaneously from multiple goroutines.

+

func (*T) Log

func (c *T) Log(args ...any)

Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag.

+

func (*T) Logf

func (c *T) Logf(format string, args ...any)

Logf formats its arguments according to the format, analogous to Printf, and records the text in the error log. A final newline is added if not provided. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag.

+

func (*T) Name 1.8

func (c *T) Name() string

Name returns the name of the running (sub-) test or benchmark.

+

The name will include the name of the test along with the names of any nested sub-tests. If two sibling sub-tests have the same name, Name will append a suffix to guarantee the returned name is unique.

+

func (*T) Parallel

func (t *T) Parallel()

Parallel signals that this test is to be run in parallel with (and only with) other parallel tests. When a test is run multiple times due to use of -test.count or -test.cpu, multiple instances of a single test never run in parallel with each other.

+

func (*T) Run 1.7

func (t *T) Run(name string, f func(t *T)) bool

Run runs f as a subtest of t called name. It runs f in a separate goroutine and blocks until f returns or calls t.Parallel to become a parallel test. Run reports whether f succeeded (or at least did not fail before calling t.Parallel).

+

Run may be called simultaneously from multiple goroutines, but all such calls must return before the outer test function for t returns.

+

func (*T) Setenv 1.17

func (t *T) Setenv(key, value string)

Setenv calls os.Setenv(key, value) and uses Cleanup to restore the environment variable to its original value after the test.

+

Because Setenv affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors.

+

func (*T) Skip 1.1

func (c *T) Skip(args ...any)

Skip is equivalent to Log followed by SkipNow.

+

func (*T) SkipNow 1.1

func (c *T) SkipNow()

SkipNow marks the test as having been skipped and stops its execution by calling runtime.Goexit. If a test fails (see Error, Errorf, Fail) and is then skipped, it is still considered to have failed. Execution will continue at the next test or benchmark. See also FailNow. SkipNow must be called from the goroutine running the test, not from other goroutines created during the test. Calling SkipNow does not stop those other goroutines.

+

func (*T) Skipf 1.1

func (c *T) Skipf(format string, args ...any)

Skipf is equivalent to Logf followed by SkipNow.

+

func (*T) Skipped 1.1

func (c *T) Skipped() bool

Skipped reports whether the test was skipped.

+

func (*T) TempDir 1.15

func (c *T) TempDir() string

TempDir returns a temporary directory for the test to use. The directory is automatically removed when the test and all its subtests complete. Each subsequent call to t.TempDir returns a unique directory; if the directory creation fails, TempDir terminates the test by calling Fatal.

+

type TB 1.2

TB is the interface common to T, B, and F.

+
type TB interface {
+    Cleanup(func())
+    Error(args ...any)
+    Errorf(format string, args ...any)
+    Fail()
+    FailNow()
+    Failed() bool
+    Fatal(args ...any)
+    Fatalf(format string, args ...any)
+    Helper()
+    Log(args ...any)
+    Logf(format string, args ...any)
+    Name() string
+    Setenv(key, value string)
+    Skip(args ...any)
+    SkipNow()
+    Skipf(format string, args ...any)
+    Skipped() bool
+    TempDir() string
+    // contains filtered or unexported methods
+}

Subdirectories

Name Synopsis
..
fstest Package fstest implements support for testing implementations and users of file systems.
iotest Package iotest implements Readers and Writers useful mainly for testing.
quick Package quick implements utility functions to help with black box testing.
slogtest Package slogtest implements support for testing implementations of log/slog.Handler.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/testing/ +

+
diff --git a/devdocs/go/testing%2Fiotest%2Findex.html b/devdocs/go/testing%2Fiotest%2Findex.html new file mode 100644 index 00000000..353a62e9 --- /dev/null +++ b/devdocs/go/testing%2Fiotest%2Findex.html @@ -0,0 +1,39 @@ +

Package iotest

Overview

Package iotest implements Readers and Writers useful mainly for testing.

Index

Examples

ErrReader

Package files

logger.go reader.go writer.go

Variables

ErrTimeout is a fake timeout error.

+
var ErrTimeout = errors.New("timeout")

func DataErrReader

func DataErrReader(r io.Reader) io.Reader

DataErrReader changes the way errors are handled by a Reader. Normally, a Reader returns an error (typically EOF) from the first Read call after the last piece of data is read. DataErrReader wraps a Reader and changes its behavior so the final error is returned along with the final data, instead of in the first call after the final data.

+

func ErrReader 1.16

func ErrReader(err error) io.Reader

ErrReader returns an io.Reader that returns 0, err from all Read calls.

Example +

Code:

// A reader that always returns a custom error.
+r := iotest.ErrReader(errors.New("custom error"))
+n, err := r.Read(nil)
+fmt.Printf("n:   %d\nerr: %q\n", n, err)
+
+

Output:

n:   0
+err: "custom error"
+

func HalfReader

func HalfReader(r io.Reader) io.Reader

HalfReader returns a Reader that implements Read by reading half as many requested bytes from r.

+

func NewReadLogger

func NewReadLogger(prefix string, r io.Reader) io.Reader

NewReadLogger returns a reader that behaves like r except that it logs (using log.Printf) each read to standard error, printing the prefix and the hexadecimal data read.

+

func NewWriteLogger

func NewWriteLogger(prefix string, w io.Writer) io.Writer

NewWriteLogger returns a writer that behaves like w except that it logs (using log.Printf) each write to standard error, printing the prefix and the hexadecimal data written.

+

func OneByteReader

func OneByteReader(r io.Reader) io.Reader

OneByteReader returns a Reader that implements each non-empty Read by reading one byte from r.

+

func TestReader 1.16

func TestReader(r io.Reader, content []byte) error

TestReader tests that reading from r returns the expected file content. It does reads of different sizes, until EOF. If r implements io.ReaderAt or io.Seeker, TestReader also checks that those operations behave as they should.

+

If TestReader finds any misbehaviors, it returns an error reporting them. The error text may span multiple lines.

+

func TimeoutReader

func TimeoutReader(r io.Reader) io.Reader

TimeoutReader returns ErrTimeout on the second read with no data. Subsequent calls to read succeed.

+

func TruncateWriter

func TruncateWriter(w io.Writer, n int64) io.Writer

TruncateWriter returns a Writer that writes to w but stops silently after n bytes.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/testing/iotest/ +

+
diff --git a/devdocs/go/testing%2Fquick%2Findex.html b/devdocs/go/testing%2Fquick%2Findex.html new file mode 100644 index 00000000..d7c9f316 --- /dev/null +++ b/devdocs/go/testing%2Fquick%2Findex.html @@ -0,0 +1,74 @@ +

Package quick

Overview

Package quick implements utility functions to help with black box testing.

+

The testing/quick package is frozen and is not accepting new features.

Index

Package files

quick.go

func Check

func Check(f any, config *Config) error

Check looks for an input to f, any function that returns bool, such that f returns false. It calls f repeatedly, with arbitrary values for each argument. If f returns false on a given input, Check returns that input as a *CheckError. For example:

+
func TestOddMultipleOfThree(t *testing.T) {
+	f := func(x int) bool {
+		y := OddMultipleOfThree(x)
+		return y%2 == 1 && y%3 == 0
+	}
+	if err := quick.Check(f, nil); err != nil {
+		t.Error(err)
+	}
+}
+

func CheckEqual

func CheckEqual(f, g any, config *Config) error

CheckEqual looks for an input on which f and g return different results. It calls f and g repeatedly with arbitrary values for each argument. If f and g return different answers, CheckEqual returns a *CheckEqualError describing the input and the outputs.

+

func Value

func Value(t reflect.Type, rand *rand.Rand) (value reflect.Value, ok bool)

Value returns an arbitrary value of the given type. If the type implements the Generator interface, that will be used. Note: To create arbitrary values for structs, all the fields must be exported.

+

type CheckEqualError

A CheckEqualError is the result CheckEqual finding an error.

+
type CheckEqualError struct {
+    CheckError
+    Out1 []any
+    Out2 []any
+}
+

func (*CheckEqualError) Error

func (s *CheckEqualError) Error() string

type CheckError

A CheckError is the result of Check finding an error.

+
type CheckError struct {
+    Count int
+    In    []any
+}
+

func (*CheckError) Error

func (s *CheckError) Error() string

type Config

A Config structure contains options for running a test.

+
type Config struct {
+    // MaxCount sets the maximum number of iterations.
+    // If zero, MaxCountScale is used.
+    MaxCount int
+    // MaxCountScale is a non-negative scale factor applied to the
+    // default maximum.
+    // A count of zero implies the default, which is usually 100
+    // but can be set by the -quickchecks flag.
+    MaxCountScale float64
+    // Rand specifies a source of random numbers.
+    // If nil, a default pseudo-random source will be used.
+    Rand *rand.Rand
+    // Values specifies a function to generate a slice of
+    // arbitrary reflect.Values that are congruent with the
+    // arguments to the function being tested.
+    // If nil, the top-level Value function is used to generate them.
+    Values func([]reflect.Value, *rand.Rand)
+}
+

type Generator

A Generator can generate random values of its own type.

+
type Generator interface {
+    // Generate returns a random instance of the type on which it is a
+    // method using the size as a size hint.
+    Generate(rand *rand.Rand, size int) reflect.Value
+}

type SetupError

A SetupError is the result of an error in the way that check is being used, independent of the functions being tested.

+
type SetupError string

func (SetupError) Error

func (s SetupError) Error() string
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/testing/quick/ +

+
diff --git a/devdocs/go/testing%2Fslogtest%2Findex.html b/devdocs/go/testing%2Fslogtest%2Findex.html new file mode 100644 index 00000000..ee6e7213 --- /dev/null +++ b/devdocs/go/testing%2Fslogtest%2Findex.html @@ -0,0 +1,42 @@ +

Package slogtest

Overview

Package slogtest implements support for testing implementations of log/slog.Handler.

Example (Parsing) +

This example demonstrates one technique for testing a handler with this package. The handler is given a [bytes.Buffer] to write to, and each line of the resulting output is parsed. For JSON output, [encoding/json.Unmarshal] produces a result in the desired format when given a pointer to a map[string]any.

Code:

var buf bytes.Buffer
+h := slog.NewJSONHandler(&buf, nil)
+
+results := func() []map[string]any {
+    var ms []map[string]any
+    for _, line := range bytes.Split(buf.Bytes(), []byte{'\n'}) {
+        if len(line) == 0 {
+            continue
+        }
+        var m map[string]any
+        if err := json.Unmarshal(line, &m); err != nil {
+            panic(err) // In a real test, use t.Fatal.
+        }
+        ms = append(ms, m)
+    }
+    return ms
+}
+err := slogtest.TestHandler(h, results)
+if err != nil {
+    log.Fatal(err)
+}
+
+

Index

Examples

Package (Parsing)

Package files

slogtest.go

func Run 1.22

func Run(t *testing.T, newHandler func(*testing.T) slog.Handler, result func(*testing.T) map[string]any)

Run exercises a slog.Handler on the same test cases as TestHandler, but runs each case in a subtest. For each test case, it first calls newHandler to get an instance of the handler under test, then runs the test case, then calls result to get the result. If the test case fails, it calls t.Error.

+

func TestHandler 1.21

func TestHandler(h slog.Handler, results func() []map[string]any) error

TestHandler tests a slog.Handler. If TestHandler finds any misbehaviors, it returns an error for each, combined into a single error with errors.Join.

+

TestHandler installs the given Handler in a slog.Logger and makes several calls to the Logger's output methods. The Handler should be enabled for levels Info and above.

+

The results function is invoked after all such calls. It should return a slice of map[string]any, one for each call to a Logger output method. The keys and values of the map should correspond to the keys and values of the Handler's output. Each group in the output should be represented as its own nested map[string]any. The standard keys slog.TimeKey, slog.LevelKey and slog.MessageKey should be used.

+

If the Handler outputs JSON, then calling encoding/json.Unmarshal with a `map[string]any` will create the right data structure.

+

If a Handler intentionally drops an attribute that is checked by a test, then the results function should check for its absence and add it to the map it returns.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/testing/slogtest/ +

+
diff --git a/devdocs/go/text%2Fscanner%2Findex.html b/devdocs/go/text%2Fscanner%2Findex.html new file mode 100644 index 00000000..b3592dee --- /dev/null +++ b/devdocs/go/text%2Fscanner%2Findex.html @@ -0,0 +1,226 @@ +

Package scanner

Overview

Package scanner provides a scanner and tokenizer for UTF-8-encoded text. It takes an io.Reader providing the source, which then can be tokenized through repeated calls to the Scan function. For compatibility with existing tools, the NUL character is not allowed. If the first character in the source is a UTF-8 encoded byte order mark (BOM), it is discarded.

+

By default, a Scanner skips white space and Go comments and recognizes all literals as defined by the Go language specification. It may be customized to recognize only a subset of those literals and to recognize different identifier and white space characters.

Example +

Code:

const src = `
+// This is scanned code.
+if a > 10 {
+    someParsable = text
+}`
+
+var s scanner.Scanner
+s.Init(strings.NewReader(src))
+s.Filename = "example"
+for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
+    fmt.Printf("%s: %s\n", s.Position, s.TokenText())
+}
+
+

Output:

example:3:1: if
+example:3:4: a
+example:3:6: >
+example:3:8: 10
+example:3:11: {
+example:4:2: someParsable
+example:4:15: =
+example:4:17: text
+example:5:1: }
+

Example (IsIdentRune) +

Code:

const src = "%var1 var2%"
+
+var s scanner.Scanner
+s.Init(strings.NewReader(src))
+s.Filename = "default"
+
+for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
+    fmt.Printf("%s: %s\n", s.Position, s.TokenText())
+}
+
+fmt.Println()
+s.Init(strings.NewReader(src))
+s.Filename = "percent"
+
+// treat leading '%' as part of an identifier
+s.IsIdentRune = func(ch rune, i int) bool {
+    return ch == '%' && i == 0 || unicode.IsLetter(ch) || unicode.IsDigit(ch) && i > 0
+}
+
+for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
+    fmt.Printf("%s: %s\n", s.Position, s.TokenText())
+}
+
+

Output:

default:1:1: %
+default:1:2: var1
+default:1:7: var2
+default:1:11: %
+
+percent:1:1: %var1
+percent:1:7: var2
+percent:1:11: %
+

Example (Mode) +

Code:

const src = `
+    // Comment begins at column 5.
+
+This line should not be included in the output.
+
+/*
+This multiline comment
+should be extracted in
+its entirety.
+*/
+`
+
+var s scanner.Scanner
+s.Init(strings.NewReader(src))
+s.Filename = "comments"
+s.Mode ^= scanner.SkipComments // don't skip comments
+
+for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
+    txt := s.TokenText()
+    if strings.HasPrefix(txt, "//") || strings.HasPrefix(txt, "/*") {
+        fmt.Printf("%s: %s\n", s.Position, txt)
+    }
+}
+
+

Output:

comments:2:5: // Comment begins at column 5.
+comments:6:1: /*
+This multiline comment
+should be extracted in
+its entirety.
+*/
+

Example (Whitespace) +

Code:

// tab-separated values
+const src = `aa	ab	ac	ad
+ba	bb	bc	bd
+ca	cb	cc	cd
+da	db	dc	dd`
+
+var (
+    col, row int
+    s        scanner.Scanner
+    tsv      [4][4]string // large enough for example above
+)
+s.Init(strings.NewReader(src))
+s.Whitespace ^= 1<<'\t' | 1<<'\n' // don't skip tabs and new lines
+
+for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
+    switch tok {
+    case '\n':
+        row++
+        col = 0
+    case '\t':
+        col++
+    default:
+        tsv[row][col] = s.TokenText()
+    }
+}
+
+fmt.Print(tsv)
+
+

Output:

[[aa ab ac ad] [ba bb bc bd] [ca cb cc cd] [da db dc dd]]
+

Index

Examples

Package
Package (IsIdentRune)
Package (Mode)
Package (Whitespace)

Package files

scanner.go

Constants

Predefined mode bits to control recognition of tokens. For instance, to configure a Scanner such that it only recognizes (Go) identifiers, integers, and skips comments, set the Scanner's Mode field to:

+
ScanIdents | ScanInts | SkipComments
+

With the exceptions of comments, which are skipped if SkipComments is set, unrecognized tokens are not ignored. Instead, the scanner simply returns the respective individual characters (or possibly sub-tokens). For instance, if the mode is ScanIdents (not ScanStrings), the string "foo" is scanned as the token sequence '"' Ident '"'.

+

Use GoTokens to configure the Scanner such that it accepts all Go literal tokens including Go identifiers. Comments will be skipped.

+
const (
+    ScanIdents     = 1 << -Ident
+    ScanInts       = 1 << -Int
+    ScanFloats     = 1 << -Float // includes Ints and hexadecimal floats
+    ScanChars      = 1 << -Char
+    ScanStrings    = 1 << -String
+    ScanRawStrings = 1 << -RawString
+    ScanComments   = 1 << -Comment
+    SkipComments   = 1 << -skipComment // if set with ScanComments, comments become white space
+    GoTokens       = ScanIdents | ScanFloats | ScanChars | ScanStrings | ScanRawStrings | ScanComments | SkipComments
+)

The result of Scan is one of these tokens or a Unicode character.

+
const (
+    EOF = -(iota + 1)
+    Ident
+    Int
+    Float
+    Char
+    String
+    RawString
+    Comment
+)

GoWhitespace is the default value for the Scanner's Whitespace field. Its value selects Go's white space characters.

+
const GoWhitespace = 1<<'\t' | 1<<'\n' | 1<<'\r' | 1<<' '

func TokenString

func TokenString(tok rune) string

TokenString returns a printable string for a token or Unicode character.

+

type Position

Position is a value that represents a source position. A position is valid if Line > 0.

+
type Position struct {
+    Filename string // filename, if any
+    Offset   int    // byte offset, starting at 0
+    Line     int    // line number, starting at 1
+    Column   int    // column number, starting at 1 (character count per line)
+}
+

func (*Position) IsValid

func (pos *Position) IsValid() bool

IsValid reports whether the position is valid.

+

func (Position) String

func (pos Position) String() string

type Scanner

A Scanner implements reading of Unicode characters and tokens from an io.Reader.

+
type Scanner struct {
+
+    // Error is called for each error encountered. If no Error
+    // function is set, the error is reported to os.Stderr.
+    Error func(s *Scanner, msg string)
+
+    // ErrorCount is incremented by one for each error encountered.
+    ErrorCount int
+
+    // The Mode field controls which tokens are recognized. For instance,
+    // to recognize Ints, set the ScanInts bit in Mode. The field may be
+    // changed at any time.
+    Mode uint
+
+    // The Whitespace field controls which characters are recognized
+    // as white space. To recognize a character ch <= ' ' as white space,
+    // set the ch'th bit in Whitespace (the Scanner's behavior is undefined
+    // for values ch > ' '). The field may be changed at any time.
+    Whitespace uint64
+
+    // IsIdentRune is a predicate controlling the characters accepted
+    // as the ith rune in an identifier. The set of valid characters
+    // must not intersect with the set of white space characters.
+    // If no IsIdentRune function is set, regular Go identifiers are
+    // accepted instead. The field may be changed at any time.
+    IsIdentRune func(ch rune, i int) bool // Go 1.4
+
+    // Start position of most recently scanned token; set by Scan.
+    // Calling Init or Next invalidates the position (Line == 0).
+    // The Filename field is always left untouched by the Scanner.
+    // If an error is reported (via Error) and Position is invalid,
+    // the scanner is not inside a token. Call Pos to obtain an error
+    // position in that case, or to obtain the position immediately
+    // after the most recently scanned token.
+    Position
+    // contains filtered or unexported fields
+}
+

func (*Scanner) Init

func (s *Scanner) Init(src io.Reader) *Scanner

Init initializes a Scanner with a new source and returns s. Error is set to nil, ErrorCount is set to 0, Mode is set to GoTokens, and Whitespace is set to GoWhitespace.

+

func (*Scanner) Next

func (s *Scanner) Next() rune

Next reads and returns the next Unicode character. It returns EOF at the end of the source. It reports a read error by calling s.Error, if not nil; otherwise it prints an error message to os.Stderr. Next does not update the Scanner's Position field; use Pos() to get the current position.

+

func (*Scanner) Peek

func (s *Scanner) Peek() rune

Peek returns the next Unicode character in the source without advancing the scanner. It returns EOF if the scanner's position is at the last character of the source.

+

func (*Scanner) Pos

func (s *Scanner) Pos() (pos Position)

Pos returns the position of the character immediately after the character or token returned by the last call to Next or Scan. Use the Scanner's Position field for the start position of the most recently scanned token.

+

func (*Scanner) Scan

func (s *Scanner) Scan() rune

Scan reads the next token or Unicode character from source and returns it. It only recognizes tokens t for which the respective Mode bit (1<<-t) is set. It returns EOF at the end of the source. It reports scanner errors (read and token errors) by calling s.Error, if not nil; otherwise it prints an error message to os.Stderr.

+

func (*Scanner) TokenText

func (s *Scanner) TokenText() string

TokenText returns the string corresponding to the most recently scanned token. Valid after calling Scan and in calls of Scanner.Error.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/text/scanner/ +

+
diff --git a/devdocs/go/text%2Ftabwriter%2Findex.html b/devdocs/go/text%2Ftabwriter%2Findex.html new file mode 100644 index 00000000..e1582929 --- /dev/null +++ b/devdocs/go/text%2Ftabwriter%2Findex.html @@ -0,0 +1,134 @@ +

Package tabwriter

Overview

Package tabwriter implements a write filter (tabwriter.Writer) that translates tabbed columns in input into properly aligned text.

+

The package is using the Elastic Tabstops algorithm described at http://nickgravgaard.com/elastictabstops/index.html.

+

The text/tabwriter package is frozen and is not accepting new features.

Example (Elastic) +

Code:

// Observe how the b's and the d's, despite appearing in the
+// second cell of each line, belong to different columns.
+w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, '.', tabwriter.AlignRight|tabwriter.Debug)
+fmt.Fprintln(w, "a\tb\tc")
+fmt.Fprintln(w, "aa\tbb\tcc")
+fmt.Fprintln(w, "aaa\t") // trailing tab
+fmt.Fprintln(w, "aaaa\tdddd\teeee")
+w.Flush()
+
+

Output:

....a|..b|c
+...aa|.bb|cc
+..aaa|
+.aaaa|.dddd|eeee
+

Example (TrailingTab) +

Code:

// Observe that the third line has no trailing tab,
+// so its final cell is not part of an aligned column.
+const padding = 3
+w := tabwriter.NewWriter(os.Stdout, 0, 0, padding, '-', tabwriter.AlignRight|tabwriter.Debug)
+fmt.Fprintln(w, "a\tb\taligned\t")
+fmt.Fprintln(w, "aa\tbb\taligned\t")
+fmt.Fprintln(w, "aaa\tbbb\tunaligned") // no trailing tab
+fmt.Fprintln(w, "aaaa\tbbbb\taligned\t")
+w.Flush()
+
+

Output:

------a|------b|---aligned|
+-----aa|-----bb|---aligned|
+----aaa|----bbb|unaligned
+---aaaa|---bbbb|---aligned|
+

Index

Examples

Writer.Init
Package (Elastic)
Package (TrailingTab)

Package files

tabwriter.go

Constants

Formatting can be controlled with these flags.

+
const (
+    // Ignore html tags and treat entities (starting with '&'
+    // and ending in ';') as single characters (width = 1).
+    FilterHTML uint = 1 << iota
+
+    // Strip Escape characters bracketing escaped text segments
+    // instead of passing them through unchanged with the text.
+    StripEscape
+
+    // Force right-alignment of cell content.
+    // Default is left-alignment.
+    AlignRight
+
+    // Handle empty columns as if they were not present in
+    // the input in the first place.
+    DiscardEmptyColumns
+
+    // Always use tabs for indentation columns (i.e., padding of
+    // leading empty cells on the left) independent of padchar.
+    TabIndent
+
+    // Print a vertical bar ('|') between columns (after formatting).
+    // Discarded columns appear as zero-width columns ("||").
+    Debug
+)

To escape a text segment, bracket it with Escape characters. For instance, the tab in this string "Ignore this tab: \xff\t\xff" does not terminate a cell and constitutes a single character of width one for formatting purposes.

+

The value 0xff was chosen because it cannot appear in a valid UTF-8 sequence.

+
const Escape = '\xff'

type Writer

A Writer is a filter that inserts padding around tab-delimited columns in its input to align them in the output.

+

The Writer treats incoming bytes as UTF-8-encoded text consisting of cells terminated by horizontal ('\t') or vertical ('\v') tabs, and newline ('\n') or formfeed ('\f') characters; both newline and formfeed act as line breaks.

+

Tab-terminated cells in contiguous lines constitute a column. The Writer inserts padding as needed to make all cells in a column have the same width, effectively aligning the columns. It assumes that all characters have the same width, except for tabs for which a tabwidth must be specified. Column cells must be tab-terminated, not tab-separated: non-tab terminated trailing text at the end of a line forms a cell but that cell is not part of an aligned column. For instance, in this example (where | stands for a horizontal tab):

+
aaaa|bbb|d
+aa  |b  |dd
+a   |
+aa  |cccc|eee
+

the b and c are in distinct columns (the b column is not contiguous all the way). The d and e are not in a column at all (there's no terminating tab, nor would the column be contiguous).

+

The Writer assumes that all Unicode code points have the same width; this may not be true in some fonts or if the string contains combining characters.

+

If DiscardEmptyColumns is set, empty columns that are terminated entirely by vertical (or "soft") tabs are discarded. Columns terminated by horizontal (or "hard") tabs are not affected by this flag.

+

If a Writer is configured to filter HTML, HTML tags and entities are passed through. The widths of tags and entities are assumed to be zero (tags) and one (entities) for formatting purposes.

+

A segment of text may be escaped by bracketing it with Escape characters. The tabwriter passes escaped text segments through unchanged. In particular, it does not interpret any tabs or line breaks within the segment. If the StripEscape flag is set, the Escape characters are stripped from the output; otherwise they are passed through as well. For the purpose of formatting, the width of the escaped text is always computed excluding the Escape characters.

+

The formfeed character acts like a newline but it also terminates all columns in the current line (effectively calling Flush). Tab- terminated cells in the next line start new columns. Unless found inside an HTML tag or inside an escaped text segment, formfeed characters appear as newlines in the output.

+

The Writer must buffer input internally, because proper spacing of one line may depend on the cells in future lines. Clients must call Flush when done calling Write.

+
type Writer struct {
+    // contains filtered or unexported fields
+}
+

func NewWriter

func NewWriter(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer

NewWriter allocates and initializes a new tabwriter.Writer. The parameters are the same as for the Init function.

+

func (*Writer) Flush

func (b *Writer) Flush() error

Flush should be called after the last call to Write to ensure that any data buffered in the Writer is written to output. Any incomplete escape sequence at the end is considered complete for formatting purposes.

+

func (*Writer) Init

func (b *Writer) Init(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer

A Writer must be initialized with a call to Init. The first parameter (output) specifies the filter output. The remaining parameters control the formatting:

+
minwidth	minimal cell width including any padding
+tabwidth	width of tab characters (equivalent number of spaces)
+padding		padding added to a cell before computing its width
+padchar		ASCII char used for padding
+		if padchar == '\t', the Writer will assume that the
+		width of a '\t' in the formatted output is tabwidth,
+		and cells are left-aligned independent of align_left
+		(for correct-looking results, tabwidth must correspond
+		to the tab width in the viewer displaying the result)
+flags		formatting control
+

Example +

Code:

w := new(tabwriter.Writer)
+
+// Format in tab-separated columns with a tab stop of 8.
+w.Init(os.Stdout, 0, 8, 0, '\t', 0)
+fmt.Fprintln(w, "a\tb\tc\td\t.")
+fmt.Fprintln(w, "123\t12345\t1234567\t123456789\t.")
+fmt.Fprintln(w)
+w.Flush()
+
+// Format right-aligned in space-separated columns of minimal width 5
+// and at least one blank of padding (so wider column entries do not
+// touch each other).
+w.Init(os.Stdout, 5, 0, 1, ' ', tabwriter.AlignRight)
+fmt.Fprintln(w, "a\tb\tc\td\t.")
+fmt.Fprintln(w, "123\t12345\t1234567\t123456789\t.")
+fmt.Fprintln(w)
+w.Flush()
+
+

Output:

a	b	c	d		.
+123	12345	1234567	123456789	.
+
+    a     b       c         d.
+  123 12345 1234567 123456789.
+

func (*Writer) Write

func (b *Writer) Write(buf []byte) (n int, err error)

Write writes buf to the writer b. The only errors returned are ones encountered while writing to the underlying output stream.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/text/tabwriter/ +

+
diff --git a/devdocs/go/text%2Ftemplate%2Findex.html b/devdocs/go/text%2Ftemplate%2Findex.html new file mode 100644 index 00000000..662ae149 --- /dev/null +++ b/devdocs/go/text%2Ftemplate%2Findex.html @@ -0,0 +1,640 @@ +

Package template

Overview

Package template implements data-driven templates for generating textual output.

+

To generate HTML output, see html/template, which has the same interface as this package but automatically secures HTML output against certain attacks.

+

Templates are executed by applying them to a data structure. Annotations in the template refer to elements of the data structure (typically a field of a struct or a key in a map) to control execution and derive values to be displayed. Execution of the template walks the structure and sets the cursor, represented by a period '.' and called "dot", to the value at the current location in the structure as execution proceeds.

+

The input text for a template is UTF-8-encoded text in any format. "Actions"--data evaluations or control structures--are delimited by "{{" and "}}"; all text outside actions is copied to the output unchanged.

+

Once parsed, a template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

+

Here is a trivial example that prints "17 items are made of wool".

+
type Inventory struct {
+	Material string
+	Count    uint
+}
+sweaters := Inventory{"wool", 17}
+tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
+if err != nil { panic(err) }
+err = tmpl.Execute(os.Stdout, sweaters)
+if err != nil { panic(err) }
+

More intricate examples appear below.

+

Text and spaces

By default, all text between actions is copied verbatim when the template is executed. For example, the string " items are made of " in the example above appears on standard output when the program is run.

+

However, to aid in formatting template source code, if an action's left delimiter (by default "{{") is followed immediately by a minus sign and white space, all trailing white space is trimmed from the immediately preceding text. Similarly, if the right delimiter ("}}") is preceded by white space and a minus sign, all leading white space is trimmed from the immediately following text. In these trim markers, the white space must be present: "{{- 3}}" is like "{{3}}" but trims the immediately preceding text, while "{{-3}}" parses as an action containing the number -3.

+

For instance, when executing the template whose source is

+
"{{23 -}} < {{- 45}}"
+

the generated output would be

+
"23<45"
+

For this trimming, the definition of white space characters is the same as in Go: space, horizontal tab, carriage return, and newline.

+

Actions

Here is the list of actions. "Arguments" and "pipelines" are evaluations of data, defined in detail in the corresponding sections that follow.

+
{{/* a comment */}}
+{{- /* a comment with white space trimmed from preceding and following text */ -}}
+	A comment; discarded. May contain newlines.
+	Comments do not nest and must start and end at the
+	delimiters, as shown here.
+
+{{pipeline}}
+	The default textual representation (the same as would be
+	printed by fmt.Print) of the value of the pipeline is copied
+	to the output.
+
+{{if pipeline}} T1 {{end}}
+	If the value of the pipeline is empty, no output is generated;
+	otherwise, T1 is executed. The empty values are false, 0, any
+	nil pointer or interface value, and any array, slice, map, or
+	string of length zero.
+	Dot is unaffected.
+
+{{if pipeline}} T1 {{else}} T0 {{end}}
+	If the value of the pipeline is empty, T0 is executed;
+	otherwise, T1 is executed. Dot is unaffected.
+
+{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
+	To simplify the appearance of if-else chains, the else action
+	of an if may include another if directly; the effect is exactly
+	the same as writing
+		{{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}}
+
+{{range pipeline}} T1 {{end}}
+	The value of the pipeline must be an array, slice, map, or channel.
+	If the value of the pipeline has length zero, nothing is output;
+	otherwise, dot is set to the successive elements of the array,
+	slice, or map and T1 is executed. If the value is a map and the
+	keys are of basic type with a defined order, the elements will be
+	visited in sorted key order.
+
+{{range pipeline}} T1 {{else}} T0 {{end}}
+	The value of the pipeline must be an array, slice, map, or channel.
+	If the value of the pipeline has length zero, dot is unaffected and
+	T0 is executed; otherwise, dot is set to the successive elements
+	of the array, slice, or map and T1 is executed.
+
+{{break}}
+	The innermost {{range pipeline}} loop is ended early, stopping the
+	current iteration and bypassing all remaining iterations.
+
+{{continue}}
+	The current iteration of the innermost {{range pipeline}} loop is
+	stopped, and the loop starts the next iteration.
+
+{{template "name"}}
+	The template with the specified name is executed with nil data.
+
+{{template "name" pipeline}}
+	The template with the specified name is executed with dot set
+	to the value of the pipeline.
+
+{{block "name" pipeline}} T1 {{end}}
+	A block is shorthand for defining a template
+		{{define "name"}} T1 {{end}}
+	and then executing it in place
+		{{template "name" pipeline}}
+	The typical use is to define a set of root templates that are
+	then customized by redefining the block templates within.
+
+{{with pipeline}} T1 {{end}}
+	If the value of the pipeline is empty, no output is generated;
+	otherwise, dot is set to the value of the pipeline and T1 is
+	executed.
+
+{{with pipeline}} T1 {{else}} T0 {{end}}
+	If the value of the pipeline is empty, dot is unaffected and T0
+	is executed; otherwise, dot is set to the value of the pipeline
+	and T1 is executed.
+

Arguments

An argument is a simple value, denoted by one of the following.

+

Arguments may evaluate to any type; if they are pointers the implementation automatically indirects to the base type when required. If an evaluation yields a function value, such as a function-valued field of a struct, the function is not invoked automatically, but it can be used as a truth value for an if action and the like. To invoke it, use the call function, defined below.

+

Pipelines

A pipeline is a possibly chained sequence of "commands". A command is a simple value (argument) or a function or method call, possibly with multiple arguments:

+
Argument
+	The result is the value of evaluating the argument.
+.Method [Argument...]
+	The method can be alone or the last element of a chain but,
+	unlike methods in the middle of a chain, it can take arguments.
+	The result is the value of calling the method with the
+	arguments:
+		dot.Method(Argument1, etc.)
+functionName [Argument...]
+	The result is the value of calling the function associated
+	with the name:
+		function(Argument1, etc.)
+	Functions and function names are described below.
+

A pipeline may be "chained" by separating a sequence of commands with pipeline characters '|'. In a chained pipeline, the result of each command is passed as the last argument of the following command. The output of the final command in the pipeline is the value of the pipeline.

+

The output of a command will be either one value or two values, the second of which has type error. If that second value is present and evaluates to non-nil, execution terminates and the error is returned to the caller of Execute.

+

Variables

A pipeline inside an action may initialize a variable to capture the result. The initialization has syntax

+
$variable := pipeline
+

where $variable is the name of the variable. An action that declares a variable produces no output.

+

Variables previously declared can also be assigned, using the syntax

+
$variable = pipeline
+

If a "range" action initializes a variable, the variable is set to the successive elements of the iteration. Also, a "range" may declare two variables, separated by a comma:

+
range $index, $element := pipeline
+

in which case $index and $element are set to the successive values of the array/slice index or map key and element, respectively. Note that if there is only one variable, it is assigned the element; this is opposite to the convention in Go range clauses.

+

A variable's scope extends to the "end" action of the control structure ("if", "with", or "range") in which it is declared, or to the end of the template if there is no such control structure. A template invocation does not inherit variables from the point of its invocation.

+

When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

+

Examples

Here are some example one-line templates demonstrating pipelines and variables. All produce the quoted word "output":

+
{{"\"output\""}}
+	A string constant.
+{{`"output"`}}
+	A raw string constant.
+{{printf "%q" "output"}}
+	A function call.
+{{"output" | printf "%q"}}
+	A function call whose final argument comes from the previous
+	command.
+{{printf "%q" (print "out" "put")}}
+	A parenthesized argument.
+{{"put" | printf "%s%s" "out" | printf "%q"}}
+	A more elaborate call.
+{{"output" | printf "%s" | printf "%q"}}
+	A longer chain.
+{{with "output"}}{{printf "%q" .}}{{end}}
+	A with action using dot.
+{{with $x := "output" | printf "%q"}}{{$x}}{{end}}
+	A with action that creates and uses a variable.
+{{with $x := "output"}}{{printf "%q" $x}}{{end}}
+	A with action that uses the variable in another action.
+{{with $x := "output"}}{{$x | printf "%q"}}{{end}}
+	The same, but pipelined.
+

Functions

During execution functions are found in two function maps: first in the template, then in the global function map. By default, no functions are defined in the template but the Funcs method can be used to add them.

+

Predefined global functions are named as follows.

+
and
+	Returns the boolean AND of its arguments by returning the
+	first empty argument or the last argument. That is,
+	"and x y" behaves as "if x then y else x."
+	Evaluation proceeds through the arguments left to right
+	and returns when the result is determined.
+call
+	Returns the result of calling the first argument, which
+	must be a function, with the remaining arguments as parameters.
+	Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where
+	Y is a func-valued field, map entry, or the like.
+	The first argument must be the result of an evaluation
+	that yields a value of function type (as distinct from
+	a predefined function such as print). The function must
+	return either one or two result values, the second of which
+	is of type error. If the arguments don't match the function
+	or the returned error value is non-nil, execution stops.
+html
+	Returns the escaped HTML equivalent of the textual
+	representation of its arguments. This function is unavailable
+	in html/template, with a few exceptions.
+index
+	Returns the result of indexing its first argument by the
+	following arguments. Thus "index x 1 2 3" is, in Go syntax,
+	x[1][2][3]. Each indexed item must be a map, slice, or array.
+slice
+	slice returns the result of slicing its first argument by the
+	remaining arguments. Thus "slice x 1 2" is, in Go syntax, x[1:2],
+	while "slice x" is x[:], "slice x 1" is x[1:], and "slice x 1 2 3"
+	is x[1:2:3]. The first argument must be a string, slice, or array.
+js
+	Returns the escaped JavaScript equivalent of the textual
+	representation of its arguments.
+len
+	Returns the integer length of its argument.
+not
+	Returns the boolean negation of its single argument.
+or
+	Returns the boolean OR of its arguments by returning the
+	first non-empty argument or the last argument, that is,
+	"or x y" behaves as "if x then x else y".
+	Evaluation proceeds through the arguments left to right
+	and returns when the result is determined.
+print
+	An alias for fmt.Sprint
+printf
+	An alias for fmt.Sprintf
+println
+	An alias for fmt.Sprintln
+urlquery
+	Returns the escaped value of the textual representation of
+	its arguments in a form suitable for embedding in a URL query.
+	This function is unavailable in html/template, with a few
+	exceptions.
+

The boolean functions take any zero value to be false and a non-zero value to be true.

+

There is also a set of binary comparison operators defined as functions:

+
eq
+	Returns the boolean truth of arg1 == arg2
+ne
+	Returns the boolean truth of arg1 != arg2
+lt
+	Returns the boolean truth of arg1 < arg2
+le
+	Returns the boolean truth of arg1 <= arg2
+gt
+	Returns the boolean truth of arg1 > arg2
+ge
+	Returns the boolean truth of arg1 >= arg2
+

For simpler multi-way equality tests, eq (only) accepts two or more arguments and compares the second and subsequent to the first, returning in effect

+
arg1==arg2 || arg1==arg3 || arg1==arg4 ...
+

(Unlike with || in Go, however, eq is a function call and all the arguments will be evaluated.)

+

The comparison functions work on any values whose type Go defines as comparable. For basic types such as integers, the rules are relaxed: size and exact type are ignored, so any integer value, signed or unsigned, may be compared with any other integer value. (The arithmetic value is compared, not the bit pattern, so all negative integers are less than all unsigned integers.) However, as usual, one may not compare an int with a float32 and so on.

+

Associated templates

Each template is named by a string specified when it is created. Also, each template is associated with zero or more other templates that it may invoke by name; such associations are transitive and form a name space of templates.

+

A template may use a template invocation to instantiate another associated template; see the explanation of the "template" action above. The name must be that of a template associated with the template that contains the invocation.

+

Nested template definitions

When parsing a template, another template may be defined and associated with the template being parsed. Template definitions must appear at the top level of the template, much like global variables in a Go program.

+

The syntax of such definitions is to surround each template declaration with a "define" and "end" action.

+

The define action names the template being created by providing a string constant. Here is a simple example:

+
{{define "T1"}}ONE{{end}}
+{{define "T2"}}TWO{{end}}
+{{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}
+{{template "T3"}}
+

This defines two templates, T1 and T2, and a third T3 that invokes the other two when it is executed. Finally it invokes T3. If executed this template will produce the text

+
ONE TWO
+

By construction, a template may reside in only one association. If it's necessary to have a template addressable from multiple associations, the template definition must be parsed multiple times to create distinct *Template values, or must be copied with Template.Clone or Template.AddParseTree.

+

Parse may be called multiple times to assemble the various associated templates; see ParseFiles, ParseGlob, Template.ParseFiles and Template.ParseGlob for simple ways to parse related templates stored in files.

+

A template may be executed directly or through Template.ExecuteTemplate, which executes an associated template identified by name. To invoke our example above, we might write,

+
err := tmpl.Execute(os.Stdout, "no data needed")
+if err != nil {
+	log.Fatalf("execution failed: %s", err)
+}
+

or to invoke a particular template explicitly by name,

+
err := tmpl.ExecuteTemplate(os.Stdout, "T2", "no data needed")
+if err != nil {
+	log.Fatalf("execution failed: %s", err)
+}
+

Index

Examples

Template
Template (Block)
Template (Func)
Template (Glob)
Template (Helpers)
Template (Share)

Package files

doc.go exec.go funcs.go helper.go option.go template.go

func HTMLEscape

func HTMLEscape(w io.Writer, b []byte)

HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.

+

func HTMLEscapeString

func HTMLEscapeString(s string) string

HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.

+

func HTMLEscaper

func HTMLEscaper(args ...any) string

HTMLEscaper returns the escaped HTML equivalent of the textual representation of its arguments.

+

func IsTrue 1.6

func IsTrue(val any) (truth, ok bool)

IsTrue reports whether the value is 'true', in the sense of not the zero of its type, and whether the value has a meaningful truth value. This is the definition of truth used by if and other such actions.

+

func JSEscape

func JSEscape(w io.Writer, b []byte)

JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.

+

func JSEscapeString

func JSEscapeString(s string) string

JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.

+

func JSEscaper

func JSEscaper(args ...any) string

JSEscaper returns the escaped JavaScript equivalent of the textual representation of its arguments.

+

func URLQueryEscaper

func URLQueryEscaper(args ...any) string

URLQueryEscaper returns the escaped value of the textual representation of its arguments in a form suitable for embedding in a URL query.

+

type ExecError 1.6

ExecError is the custom error type returned when Execute has an error evaluating its template. (If a write error occurs, the actual error is returned; it will not be of type ExecError.)

+
type ExecError struct {
+    Name string // Name of template.
+    Err  error  // Pre-formatted error.
+}
+

func (ExecError) Error 1.6

func (e ExecError) Error() string

func (ExecError) Unwrap 1.13

func (e ExecError) Unwrap() error

type FuncMap

FuncMap is the type of the map defining the mapping from names to functions. Each function must have either a single return value, or two return values of which the second has type error. In that case, if the second (error) return value evaluates to non-nil during execution, execution terminates and Execute returns that error.

+

Errors returned by Execute wrap the underlying error; call errors.As to unwrap them.

+

When template execution invokes a function with an argument list, that list must be assignable to the function's parameter types. Functions meant to apply to arguments of arbitrary type can use parameters of type interface{} or of type reflect.Value. Similarly, functions meant to return a result of arbitrary type can return interface{} or reflect.Value.

+
type FuncMap map[string]any

type Template

Template is the representation of a parsed template. The *parse.Tree field is exported only for use by html/template and should be treated as unexported by all other clients.

+
type Template struct {
+    *parse.Tree
+    // contains filtered or unexported fields
+}
+

Example +

Code:

// Define a template.
+const letter = `
+Dear {{.Name}},
+{{if .Attended}}
+It was a pleasure to see you at the wedding.
+{{- else}}
+It is a shame you couldn't make it to the wedding.
+{{- end}}
+{{with .Gift -}}
+Thank you for the lovely {{.}}.
+{{end}}
+Best wishes,
+Josie
+`
+
+// Prepare some data to insert into the template.
+type Recipient struct {
+    Name, Gift string
+    Attended   bool
+}
+var recipients = []Recipient{
+    {"Aunt Mildred", "bone china tea set", true},
+    {"Uncle John", "moleskin pants", false},
+    {"Cousin Rodney", "", false},
+}
+
+// Create a new template and parse the letter into it.
+t := template.Must(template.New("letter").Parse(letter))
+
+// Execute the template for each recipient.
+for _, r := range recipients {
+    err := t.Execute(os.Stdout, r)
+    if err != nil {
+        log.Println("executing template:", err)
+    }
+}
+
+

Output:

Dear Aunt Mildred,
+
+It was a pleasure to see you at the wedding.
+Thank you for the lovely bone china tea set.
+
+Best wishes,
+Josie
+
+Dear Uncle John,
+
+It is a shame you couldn't make it to the wedding.
+Thank you for the lovely moleskin pants.
+
+Best wishes,
+Josie
+
+Dear Cousin Rodney,
+
+It is a shame you couldn't make it to the wedding.
+
+Best wishes,
+Josie
+

Example (Block) +

Code:

const (
+    master  = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}`
+    overlay = `{{define "list"}} {{join . ", "}}{{end}} `
+)
+var (
+    funcs     = template.FuncMap{"join": strings.Join}
+    guardians = []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"}
+)
+masterTmpl, err := template.New("master").Funcs(funcs).Parse(master)
+if err != nil {
+    log.Fatal(err)
+}
+overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay)
+if err != nil {
+    log.Fatal(err)
+}
+if err := masterTmpl.Execute(os.Stdout, guardians); err != nil {
+    log.Fatal(err)
+}
+if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil {
+    log.Fatal(err)
+}
+

Output:

Names:
+- Gamora
+- Groot
+- Nebula
+- Rocket
+- Star-Lord
+Names: Gamora, Groot, Nebula, Rocket, Star-Lord
+

Example (Func) +

This example demonstrates a custom function to process template text. It installs the strings.Title function and uses it to Make Title Text Look Good In Our Template's Output.

Code:

// First we create a FuncMap with which to register the function.
+funcMap := template.FuncMap{
+    // The name "title" is what the function will be called in the template text.
+    "title": strings.Title,
+}
+
+// A simple template definition to test our function.
+// We print the input text several ways:
+// - the original
+// - title-cased
+// - title-cased and then printed with %q
+// - printed with %q and then title-cased.
+const templateText = `
+Input: {{printf "%q" .}}
+Output 0: {{title .}}
+Output 1: {{title . | printf "%q"}}
+Output 2: {{printf "%q" . | title}}
+`
+
+// Create a template, add the function map, and parse the text.
+tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText)
+if err != nil {
+    log.Fatalf("parsing: %s", err)
+}
+
+// Run the template to verify the output.
+err = tmpl.Execute(os.Stdout, "the go programming language")
+if err != nil {
+    log.Fatalf("execution: %s", err)
+}
+
+

Output:

Input: "the go programming language"
+Output 0: The Go Programming Language
+Output 1: "The Go Programming Language"
+Output 2: "The Go Programming Language"
+

Example (Glob) +

Here we demonstrate loading a set of templates from a directory.

Code:

// Here we create a temporary directory and populate it with our sample
+// template definition files; usually the template files would already
+// exist in some location known to the program.
+dir := createTestDir([]templateFile{
+    // T0.tmpl is a plain template file that just invokes T1.
+    {"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`},
+    // T1.tmpl defines a template, T1 that invokes T2.
+    {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
+    // T2.tmpl defines a template T2.
+    {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
+})
+// Clean up after the test; another quirk of running as an example.
+defer os.RemoveAll(dir)
+
+// pattern is the glob pattern used to find all the template files.
+pattern := filepath.Join(dir, "*.tmpl")
+
+// Here starts the example proper.
+// T0.tmpl is the first name matched, so it becomes the starting template,
+// the value returned by ParseGlob.
+tmpl := template.Must(template.ParseGlob(pattern))
+
+err := tmpl.Execute(os.Stdout, nil)
+if err != nil {
+    log.Fatalf("template execution: %s", err)
+}
+

Output:

T0 invokes T1: (T1 invokes T2: (This is T2))
+

Example (Helpers) +

This example demonstrates one way to share some templates and use them in different contexts. In this variant we add multiple driver templates by hand to an existing bundle of templates.

Code:

// Here we create a temporary directory and populate it with our sample
+// template definition files; usually the template files would already
+// exist in some location known to the program.
+dir := createTestDir([]templateFile{
+    // T1.tmpl defines a template, T1 that invokes T2.
+    {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
+    // T2.tmpl defines a template T2.
+    {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
+})
+// Clean up after the test; another quirk of running as an example.
+defer os.RemoveAll(dir)
+
+// pattern is the glob pattern used to find all the template files.
+pattern := filepath.Join(dir, "*.tmpl")
+
+// Here starts the example proper.
+// Load the helpers.
+templates := template.Must(template.ParseGlob(pattern))
+// Add one driver template to the bunch; we do this with an explicit template definition.
+_, err := templates.Parse("{{define `driver1`}}Driver 1 calls T1: ({{template `T1`}})\n{{end}}")
+if err != nil {
+    log.Fatal("parsing driver1: ", err)
+}
+// Add another driver template.
+_, err = templates.Parse("{{define `driver2`}}Driver 2 calls T2: ({{template `T2`}})\n{{end}}")
+if err != nil {
+    log.Fatal("parsing driver2: ", err)
+}
+// We load all the templates before execution. This package does not require
+// that behavior but html/template's escaping does, so it's a good habit.
+err = templates.ExecuteTemplate(os.Stdout, "driver1", nil)
+if err != nil {
+    log.Fatalf("driver1 execution: %s", err)
+}
+err = templates.ExecuteTemplate(os.Stdout, "driver2", nil)
+if err != nil {
+    log.Fatalf("driver2 execution: %s", err)
+}
+

Output:

Driver 1 calls T1: (T1 invokes T2: (This is T2))
+Driver 2 calls T2: (This is T2)
+

Example (Share) +

This example demonstrates how to use one group of driver templates with distinct sets of helper templates.

Code:

// Here we create a temporary directory and populate it with our sample
+// template definition files; usually the template files would already
+// exist in some location known to the program.
+dir := createTestDir([]templateFile{
+    // T0.tmpl is a plain template file that just invokes T1.
+    {"T0.tmpl", "T0 ({{.}} version) invokes T1: ({{template `T1`}})\n"},
+    // T1.tmpl defines a template, T1 that invokes T2. Note T2 is not defined
+    {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
+})
+// Clean up after the test; another quirk of running as an example.
+defer os.RemoveAll(dir)
+
+// pattern is the glob pattern used to find all the template files.
+pattern := filepath.Join(dir, "*.tmpl")
+
+// Here starts the example proper.
+// Load the drivers.
+drivers := template.Must(template.ParseGlob(pattern))
+
+// We must define an implementation of the T2 template. First we clone
+// the drivers, then add a definition of T2 to the template name space.
+
+// 1. Clone the helper set to create a new name space from which to run them.
+first, err := drivers.Clone()
+if err != nil {
+    log.Fatal("cloning helpers: ", err)
+}
+// 2. Define T2, version A, and parse it.
+_, err = first.Parse("{{define `T2`}}T2, version A{{end}}")
+if err != nil {
+    log.Fatal("parsing T2: ", err)
+}
+
+// Now repeat the whole thing, using a different version of T2.
+// 1. Clone the drivers.
+second, err := drivers.Clone()
+if err != nil {
+    log.Fatal("cloning drivers: ", err)
+}
+// 2. Define T2, version B, and parse it.
+_, err = second.Parse("{{define `T2`}}T2, version B{{end}}")
+if err != nil {
+    log.Fatal("parsing T2: ", err)
+}
+
+// Execute the templates in the reverse order to verify the
+// first is unaffected by the second.
+err = second.ExecuteTemplate(os.Stdout, "T0.tmpl", "second")
+if err != nil {
+    log.Fatalf("second execution: %s", err)
+}
+err = first.ExecuteTemplate(os.Stdout, "T0.tmpl", "first")
+if err != nil {
+    log.Fatalf("first: execution: %s", err)
+}
+
+

Output:

T0 (second version) invokes T1: (T1 invokes T2: (T2, version B))
+T0 (first version) invokes T1: (T1 invokes T2: (T2, version A))
+

func Must

func Must(t *Template, err error) *Template

Must is a helper that wraps a call to a function returning (*Template, error) and panics if the error is non-nil. It is intended for use in variable initializations such as

+
var t = template.Must(template.New("name").Parse("text"))
+

func New

func New(name string) *Template

New allocates a new, undefined template with the given name.

+

func ParseFS 1.16

func ParseFS(fsys fs.FS, patterns ...string) (*Template, error)

ParseFS is like ParseFiles or ParseGlob but reads from the file system fsys instead of the host operating system's file system. It accepts a list of glob patterns. (Note that most file names serve as glob patterns matching only themselves.)

+

func ParseFiles

func ParseFiles(filenames ...string) (*Template, error)

ParseFiles creates a new Template and parses the template definitions from the named files. The returned template's name will have the base name and parsed contents of the first file. There must be at least one file. If an error occurs, parsing stops and the returned *Template is nil.

+

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results. For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template named "foo", while "a/foo" is unavailable.

+

func ParseGlob

func ParseGlob(pattern string) (*Template, error)

ParseGlob creates a new Template and parses the template definitions from the files identified by the pattern. The files are matched according to the semantics of filepath.Match, and the pattern must match at least one file. The returned template will have the (base) name and (parsed) contents of the first file matched by the pattern. ParseGlob is equivalent to calling ParseFiles with the list of files matched by the pattern.

+

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

+

func (*Template) AddParseTree

func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)

AddParseTree associates the argument parse tree with the template t, giving it the specified name. If the template has not been defined, this tree becomes its definition. If it has been defined and already has that name, the existing definition is replaced; otherwise a new template is created, defined, and returned.

+

func (*Template) Clone

func (t *Template) Clone() (*Template, error)

Clone returns a duplicate of the template, including all associated templates. The actual representation is not copied, but the name space of associated templates is, so further calls to Parse in the copy will add templates to the copy but not to the original. Clone can be used to prepare common templates and use them with variant definitions for other templates by adding the variants after the clone is made.

+

func (*Template) DefinedTemplates 1.5

func (t *Template) DefinedTemplates() string

DefinedTemplates returns a string listing the defined templates, prefixed by the string "; defined templates are: ". If there are none, it returns the empty string. For generating an error message here and in html/template.

+

func (*Template) Delims

func (t *Template) Delims(left, right string) *Template

Delims sets the action delimiters to the specified strings, to be used in subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template definitions will inherit the settings. An empty delimiter stands for the corresponding default: {{ or }}. The return value is the template, so calls can be chained.

+

func (*Template) Execute

func (t *Template) Execute(wr io.Writer, data any) error

Execute applies a parsed template to the specified data object, and writes the output to wr. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

+

If data is a reflect.Value, the template applies to the concrete value that the reflect.Value holds, as in fmt.Print.

+

func (*Template) ExecuteTemplate

func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error

ExecuteTemplate applies the template associated with t that has the given name to the specified data object and writes the output to wr. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

+

func (*Template) Funcs

func (t *Template) Funcs(funcMap FuncMap) *Template

Funcs adds the elements of the argument map to the template's function map. It must be called before the template is parsed. It panics if a value in the map is not a function with appropriate return type or if the name cannot be used syntactically as a function in a template. It is legal to overwrite elements of the map. The return value is the template, so calls can be chained.

+

func (*Template) Lookup

func (t *Template) Lookup(name string) *Template

Lookup returns the template with the given name that is associated with t. It returns nil if there is no such template or the template has no definition.

+

func (*Template) Name

func (t *Template) Name() string

Name returns the name of the template.

+

func (*Template) New

func (t *Template) New(name string) *Template

New allocates a new, undefined template associated with the given one and with the same delimiters. The association, which is transitive, allows one template to invoke another with a {{template}} action.

+

Because associated templates share underlying data, template construction cannot be done safely in parallel. Once the templates are constructed, they can be executed in parallel.

+

func (*Template) Option 1.5

func (t *Template) Option(opt ...string) *Template

Option sets options for the template. Options are described by strings, either a simple string or "key=value". There can be at most one equals sign in an option string. If the option string is unrecognized or otherwise invalid, Option panics.

+

Known options:

+

missingkey: Control the behavior during execution if a map is indexed with a key that is not present in the map.

+
"missingkey=default" or "missingkey=invalid"
+	The default behavior: Do nothing and continue execution.
+	If printed, the result of the index operation is the string
+	"<no value>".
+"missingkey=zero"
+	The operation returns the zero value for the map type's element.
+"missingkey=error"
+	Execution stops immediately with an error.
+

func (*Template) Parse

func (t *Template) Parse(text string) (*Template, error)

Parse parses text as a template body for t. Named template definitions ({{define ...}} or {{block ...}} statements) in text define additional templates associated with t and are removed from the definition of t itself.

+

Templates can be redefined in successive calls to Parse. A template definition with a body containing only white space and comments is considered empty and will not replace an existing template's body. This allows using Parse to add new named template definitions without overwriting the main template body.

+

func (*Template) ParseFS 1.16

func (t *Template) ParseFS(fsys fs.FS, patterns ...string) (*Template, error)

ParseFS is like ParseFiles or ParseGlob but reads from the file system fsys instead of the host operating system's file system. It accepts a list of glob patterns. (Note that most file names serve as glob patterns matching only themselves.)

+

func (*Template) ParseFiles

func (t *Template) ParseFiles(filenames ...string) (*Template, error)

ParseFiles parses the named files and associates the resulting templates with t. If an error occurs, parsing stops and the returned template is nil; otherwise it is t. There must be at least one file. Since the templates created by ParseFiles are named by the base names of the argument files, t should usually have the name of one of the (base) names of the files. If it does not, depending on t's contents before calling ParseFiles, t.Execute may fail. In that case use t.ExecuteTemplate to execute a valid template.

+

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

+

func (*Template) ParseGlob

func (t *Template) ParseGlob(pattern string) (*Template, error)

ParseGlob parses the template definitions in the files identified by the pattern and associates the resulting templates with t. The files are matched according to the semantics of filepath.Match, and the pattern must match at least one file. ParseGlob is equivalent to calling t.ParseFiles with the list of files matched by the pattern.

+

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

+

func (*Template) Templates

func (t *Template) Templates() []*Template

Templates returns a slice of defined templates associated with t.

+

Subdirectories

Name Synopsis
..
parse Package parse builds parse trees for templates as defined by text/template and html/template.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/text/template/ +

+
diff --git a/devdocs/go/text%2Ftemplate%2Fparse%2Findex.html b/devdocs/go/text%2Ftemplate%2Fparse%2Findex.html new file mode 100644 index 00000000..d5b46c60 --- /dev/null +++ b/devdocs/go/text%2Ftemplate%2Fparse%2Findex.html @@ -0,0 +1,385 @@ +

Package parse

Overview

Package parse builds parse trees for templates as defined by text/template and html/template. Clients should use those packages to construct templates rather than this one, which provides shared internal data structures not intended for general use.

Index

Package files

lex.go node.go parse.go

func IsEmptyTree

func IsEmptyTree(n Node) bool

IsEmptyTree reports whether this tree (node) is empty of everything but space or comments.

+

func Parse

func Parse(name, text, leftDelim, rightDelim string, funcs ...map[string]any) (map[string]*Tree, error)

Parse returns a map from template name to parse.Tree, created by parsing the templates described in the argument string. The top-level template will be given the specified name. If an error is encountered, parsing stops and an empty map is returned with the error.

+

type ActionNode

ActionNode holds an action (something bounded by delimiters). Control actions have their own nodes; ActionNode represents simple ones such as field evaluations and parenthesized pipelines.

+
type ActionNode struct {
+    NodeType
+    Pos
+
+    Line int       // The line number in the input. Deprecated: Kept for compatibility.
+    Pipe *PipeNode // The pipeline in the action.
+    // contains filtered or unexported fields
+}
+

func (*ActionNode) Copy

func (a *ActionNode) Copy() Node

func (*ActionNode) String

func (a *ActionNode) String() string

type BoolNode

BoolNode holds a boolean constant.

+
type BoolNode struct {
+    NodeType
+    Pos
+
+    True bool // The value of the boolean constant.
+    // contains filtered or unexported fields
+}
+

func (*BoolNode) Copy

func (b *BoolNode) Copy() Node

func (*BoolNode) String

func (b *BoolNode) String() string

type BranchNode

BranchNode is the common representation of if, range, and with.

+
type BranchNode struct {
+    NodeType
+    Pos
+
+    Line     int       // The line number in the input. Deprecated: Kept for compatibility.
+    Pipe     *PipeNode // The pipeline to be evaluated.
+    List     *ListNode // What to execute if the value is non-empty.
+    ElseList *ListNode // What to execute if the value is empty (nil if absent).
+    // contains filtered or unexported fields
+}
+

func (*BranchNode) Copy 1.4

func (b *BranchNode) Copy() Node

func (*BranchNode) String

func (b *BranchNode) String() string

type BreakNode 1.18

BreakNode represents a {{break}} action.

+
type BreakNode struct {
+    NodeType
+    Pos
+    Line int
+    // contains filtered or unexported fields
+}
+

func (*BreakNode) Copy 1.18

func (b *BreakNode) Copy() Node

func (*BreakNode) String 1.18

func (b *BreakNode) String() string

type ChainNode 1.1

ChainNode holds a term followed by a chain of field accesses (identifier starting with '.'). The names may be chained ('.x.y'). The periods are dropped from each ident.

+
type ChainNode struct {
+    NodeType
+    Pos
+
+    Node  Node
+    Field []string // The identifiers in lexical order.
+    // contains filtered or unexported fields
+}
+

func (*ChainNode) Add 1.1

func (c *ChainNode) Add(field string)

Add adds the named field (which should start with a period) to the end of the chain.

+

func (*ChainNode) Copy 1.1

func (c *ChainNode) Copy() Node

func (*ChainNode) String 1.1

func (c *ChainNode) String() string

type CommandNode

CommandNode holds a command (a pipeline inside an evaluating action).

+
type CommandNode struct {
+    NodeType
+    Pos
+
+    Args []Node // Arguments in lexical order: Identifier, field, or constant.
+    // contains filtered or unexported fields
+}
+

func (*CommandNode) Copy

func (c *CommandNode) Copy() Node

func (*CommandNode) String

func (c *CommandNode) String() string

type CommentNode 1.16

CommentNode holds a comment.

+
type CommentNode struct {
+    NodeType
+    Pos
+
+    Text string // Comment text.
+    // contains filtered or unexported fields
+}
+

func (*CommentNode) Copy 1.16

func (c *CommentNode) Copy() Node

func (*CommentNode) String 1.16

func (c *CommentNode) String() string

type ContinueNode 1.18

ContinueNode represents a {{continue}} action.

+
type ContinueNode struct {
+    NodeType
+    Pos
+    Line int
+    // contains filtered or unexported fields
+}
+

func (*ContinueNode) Copy 1.18

func (c *ContinueNode) Copy() Node

func (*ContinueNode) String 1.18

func (c *ContinueNode) String() string

type DotNode

DotNode holds the special identifier '.'.

+
type DotNode struct {
+    NodeType
+    Pos
+    // contains filtered or unexported fields
+}
+

func (*DotNode) Copy

func (d *DotNode) Copy() Node

func (*DotNode) String

func (d *DotNode) String() string

func (*DotNode) Type

func (d *DotNode) Type() NodeType

type FieldNode

FieldNode holds a field (identifier starting with '.'). The names may be chained ('.x.y'). The period is dropped from each ident.

+
type FieldNode struct {
+    NodeType
+    Pos
+
+    Ident []string // The identifiers in lexical order.
+    // contains filtered or unexported fields
+}
+

func (*FieldNode) Copy

func (f *FieldNode) Copy() Node

func (*FieldNode) String

func (f *FieldNode) String() string

type IdentifierNode

IdentifierNode holds an identifier.

+
type IdentifierNode struct {
+    NodeType
+    Pos
+
+    Ident string // The identifier's name.
+    // contains filtered or unexported fields
+}
+

func NewIdentifier

func NewIdentifier(ident string) *IdentifierNode

NewIdentifier returns a new IdentifierNode with the given identifier name.

+

func (*IdentifierNode) Copy

func (i *IdentifierNode) Copy() Node

func (*IdentifierNode) SetPos 1.1

func (i *IdentifierNode) SetPos(pos Pos) *IdentifierNode

SetPos sets the position. NewIdentifier is a public method so we can't modify its signature. Chained for convenience. TODO: fix one day?

+

func (*IdentifierNode) SetTree 1.4

func (i *IdentifierNode) SetTree(t *Tree) *IdentifierNode

SetTree sets the parent tree for the node. NewIdentifier is a public method so we can't modify its signature. Chained for convenience. TODO: fix one day?

+

func (*IdentifierNode) String

func (i *IdentifierNode) String() string

type IfNode

IfNode represents an {{if}} action and its commands.

+
type IfNode struct {
+    BranchNode
+}
+

func (*IfNode) Copy

func (i *IfNode) Copy() Node

type ListNode

ListNode holds a sequence of nodes.

+
type ListNode struct {
+    NodeType
+    Pos
+
+    Nodes []Node // The element nodes in lexical order.
+    // contains filtered or unexported fields
+}
+

func (*ListNode) Copy

func (l *ListNode) Copy() Node

func (*ListNode) CopyList

func (l *ListNode) CopyList() *ListNode

func (*ListNode) String

func (l *ListNode) String() string

type Mode 1.16

A mode value is a set of flags (or 0). Modes control parser behavior.

+
type Mode uint
const (
+    ParseComments Mode = 1 << iota // parse comments and add them to AST
+    SkipFuncCheck                  // do not check that functions are defined
+)

type NilNode 1.1

NilNode holds the special identifier 'nil' representing an untyped nil constant.

+
type NilNode struct {
+    NodeType
+    Pos
+    // contains filtered or unexported fields
+}
+

func (*NilNode) Copy 1.1

func (n *NilNode) Copy() Node

func (*NilNode) String 1.1

func (n *NilNode) String() string

func (*NilNode) Type 1.1

func (n *NilNode) Type() NodeType

type Node

A Node is an element in the parse tree. The interface is trivial. The interface contains an unexported method so that only types local to this package can satisfy it.

+
type Node interface {
+    Type() NodeType
+    String() string
+    // Copy does a deep copy of the Node and all its components.
+    // To avoid type assertions, some XxxNodes also have specialized
+    // CopyXxx methods that return *XxxNode.
+    Copy() Node
+    Position() Pos // byte position of start of node in full original input string
+    // contains filtered or unexported methods
+}

type NodeType

NodeType identifies the type of a parse tree node.

+
type NodeType int
const (
+    NodeText    NodeType = iota // Plain text.
+    NodeAction                  // A non-control action such as a field evaluation.
+    NodeBool                    // A boolean constant.
+    NodeChain                   // A sequence of field accesses.
+    NodeCommand                 // An element of a pipeline.
+    NodeDot                     // The cursor, dot.
+
+    NodeField      // A field or method name.
+    NodeIdentifier // An identifier; always a function name.
+    NodeIf         // An if action.
+    NodeList       // A list of Nodes.
+    NodeNil        // An untyped nil constant.
+    NodeNumber     // A numerical constant.
+    NodePipe       // A pipeline of commands.
+    NodeRange      // A range action.
+    NodeString     // A string constant.
+    NodeTemplate   // A template invocation action.
+    NodeVariable   // A $ variable.
+    NodeWith       // A with action.
+    NodeComment    // A comment.
+    NodeBreak      // A break action.
+    NodeContinue   // A continue action.
+)

func (NodeType) Type

func (t NodeType) Type() NodeType

Type returns itself and provides an easy default implementation for embedding in a Node. Embedded in all non-trivial Nodes.

+

type NumberNode

NumberNode holds a number: signed or unsigned integer, float, or complex. The value is parsed and stored under all the types that can represent the value. This simulates in a small amount of code the behavior of Go's ideal constants.

+
type NumberNode struct {
+    NodeType
+    Pos
+
+    IsInt      bool       // Number has an integral value.
+    IsUint     bool       // Number has an unsigned integral value.
+    IsFloat    bool       // Number has a floating-point value.
+    IsComplex  bool       // Number is complex.
+    Int64      int64      // The signed integer value.
+    Uint64     uint64     // The unsigned integer value.
+    Float64    float64    // The floating-point value.
+    Complex128 complex128 // The complex value.
+    Text       string     // The original textual representation from the input.
+    // contains filtered or unexported fields
+}
+

func (*NumberNode) Copy

func (n *NumberNode) Copy() Node

func (*NumberNode) String

func (n *NumberNode) String() string

type PipeNode

PipeNode holds a pipeline with optional declaration

+
type PipeNode struct {
+    NodeType
+    Pos
+
+    Line     int             // The line number in the input. Deprecated: Kept for compatibility.
+    IsAssign bool            // The variables are being assigned, not declared; added in Go 1.11
+    Decl     []*VariableNode // Variables in lexical order.
+    Cmds     []*CommandNode  // The commands in lexical order.
+    // contains filtered or unexported fields
+}
+

func (*PipeNode) Copy

func (p *PipeNode) Copy() Node

func (*PipeNode) CopyPipe

func (p *PipeNode) CopyPipe() *PipeNode

func (*PipeNode) String

func (p *PipeNode) String() string

type Pos 1.1

Pos represents a byte position in the original input text from which this template was parsed.

+
type Pos int

func (Pos) Position 1.1

func (p Pos) Position() Pos

type RangeNode

RangeNode represents a {{range}} action and its commands.

+
type RangeNode struct {
+    BranchNode
+}
+

func (*RangeNode) Copy

func (r *RangeNode) Copy() Node

type StringNode

StringNode holds a string constant. The value has been "unquoted".

+
type StringNode struct {
+    NodeType
+    Pos
+
+    Quoted string // The original text of the string, with quotes.
+    Text   string // The string, after quote processing.
+    // contains filtered or unexported fields
+}
+

func (*StringNode) Copy

func (s *StringNode) Copy() Node

func (*StringNode) String

func (s *StringNode) String() string

type TemplateNode

TemplateNode represents a {{template}} action.

+
type TemplateNode struct {
+    NodeType
+    Pos
+
+    Line int       // The line number in the input. Deprecated: Kept for compatibility.
+    Name string    // The name of the template (unquoted).
+    Pipe *PipeNode // The command to evaluate as dot for the template.
+    // contains filtered or unexported fields
+}
+

func (*TemplateNode) Copy

func (t *TemplateNode) Copy() Node

func (*TemplateNode) String

func (t *TemplateNode) String() string

type TextNode

TextNode holds plain text.

+
type TextNode struct {
+    NodeType
+    Pos
+
+    Text []byte // The text; may span newlines.
+    // contains filtered or unexported fields
+}
+

func (*TextNode) Copy

func (t *TextNode) Copy() Node

func (*TextNode) String

func (t *TextNode) String() string

type Tree

Tree is the representation of a single parsed template.

+
type Tree struct {
+    Name      string    // name of the template represented by the tree.
+    ParseName string    // name of the top-level template during parsing, for error messages; added in Go 1.1
+    Root      *ListNode // top-level root of the tree.
+    Mode      Mode      // parsing mode; added in Go 1.16
+    // contains filtered or unexported fields
+}
+

func New

func New(name string, funcs ...map[string]any) *Tree

New allocates a new parse tree with the given name.

+

func (*Tree) Copy 1.2

func (t *Tree) Copy() *Tree

Copy returns a copy of the Tree. Any parsing state is discarded.

+

func (*Tree) ErrorContext 1.1

func (t *Tree) ErrorContext(n Node) (location, context string)

ErrorContext returns a textual representation of the location of the node in the input text. The receiver is only used when the node does not have a pointer to the tree inside, which can occur in old code.

+

func (*Tree) Parse

func (t *Tree) Parse(text, leftDelim, rightDelim string, treeSet map[string]*Tree, funcs ...map[string]any) (tree *Tree, err error)

Parse parses the template definition string to construct a representation of the template for execution. If either action delimiter string is empty, the default ("{{" or "}}") is used. Embedded template definitions are added to the treeSet map.

+

type VariableNode

VariableNode holds a list of variable names, possibly with chained field accesses. The dollar sign is part of the (first) name.

+
type VariableNode struct {
+    NodeType
+    Pos
+
+    Ident []string // Variable name and fields in lexical order.
+    // contains filtered or unexported fields
+}
+

func (*VariableNode) Copy

func (v *VariableNode) Copy() Node

func (*VariableNode) String

func (v *VariableNode) String() string

type WithNode

WithNode represents a {{with}} action and its commands.

+
type WithNode struct {
+    BranchNode
+}
+

func (*WithNode) Copy

func (w *WithNode) Copy() Node
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/text/template/parse/ +

+
diff --git a/devdocs/go/time%2Findex.html b/devdocs/go/time%2Findex.html new file mode 100644 index 00000000..3bced765 --- /dev/null +++ b/devdocs/go/time%2Findex.html @@ -0,0 +1,1035 @@ +

Package time

Overview

Package time provides functionality for measuring and displaying time.

+

The calendrical calculations always assume a Gregorian calendar, with no leap seconds.

+

Monotonic Clocks

Operating systems provide both a “wall clock,” which is subject to changes for clock synchronization, and a “monotonic clock,” which is not. The general rule is that the wall clock is for telling time and the monotonic clock is for measuring time. Rather than split the API, in this package the Time returned by time.Now contains both a wall clock reading and a monotonic clock reading; later time-telling operations use the wall clock reading, but later time-measuring operations, specifically comparisons and subtractions, use the monotonic clock reading.

+

For example, this code always computes a positive elapsed time of approximately 20 milliseconds, even if the wall clock is changed during the operation being timed:

+
start := time.Now()
+... operation that takes 20 milliseconds ...
+t := time.Now()
+elapsed := t.Sub(start)
+

Other idioms, such as time.Since(start), time.Until(deadline), and time.Now().Before(deadline), are similarly robust against wall clock resets.

+

The rest of this section gives the precise details of how operations use monotonic clocks, but understanding those details is not required to use this package.

+

The Time returned by time.Now contains a monotonic clock reading. If Time t has a monotonic clock reading, t.Add adds the same duration to both the wall clock and monotonic clock readings to compute the result. Because t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time computations, they always strip any monotonic clock reading from their results. Because t.In, t.Local, and t.UTC are used for their effect on the interpretation of the wall time, they also strip any monotonic clock reading from their results. The canonical way to strip a monotonic clock reading is to use t = t.Round(0).

+

If Times t and u both contain monotonic clock readings, the operations t.After(u), t.Before(u), t.Equal(u), t.Compare(u), and t.Sub(u) are carried out using the monotonic clock readings alone, ignoring the wall clock readings. If either t or u contains no monotonic clock reading, these operations fall back to using the wall clock readings.

+

On some systems the monotonic clock will stop if the computer goes to sleep. On such a system, t.Sub(u) may not accurately reflect the actual time that passed between t and u.

+

Because the monotonic clock reading has no meaning outside the current process, the serialized forms generated by t.GobEncode, t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic clock reading, and t.Format provides no format for it. Similarly, the constructors time.Date, time.Parse, time.ParseInLocation, and time.Unix, as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. t.UnmarshalJSON, and t.UnmarshalText always create times with no monotonic clock reading.

+

The monotonic clock reading exists only in Time values. It is not a part of Duration values or the Unix times returned by t.Unix and friends.

+

Note that the Go == operator compares not just the time instant but also the Location and the monotonic clock reading. See the documentation for the Time type for a discussion of equality testing for Time values.

+

For debugging, the result of t.String does include the monotonic clock reading if present. If t != u because of different monotonic clock readings, that difference will be visible when printing t.String() and u.String().

+

Timer Resolution

Timer resolution varies depending on the Go runtime, the operating system and the underlying hardware. On Unix, the resolution is approximately 1ms. On Windows, the default resolution is approximately 16ms, but a higher resolution may be requested using golang.org/x/sys/windows.TimeBeginPeriod.

Index

Examples

After
Date
Duration
Duration.Hours
Duration.Microseconds
Duration.Milliseconds
Duration.Minutes
Duration.Nanoseconds
Duration.Round
Duration.Seconds
Duration.String
Duration.Truncate
FixedZone
LoadLocation
Location
Month
NewTicker
Parse
ParseDuration
ParseInLocation
Sleep
Tick
Time.Add
Time.AddDate
Time.After
Time.AppendFormat
Time.Before
Time.Date
Time.Day
Time.Equal
Time.Format
Time.Format (Pad)
Time.GoString
Time.Round
Time.String
Time.Sub
Time.Truncate
Time.Unix
Unix
UnixMicro
UnixMilli

Package files

format.go format_rfc3339.go sleep.go sys_unix.go tick.go time.go zoneinfo.go zoneinfo_goroot.go zoneinfo_read.go zoneinfo_unix.go

Constants

These are predefined layouts for use in Time.Format and time.Parse. The reference time used in these layouts is the specific time stamp:

+
01/02 03:04:05PM '06 -0700
+

(January 2, 15:04:05, 2006, in time zone seven hours west of GMT). That value is recorded as the constant named Layout, listed below. As a Unix time, this is 1136239445. Since MST is GMT-0700, the reference would be printed by the Unix date command as:

+
Mon Jan 2 15:04:05 MST 2006
+

It is a regrettable historic error that the date uses the American convention of putting the numerical month before the day.

+

The example for Time.Format demonstrates the working of the layout string in detail and is a good reference.

+

Note that the RFC822, RFC850, and RFC1123 formats should be applied only to local times. Applying them to UTC times will use "UTC" as the time zone abbreviation, while strictly speaking those RFCs require the use of "GMT" in that case. In general RFC1123Z should be used instead of RFC1123 for servers that insist on that format, and RFC3339 should be preferred for new protocols. RFC3339, RFC822, RFC822Z, RFC1123, and RFC1123Z are useful for formatting; when used with time.Parse they do not accept all the time formats permitted by the RFCs and they do accept time formats not formally defined. The RFC3339Nano format removes trailing zeros from the seconds field and thus may not sort correctly once formatted.

+

Most programs can use one of the defined constants as the layout passed to Format or Parse. The rest of this comment can be ignored unless you are creating a custom layout string.

+

To define your own format, write down what the reference time would look like formatted your way; see the values of constants like ANSIC, StampMicro or Kitchen for examples. The model is to demonstrate what the reference time looks like so that the Format and Parse methods can apply the same transformation to a general time value.

+

Here is a summary of the components of a layout string. Each element shows by example the formatting of an element of the reference time. Only these values are recognized. Text in the layout string that is not recognized as part of the reference time is echoed verbatim during Format and expected to appear verbatim in the input to Parse.

+
Year: "2006" "06"
+Month: "Jan" "January" "01" "1"
+Day of the week: "Mon" "Monday"
+Day of the month: "2" "_2" "02"
+Day of the year: "__2" "002"
+Hour: "15" "3" "03" (PM or AM)
+Minute: "4" "04"
+Second: "5" "05"
+AM/PM mark: "PM"
+

Numeric time zone offsets format as follows:

+
"-0700"     ±hhmm
+"-07:00"    ±hh:mm
+"-07"       ±hh
+"-070000"   ±hhmmss
+"-07:00:00" ±hh:mm:ss
+

Replacing the sign in the format with a Z triggers the ISO 8601 behavior of printing Z instead of an offset for the UTC zone. Thus:

+
"Z0700"      Z or ±hhmm
+"Z07:00"     Z or ±hh:mm
+"Z07"        Z or ±hh
+"Z070000"    Z or ±hhmmss
+"Z07:00:00"  Z or ±hh:mm:ss
+

Within the format string, the underscores in "_2" and "__2" represent spaces that may be replaced by digits if the following number has multiple digits, for compatibility with fixed-width Unix time formats. A leading zero represents a zero-padded value.

+

The formats __2 and 002 are space-padded and zero-padded three-character day of year; there is no unpadded day of year format.

+

A comma or decimal point followed by one or more zeros represents a fractional second, printed to the given number of decimal places. A comma or decimal point followed by one or more nines represents a fractional second, printed to the given number of decimal places, with trailing zeros removed. For example "15:04:05,000" or "15:04:05.000" formats or parses with millisecond precision.

+

Some valid layouts are invalid time values for time.Parse, due to formats such as _ for space padding and Z for zone information.

+
const (
+    Layout      = "01/02 03:04:05PM '06 -0700" // The reference time, in numerical order.
+    ANSIC       = "Mon Jan _2 15:04:05 2006"
+    UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
+    RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
+    RFC822      = "02 Jan 06 15:04 MST"
+    RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
+    RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
+    RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
+    RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
+    RFC3339     = "2006-01-02T15:04:05Z07:00"
+    RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
+    Kitchen     = "3:04PM"
+    // Handy time stamps.
+    Stamp      = "Jan _2 15:04:05"
+    StampMilli = "Jan _2 15:04:05.000"
+    StampMicro = "Jan _2 15:04:05.000000"
+    StampNano  = "Jan _2 15:04:05.000000000"
+    DateTime   = "2006-01-02 15:04:05"
+    DateOnly   = "2006-01-02"
+    TimeOnly   = "15:04:05"
+)

Common durations. There is no definition for units of Day or larger to avoid confusion across daylight savings time zone transitions.

+

To count the number of units in a Duration, divide:

+
second := time.Second
+fmt.Print(int64(second/time.Millisecond)) // prints 1000
+

To convert an integer number of units to a Duration, multiply:

+
seconds := 10
+fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
+
const (
+    Nanosecond  Duration = 1
+    Microsecond          = 1000 * Nanosecond
+    Millisecond          = 1000 * Microsecond
+    Second               = 1000 * Millisecond
+    Minute               = 60 * Second
+    Hour                 = 60 * Minute
+)

func After

func After(d Duration) <-chan Time

After waits for the duration to elapse and then sends the current time on the returned channel. It is equivalent to NewTimer(d).C. The underlying Timer is not recovered by the garbage collector until the timer fires. If efficiency is a concern, use NewTimer instead and call Timer.Stop if the timer is no longer needed.

Example +

Code:

+select {
+case m := <-c:
+    handle(m)
+case <-time.After(10 * time.Second):
+    fmt.Println("timed out")
+}
+

func Sleep

func Sleep(d Duration)

Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately.

Example +

Code:

+time.Sleep(100 * time.Millisecond)
+

func Tick

func Tick(d Duration) <-chan Time

Tick is a convenience wrapper for NewTicker providing access to the ticking channel only. While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks". Unlike NewTicker, Tick will return nil if d <= 0.

Example +

Code:

+c := time.Tick(5 * time.Second)
+for next := range c {
+    fmt.Printf("%v %s\n", next, statusUpdate())
+}
+

type Duration

A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years.

+
type Duration int64

Example +

Code:

+t0 := time.Now()
+expensiveCall()
+t1 := time.Now()
+fmt.Printf("The call took %v to run.\n", t1.Sub(t0))
+

func ParseDuration

func ParseDuration(s string) (Duration, error)

ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

Example +

Code:

hours, _ := time.ParseDuration("10h")
+complex, _ := time.ParseDuration("1h10m10s")
+micro, _ := time.ParseDuration("1µs")
+// The package also accepts the incorrect but common prefix u for micro.
+micro2, _ := time.ParseDuration("1us")
+
+fmt.Println(hours)
+fmt.Println(complex)
+fmt.Printf("There are %.0f seconds in %v.\n", complex.Seconds(), complex)
+fmt.Printf("There are %d nanoseconds in %v.\n", micro.Nanoseconds(), micro)
+fmt.Printf("There are %6.2e seconds in %v.\n", micro2.Seconds(), micro)
+

Output:

10h0m0s
+1h10m10s
+There are 4210 seconds in 1h10m10s.
+There are 1000 nanoseconds in 1µs.
+There are 1.00e-06 seconds in 1µs.
+

func Since

func Since(t Time) Duration

Since returns the time elapsed since t. It is shorthand for time.Now().Sub(t).

+

func Until 1.8

func Until(t Time) Duration

Until returns the duration until t. It is shorthand for t.Sub(time.Now()).

+

func (Duration) Abs 1.19

func (d Duration) Abs() Duration

Abs returns the absolute value of d. As a special case, math.MinInt64 is converted to math.MaxInt64.

+

func (Duration) Hours

func (d Duration) Hours() float64

Hours returns the duration as a floating point number of hours.

Example +

Code:

h, _ := time.ParseDuration("4h30m")
+fmt.Printf("I've got %.1f hours of work left.", h.Hours())
+

Output:

I've got 4.5 hours of work left.
+

func (Duration) Microseconds 1.13

func (d Duration) Microseconds() int64

Microseconds returns the duration as an integer microsecond count.

Example +

Code:

u, _ := time.ParseDuration("1s")
+fmt.Printf("One second is %d microseconds.\n", u.Microseconds())
+

Output:

One second is 1000000 microseconds.
+

func (Duration) Milliseconds 1.13

func (d Duration) Milliseconds() int64

Milliseconds returns the duration as an integer millisecond count.

Example +

Code:

u, _ := time.ParseDuration("1s")
+fmt.Printf("One second is %d milliseconds.\n", u.Milliseconds())
+

Output:

One second is 1000 milliseconds.
+

func (Duration) Minutes

func (d Duration) Minutes() float64

Minutes returns the duration as a floating point number of minutes.

Example +

Code:

m, _ := time.ParseDuration("1h30m")
+fmt.Printf("The movie is %.0f minutes long.", m.Minutes())
+

Output:

The movie is 90 minutes long.
+

func (Duration) Nanoseconds

func (d Duration) Nanoseconds() int64

Nanoseconds returns the duration as an integer nanosecond count.

Example +

Code:

u, _ := time.ParseDuration("1µs")
+fmt.Printf("One microsecond is %d nanoseconds.\n", u.Nanoseconds())
+

Output:

One microsecond is 1000 nanoseconds.
+

func (Duration) Round 1.9

func (d Duration) Round(m Duration) Duration

Round returns the result of rounding d to the nearest multiple of m. The rounding behavior for halfway values is to round away from zero. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, Round returns the maximum (or minimum) duration. If m <= 0, Round returns d unchanged.

Example +

Code:

d, err := time.ParseDuration("1h15m30.918273645s")
+if err != nil {
+    panic(err)
+}
+
+round := []time.Duration{
+    time.Nanosecond,
+    time.Microsecond,
+    time.Millisecond,
+    time.Second,
+    2 * time.Second,
+    time.Minute,
+    10 * time.Minute,
+    time.Hour,
+}
+
+for _, r := range round {
+    fmt.Printf("d.Round(%6s) = %s\n", r, d.Round(r).String())
+}
+

Output:

d.Round(   1ns) = 1h15m30.918273645s
+d.Round(   1µs) = 1h15m30.918274s
+d.Round(   1ms) = 1h15m30.918s
+d.Round(    1s) = 1h15m31s
+d.Round(    2s) = 1h15m30s
+d.Round(  1m0s) = 1h16m0s
+d.Round( 10m0s) = 1h20m0s
+d.Round(1h0m0s) = 1h0m0s
+

func (Duration) Seconds

func (d Duration) Seconds() float64

Seconds returns the duration as a floating point number of seconds.

Example +

Code:

m, _ := time.ParseDuration("1m30s")
+fmt.Printf("Take off in t-%.0f seconds.", m.Seconds())
+

Output:

Take off in t-90 seconds.
+

func (Duration) String

func (d Duration) String() string

String returns a string representing the duration in the form "72h3m0.5s". Leading zero units are omitted. As a special case, durations less than one second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure that the leading digit is non-zero. The zero duration formats as 0s.

Example +

Code:

fmt.Println(1*time.Hour + 2*time.Minute + 300*time.Millisecond)
+fmt.Println(300 * time.Millisecond)
+

Output:

1h2m0.3s
+300ms
+

func (Duration) Truncate 1.9

func (d Duration) Truncate(m Duration) Duration

Truncate returns the result of rounding d toward zero to a multiple of m. If m <= 0, Truncate returns d unchanged.

Example +

Code:

d, err := time.ParseDuration("1h15m30.918273645s")
+if err != nil {
+    panic(err)
+}
+
+trunc := []time.Duration{
+    time.Nanosecond,
+    time.Microsecond,
+    time.Millisecond,
+    time.Second,
+    2 * time.Second,
+    time.Minute,
+    10 * time.Minute,
+    time.Hour,
+}
+
+for _, t := range trunc {
+    fmt.Printf("d.Truncate(%6s) = %s\n", t, d.Truncate(t).String())
+}
+

Output:

d.Truncate(   1ns) = 1h15m30.918273645s
+d.Truncate(   1µs) = 1h15m30.918273s
+d.Truncate(   1ms) = 1h15m30.918s
+d.Truncate(    1s) = 1h15m30s
+d.Truncate(    2s) = 1h15m30s
+d.Truncate(  1m0s) = 1h15m0s
+d.Truncate( 10m0s) = 1h10m0s
+d.Truncate(1h0m0s) = 1h0m0s
+

type Location

A Location maps time instants to the zone in use at that time. Typically, the Location represents the collection of time offsets in use in a geographical area. For many Locations the time offset varies depending on whether daylight savings time is in use at the time instant.

+

Location is used to provide a time zone in a printed Time value and for calculations involving intervals that may cross daylight savings time boundaries.

+
type Location struct {
+    // contains filtered or unexported fields
+}
+

Local represents the system's local time zone. On Unix systems, Local consults the TZ environment variable to find the time zone to use. No TZ means use the system default /etc/localtime. TZ="" means use UTC. TZ="foo" means use file foo in the system timezone directory.

+
var Local *Location = &localLoc

UTC represents Universal Coordinated Time (UTC).

+
var UTC *Location = &utcLoc

Example +

Code:

// China doesn't have daylight saving. It uses a fixed 8 hour offset from UTC.
+secondsEastOfUTC := int((8 * time.Hour).Seconds())
+beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
+
+// If the system has a timezone database present, it's possible to load a location
+// from that, e.g.:
+//    newYork, err := time.LoadLocation("America/New_York")
+
+// Creating a time requires a location. Common locations are time.Local and time.UTC.
+timeInUTC := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
+sameTimeInBeijing := time.Date(2009, 1, 1, 20, 0, 0, 0, beijing)
+
+// Although the UTC clock time is 1200 and the Beijing clock time is 2000, Beijing is
+// 8 hours ahead so the two dates actually represent the same instant.
+timesAreEqual := timeInUTC.Equal(sameTimeInBeijing)
+fmt.Println(timesAreEqual)
+
+

Output:

true
+

func FixedZone

func FixedZone(name string, offset int) *Location

FixedZone returns a Location that always uses the given zone name and offset (seconds east of UTC).

Example +

Code:

loc := time.FixedZone("UTC-8", -8*60*60)
+t := time.Date(2009, time.November, 10, 23, 0, 0, 0, loc)
+fmt.Println("The time is:", t.Format(time.RFC822))
+

Output:

The time is: 10 Nov 09 23:00 UTC-8
+

func LoadLocation

func LoadLocation(name string) (*Location, error)

LoadLocation returns the Location with the given name.

+

If the name is "" or "UTC", LoadLocation returns UTC. If the name is "Local", LoadLocation returns Local.

+

Otherwise, the name is taken to be a location name corresponding to a file in the IANA Time Zone database, such as "America/New_York".

+

LoadLocation looks for the IANA Time Zone database in the following locations in order:

+

Example +

Code:

location, err := time.LoadLocation("America/Los_Angeles")
+if err != nil {
+    panic(err)
+}
+
+timeInUTC := time.Date(2018, 8, 30, 12, 0, 0, 0, time.UTC)
+fmt.Println(timeInUTC.In(location))
+

Output:

2018-08-30 05:00:00 -0700 PDT
+

func LoadLocationFromTZData 1.10

func LoadLocationFromTZData(name string, data []byte) (*Location, error)

LoadLocationFromTZData returns a Location with the given name initialized from the IANA Time Zone database-formatted data. The data should be in the format of a standard IANA time zone file (for example, the content of /etc/localtime on Unix systems).

+

func (*Location) String

func (l *Location) String() string

String returns a descriptive name for the time zone information, corresponding to the name argument to LoadLocation or FixedZone.

+

type Month

A Month specifies a month of the year (January = 1, ...).

+
type Month int
const (
+    January Month = 1 + iota
+    February
+    March
+    April
+    May
+    June
+    July
+    August
+    September
+    October
+    November
+    December
+)

Example +

Code:

+_, month, day := time.Now().Date()
+if month == time.November && day == 10 {
+    fmt.Println("Happy Go day!")
+}
+

func (Month) String

func (m Month) String() string

String returns the English name of the month ("January", "February", ...).

+

type ParseError

ParseError describes a problem parsing a time string.

+
type ParseError struct {
+    Layout     string
+    Value      string
+    LayoutElem string
+    ValueElem  string
+    Message    string
+}
+

func (*ParseError) Error

func (e *ParseError) Error() string

Error returns the string representation of a ParseError.

+

type Ticker

A Ticker holds a channel that delivers “ticks” of a clock at intervals.

+
type Ticker struct {
+    C <-chan Time // The channel on which the ticks are delivered.
+    // contains filtered or unexported fields
+}
+

func NewTicker

func NewTicker(d Duration) *Ticker

NewTicker returns a new Ticker containing a channel that will send the current time on the channel after each tick. The period of the ticks is specified by the duration argument. The ticker will adjust the time interval or drop ticks to make up for slow receivers. The duration d must be greater than zero; if not, NewTicker will panic. Stop the ticker to release associated resources.

Example +

Code:

+ticker := time.NewTicker(time.Second)
+defer ticker.Stop()
+done := make(chan bool)
+go func() {
+    time.Sleep(10 * time.Second)
+    done <- true
+}()
+for {
+    select {
+    case <-done:
+        fmt.Println("Done!")
+        return
+    case t := <-ticker.C:
+        fmt.Println("Current time: ", t)
+    }
+}
+

func (*Ticker) Reset 1.15

func (t *Ticker) Reset(d Duration)

Reset stops a ticker and resets its period to the specified duration. The next tick will arrive after the new period elapses. The duration d must be greater than zero; if not, Reset will panic.

+

func (*Ticker) Stop

func (t *Ticker) Stop()

Stop turns off a ticker. After Stop, no more ticks will be sent. Stop does not close the channel, to prevent a concurrent goroutine reading from the channel from seeing an erroneous "tick".

+

type Time

A Time represents an instant in time with nanosecond precision.

+

Programs using times should typically store and pass them as values, not pointers. That is, time variables and struct fields should be of type time.Time, not *time.Time.

+

A Time value can be used by multiple goroutines simultaneously except that the methods GobDecode, UnmarshalBinary, UnmarshalJSON and UnmarshalText are not concurrency-safe.

+

Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.

+

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. As this time is unlikely to come up in practice, the IsZero method gives a simple way of detecting a time that has not been initialized explicitly.

+

Each time has an associated Location. The methods Local, UTC, and In return a Time with a specific Location. Changing the Location of a Time value with these methods does not change the actual instant it represents, only the time zone in which to interpret it.

+

Representations of a Time value saved by the GobEncode, MarshalBinary, MarshalJSON, and MarshalText methods store the Time.Location's offset, but not the location name. They therefore lose information about Daylight Saving Time.

+

In addition to the required “wall clock” reading, a Time may contain an optional reading of the current process's monotonic clock, to provide additional precision for comparison or subtraction. See the “Monotonic Clocks” section in the package documentation for details.

+

Note that the Go == operator compares not just the time instant but also the Location and the monotonic clock reading. Therefore, Time values should not be used as map or database keys without first guaranteeing that the identical Location has been set for all values, which can be achieved through use of the UTC or Local method, and that the monotonic clock reading has been stripped by setting t = t.Round(0). In general, prefer t.Equal(u) to t == u, since t.Equal uses the most accurate comparison available and correctly handles the case when only one of its arguments has a monotonic clock reading.

+
type Time struct {
+    // contains filtered or unexported fields
+}
+

func Date

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

Date returns the Time corresponding to

+
yyyy-mm-dd hh:mm:ss + nsec nanoseconds
+

in the appropriate zone for that time in the given location.

+

The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.

+

A daylight savings time transition skips or repeats times. For example, in the United States, March 13, 2011 2:15am never occurred, while November 6, 2011 1:15am occurred twice. In such cases, the choice of time zone, and therefore the time, is not well-defined. Date returns a time that is correct in one of the two zones involved in the transition, but it does not guarantee which.

+

Date panics if loc is nil.

Example +

Code:

t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
+fmt.Printf("Go launched at %s\n", t.Local())
+

Output:

Go launched at 2009-11-10 15:00:00 -0800 PST
+

func Now

func Now() Time

Now returns the current local time.

+

func Parse

func Parse(layout, value string) (Time, error)

Parse parses a formatted string and returns the time value it represents. See the documentation for the constant called Layout to see how to represent the format. The second argument must be parseable using the format string (layout) provided as the first argument.

+

The example for Time.Format demonstrates the working of the layout string in detail and is a good reference.

+

When parsing (only), the input may contain a fractional second field immediately after the seconds field, even if the layout does not signify its presence. In that case either a comma or a decimal point followed by a maximal series of digits is parsed as a fractional second. Fractional seconds are truncated to nanosecond precision.

+

Elements omitted from the layout are assumed to be zero or, when zero is impossible, one, so parsing "3:04pm" returns the time corresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is 0, this time is before the zero Time). Years must be in the range 0000..9999. The day of the week is checked for syntax but it is otherwise ignored.

+

For layouts specifying the two-digit year 06, a value NN >= 69 will be treated as 19NN and a value NN < 69 will be treated as 20NN.

+

The remainder of this comment describes the handling of time zones.

+

In the absence of a time zone indicator, Parse returns a time in UTC.

+

When parsing a time with a zone offset like -0700, if the offset corresponds to a time zone used by the current location (Local), then Parse uses that location and zone in the returned time. Otherwise it records the time as being in a fabricated location with time fixed at the given zone offset.

+

When parsing a time with a zone abbreviation like MST, if the zone abbreviation has a defined offset in the current location, then that offset is used. The zone abbreviation "UTC" is recognized as UTC regardless of location. If the zone abbreviation is unknown, Parse records the time as being in a fabricated location with the given zone abbreviation and a zero offset. This choice means that such a time can be parsed and reformatted with the same layout losslessly, but the exact instant used in the representation will differ by the actual zone offset. To avoid such problems, prefer time layouts that use a numeric zone offset, or use ParseInLocation.

Example +

Code:

// See the example for Time.Format for a thorough description of how
+// to define the layout string to parse a time.Time value; Parse and
+// Format use the same model to describe their input and output.
+
+// longForm shows by example how the reference time would be represented in
+// the desired layout.
+const longForm = "Jan 2, 2006 at 3:04pm (MST)"
+t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
+fmt.Println(t)
+
+// shortForm is another way the reference time would be represented
+// in the desired layout; it has no time zone present.
+// Note: without explicit zone, returns time in UTC.
+const shortForm = "2006-Jan-02"
+t, _ = time.Parse(shortForm, "2013-Feb-03")
+fmt.Println(t)
+
+// Some valid layouts are invalid time values, due to format specifiers
+// such as _ for space padding and Z for zone information.
+// For example the RFC3339 layout 2006-01-02T15:04:05Z07:00
+// contains both Z and a time zone offset in order to handle both valid options:
+// 2006-01-02T15:04:05Z
+// 2006-01-02T15:04:05+07:00
+t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
+fmt.Println(t)
+t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05+07:00")
+fmt.Println(t)
+_, err := time.Parse(time.RFC3339, time.RFC3339)
+fmt.Println("error", err) // Returns an error as the layout is not a valid time value
+
+

Output:

2013-02-03 19:54:00 -0800 PST
+2013-02-03 00:00:00 +0000 UTC
+2006-01-02 15:04:05 +0000 UTC
+2006-01-02 15:04:05 +0700 +0700
+error parsing time "2006-01-02T15:04:05Z07:00": extra text: "07:00"
+

func ParseInLocation 1.1

func ParseInLocation(layout, value string, loc *Location) (Time, error)

ParseInLocation is like Parse but differs in two important ways. First, in the absence of time zone information, Parse interprets a time as UTC; ParseInLocation interprets the time as in the given location. Second, when given a zone offset or abbreviation, Parse tries to match it against the Local location; ParseInLocation uses the given location.

Example +

Code:

loc, _ := time.LoadLocation("Europe/Berlin")
+
+// This will look for the name CEST in the Europe/Berlin time zone.
+const longForm = "Jan 2, 2006 at 3:04pm (MST)"
+t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
+fmt.Println(t)
+
+// Note: without explicit zone, returns time in given location.
+const shortForm = "2006-Jan-02"
+t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
+fmt.Println(t)
+
+

Output:

2012-07-09 05:02:00 +0200 CEST
+2012-07-09 00:00:00 +0200 CEST
+

func Unix

func Unix(sec int64, nsec int64) Time

Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC. It is valid to pass nsec outside the range [0, 999999999]. Not all sec values have a corresponding time value. One such value is 1<<63-1 (the largest int64 value).

Example +

Code:

unixTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
+fmt.Println(unixTime.Unix())
+t := time.Unix(unixTime.Unix(), 0).UTC()
+fmt.Println(t)
+
+

Output:

1257894000
+2009-11-10 23:00:00 +0000 UTC
+

func UnixMicro 1.17

func UnixMicro(usec int64) Time

UnixMicro returns the local Time corresponding to the given Unix time, usec microseconds since January 1, 1970 UTC.

Example +

Code:

umt := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
+fmt.Println(umt.UnixMicro())
+t := time.UnixMicro(umt.UnixMicro()).UTC()
+fmt.Println(t)
+
+

Output:

1257894000000000
+2009-11-10 23:00:00 +0000 UTC
+

func UnixMilli 1.17

func UnixMilli(msec int64) Time

UnixMilli returns the local Time corresponding to the given Unix time, msec milliseconds since January 1, 1970 UTC.

Example +

Code:

umt := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
+fmt.Println(umt.UnixMilli())
+t := time.UnixMilli(umt.UnixMilli()).UTC()
+fmt.Println(t)
+
+

Output:

1257894000000
+2009-11-10 23:00:00 +0000 UTC
+

func (Time) Add

func (t Time) Add(d Duration) Time

Add returns the time t+d.

Example +

Code:

start := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
+afterTenSeconds := start.Add(time.Second * 10)
+afterTenMinutes := start.Add(time.Minute * 10)
+afterTenHours := start.Add(time.Hour * 10)
+afterTenDays := start.Add(time.Hour * 24 * 10)
+
+fmt.Printf("start = %v\n", start)
+fmt.Printf("start.Add(time.Second * 10) = %v\n", afterTenSeconds)
+fmt.Printf("start.Add(time.Minute * 10) = %v\n", afterTenMinutes)
+fmt.Printf("start.Add(time.Hour * 10) = %v\n", afterTenHours)
+fmt.Printf("start.Add(time.Hour * 24 * 10) = %v\n", afterTenDays)
+
+

Output:

start = 2009-01-01 12:00:00 +0000 UTC
+start.Add(time.Second * 10) = 2009-01-01 12:00:10 +0000 UTC
+start.Add(time.Minute * 10) = 2009-01-01 12:10:00 +0000 UTC
+start.Add(time.Hour * 10) = 2009-01-01 22:00:00 +0000 UTC
+start.Add(time.Hour * 24 * 10) = 2009-01-11 12:00:00 +0000 UTC
+

func (Time) AddDate

func (t Time) AddDate(years int, months int, days int) Time

AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.

+

Note that dates are fundamentally coupled to timezones, and calendrical periods like days don't have fixed durations. AddDate uses the Location of the Time value to determine these durations. That means that the same AddDate arguments can produce a different shift in absolute time depending on the base Time value and its Location. For example, AddDate(0, 0, 1) applied to 12:00 on March 27 always returns 12:00 on March 28. At some locations and in some years this is a 24 hour shift. In others it's a 23 hour shift due to daylight savings time transitions.

+

AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31.

Example +

Code:

start := time.Date(2023, 03, 25, 12, 0, 0, 0, time.UTC)
+oneDayLater := start.AddDate(0, 0, 1)
+dayDuration := oneDayLater.Sub(start)
+oneMonthLater := start.AddDate(0, 1, 0)
+oneYearLater := start.AddDate(1, 0, 0)
+
+zurich, err := time.LoadLocation("Europe/Zurich")
+if err != nil {
+    panic(err)
+}
+// This was the day before a daylight saving time transition in Zürich.
+startZurich := time.Date(2023, 03, 25, 12, 0, 0, 0, zurich)
+oneDayLaterZurich := startZurich.AddDate(0, 0, 1)
+dayDurationZurich := oneDayLaterZurich.Sub(startZurich)
+
+fmt.Printf("oneDayLater: start.AddDate(0, 0, 1) = %v\n", oneDayLater)
+fmt.Printf("oneMonthLater: start.AddDate(0, 1, 0) = %v\n", oneMonthLater)
+fmt.Printf("oneYearLater: start.AddDate(1, 0, 0) = %v\n", oneYearLater)
+fmt.Printf("oneDayLaterZurich: startZurich.AddDate(0, 0, 1) = %v\n", oneDayLaterZurich)
+fmt.Printf("Day duration in UTC: %v | Day duration in Zürich: %v\n", dayDuration, dayDurationZurich)
+
+

Output:

oneDayLater: start.AddDate(0, 0, 1) = 2023-03-26 12:00:00 +0000 UTC
+oneMonthLater: start.AddDate(0, 1, 0) = 2023-04-25 12:00:00 +0000 UTC
+oneYearLater: start.AddDate(1, 0, 0) = 2024-03-25 12:00:00 +0000 UTC
+oneDayLaterZurich: startZurich.AddDate(0, 0, 1) = 2023-03-26 12:00:00 +0200 CEST
+Day duration in UTC: 24h0m0s | Day duration in Zürich: 23h0m0s
+

func (Time) After

func (t Time) After(u Time) bool

After reports whether the time instant t is after u.

Example +

Code:

year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
+year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
+
+isYear3000AfterYear2000 := year3000.After(year2000) // True
+isYear2000AfterYear3000 := year2000.After(year3000) // False
+
+fmt.Printf("year3000.After(year2000) = %v\n", isYear3000AfterYear2000)
+fmt.Printf("year2000.After(year3000) = %v\n", isYear2000AfterYear3000)
+
+

Output:

year3000.After(year2000) = true
+year2000.After(year3000) = false
+

func (Time) AppendFormat 1.5

func (t Time) AppendFormat(b []byte, layout string) []byte

AppendFormat is like Format but appends the textual representation to b and returns the extended buffer.

Example +

Code:

t := time.Date(2017, time.November, 4, 11, 0, 0, 0, time.UTC)
+text := []byte("Time: ")
+
+text = t.AppendFormat(text, time.Kitchen)
+fmt.Println(string(text))
+
+

Output:

Time: 11:00AM
+

func (Time) Before

func (t Time) Before(u Time) bool

Before reports whether the time instant t is before u.

Example +

Code:

year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
+year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
+
+isYear2000BeforeYear3000 := year2000.Before(year3000) // True
+isYear3000BeforeYear2000 := year3000.Before(year2000) // False
+
+fmt.Printf("year2000.Before(year3000) = %v\n", isYear2000BeforeYear3000)
+fmt.Printf("year3000.Before(year2000) = %v\n", isYear3000BeforeYear2000)
+
+

Output:

year2000.Before(year3000) = true
+year3000.Before(year2000) = false
+

func (Time) Clock

func (t Time) Clock() (hour, min, sec int)

Clock returns the hour, minute, and second within the day specified by t.

+

func (Time) Compare 1.20

func (t Time) Compare(u Time) int

Compare compares the time instant t with u. If t is before u, it returns -1; if t is after u, it returns +1; if they're the same, it returns 0.

+

func (Time) Date

func (t Time) Date() (year int, month Month, day int)

Date returns the year, month, and day in which t occurs.

Example +

Code:

d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
+year, month, day := d.Date()
+
+fmt.Printf("year = %v\n", year)
+fmt.Printf("month = %v\n", month)
+fmt.Printf("day = %v\n", day)
+
+

Output:

year = 2000
+month = February
+day = 1
+

func (Time) Day

func (t Time) Day() int

Day returns the day of the month specified by t.

Example +

Code:

d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
+day := d.Day()
+
+fmt.Printf("day = %v\n", day)
+
+

Output:

day = 1
+

func (Time) Equal

func (t Time) Equal(u Time) bool

Equal reports whether t and u represent the same time instant. Two times can be equal even if they are in different locations. For example, 6:00 +0200 and 4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead.

Example +

Code:

secondsEastOfUTC := int((8 * time.Hour).Seconds())
+beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
+
+// Unlike the equal operator, Equal is aware that d1 and d2 are the
+// same instant but in different time zones.
+d1 := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
+d2 := time.Date(2000, 2, 1, 20, 30, 0, 0, beijing)
+
+datesEqualUsingEqualOperator := d1 == d2
+datesEqualUsingFunction := d1.Equal(d2)
+
+fmt.Printf("datesEqualUsingEqualOperator = %v\n", datesEqualUsingEqualOperator)
+fmt.Printf("datesEqualUsingFunction = %v\n", datesEqualUsingFunction)
+
+

Output:

datesEqualUsingEqualOperator = false
+datesEqualUsingFunction = true
+

func (Time) Format

func (t Time) Format(layout string) string

Format returns a textual representation of the time value formatted according to the layout defined by the argument. See the documentation for the constant called Layout to see how to represent the layout format.

+

The executable example for Time.Format demonstrates the working of the layout string in detail and is a good reference.

Example +

Code:

// Parse a time value from a string in the standard Unix format.
+t, err := time.Parse(time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
+if err != nil { // Always check errors even if they should not happen.
+    panic(err)
+}
+
+tz, err := time.LoadLocation("Asia/Shanghai")
+if err != nil { // Always check errors even if they should not happen.
+    panic(err)
+}
+
+// time.Time's Stringer method is useful without any format.
+fmt.Println("default format:", t)
+
+// Predefined constants in the package implement common layouts.
+fmt.Println("Unix format:", t.Format(time.UnixDate))
+
+// The time zone attached to the time value affects its output.
+fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))
+
+fmt.Println("in Shanghai with seconds:", t.In(tz).Format("2006-01-02T15:04:05 -070000"))
+
+fmt.Println("in Shanghai with colon seconds:", t.In(tz).Format("2006-01-02T15:04:05 -07:00:00"))
+
+// The rest of this function demonstrates the properties of the
+// layout string used in the format.
+
+// The layout string used by the Parse function and Format method
+// shows by example how the reference time should be represented.
+// We stress that one must show how the reference time is formatted,
+// not a time of the user's choosing. Thus each layout string is a
+// representation of the time stamp,
+//	Jan 2 15:04:05 2006 MST
+// An easy way to remember this value is that it holds, when presented
+// in this order, the values (lined up with the elements above):
+//	  1 2  3  4  5    6  -7
+// There are some wrinkles illustrated below.
+
+// Most uses of Format and Parse use constant layout strings such as
+// the ones defined in this package, but the interface is flexible,
+// as these examples show.
+
+// Define a helper function to make the examples' output look nice.
+do := func(name, layout, want string) {
+    got := t.Format(layout)
+    if want != got {
+        fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
+        return
+    }
+    fmt.Printf("%-16s %q gives %q\n", name, layout, got)
+}
+
+// Print a header in our output.
+fmt.Printf("\nFormats:\n\n")
+
+// Simple starter examples.
+do("Basic full date", "Mon Jan 2 15:04:05 MST 2006", "Wed Feb 25 11:06:39 PST 2015")
+do("Basic short date", "2006/01/02", "2015/02/25")
+
+// The hour of the reference time is 15, or 3PM. The layout can express
+// it either way, and since our value is the morning we should see it as
+// an AM time. We show both in one format string. Lower case too.
+do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")
+
+// When parsing, if the seconds value is followed by a decimal point
+// and some digits, that is taken as a fraction of a second even if
+// the layout string does not represent the fractional second.
+// Here we add a fractional second to our time value used above.
+t, err = time.Parse(time.UnixDate, "Wed Feb 25 11:06:39.1234 PST 2015")
+if err != nil {
+    panic(err)
+}
+// It does not appear in the output if the layout string does not contain
+// a representation of the fractional second.
+do("No fraction", time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
+
+// Fractional seconds can be printed by adding a run of 0s or 9s after
+// a decimal point in the seconds value in the layout string.
+// If the layout digits are 0s, the fractional second is of the specified
+// width. Note that the output has a trailing zero.
+do("0s for fraction", "15:04:05.00000", "11:06:39.12340")
+
+// If the fraction in the layout is 9s, trailing zeros are dropped.
+do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")
+
+

Output:

default format: 2015-02-25 11:06:39 -0800 PST
+Unix format: Wed Feb 25 11:06:39 PST 2015
+Same, in UTC: Wed Feb 25 19:06:39 UTC 2015
+in Shanghai with seconds: 2015-02-26T03:06:39 +080000
+in Shanghai with colon seconds: 2015-02-26T03:06:39 +08:00:00
+
+Formats:
+
+Basic full date  "Mon Jan 2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015"
+Basic short date "2006/01/02" gives "2015/02/25"
+AM/PM            "3PM==3pm==15h" gives "11AM==11am==11h"
+No fraction      "Mon Jan _2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015"
+0s for fraction  "15:04:05.00000" gives "11:06:39.12340"
+9s for fraction  "15:04:05.99999999" gives "11:06:39.1234"
+

Example (Pad) +

Code:

// Parse a time value from a string in the standard Unix format.
+t, err := time.Parse(time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
+if err != nil { // Always check errors even if they should not happen.
+    panic(err)
+}
+
+// Define a helper function to make the examples' output look nice.
+do := func(name, layout, want string) {
+    got := t.Format(layout)
+    if want != got {
+        fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
+        return
+    }
+    fmt.Printf("%-16s %q gives %q\n", name, layout, got)
+}
+
+// The predefined constant Unix uses an underscore to pad the day.
+do("Unix", time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")
+
+// For fixed-width printing of values, such as the date, that may be one or
+// two characters (7 vs. 07), use an _ instead of a space in the layout string.
+// Here we print just the day, which is 2 in our layout string and 7 in our
+// value.
+do("No pad", "<2>", "<7>")
+
+// An underscore represents a space pad, if the date only has one digit.
+do("Spaces", "<_2>", "< 7>")
+
+// A "0" indicates zero padding for single-digit values.
+do("Zeros", "<02>", "<07>")
+
+// If the value is already the right width, padding is not used.
+// For instance, the second (05 in the reference time) in our value is 39,
+// so it doesn't need padding, but the minutes (04, 06) does.
+do("Suppressed pad", "04:05", "06:39")
+
+

Output:

Unix             "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar  7 11:06:39 PST 2015"
+No pad           "<2>" gives "<7>"
+Spaces           "<_2>" gives "< 7>"
+Zeros            "<02>" gives "<07>"
+Suppressed pad   "04:05" gives "06:39"
+

func (Time) GoString 1.17

func (t Time) GoString() string

GoString implements fmt.GoStringer and formats t to be printed in Go source code.

Example +

Code:

t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
+fmt.Println(t.GoString())
+t = t.Add(1 * time.Minute)
+fmt.Println(t.GoString())
+t = t.AddDate(0, 1, 0)
+fmt.Println(t.GoString())
+t, _ = time.Parse("Jan 2, 2006 at 3:04pm (MST)", "Feb 3, 2013 at 7:54pm (UTC)")
+fmt.Println(t.GoString())
+
+

Output:

time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
+time.Date(2009, time.November, 10, 23, 1, 0, 0, time.UTC)
+time.Date(2009, time.December, 10, 23, 1, 0, 0, time.UTC)
+time.Date(2013, time.February, 3, 19, 54, 0, 0, time.UTC)
+

func (*Time) GobDecode

func (t *Time) GobDecode(data []byte) error

GobDecode implements the gob.GobDecoder interface.

+

func (Time) GobEncode

func (t Time) GobEncode() ([]byte, error)

GobEncode implements the gob.GobEncoder interface.

+

func (Time) Hour

func (t Time) Hour() int

Hour returns the hour within the day specified by t, in the range [0, 23].

+

func (Time) ISOWeek

func (t Time) ISOWeek() (year, week int)

ISOWeek returns the ISO 8601 year and week number in which t occurs. Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1.

+

func (Time) In

func (t Time) In(loc *Location) Time

In returns a copy of t representing the same time instant, but with the copy's location information set to loc for display purposes.

+

In panics if loc is nil.

+

func (Time) IsDST 1.17

func (t Time) IsDST() bool

IsDST reports whether the time in the configured location is in Daylight Savings Time.

+

func (Time) IsZero

func (t Time) IsZero() bool

IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.

+

func (Time) Local

func (t Time) Local() Time

Local returns t with the location set to local time.

+

func (Time) Location

func (t Time) Location() *Location

Location returns the time zone information associated with t.

+

func (Time) MarshalBinary 1.2

func (t Time) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

+

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. The time is a quoted string in the RFC 3339 format with sub-second precision. If the timestamp cannot be represented as valid RFC 3339 (e.g., the year is out of range), then an error is reported.

+

func (Time) MarshalText 1.2

func (t Time) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The time is formatted in RFC 3339 format with sub-second precision. If the timestamp cannot be represented as valid RFC 3339 (e.g., the year is out of range), then an error is reported.

+

func (Time) Minute

func (t Time) Minute() int

Minute returns the minute offset within the hour specified by t, in the range [0, 59].

+

func (Time) Month

func (t Time) Month() Month

Month returns the month of the year specified by t.

+

func (Time) Nanosecond

func (t Time) Nanosecond() int

Nanosecond returns the nanosecond offset within the second specified by t, in the range [0, 999999999].

+

func (Time) Round 1.1

func (t Time) Round(d Duration) Time

Round returns the result of rounding t to the nearest multiple of d (since the zero time). The rounding behavior for halfway values is to round up. If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged.

+

Round operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Round(Hour) may return a time with a non-zero minute, depending on the time's Location.

Example +

Code:

t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC)
+round := []time.Duration{
+    time.Nanosecond,
+    time.Microsecond,
+    time.Millisecond,
+    time.Second,
+    2 * time.Second,
+    time.Minute,
+    10 * time.Minute,
+    time.Hour,
+}
+
+for _, d := range round {
+    fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))
+}
+

Output:

t.Round(   1ns) = 12:15:30.918273645
+t.Round(   1µs) = 12:15:30.918274
+t.Round(   1ms) = 12:15:30.918
+t.Round(    1s) = 12:15:31
+t.Round(    2s) = 12:15:30
+t.Round(  1m0s) = 12:16:00
+t.Round( 10m0s) = 12:20:00
+t.Round(1h0m0s) = 12:00:00
+

func (Time) Second

func (t Time) Second() int

Second returns the second offset within the minute specified by t, in the range [0, 59].

+

func (Time) String

func (t Time) String() string

String returns the time formatted using the format string

+
"2006-01-02 15:04:05.999999999 -0700 MST"
+

If the time has a monotonic clock reading, the returned string includes a final field "m=±<value>", where value is the monotonic clock reading formatted as a decimal number of seconds.

+

The returned string is meant for debugging; for a stable serialized representation, use t.MarshalText, t.MarshalBinary, or t.Format with an explicit format string.

Example +

Code:

timeWithNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 15, time.UTC)
+withNanoseconds := timeWithNanoseconds.String()
+
+timeWithoutNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 0, time.UTC)
+withoutNanoseconds := timeWithoutNanoseconds.String()
+
+fmt.Printf("withNanoseconds = %v\n", string(withNanoseconds))
+fmt.Printf("withoutNanoseconds = %v\n", string(withoutNanoseconds))
+
+

Output:

withNanoseconds = 2000-02-01 12:13:14.000000015 +0000 UTC
+withoutNanoseconds = 2000-02-01 12:13:14 +0000 UTC
+

func (Time) Sub

func (t Time) Sub(u Time) Duration

Sub returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d).

Example +

Code:

start := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
+end := time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC)
+
+difference := end.Sub(start)
+fmt.Printf("difference = %v\n", difference)
+
+

Output:

difference = 12h0m0s
+

func (Time) Truncate 1.1

func (t Time) Truncate(d Duration) Time

Truncate returns the result of rounding t down to a multiple of d (since the zero time). If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged.

+

Truncate operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Truncate(Hour) may return a time with a non-zero minute, depending on the time's Location.

Example +

Code:

t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")
+trunc := []time.Duration{
+    time.Nanosecond,
+    time.Microsecond,
+    time.Millisecond,
+    time.Second,
+    2 * time.Second,
+    time.Minute,
+    10 * time.Minute,
+}
+
+for _, d := range trunc {
+    fmt.Printf("t.Truncate(%5s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))
+}
+// To round to the last midnight in the local timezone, create a new Date.
+midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
+_ = midnight
+
+

Output:

t.Truncate(  1ns) = 12:15:30.918273645
+t.Truncate(  1µs) = 12:15:30.918273
+t.Truncate(  1ms) = 12:15:30.918
+t.Truncate(   1s) = 12:15:30
+t.Truncate(   2s) = 12:15:30
+t.Truncate( 1m0s) = 12:15:00
+t.Truncate(10m0s) = 12:10:00
+

func (Time) UTC

func (t Time) UTC() Time

UTC returns t with the location set to UTC.

+

func (Time) Unix

func (t Time) Unix() int64

Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. The result does not depend on the location associated with t. Unix-like operating systems often record time as a 32-bit count of seconds, but since the method here returns a 64-bit value it is valid for billions of years into the past or future.

Example +

Code:

// 1 billion seconds of Unix, three ways.
+fmt.Println(time.Unix(1e9, 0).UTC())     // 1e9 seconds
+fmt.Println(time.Unix(0, 1e18).UTC())    // 1e18 nanoseconds
+fmt.Println(time.Unix(2e9, -1e18).UTC()) // 2e9 seconds - 1e18 nanoseconds
+
+t := time.Date(2001, time.September, 9, 1, 46, 40, 0, time.UTC)
+fmt.Println(t.Unix())     // seconds since 1970
+fmt.Println(t.UnixNano()) // nanoseconds since 1970
+
+

Output:

2001-09-09 01:46:40 +0000 UTC
+2001-09-09 01:46:40 +0000 UTC
+2001-09-09 01:46:40 +0000 UTC
+1000000000
+1000000000000000000
+

func (Time) UnixMicro 1.17

func (t Time) UnixMicro() int64

UnixMicro returns t as a Unix time, the number of microseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in microseconds cannot be represented by an int64 (a date before year -290307 or after year 294246). The result does not depend on the location associated with t.

+

func (Time) UnixMilli 1.17

func (t Time) UnixMilli() int64

UnixMilli returns t as a Unix time, the number of milliseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in milliseconds cannot be represented by an int64 (a date more than 292 million years before or after 1970). The result does not depend on the location associated with t.

+

func (Time) UnixNano

func (t Time) UnixNano() int64

UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in nanoseconds cannot be represented by an int64 (a date before the year 1678 or after 2262). Note that this means the result of calling UnixNano on the zero Time is undefined. The result does not depend on the location associated with t.

+

func (*Time) UnmarshalBinary 1.2

func (t *Time) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

+

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. The time must be a quoted string in the RFC 3339 format.

+

func (*Time) UnmarshalText 1.2

func (t *Time) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The time must be in the RFC 3339 format.

+

func (Time) Weekday

func (t Time) Weekday() Weekday

Weekday returns the day of the week specified by t.

+

func (Time) Year

func (t Time) Year() int

Year returns the year in which t occurs.

+

func (Time) YearDay 1.1

func (t Time) YearDay() int

YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, and [1,366] in leap years.

+

func (Time) Zone

func (t Time) Zone() (name string, offset int)

Zone computes the time zone in effect at time t, returning the abbreviated name of the zone (such as "CET") and its offset in seconds east of UTC.

+

func (Time) ZoneBounds 1.19

func (t Time) ZoneBounds() (start, end Time)

ZoneBounds returns the bounds of the time zone in effect at time t. The zone begins at start and the next zone begins at end. If the zone begins at the beginning of time, start will be returned as a zero Time. If the zone goes on forever, end will be returned as a zero Time. The Location of the returned times will be the same as t.

+

type Timer

The Timer type represents a single event. When the Timer expires, the current time will be sent on C, unless the Timer was created by AfterFunc. A Timer must be created with NewTimer or AfterFunc.

+
type Timer struct {
+    C <-chan Time
+    // contains filtered or unexported fields
+}
+

func AfterFunc

func AfterFunc(d Duration, f func()) *Timer

AfterFunc waits for the duration to elapse and then calls f in its own goroutine. It returns a Timer that can be used to cancel the call using its Stop method. The returned Timer's C field is not used and will be nil.

+

func NewTimer

func NewTimer(d Duration) *Timer

NewTimer creates a new Timer that will send the current time on its channel after at least duration d.

+

func (*Timer) Reset 1.1

func (t *Timer) Reset(d Duration) bool

Reset changes the timer to expire after duration d. It returns true if the timer had been active, false if the timer had expired or been stopped.

+

For a Timer created with NewTimer, Reset should be invoked only on stopped or expired timers with drained channels.

+

If a program has already received a value from t.C, the timer is known to have expired and the channel drained, so t.Reset can be used directly. If a program has not yet received a value from t.C, however, the timer must be stopped and—if Stop reports that the timer expired before being stopped—the channel explicitly drained:

+
if !t.Stop() {
+	<-t.C
+}
+t.Reset(d)
+

This should not be done concurrent to other receives from the Timer's channel.

+

Note that it is not possible to use Reset's return value correctly, as there is a race condition between draining the channel and the new timer expiring. Reset should always be invoked on stopped or expired channels, as described above. The return value exists to preserve compatibility with existing programs.

+

For a Timer created with AfterFunc(d, f), Reset either reschedules when f will run, in which case Reset returns true, or schedules f to run again, in which case it returns false. When Reset returns false, Reset neither waits for the prior f to complete before returning nor does it guarantee that the subsequent goroutine running f does not run concurrently with the prior one. If the caller needs to know whether the prior execution of f is completed, it must coordinate with f explicitly.

+

func (*Timer) Stop

func (t *Timer) Stop() bool

Stop prevents the Timer from firing. It returns true if the call stops the timer, false if the timer has already expired or been stopped. Stop does not close the channel, to prevent a read from the channel succeeding incorrectly.

+

To ensure the channel is empty after a call to Stop, check the return value and drain the channel. For example, assuming the program has not received from t.C already:

+
if !t.Stop() {
+	<-t.C
+}
+

This cannot be done concurrent to other receives from the Timer's channel or other calls to the Timer's Stop method.

+

For a timer created with AfterFunc(d, f), if t.Stop returns false, then the timer has already expired and the function f has been started in its own goroutine; Stop does not wait for f to complete before returning. If the caller needs to know whether f is completed, it must coordinate with f explicitly.

+

type Weekday

A Weekday specifies a day of the week (Sunday = 0, ...).

+
type Weekday int
const (
+    Sunday Weekday = iota
+    Monday
+    Tuesday
+    Wednesday
+    Thursday
+    Friday
+    Saturday
+)

func (Weekday) String

func (d Weekday) String() string

String returns the English name of the day ("Sunday", "Monday", ...).

+

Subdirectories

Name Synopsis
..
tzdata Package tzdata provides an embedded copy of the timezone database.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/time/ +

+
diff --git a/devdocs/go/time%2Ftzdata%2Findex.html b/devdocs/go/time%2Ftzdata%2Findex.html new file mode 100644 index 00000000..5335b358 --- /dev/null +++ b/devdocs/go/time%2Ftzdata%2Findex.html @@ -0,0 +1,13 @@ +

Package tzdata

Overview

Package tzdata provides an embedded copy of the timezone database. If this package is imported anywhere in the program, then if the time package cannot find tzdata files on the system, it will use this embedded information.

+

Importing this package will increase the size of a program by about 450 KB.

+

This package should normally be imported by a program's main package, not by a library. Libraries normally shouldn't decide whether to include the timezone database in a program.

+

This package will be automatically imported if you build with -tags timetzdata.

Index

Package files

tzdata.go zzipdata.go

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/time/tzdata/ +

+
diff --git a/devdocs/go/unicode%2Findex.html b/devdocs/go/unicode%2Findex.html new file mode 100644 index 00000000..dd594327 --- /dev/null +++ b/devdocs/go/unicode%2Findex.html @@ -0,0 +1,830 @@ +

Package unicode

Overview

Package unicode provides data and functions to test some properties of Unicode code points.

Example (Is) +

Functions starting with "Is" can be used to inspect which table of range a rune belongs to. Note that runes may fit into more than one range.

Code:

// constant with mixed type runes
+const mixed = "\b5Ὂg̀9! ℃ᾭG"
+for _, c := range mixed {
+    fmt.Printf("For %q:\n", c)
+    if unicode.IsControl(c) {
+        fmt.Println("\tis control rune")
+    }
+    if unicode.IsDigit(c) {
+        fmt.Println("\tis digit rune")
+    }
+    if unicode.IsGraphic(c) {
+        fmt.Println("\tis graphic rune")
+    }
+    if unicode.IsLetter(c) {
+        fmt.Println("\tis letter rune")
+    }
+    if unicode.IsLower(c) {
+        fmt.Println("\tis lower case rune")
+    }
+    if unicode.IsMark(c) {
+        fmt.Println("\tis mark rune")
+    }
+    if unicode.IsNumber(c) {
+        fmt.Println("\tis number rune")
+    }
+    if unicode.IsPrint(c) {
+        fmt.Println("\tis printable rune")
+    }
+    if !unicode.IsPrint(c) {
+        fmt.Println("\tis not printable rune")
+    }
+    if unicode.IsPunct(c) {
+        fmt.Println("\tis punct rune")
+    }
+    if unicode.IsSpace(c) {
+        fmt.Println("\tis space rune")
+    }
+    if unicode.IsSymbol(c) {
+        fmt.Println("\tis symbol rune")
+    }
+    if unicode.IsTitle(c) {
+        fmt.Println("\tis title case rune")
+    }
+    if unicode.IsUpper(c) {
+        fmt.Println("\tis upper case rune")
+    }
+}
+
+

Output:

For '\b':
+	is control rune
+	is not printable rune
+For '5':
+	is digit rune
+	is graphic rune
+	is number rune
+	is printable rune
+For 'Ὂ':
+	is graphic rune
+	is letter rune
+	is printable rune
+	is upper case rune
+For 'g':
+	is graphic rune
+	is letter rune
+	is lower case rune
+	is printable rune
+For '̀':
+	is graphic rune
+	is mark rune
+	is printable rune
+For '9':
+	is digit rune
+	is graphic rune
+	is number rune
+	is printable rune
+For '!':
+	is graphic rune
+	is printable rune
+	is punct rune
+For ' ':
+	is graphic rune
+	is printable rune
+	is space rune
+For '℃':
+	is graphic rune
+	is printable rune
+	is symbol rune
+For 'ᾭ':
+	is graphic rune
+	is letter rune
+	is printable rune
+	is title case rune
+For 'G':
+	is graphic rune
+	is letter rune
+	is printable rune
+	is upper case rune
+

Index

Examples

IsDigit
IsLetter
IsLower
IsNumber
IsSpace
IsTitle
IsUpper
SimpleFold
SpecialCase
To
ToLower
ToTitle
ToUpper
Package (Is)

Package files

casetables.go digit.go graphic.go letter.go tables.go

Constants

const (
+    MaxRune         = '\U0010FFFF' // Maximum valid Unicode code point.
+    ReplacementChar = '\uFFFD'     // Represents invalid code points.
+    MaxASCII        = '\u007F'     // maximum ASCII value.
+    MaxLatin1       = '\u00FF'     // maximum Latin-1 value.
+)

Indices into the Delta arrays inside CaseRanges for case mapping.

+
const (
+    UpperCase = iota
+    LowerCase
+    TitleCase
+    MaxCase
+)

If the Delta field of a CaseRange is UpperLower, it means this CaseRange represents a sequence of the form (say) Upper Lower Upper Lower.

+
const (
+    UpperLower = MaxRune + 1 // (Cannot be a valid delta.)
+)

Version is the Unicode edition from which the tables are derived.

+
const Version = "15.0.0"

Variables

These variables have type *RangeTable.

+
var (
+    Cc     = _Cc // Cc is the set of Unicode characters in category Cc (Other, control).
+    Cf     = _Cf // Cf is the set of Unicode characters in category Cf (Other, format).
+    Co     = _Co // Co is the set of Unicode characters in category Co (Other, private use).
+    Cs     = _Cs // Cs is the set of Unicode characters in category Cs (Other, surrogate).
+    Digit  = _Nd // Digit is the set of Unicode characters with the "decimal digit" property.
+    Nd     = _Nd // Nd is the set of Unicode characters in category Nd (Number, decimal digit).
+    Letter = _L  // Letter/L is the set of Unicode letters, category L.
+    L      = _L
+    Lm     = _Lm // Lm is the set of Unicode characters in category Lm (Letter, modifier).
+    Lo     = _Lo // Lo is the set of Unicode characters in category Lo (Letter, other).
+    Lower  = _Ll // Lower is the set of Unicode lower case letters.
+    Ll     = _Ll // Ll is the set of Unicode characters in category Ll (Letter, lowercase).
+    Mark   = _M  // Mark/M is the set of Unicode mark characters, category M.
+    M      = _M
+    Mc     = _Mc // Mc is the set of Unicode characters in category Mc (Mark, spacing combining).
+    Me     = _Me // Me is the set of Unicode characters in category Me (Mark, enclosing).
+    Mn     = _Mn // Mn is the set of Unicode characters in category Mn (Mark, nonspacing).
+    Nl     = _Nl // Nl is the set of Unicode characters in category Nl (Number, letter).
+    No     = _No // No is the set of Unicode characters in category No (Number, other).
+    Number = _N  // Number/N is the set of Unicode number characters, category N.
+    N      = _N
+    Other  = _C // Other/C is the set of Unicode control and special characters, category C.
+    C      = _C
+    Pc     = _Pc // Pc is the set of Unicode characters in category Pc (Punctuation, connector).
+    Pd     = _Pd // Pd is the set of Unicode characters in category Pd (Punctuation, dash).
+    Pe     = _Pe // Pe is the set of Unicode characters in category Pe (Punctuation, close).
+    Pf     = _Pf // Pf is the set of Unicode characters in category Pf (Punctuation, final quote).
+    Pi     = _Pi // Pi is the set of Unicode characters in category Pi (Punctuation, initial quote).
+    Po     = _Po // Po is the set of Unicode characters in category Po (Punctuation, other).
+    Ps     = _Ps // Ps is the set of Unicode characters in category Ps (Punctuation, open).
+    Punct  = _P  // Punct/P is the set of Unicode punctuation characters, category P.
+    P      = _P
+    Sc     = _Sc // Sc is the set of Unicode characters in category Sc (Symbol, currency).
+    Sk     = _Sk // Sk is the set of Unicode characters in category Sk (Symbol, modifier).
+    Sm     = _Sm // Sm is the set of Unicode characters in category Sm (Symbol, math).
+    So     = _So // So is the set of Unicode characters in category So (Symbol, other).
+    Space  = _Z  // Space/Z is the set of Unicode space characters, category Z.
+    Z      = _Z
+    Symbol = _S // Symbol/S is the set of Unicode symbol characters, category S.
+    S      = _S
+    Title  = _Lt // Title is the set of Unicode title case letters.
+    Lt     = _Lt // Lt is the set of Unicode characters in category Lt (Letter, titlecase).
+    Upper  = _Lu // Upper is the set of Unicode upper case letters.
+    Lu     = _Lu // Lu is the set of Unicode characters in category Lu (Letter, uppercase).
+    Zl     = _Zl // Zl is the set of Unicode characters in category Zl (Separator, line).
+    Zp     = _Zp // Zp is the set of Unicode characters in category Zp (Separator, paragraph).
+    Zs     = _Zs // Zs is the set of Unicode characters in category Zs (Separator, space).
+)

These variables have type *RangeTable.

+
var (
+    Adlam                  = _Adlam                  // Adlam is the set of Unicode characters in script Adlam.
+    Ahom                   = _Ahom                   // Ahom is the set of Unicode characters in script Ahom.
+    Anatolian_Hieroglyphs  = _Anatolian_Hieroglyphs  // Anatolian_Hieroglyphs is the set of Unicode characters in script Anatolian_Hieroglyphs.
+    Arabic                 = _Arabic                 // Arabic is the set of Unicode characters in script Arabic.
+    Armenian               = _Armenian               // Armenian is the set of Unicode characters in script Armenian.
+    Avestan                = _Avestan                // Avestan is the set of Unicode characters in script Avestan.
+    Balinese               = _Balinese               // Balinese is the set of Unicode characters in script Balinese.
+    Bamum                  = _Bamum                  // Bamum is the set of Unicode characters in script Bamum.
+    Bassa_Vah              = _Bassa_Vah              // Bassa_Vah is the set of Unicode characters in script Bassa_Vah.
+    Batak                  = _Batak                  // Batak is the set of Unicode characters in script Batak.
+    Bengali                = _Bengali                // Bengali is the set of Unicode characters in script Bengali.
+    Bhaiksuki              = _Bhaiksuki              // Bhaiksuki is the set of Unicode characters in script Bhaiksuki.
+    Bopomofo               = _Bopomofo               // Bopomofo is the set of Unicode characters in script Bopomofo.
+    Brahmi                 = _Brahmi                 // Brahmi is the set of Unicode characters in script Brahmi.
+    Braille                = _Braille                // Braille is the set of Unicode characters in script Braille.
+    Buginese               = _Buginese               // Buginese is the set of Unicode characters in script Buginese.
+    Buhid                  = _Buhid                  // Buhid is the set of Unicode characters in script Buhid.
+    Canadian_Aboriginal    = _Canadian_Aboriginal    // Canadian_Aboriginal is the set of Unicode characters in script Canadian_Aboriginal.
+    Carian                 = _Carian                 // Carian is the set of Unicode characters in script Carian.
+    Caucasian_Albanian     = _Caucasian_Albanian     // Caucasian_Albanian is the set of Unicode characters in script Caucasian_Albanian.
+    Chakma                 = _Chakma                 // Chakma is the set of Unicode characters in script Chakma.
+    Cham                   = _Cham                   // Cham is the set of Unicode characters in script Cham.
+    Cherokee               = _Cherokee               // Cherokee is the set of Unicode characters in script Cherokee.
+    Chorasmian             = _Chorasmian             // Chorasmian is the set of Unicode characters in script Chorasmian.
+    Common                 = _Common                 // Common is the set of Unicode characters in script Common.
+    Coptic                 = _Coptic                 // Coptic is the set of Unicode characters in script Coptic.
+    Cuneiform              = _Cuneiform              // Cuneiform is the set of Unicode characters in script Cuneiform.
+    Cypriot                = _Cypriot                // Cypriot is the set of Unicode characters in script Cypriot.
+    Cypro_Minoan           = _Cypro_Minoan           // Cypro_Minoan is the set of Unicode characters in script Cypro_Minoan.
+    Cyrillic               = _Cyrillic               // Cyrillic is the set of Unicode characters in script Cyrillic.
+    Deseret                = _Deseret                // Deseret is the set of Unicode characters in script Deseret.
+    Devanagari             = _Devanagari             // Devanagari is the set of Unicode characters in script Devanagari.
+    Dives_Akuru            = _Dives_Akuru            // Dives_Akuru is the set of Unicode characters in script Dives_Akuru.
+    Dogra                  = _Dogra                  // Dogra is the set of Unicode characters in script Dogra.
+    Duployan               = _Duployan               // Duployan is the set of Unicode characters in script Duployan.
+    Egyptian_Hieroglyphs   = _Egyptian_Hieroglyphs   // Egyptian_Hieroglyphs is the set of Unicode characters in script Egyptian_Hieroglyphs.
+    Elbasan                = _Elbasan                // Elbasan is the set of Unicode characters in script Elbasan.
+    Elymaic                = _Elymaic                // Elymaic is the set of Unicode characters in script Elymaic.
+    Ethiopic               = _Ethiopic               // Ethiopic is the set of Unicode characters in script Ethiopic.
+    Georgian               = _Georgian               // Georgian is the set of Unicode characters in script Georgian.
+    Glagolitic             = _Glagolitic             // Glagolitic is the set of Unicode characters in script Glagolitic.
+    Gothic                 = _Gothic                 // Gothic is the set of Unicode characters in script Gothic.
+    Grantha                = _Grantha                // Grantha is the set of Unicode characters in script Grantha.
+    Greek                  = _Greek                  // Greek is the set of Unicode characters in script Greek.
+    Gujarati               = _Gujarati               // Gujarati is the set of Unicode characters in script Gujarati.
+    Gunjala_Gondi          = _Gunjala_Gondi          // Gunjala_Gondi is the set of Unicode characters in script Gunjala_Gondi.
+    Gurmukhi               = _Gurmukhi               // Gurmukhi is the set of Unicode characters in script Gurmukhi.
+    Han                    = _Han                    // Han is the set of Unicode characters in script Han.
+    Hangul                 = _Hangul                 // Hangul is the set of Unicode characters in script Hangul.
+    Hanifi_Rohingya        = _Hanifi_Rohingya        // Hanifi_Rohingya is the set of Unicode characters in script Hanifi_Rohingya.
+    Hanunoo                = _Hanunoo                // Hanunoo is the set of Unicode characters in script Hanunoo.
+    Hatran                 = _Hatran                 // Hatran is the set of Unicode characters in script Hatran.
+    Hebrew                 = _Hebrew                 // Hebrew is the set of Unicode characters in script Hebrew.
+    Hiragana               = _Hiragana               // Hiragana is the set of Unicode characters in script Hiragana.
+    Imperial_Aramaic       = _Imperial_Aramaic       // Imperial_Aramaic is the set of Unicode characters in script Imperial_Aramaic.
+    Inherited              = _Inherited              // Inherited is the set of Unicode characters in script Inherited.
+    Inscriptional_Pahlavi  = _Inscriptional_Pahlavi  // Inscriptional_Pahlavi is the set of Unicode characters in script Inscriptional_Pahlavi.
+    Inscriptional_Parthian = _Inscriptional_Parthian // Inscriptional_Parthian is the set of Unicode characters in script Inscriptional_Parthian.
+    Javanese               = _Javanese               // Javanese is the set of Unicode characters in script Javanese.
+    Kaithi                 = _Kaithi                 // Kaithi is the set of Unicode characters in script Kaithi.
+    Kannada                = _Kannada                // Kannada is the set of Unicode characters in script Kannada.
+    Katakana               = _Katakana               // Katakana is the set of Unicode characters in script Katakana.
+    Kawi                   = _Kawi                   // Kawi is the set of Unicode characters in script Kawi.
+    Kayah_Li               = _Kayah_Li               // Kayah_Li is the set of Unicode characters in script Kayah_Li.
+    Kharoshthi             = _Kharoshthi             // Kharoshthi is the set of Unicode characters in script Kharoshthi.
+    Khitan_Small_Script    = _Khitan_Small_Script    // Khitan_Small_Script is the set of Unicode characters in script Khitan_Small_Script.
+    Khmer                  = _Khmer                  // Khmer is the set of Unicode characters in script Khmer.
+    Khojki                 = _Khojki                 // Khojki is the set of Unicode characters in script Khojki.
+    Khudawadi              = _Khudawadi              // Khudawadi is the set of Unicode characters in script Khudawadi.
+    Lao                    = _Lao                    // Lao is the set of Unicode characters in script Lao.
+    Latin                  = _Latin                  // Latin is the set of Unicode characters in script Latin.
+    Lepcha                 = _Lepcha                 // Lepcha is the set of Unicode characters in script Lepcha.
+    Limbu                  = _Limbu                  // Limbu is the set of Unicode characters in script Limbu.
+    Linear_A               = _Linear_A               // Linear_A is the set of Unicode characters in script Linear_A.
+    Linear_B               = _Linear_B               // Linear_B is the set of Unicode characters in script Linear_B.
+    Lisu                   = _Lisu                   // Lisu is the set of Unicode characters in script Lisu.
+    Lycian                 = _Lycian                 // Lycian is the set of Unicode characters in script Lycian.
+    Lydian                 = _Lydian                 // Lydian is the set of Unicode characters in script Lydian.
+    Mahajani               = _Mahajani               // Mahajani is the set of Unicode characters in script Mahajani.
+    Makasar                = _Makasar                // Makasar is the set of Unicode characters in script Makasar.
+    Malayalam              = _Malayalam              // Malayalam is the set of Unicode characters in script Malayalam.
+    Mandaic                = _Mandaic                // Mandaic is the set of Unicode characters in script Mandaic.
+    Manichaean             = _Manichaean             // Manichaean is the set of Unicode characters in script Manichaean.
+    Marchen                = _Marchen                // Marchen is the set of Unicode characters in script Marchen.
+    Masaram_Gondi          = _Masaram_Gondi          // Masaram_Gondi is the set of Unicode characters in script Masaram_Gondi.
+    Medefaidrin            = _Medefaidrin            // Medefaidrin is the set of Unicode characters in script Medefaidrin.
+    Meetei_Mayek           = _Meetei_Mayek           // Meetei_Mayek is the set of Unicode characters in script Meetei_Mayek.
+    Mende_Kikakui          = _Mende_Kikakui          // Mende_Kikakui is the set of Unicode characters in script Mende_Kikakui.
+    Meroitic_Cursive       = _Meroitic_Cursive       // Meroitic_Cursive is the set of Unicode characters in script Meroitic_Cursive.
+    Meroitic_Hieroglyphs   = _Meroitic_Hieroglyphs   // Meroitic_Hieroglyphs is the set of Unicode characters in script Meroitic_Hieroglyphs.
+    Miao                   = _Miao                   // Miao is the set of Unicode characters in script Miao.
+    Modi                   = _Modi                   // Modi is the set of Unicode characters in script Modi.
+    Mongolian              = _Mongolian              // Mongolian is the set of Unicode characters in script Mongolian.
+    Mro                    = _Mro                    // Mro is the set of Unicode characters in script Mro.
+    Multani                = _Multani                // Multani is the set of Unicode characters in script Multani.
+    Myanmar                = _Myanmar                // Myanmar is the set of Unicode characters in script Myanmar.
+    Nabataean              = _Nabataean              // Nabataean is the set of Unicode characters in script Nabataean.
+    Nag_Mundari            = _Nag_Mundari            // Nag_Mundari is the set of Unicode characters in script Nag_Mundari.
+    Nandinagari            = _Nandinagari            // Nandinagari is the set of Unicode characters in script Nandinagari.
+    New_Tai_Lue            = _New_Tai_Lue            // New_Tai_Lue is the set of Unicode characters in script New_Tai_Lue.
+    Newa                   = _Newa                   // Newa is the set of Unicode characters in script Newa.
+    Nko                    = _Nko                    // Nko is the set of Unicode characters in script Nko.
+    Nushu                  = _Nushu                  // Nushu is the set of Unicode characters in script Nushu.
+    Nyiakeng_Puachue_Hmong = _Nyiakeng_Puachue_Hmong // Nyiakeng_Puachue_Hmong is the set of Unicode characters in script Nyiakeng_Puachue_Hmong.
+    Ogham                  = _Ogham                  // Ogham is the set of Unicode characters in script Ogham.
+    Ol_Chiki               = _Ol_Chiki               // Ol_Chiki is the set of Unicode characters in script Ol_Chiki.
+    Old_Hungarian          = _Old_Hungarian          // Old_Hungarian is the set of Unicode characters in script Old_Hungarian.
+    Old_Italic             = _Old_Italic             // Old_Italic is the set of Unicode characters in script Old_Italic.
+    Old_North_Arabian      = _Old_North_Arabian      // Old_North_Arabian is the set of Unicode characters in script Old_North_Arabian.
+    Old_Permic             = _Old_Permic             // Old_Permic is the set of Unicode characters in script Old_Permic.
+    Old_Persian            = _Old_Persian            // Old_Persian is the set of Unicode characters in script Old_Persian.
+    Old_Sogdian            = _Old_Sogdian            // Old_Sogdian is the set of Unicode characters in script Old_Sogdian.
+    Old_South_Arabian      = _Old_South_Arabian      // Old_South_Arabian is the set of Unicode characters in script Old_South_Arabian.
+    Old_Turkic             = _Old_Turkic             // Old_Turkic is the set of Unicode characters in script Old_Turkic.
+    Old_Uyghur             = _Old_Uyghur             // Old_Uyghur is the set of Unicode characters in script Old_Uyghur.
+    Oriya                  = _Oriya                  // Oriya is the set of Unicode characters in script Oriya.
+    Osage                  = _Osage                  // Osage is the set of Unicode characters in script Osage.
+    Osmanya                = _Osmanya                // Osmanya is the set of Unicode characters in script Osmanya.
+    Pahawh_Hmong           = _Pahawh_Hmong           // Pahawh_Hmong is the set of Unicode characters in script Pahawh_Hmong.
+    Palmyrene              = _Palmyrene              // Palmyrene is the set of Unicode characters in script Palmyrene.
+    Pau_Cin_Hau            = _Pau_Cin_Hau            // Pau_Cin_Hau is the set of Unicode characters in script Pau_Cin_Hau.
+    Phags_Pa               = _Phags_Pa               // Phags_Pa is the set of Unicode characters in script Phags_Pa.
+    Phoenician             = _Phoenician             // Phoenician is the set of Unicode characters in script Phoenician.
+    Psalter_Pahlavi        = _Psalter_Pahlavi        // Psalter_Pahlavi is the set of Unicode characters in script Psalter_Pahlavi.
+    Rejang                 = _Rejang                 // Rejang is the set of Unicode characters in script Rejang.
+    Runic                  = _Runic                  // Runic is the set of Unicode characters in script Runic.
+    Samaritan              = _Samaritan              // Samaritan is the set of Unicode characters in script Samaritan.
+    Saurashtra             = _Saurashtra             // Saurashtra is the set of Unicode characters in script Saurashtra.
+    Sharada                = _Sharada                // Sharada is the set of Unicode characters in script Sharada.
+    Shavian                = _Shavian                // Shavian is the set of Unicode characters in script Shavian.
+    Siddham                = _Siddham                // Siddham is the set of Unicode characters in script Siddham.
+    SignWriting            = _SignWriting            // SignWriting is the set of Unicode characters in script SignWriting.
+    Sinhala                = _Sinhala                // Sinhala is the set of Unicode characters in script Sinhala.
+    Sogdian                = _Sogdian                // Sogdian is the set of Unicode characters in script Sogdian.
+    Sora_Sompeng           = _Sora_Sompeng           // Sora_Sompeng is the set of Unicode characters in script Sora_Sompeng.
+    Soyombo                = _Soyombo                // Soyombo is the set of Unicode characters in script Soyombo.
+    Sundanese              = _Sundanese              // Sundanese is the set of Unicode characters in script Sundanese.
+    Syloti_Nagri           = _Syloti_Nagri           // Syloti_Nagri is the set of Unicode characters in script Syloti_Nagri.
+    Syriac                 = _Syriac                 // Syriac is the set of Unicode characters in script Syriac.
+    Tagalog                = _Tagalog                // Tagalog is the set of Unicode characters in script Tagalog.
+    Tagbanwa               = _Tagbanwa               // Tagbanwa is the set of Unicode characters in script Tagbanwa.
+    Tai_Le                 = _Tai_Le                 // Tai_Le is the set of Unicode characters in script Tai_Le.
+    Tai_Tham               = _Tai_Tham               // Tai_Tham is the set of Unicode characters in script Tai_Tham.
+    Tai_Viet               = _Tai_Viet               // Tai_Viet is the set of Unicode characters in script Tai_Viet.
+    Takri                  = _Takri                  // Takri is the set of Unicode characters in script Takri.
+    Tamil                  = _Tamil                  // Tamil is the set of Unicode characters in script Tamil.
+    Tangsa                 = _Tangsa                 // Tangsa is the set of Unicode characters in script Tangsa.
+    Tangut                 = _Tangut                 // Tangut is the set of Unicode characters in script Tangut.
+    Telugu                 = _Telugu                 // Telugu is the set of Unicode characters in script Telugu.
+    Thaana                 = _Thaana                 // Thaana is the set of Unicode characters in script Thaana.
+    Thai                   = _Thai                   // Thai is the set of Unicode characters in script Thai.
+    Tibetan                = _Tibetan                // Tibetan is the set of Unicode characters in script Tibetan.
+    Tifinagh               = _Tifinagh               // Tifinagh is the set of Unicode characters in script Tifinagh.
+    Tirhuta                = _Tirhuta                // Tirhuta is the set of Unicode characters in script Tirhuta.
+    Toto                   = _Toto                   // Toto is the set of Unicode characters in script Toto.
+    Ugaritic               = _Ugaritic               // Ugaritic is the set of Unicode characters in script Ugaritic.
+    Vai                    = _Vai                    // Vai is the set of Unicode characters in script Vai.
+    Vithkuqi               = _Vithkuqi               // Vithkuqi is the set of Unicode characters in script Vithkuqi.
+    Wancho                 = _Wancho                 // Wancho is the set of Unicode characters in script Wancho.
+    Warang_Citi            = _Warang_Citi            // Warang_Citi is the set of Unicode characters in script Warang_Citi.
+    Yezidi                 = _Yezidi                 // Yezidi is the set of Unicode characters in script Yezidi.
+    Yi                     = _Yi                     // Yi is the set of Unicode characters in script Yi.
+    Zanabazar_Square       = _Zanabazar_Square       // Zanabazar_Square is the set of Unicode characters in script Zanabazar_Square.
+)

These variables have type *RangeTable.

+
var (
+    ASCII_Hex_Digit                    = _ASCII_Hex_Digit                    // ASCII_Hex_Digit is the set of Unicode characters with property ASCII_Hex_Digit.
+    Bidi_Control                       = _Bidi_Control                       // Bidi_Control is the set of Unicode characters with property Bidi_Control.
+    Dash                               = _Dash                               // Dash is the set of Unicode characters with property Dash.
+    Deprecated                         = _Deprecated                         // Deprecated is the set of Unicode characters with property Deprecated.
+    Diacritic                          = _Diacritic                          // Diacritic is the set of Unicode characters with property Diacritic.
+    Extender                           = _Extender                           // Extender is the set of Unicode characters with property Extender.
+    Hex_Digit                          = _Hex_Digit                          // Hex_Digit is the set of Unicode characters with property Hex_Digit.
+    Hyphen                             = _Hyphen                             // Hyphen is the set of Unicode characters with property Hyphen.
+    IDS_Binary_Operator                = _IDS_Binary_Operator                // IDS_Binary_Operator is the set of Unicode characters with property IDS_Binary_Operator.
+    IDS_Trinary_Operator               = _IDS_Trinary_Operator               // IDS_Trinary_Operator is the set of Unicode characters with property IDS_Trinary_Operator.
+    Ideographic                        = _Ideographic                        // Ideographic is the set of Unicode characters with property Ideographic.
+    Join_Control                       = _Join_Control                       // Join_Control is the set of Unicode characters with property Join_Control.
+    Logical_Order_Exception            = _Logical_Order_Exception            // Logical_Order_Exception is the set of Unicode characters with property Logical_Order_Exception.
+    Noncharacter_Code_Point            = _Noncharacter_Code_Point            // Noncharacter_Code_Point is the set of Unicode characters with property Noncharacter_Code_Point.
+    Other_Alphabetic                   = _Other_Alphabetic                   // Other_Alphabetic is the set of Unicode characters with property Other_Alphabetic.
+    Other_Default_Ignorable_Code_Point = _Other_Default_Ignorable_Code_Point // Other_Default_Ignorable_Code_Point is the set of Unicode characters with property Other_Default_Ignorable_Code_Point.
+    Other_Grapheme_Extend              = _Other_Grapheme_Extend              // Other_Grapheme_Extend is the set of Unicode characters with property Other_Grapheme_Extend.
+    Other_ID_Continue                  = _Other_ID_Continue                  // Other_ID_Continue is the set of Unicode characters with property Other_ID_Continue.
+    Other_ID_Start                     = _Other_ID_Start                     // Other_ID_Start is the set of Unicode characters with property Other_ID_Start.
+    Other_Lowercase                    = _Other_Lowercase                    // Other_Lowercase is the set of Unicode characters with property Other_Lowercase.
+    Other_Math                         = _Other_Math                         // Other_Math is the set of Unicode characters with property Other_Math.
+    Other_Uppercase                    = _Other_Uppercase                    // Other_Uppercase is the set of Unicode characters with property Other_Uppercase.
+    Pattern_Syntax                     = _Pattern_Syntax                     // Pattern_Syntax is the set of Unicode characters with property Pattern_Syntax.
+    Pattern_White_Space                = _Pattern_White_Space                // Pattern_White_Space is the set of Unicode characters with property Pattern_White_Space.
+    Prepended_Concatenation_Mark       = _Prepended_Concatenation_Mark       // Prepended_Concatenation_Mark is the set of Unicode characters with property Prepended_Concatenation_Mark.
+    Quotation_Mark                     = _Quotation_Mark                     // Quotation_Mark is the set of Unicode characters with property Quotation_Mark.
+    Radical                            = _Radical                            // Radical is the set of Unicode characters with property Radical.
+    Regional_Indicator                 = _Regional_Indicator                 // Regional_Indicator is the set of Unicode characters with property Regional_Indicator.
+    STerm                              = _Sentence_Terminal                  // STerm is an alias for Sentence_Terminal.
+    Sentence_Terminal                  = _Sentence_Terminal                  // Sentence_Terminal is the set of Unicode characters with property Sentence_Terminal.
+    Soft_Dotted                        = _Soft_Dotted                        // Soft_Dotted is the set of Unicode characters with property Soft_Dotted.
+    Terminal_Punctuation               = _Terminal_Punctuation               // Terminal_Punctuation is the set of Unicode characters with property Terminal_Punctuation.
+    Unified_Ideograph                  = _Unified_Ideograph                  // Unified_Ideograph is the set of Unicode characters with property Unified_Ideograph.
+    Variation_Selector                 = _Variation_Selector                 // Variation_Selector is the set of Unicode characters with property Variation_Selector.
+    White_Space                        = _White_Space                        // White_Space is the set of Unicode characters with property White_Space.
+)

CaseRanges is the table describing case mappings for all letters with non-self mappings.

+
var CaseRanges = _CaseRanges

Categories is the set of Unicode category tables.

+
var Categories = map[string]*RangeTable{
+    "C":  C,
+    "Cc": Cc,
+    "Cf": Cf,
+    "Co": Co,
+    "Cs": Cs,
+    "L":  L,
+    "Ll": Ll,
+    "Lm": Lm,
+    "Lo": Lo,
+    "Lt": Lt,
+    "Lu": Lu,
+    "M":  M,
+    "Mc": Mc,
+    "Me": Me,
+    "Mn": Mn,
+    "N":  N,
+    "Nd": Nd,
+    "Nl": Nl,
+    "No": No,
+    "P":  P,
+    "Pc": Pc,
+    "Pd": Pd,
+    "Pe": Pe,
+    "Pf": Pf,
+    "Pi": Pi,
+    "Po": Po,
+    "Ps": Ps,
+    "S":  S,
+    "Sc": Sc,
+    "Sk": Sk,
+    "Sm": Sm,
+    "So": So,
+    "Z":  Z,
+    "Zl": Zl,
+    "Zp": Zp,
+    "Zs": Zs,
+}

FoldCategory maps a category name to a table of code points outside the category that are equivalent under simple case folding to code points inside the category. If there is no entry for a category name, there are no such points.

+
var FoldCategory = map[string]*RangeTable{
+    "L":  foldL,
+    "Ll": foldLl,
+    "Lt": foldLt,
+    "Lu": foldLu,
+    "M":  foldM,
+    "Mn": foldMn,
+}

FoldScript maps a script name to a table of code points outside the script that are equivalent under simple case folding to code points inside the script. If there is no entry for a script name, there are no such points.

+
var FoldScript = map[string]*RangeTable{
+    "Common":    foldCommon,
+    "Greek":     foldGreek,
+    "Inherited": foldInherited,
+}

GraphicRanges defines the set of graphic characters according to Unicode.

+
var GraphicRanges = []*RangeTable{
+    L, M, N, P, S, Zs,
+}

PrintRanges defines the set of printable characters according to Go. ASCII space, U+0020, is handled separately.

+
var PrintRanges = []*RangeTable{
+    L, M, N, P, S,
+}

Properties is the set of Unicode property tables.

+
var Properties = map[string]*RangeTable{
+    "ASCII_Hex_Digit":                    ASCII_Hex_Digit,
+    "Bidi_Control":                       Bidi_Control,
+    "Dash":                               Dash,
+    "Deprecated":                         Deprecated,
+    "Diacritic":                          Diacritic,
+    "Extender":                           Extender,
+    "Hex_Digit":                          Hex_Digit,
+    "Hyphen":                             Hyphen,
+    "IDS_Binary_Operator":                IDS_Binary_Operator,
+    "IDS_Trinary_Operator":               IDS_Trinary_Operator,
+    "Ideographic":                        Ideographic,
+    "Join_Control":                       Join_Control,
+    "Logical_Order_Exception":            Logical_Order_Exception,
+    "Noncharacter_Code_Point":            Noncharacter_Code_Point,
+    "Other_Alphabetic":                   Other_Alphabetic,
+    "Other_Default_Ignorable_Code_Point": Other_Default_Ignorable_Code_Point,
+    "Other_Grapheme_Extend":              Other_Grapheme_Extend,
+    "Other_ID_Continue":                  Other_ID_Continue,
+    "Other_ID_Start":                     Other_ID_Start,
+    "Other_Lowercase":                    Other_Lowercase,
+    "Other_Math":                         Other_Math,
+    "Other_Uppercase":                    Other_Uppercase,
+    "Pattern_Syntax":                     Pattern_Syntax,
+    "Pattern_White_Space":                Pattern_White_Space,
+    "Prepended_Concatenation_Mark":       Prepended_Concatenation_Mark,
+    "Quotation_Mark":                     Quotation_Mark,
+    "Radical":                            Radical,
+    "Regional_Indicator":                 Regional_Indicator,
+    "Sentence_Terminal":                  Sentence_Terminal,
+    "STerm":                              Sentence_Terminal,
+    "Soft_Dotted":                        Soft_Dotted,
+    "Terminal_Punctuation":               Terminal_Punctuation,
+    "Unified_Ideograph":                  Unified_Ideograph,
+    "Variation_Selector":                 Variation_Selector,
+    "White_Space":                        White_Space,
+}

Scripts is the set of Unicode script tables.

+
var Scripts = map[string]*RangeTable{
+    "Adlam":                  Adlam,
+    "Ahom":                   Ahom,
+    "Anatolian_Hieroglyphs":  Anatolian_Hieroglyphs,
+    "Arabic":                 Arabic,
+    "Armenian":               Armenian,
+    "Avestan":                Avestan,
+    "Balinese":               Balinese,
+    "Bamum":                  Bamum,
+    "Bassa_Vah":              Bassa_Vah,
+    "Batak":                  Batak,
+    "Bengali":                Bengali,
+    "Bhaiksuki":              Bhaiksuki,
+    "Bopomofo":               Bopomofo,
+    "Brahmi":                 Brahmi,
+    "Braille":                Braille,
+    "Buginese":               Buginese,
+    "Buhid":                  Buhid,
+    "Canadian_Aboriginal":    Canadian_Aboriginal,
+    "Carian":                 Carian,
+    "Caucasian_Albanian":     Caucasian_Albanian,
+    "Chakma":                 Chakma,
+    "Cham":                   Cham,
+    "Cherokee":               Cherokee,
+    "Chorasmian":             Chorasmian,
+    "Common":                 Common,
+    "Coptic":                 Coptic,
+    "Cuneiform":              Cuneiform,
+    "Cypriot":                Cypriot,
+    "Cypro_Minoan":           Cypro_Minoan,
+    "Cyrillic":               Cyrillic,
+    "Deseret":                Deseret,
+    "Devanagari":             Devanagari,
+    "Dives_Akuru":            Dives_Akuru,
+    "Dogra":                  Dogra,
+    "Duployan":               Duployan,
+    "Egyptian_Hieroglyphs":   Egyptian_Hieroglyphs,
+    "Elbasan":                Elbasan,
+    "Elymaic":                Elymaic,
+    "Ethiopic":               Ethiopic,
+    "Georgian":               Georgian,
+    "Glagolitic":             Glagolitic,
+    "Gothic":                 Gothic,
+    "Grantha":                Grantha,
+    "Greek":                  Greek,
+    "Gujarati":               Gujarati,
+    "Gunjala_Gondi":          Gunjala_Gondi,
+    "Gurmukhi":               Gurmukhi,
+    "Han":                    Han,
+    "Hangul":                 Hangul,
+    "Hanifi_Rohingya":        Hanifi_Rohingya,
+    "Hanunoo":                Hanunoo,
+    "Hatran":                 Hatran,
+    "Hebrew":                 Hebrew,
+    "Hiragana":               Hiragana,
+    "Imperial_Aramaic":       Imperial_Aramaic,
+    "Inherited":              Inherited,
+    "Inscriptional_Pahlavi":  Inscriptional_Pahlavi,
+    "Inscriptional_Parthian": Inscriptional_Parthian,
+    "Javanese":               Javanese,
+    "Kaithi":                 Kaithi,
+    "Kannada":                Kannada,
+    "Katakana":               Katakana,
+    "Kawi":                   Kawi,
+    "Kayah_Li":               Kayah_Li,
+    "Kharoshthi":             Kharoshthi,
+    "Khitan_Small_Script":    Khitan_Small_Script,
+    "Khmer":                  Khmer,
+    "Khojki":                 Khojki,
+    "Khudawadi":              Khudawadi,
+    "Lao":                    Lao,
+    "Latin":                  Latin,
+    "Lepcha":                 Lepcha,
+    "Limbu":                  Limbu,
+    "Linear_A":               Linear_A,
+    "Linear_B":               Linear_B,
+    "Lisu":                   Lisu,
+    "Lycian":                 Lycian,
+    "Lydian":                 Lydian,
+    "Mahajani":               Mahajani,
+    "Makasar":                Makasar,
+    "Malayalam":              Malayalam,
+    "Mandaic":                Mandaic,
+    "Manichaean":             Manichaean,
+    "Marchen":                Marchen,
+    "Masaram_Gondi":          Masaram_Gondi,
+    "Medefaidrin":            Medefaidrin,
+    "Meetei_Mayek":           Meetei_Mayek,
+    "Mende_Kikakui":          Mende_Kikakui,
+    "Meroitic_Cursive":       Meroitic_Cursive,
+    "Meroitic_Hieroglyphs":   Meroitic_Hieroglyphs,
+    "Miao":                   Miao,
+    "Modi":                   Modi,
+    "Mongolian":              Mongolian,
+    "Mro":                    Mro,
+    "Multani":                Multani,
+    "Myanmar":                Myanmar,
+    "Nabataean":              Nabataean,
+    "Nag_Mundari":            Nag_Mundari,
+    "Nandinagari":            Nandinagari,
+    "New_Tai_Lue":            New_Tai_Lue,
+    "Newa":                   Newa,
+    "Nko":                    Nko,
+    "Nushu":                  Nushu,
+    "Nyiakeng_Puachue_Hmong": Nyiakeng_Puachue_Hmong,
+    "Ogham":                  Ogham,
+    "Ol_Chiki":               Ol_Chiki,
+    "Old_Hungarian":          Old_Hungarian,
+    "Old_Italic":             Old_Italic,
+    "Old_North_Arabian":      Old_North_Arabian,
+    "Old_Permic":             Old_Permic,
+    "Old_Persian":            Old_Persian,
+    "Old_Sogdian":            Old_Sogdian,
+    "Old_South_Arabian":      Old_South_Arabian,
+    "Old_Turkic":             Old_Turkic,
+    "Old_Uyghur":             Old_Uyghur,
+    "Oriya":                  Oriya,
+    "Osage":                  Osage,
+    "Osmanya":                Osmanya,
+    "Pahawh_Hmong":           Pahawh_Hmong,
+    "Palmyrene":              Palmyrene,
+    "Pau_Cin_Hau":            Pau_Cin_Hau,
+    "Phags_Pa":               Phags_Pa,
+    "Phoenician":             Phoenician,
+    "Psalter_Pahlavi":        Psalter_Pahlavi,
+    "Rejang":                 Rejang,
+    "Runic":                  Runic,
+    "Samaritan":              Samaritan,
+    "Saurashtra":             Saurashtra,
+    "Sharada":                Sharada,
+    "Shavian":                Shavian,
+    "Siddham":                Siddham,
+    "SignWriting":            SignWriting,
+    "Sinhala":                Sinhala,
+    "Sogdian":                Sogdian,
+    "Sora_Sompeng":           Sora_Sompeng,
+    "Soyombo":                Soyombo,
+    "Sundanese":              Sundanese,
+    "Syloti_Nagri":           Syloti_Nagri,
+    "Syriac":                 Syriac,
+    "Tagalog":                Tagalog,
+    "Tagbanwa":               Tagbanwa,
+    "Tai_Le":                 Tai_Le,
+    "Tai_Tham":               Tai_Tham,
+    "Tai_Viet":               Tai_Viet,
+    "Takri":                  Takri,
+    "Tamil":                  Tamil,
+    "Tangsa":                 Tangsa,
+    "Tangut":                 Tangut,
+    "Telugu":                 Telugu,
+    "Thaana":                 Thaana,
+    "Thai":                   Thai,
+    "Tibetan":                Tibetan,
+    "Tifinagh":               Tifinagh,
+    "Tirhuta":                Tirhuta,
+    "Toto":                   Toto,
+    "Ugaritic":               Ugaritic,
+    "Vai":                    Vai,
+    "Vithkuqi":               Vithkuqi,
+    "Wancho":                 Wancho,
+    "Warang_Citi":            Warang_Citi,
+    "Yezidi":                 Yezidi,
+    "Yi":                     Yi,
+    "Zanabazar_Square":       Zanabazar_Square,
+}

func In 1.2

func In(r rune, ranges ...*RangeTable) bool

In reports whether the rune is a member of one of the ranges.

+

func Is

func Is(rangeTab *RangeTable, r rune) bool

Is reports whether the rune is in the specified table of ranges.

+

func IsControl

func IsControl(r rune) bool

IsControl reports whether the rune is a control character. The C (Other) Unicode category includes more code points such as surrogates; use Is(C, r) to test for them.

+

func IsDigit

func IsDigit(r rune) bool

IsDigit reports whether the rune is a decimal digit.

Example +

Code:

fmt.Printf("%t\n", unicode.IsDigit('৩'))
+fmt.Printf("%t\n", unicode.IsDigit('A'))
+

Output:

true
+false
+

func IsGraphic

func IsGraphic(r rune) bool

IsGraphic reports whether the rune is defined as a Graphic by Unicode. Such characters include letters, marks, numbers, punctuation, symbols, and spaces, from categories L, M, N, P, S, Zs.

+

func IsLetter

func IsLetter(r rune) bool

IsLetter reports whether the rune is a letter (category L).

Example +

Code:

fmt.Printf("%t\n", unicode.IsLetter('A'))
+fmt.Printf("%t\n", unicode.IsLetter('7'))
+

Output:

true
+false
+

func IsLower

func IsLower(r rune) bool

IsLower reports whether the rune is a lower case letter.

Example +

Code:

fmt.Printf("%t\n", unicode.IsLower('a'))
+fmt.Printf("%t\n", unicode.IsLower('A'))
+

Output:

true
+false
+

func IsMark

func IsMark(r rune) bool

IsMark reports whether the rune is a mark character (category M).

+

func IsNumber

func IsNumber(r rune) bool

IsNumber reports whether the rune is a number (category N).

Example +

Code:

fmt.Printf("%t\n", unicode.IsNumber('Ⅷ'))
+fmt.Printf("%t\n", unicode.IsNumber('A'))
+

Output:

true
+false
+

func IsOneOf

func IsOneOf(ranges []*RangeTable, r rune) bool

IsOneOf reports whether the rune is a member of one of the ranges. The function "In" provides a nicer signature and should be used in preference to IsOneOf.

+

func IsPrint

func IsPrint(r rune) bool

IsPrint reports whether the rune is defined as printable by Go. Such characters include letters, marks, numbers, punctuation, symbols, and the ASCII space character, from categories L, M, N, P, S and the ASCII space character. This categorization is the same as IsGraphic except that the only spacing character is ASCII space, U+0020.

+

func IsPunct

func IsPunct(r rune) bool

IsPunct reports whether the rune is a Unicode punctuation character (category P).

+

func IsSpace

func IsSpace(r rune) bool

IsSpace reports whether the rune is a space character as defined by Unicode's White Space property; in the Latin-1 space this is

+
'\t', '\n', '\v', '\f', '\r', ' ', U+0085 (NEL), U+00A0 (NBSP).
+

Other definitions of spacing characters are set by category Z and property Pattern_White_Space.

Example +

Code:

fmt.Printf("%t\n", unicode.IsSpace(' '))
+fmt.Printf("%t\n", unicode.IsSpace('\n'))
+fmt.Printf("%t\n", unicode.IsSpace('\t'))
+fmt.Printf("%t\n", unicode.IsSpace('a'))
+

Output:

true
+true
+true
+false
+

func IsSymbol

func IsSymbol(r rune) bool

IsSymbol reports whether the rune is a symbolic character.

+

func IsTitle

func IsTitle(r rune) bool

IsTitle reports whether the rune is a title case letter.

Example +

Code:

fmt.Printf("%t\n", unicode.IsTitle('Dž'))
+fmt.Printf("%t\n", unicode.IsTitle('a'))
+

Output:

true
+false
+

func IsUpper

func IsUpper(r rune) bool

IsUpper reports whether the rune is an upper case letter.

Example +

Code:

fmt.Printf("%t\n", unicode.IsUpper('A'))
+fmt.Printf("%t\n", unicode.IsUpper('a'))
+

Output:

true
+false
+

func SimpleFold

func SimpleFold(r rune) rune

SimpleFold iterates over Unicode code points equivalent under the Unicode-defined simple case folding. Among the code points equivalent to rune (including rune itself), SimpleFold returns the smallest rune > r if one exists, or else the smallest rune >= 0. If r is not a valid Unicode code point, SimpleFold(r) returns r.

+

For example:

+
SimpleFold('A') = 'a'
+SimpleFold('a') = 'A'
+
+SimpleFold('K') = 'k'
+SimpleFold('k') = '\u212A' (Kelvin symbol, K)
+SimpleFold('\u212A') = 'K'
+
+SimpleFold('1') = '1'
+
+SimpleFold(-2) = -2
+

Example +

Code:

fmt.Printf("%#U\n", unicode.SimpleFold('A'))      // 'a'
+fmt.Printf("%#U\n", unicode.SimpleFold('a'))      // 'A'
+fmt.Printf("%#U\n", unicode.SimpleFold('K'))      // 'k'
+fmt.Printf("%#U\n", unicode.SimpleFold('k'))      // '\u212A' (Kelvin symbol, K)
+fmt.Printf("%#U\n", unicode.SimpleFold('\u212A')) // 'K'
+fmt.Printf("%#U\n", unicode.SimpleFold('1'))      // '1'
+
+

Output:

U+0061 'a'
+U+0041 'A'
+U+006B 'k'
+U+212A 'K'
+U+004B 'K'
+U+0031 '1'
+

func To

func To(_case int, r rune) rune

To maps the rune to the specified case: UpperCase, LowerCase, or TitleCase.

Example +

Code:

const lcG = 'g'
+fmt.Printf("%#U\n", unicode.To(unicode.UpperCase, lcG))
+fmt.Printf("%#U\n", unicode.To(unicode.LowerCase, lcG))
+fmt.Printf("%#U\n", unicode.To(unicode.TitleCase, lcG))
+
+const ucG = 'G'
+fmt.Printf("%#U\n", unicode.To(unicode.UpperCase, ucG))
+fmt.Printf("%#U\n", unicode.To(unicode.LowerCase, ucG))
+fmt.Printf("%#U\n", unicode.To(unicode.TitleCase, ucG))
+
+

Output:

U+0047 'G'
+U+0067 'g'
+U+0047 'G'
+U+0047 'G'
+U+0067 'g'
+U+0047 'G'
+

func ToLower

func ToLower(r rune) rune

ToLower maps the rune to lower case.

Example +

Code:

const ucG = 'G'
+fmt.Printf("%#U\n", unicode.ToLower(ucG))
+
+

Output:

U+0067 'g'
+

func ToTitle

func ToTitle(r rune) rune

ToTitle maps the rune to title case.

Example +

Code:

const ucG = 'g'
+fmt.Printf("%#U\n", unicode.ToTitle(ucG))
+
+

Output:

U+0047 'G'
+

func ToUpper

func ToUpper(r rune) rune

ToUpper maps the rune to upper case.

Example +

Code:

const ucG = 'g'
+fmt.Printf("%#U\n", unicode.ToUpper(ucG))
+
+

Output:

U+0047 'G'
+

type CaseRange

CaseRange represents a range of Unicode code points for simple (one code point to one code point) case conversion. The range runs from Lo to Hi inclusive, with a fixed stride of 1. Deltas are the number to add to the code point to reach the code point for a different case for that character. They may be negative. If zero, it means the character is in the corresponding case. There is a special case representing sequences of alternating corresponding Upper and Lower pairs. It appears with a fixed Delta of

+
{UpperLower, UpperLower, UpperLower}
+

The constant UpperLower has an otherwise impossible delta value.

+
type CaseRange struct {
+    Lo    uint32
+    Hi    uint32
+    Delta d
+}
+

type Range16

Range16 represents of a range of 16-bit Unicode code points. The range runs from Lo to Hi inclusive and has the specified stride.

+
type Range16 struct {
+    Lo     uint16
+    Hi     uint16
+    Stride uint16
+}
+

type Range32

Range32 represents of a range of Unicode code points and is used when one or more of the values will not fit in 16 bits. The range runs from Lo to Hi inclusive and has the specified stride. Lo and Hi must always be >= 1<<16.

+
type Range32 struct {
+    Lo     uint32
+    Hi     uint32
+    Stride uint32
+}
+

type RangeTable

RangeTable defines a set of Unicode code points by listing the ranges of code points within the set. The ranges are listed in two slices to save space: a slice of 16-bit ranges and a slice of 32-bit ranges. The two slices must be in sorted order and non-overlapping. Also, R32 should contain only values >= 0x10000 (1<<16).

+
type RangeTable struct {
+    R16         []Range16
+    R32         []Range32
+    LatinOffset int // number of entries in R16 with Hi <= MaxLatin1; added in Go 1.1
+}
+

type SpecialCase

SpecialCase represents language-specific case mappings such as Turkish. Methods of SpecialCase customize (by overriding) the standard mappings.

+
type SpecialCase []CaseRange
var AzeriCase SpecialCase = _TurkishCase
var TurkishCase SpecialCase = _TurkishCase

Example +

Code:

t := unicode.TurkishCase
+
+const lci = 'i'
+fmt.Printf("%#U\n", t.ToLower(lci))
+fmt.Printf("%#U\n", t.ToTitle(lci))
+fmt.Printf("%#U\n", t.ToUpper(lci))
+
+const uci = 'İ'
+fmt.Printf("%#U\n", t.ToLower(uci))
+fmt.Printf("%#U\n", t.ToTitle(uci))
+fmt.Printf("%#U\n", t.ToUpper(uci))
+
+

Output:

U+0069 'i'
+U+0130 'İ'
+U+0130 'İ'
+U+0069 'i'
+U+0130 'İ'
+U+0130 'İ'
+

func (SpecialCase) ToLower

func (special SpecialCase) ToLower(r rune) rune

ToLower maps the rune to lower case giving priority to the special mapping.

+

func (SpecialCase) ToTitle

func (special SpecialCase) ToTitle(r rune) rune

ToTitle maps the rune to title case giving priority to the special mapping.

+

func (SpecialCase) ToUpper

func (special SpecialCase) ToUpper(r rune) rune

ToUpper maps the rune to upper case giving priority to the special mapping.

+

Bugs

Subdirectories

Name Synopsis
..
utf16 Package utf16 implements encoding and decoding of UTF-16 sequences.
utf8 Package utf8 implements functions and constants to support text encoded in UTF-8.
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/unicode/ +

+
diff --git a/devdocs/go/unicode%2Futf16%2Findex.html b/devdocs/go/unicode%2Futf16%2Findex.html new file mode 100644 index 00000000..e846c303 --- /dev/null +++ b/devdocs/go/unicode%2Futf16%2Findex.html @@ -0,0 +1,22 @@ +

Package utf16

Overview

Package utf16 implements encoding and decoding of UTF-16 sequences.

Index

Package files

utf16.go

func AppendRune 1.20

func AppendRune(a []uint16, r rune) []uint16

AppendRune appends the UTF-16 encoding of the Unicode code point r to the end of p and returns the extended buffer. If the rune is not a valid Unicode code point, it appends the encoding of U+FFFD.

+

func Decode

func Decode(s []uint16) []rune

Decode returns the Unicode code point sequence represented by the UTF-16 encoding s.

+

func DecodeRune

func DecodeRune(r1, r2 rune) rune

DecodeRune returns the UTF-16 decoding of a surrogate pair. If the pair is not a valid UTF-16 surrogate pair, DecodeRune returns the Unicode replacement code point U+FFFD.

+

func Encode

func Encode(s []rune) []uint16

Encode returns the UTF-16 encoding of the Unicode code point sequence s.

+

func EncodeRune

func EncodeRune(r rune) (r1, r2 rune)

EncodeRune returns the UTF-16 surrogate pair r1, r2 for the given rune. If the rune is not a valid Unicode code point or does not need encoding, EncodeRune returns U+FFFD, U+FFFD.

+

func IsSurrogate

func IsSurrogate(r rune) bool

IsSurrogate reports whether the specified Unicode code point can appear in a surrogate pair.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/unicode/utf16/ +

+
diff --git a/devdocs/go/unicode%2Futf8%2Findex.html b/devdocs/go/unicode%2Futf8%2Findex.html new file mode 100644 index 00000000..b27d81f9 --- /dev/null +++ b/devdocs/go/unicode%2Futf8%2Findex.html @@ -0,0 +1,205 @@ +

Package utf8

Overview

Package utf8 implements functions and constants to support text encoded in UTF-8. It includes functions to translate between runes and UTF-8 byte sequences. See https://en.wikipedia.org/wiki/UTF-8

Index

Examples

AppendRune
DecodeLastRune
DecodeLastRuneInString
DecodeRune
DecodeRuneInString
EncodeRune
EncodeRune (OutOfRange)
FullRune
FullRuneInString
RuneCount
RuneCountInString
RuneLen
RuneStart
Valid
ValidRune
ValidString

Package files

utf8.go

Constants

Numbers fundamental to the encoding.

+
const (
+    RuneError = '\uFFFD'     // the "error" Rune or "Unicode replacement character"
+    RuneSelf  = 0x80         // characters below RuneSelf are represented as themselves in a single byte.
+    MaxRune   = '\U0010FFFF' // Maximum valid Unicode code point.
+    UTFMax    = 4            // maximum number of bytes of a UTF-8 encoded Unicode character.
+)

func AppendRune 1.18

func AppendRune(p []byte, r rune) []byte

AppendRune appends the UTF-8 encoding of r to the end of p and returns the extended buffer. If the rune is out of range, it appends the encoding of RuneError.

Example +

Code:

buf1 := utf8.AppendRune(nil, 0x10000)
+buf2 := utf8.AppendRune([]byte("init"), 0x10000)
+fmt.Println(string(buf1))
+fmt.Println(string(buf2))
+

Output:

𐀀
+init𐀀
+

func DecodeLastRune

func DecodeLastRune(p []byte) (r rune, size int)

DecodeLastRune unpacks the last UTF-8 encoding in p and returns the rune and its width in bytes. If p is empty it returns (RuneError, 0). Otherwise, if the encoding is invalid, it returns (RuneError, 1). Both are impossible results for correct, non-empty UTF-8.

+

An encoding is invalid if it is incorrect UTF-8, encodes a rune that is out of range, or is not the shortest possible UTF-8 encoding for the value. No other validation is performed.

Example +

Code:

b := []byte("Hello, 世界")
+
+for len(b) > 0 {
+    r, size := utf8.DecodeLastRune(b)
+    fmt.Printf("%c %v\n", r, size)
+
+    b = b[:len(b)-size]
+}
+

Output:

界 3
+世 3
+  1
+, 1
+o 1
+l 1
+l 1
+e 1
+H 1
+

func DecodeLastRuneInString

func DecodeLastRuneInString(s string) (r rune, size int)

DecodeLastRuneInString is like DecodeLastRune but its input is a string. If s is empty it returns (RuneError, 0). Otherwise, if the encoding is invalid, it returns (RuneError, 1). Both are impossible results for correct, non-empty UTF-8.

+

An encoding is invalid if it is incorrect UTF-8, encodes a rune that is out of range, or is not the shortest possible UTF-8 encoding for the value. No other validation is performed.

Example +

Code:

str := "Hello, 世界"
+
+for len(str) > 0 {
+    r, size := utf8.DecodeLastRuneInString(str)
+    fmt.Printf("%c %v\n", r, size)
+
+    str = str[:len(str)-size]
+}
+

Output:

界 3
+世 3
+  1
+, 1
+o 1
+l 1
+l 1
+e 1
+H 1
+

func DecodeRune

func DecodeRune(p []byte) (r rune, size int)

DecodeRune unpacks the first UTF-8 encoding in p and returns the rune and its width in bytes. If p is empty it returns (RuneError, 0). Otherwise, if the encoding is invalid, it returns (RuneError, 1). Both are impossible results for correct, non-empty UTF-8.

+

An encoding is invalid if it is incorrect UTF-8, encodes a rune that is out of range, or is not the shortest possible UTF-8 encoding for the value. No other validation is performed.

Example +

Code:

b := []byte("Hello, 世界")
+
+for len(b) > 0 {
+    r, size := utf8.DecodeRune(b)
+    fmt.Printf("%c %v\n", r, size)
+
+    b = b[size:]
+}
+

Output:

H 1
+e 1
+l 1
+l 1
+o 1
+, 1
+  1
+世 3
+界 3
+

func DecodeRuneInString

func DecodeRuneInString(s string) (r rune, size int)

DecodeRuneInString is like DecodeRune but its input is a string. If s is empty it returns (RuneError, 0). Otherwise, if the encoding is invalid, it returns (RuneError, 1). Both are impossible results for correct, non-empty UTF-8.

+

An encoding is invalid if it is incorrect UTF-8, encodes a rune that is out of range, or is not the shortest possible UTF-8 encoding for the value. No other validation is performed.

Example +

Code:

str := "Hello, 世界"
+
+for len(str) > 0 {
+    r, size := utf8.DecodeRuneInString(str)
+    fmt.Printf("%c %v\n", r, size)
+
+    str = str[size:]
+}
+

Output:

H 1
+e 1
+l 1
+l 1
+o 1
+, 1
+  1
+世 3
+界 3
+

func EncodeRune

func EncodeRune(p []byte, r rune) int

EncodeRune writes into p (which must be large enough) the UTF-8 encoding of the rune. If the rune is out of range, it writes the encoding of RuneError. It returns the number of bytes written.

Example +

Code:

r := '世'
+buf := make([]byte, 3)
+
+n := utf8.EncodeRune(buf, r)
+
+fmt.Println(buf)
+fmt.Println(n)
+

Output:

[228 184 150]
+3
+

Example (OutOfRange) +

Code:

runes := []rune{
+    // Less than 0, out of range.
+    -1,
+    // Greater than 0x10FFFF, out of range.
+    0x110000,
+    // The Unicode replacement character.
+    utf8.RuneError,
+}
+for i, c := range runes {
+    buf := make([]byte, 3)
+    size := utf8.EncodeRune(buf, c)
+    fmt.Printf("%d: %d %[2]s %d\n", i, buf, size)
+}
+

Output:

0: [239 191 189] � 3
+1: [239 191 189] � 3
+2: [239 191 189] � 3
+

func FullRune

func FullRune(p []byte) bool

FullRune reports whether the bytes in p begin with a full UTF-8 encoding of a rune. An invalid encoding is considered a full Rune since it will convert as a width-1 error rune.

Example +

Code:

buf := []byte{228, 184, 150} // 世
+fmt.Println(utf8.FullRune(buf))
+fmt.Println(utf8.FullRune(buf[:2]))
+

Output:

true
+false
+

func FullRuneInString

func FullRuneInString(s string) bool

FullRuneInString is like FullRune but its input is a string.

Example +

Code:

str := "世"
+fmt.Println(utf8.FullRuneInString(str))
+fmt.Println(utf8.FullRuneInString(str[:2]))
+

Output:

true
+false
+

func RuneCount

func RuneCount(p []byte) int

RuneCount returns the number of runes in p. Erroneous and short encodings are treated as single runes of width 1 byte.

Example +

Code:

buf := []byte("Hello, 世界")
+fmt.Println("bytes =", len(buf))
+fmt.Println("runes =", utf8.RuneCount(buf))
+

Output:

bytes = 13
+runes = 9
+

func RuneCountInString

func RuneCountInString(s string) (n int)

RuneCountInString is like RuneCount but its input is a string.

Example +

Code:

str := "Hello, 世界"
+fmt.Println("bytes =", len(str))
+fmt.Println("runes =", utf8.RuneCountInString(str))
+

Output:

bytes = 13
+runes = 9
+

func RuneLen

func RuneLen(r rune) int

RuneLen returns the number of bytes required to encode the rune. It returns -1 if the rune is not a valid value to encode in UTF-8.

Example +

Code:

fmt.Println(utf8.RuneLen('a'))
+fmt.Println(utf8.RuneLen('界'))
+

Output:

1
+3
+

func RuneStart

func RuneStart(b byte) bool

RuneStart reports whether the byte could be the first byte of an encoded, possibly invalid rune. Second and subsequent bytes always have the top two bits set to 10.

Example +

Code:

buf := []byte("a界")
+fmt.Println(utf8.RuneStart(buf[0]))
+fmt.Println(utf8.RuneStart(buf[1]))
+fmt.Println(utf8.RuneStart(buf[2]))
+

Output:

true
+true
+false
+

func Valid

func Valid(p []byte) bool

Valid reports whether p consists entirely of valid UTF-8-encoded runes.

Example +

Code:

valid := []byte("Hello, 世界")
+invalid := []byte{0xff, 0xfe, 0xfd}
+
+fmt.Println(utf8.Valid(valid))
+fmt.Println(utf8.Valid(invalid))
+

Output:

true
+false
+

func ValidRune 1.1

func ValidRune(r rune) bool

ValidRune reports whether r can be legally encoded as UTF-8. Code points that are out of range or a surrogate half are illegal.

Example +

Code:

valid := 'a'
+invalid := rune(0xfffffff)
+
+fmt.Println(utf8.ValidRune(valid))
+fmt.Println(utf8.ValidRune(invalid))
+

Output:

true
+false
+

func ValidString

func ValidString(s string) bool

ValidString reports whether s consists entirely of valid UTF-8-encoded runes.

Example +

Code:

valid := "Hello, 世界"
+invalid := string([]byte{0xff, 0xfe, 0xfd})
+
+fmt.Println(utf8.ValidString(valid))
+fmt.Println(utf8.ValidString(invalid))
+

Output:

true
+false
+
+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/unicode/utf8/ +

+
diff --git a/devdocs/go/unsafe%2Findex.html b/devdocs/go/unsafe%2Findex.html new file mode 100644 index 00000000..5e8827ad --- /dev/null +++ b/devdocs/go/unsafe%2Findex.html @@ -0,0 +1,120 @@ +

Package unsafe

Overview

Package unsafe contains operations that step around the type safety of Go programs.

+

Packages that import unsafe may be non-portable and are not protected by the Go 1 compatibility guidelines.

Index

Package files

unsafe.go

func Alignof

func Alignof(x ArbitraryType) uintptr

Alignof takes an expression x of any type and returns the required alignment of a hypothetical variable v as if v was declared via var v = x. It is the largest value m such that the address of v is always zero mod m. It is the same as the value returned by reflect.TypeOf(x).Align(). As a special case, if a variable s is of struct type and f is a field within that struct, then Alignof(s.f) will return the required alignment of a field of that type within a struct. This case is the same as the value returned by reflect.TypeOf(s.f).FieldAlign(). The return value of Alignof is a Go constant if the type of the argument does not have variable size. (See the description of Sizeof for a definition of variable sized types.)

+

func Offsetof

func Offsetof(x ArbitraryType) uintptr

Offsetof returns the offset within the struct of the field represented by x, which must be of the form structValue.field. In other words, it returns the number of bytes between the start of the struct and the start of the field. The return value of Offsetof is a Go constant if the type of the argument x does not have variable size. (See the description of Sizeof for a definition of variable sized types.)

+

func Sizeof

func Sizeof(x ArbitraryType) uintptr

Sizeof takes an expression x of any type and returns the size in bytes of a hypothetical variable v as if v was declared via var v = x. The size does not include any memory possibly referenced by x. For instance, if x is a slice, Sizeof returns the size of the slice descriptor, not the size of the memory referenced by the slice. For a struct, the size includes any padding introduced by field alignment. The return value of Sizeof is a Go constant if the type of the argument x does not have variable size. (A type has variable size if it is a type parameter or if it is an array or struct type with elements of variable size).

+

func String

func String(ptr *byte, len IntegerType) string

String returns a string value whose underlying bytes start at ptr and whose length is len.

+

The len argument must be of integer type or an untyped constant. A constant len argument must be non-negative and representable by a value of type int; if it is an untyped constant it is given type int. At run time, if len is negative, or if ptr is nil and len is not zero, a run-time panic occurs.

+

Since Go strings are immutable, the bytes passed to String must not be modified afterwards.

+

func StringData

func StringData(str string) *byte

StringData returns a pointer to the underlying bytes of str. For an empty string the return value is unspecified, and may be nil.

+

Since Go strings are immutable, the bytes returned by StringData must not be modified.

+

type ArbitraryType

ArbitraryType is here for the purposes of documentation only and is not actually part of the unsafe package. It represents the type of an arbitrary Go expression.

+
type ArbitraryType int

func Slice

func Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryType

The function Slice returns a slice whose underlying array starts at ptr and whose length and capacity are len. Slice(ptr, len) is equivalent to

+
(*[len]ArbitraryType)(unsafe.Pointer(ptr))[:]
+

except that, as a special case, if ptr is nil and len is zero, Slice returns nil.

+

The len argument must be of integer type or an untyped constant. A constant len argument must be non-negative and representable by a value of type int; if it is an untyped constant it is given type int. At run time, if len is negative, or if ptr is nil and len is not zero, a run-time panic occurs.

+

func SliceData

func SliceData(slice []ArbitraryType) *ArbitraryType

SliceData returns a pointer to the underlying array of the argument slice.

+

type IntegerType

IntegerType is here for the purposes of documentation only and is not actually part of the unsafe package. It represents any arbitrary integer type.

+
type IntegerType int

type Pointer

Pointer represents a pointer to an arbitrary type. There are four special operations available for type Pointer that are not available for other types:

+

Pointer therefore allows a program to defeat the type system and read and write arbitrary memory. It should be used with extreme care.

+

The following patterns involving Pointer are valid. Code not using these patterns is likely to be invalid today or to become invalid in the future. Even the valid patterns below come with important caveats.

+

Running "go vet" can help find uses of Pointer that do not conform to these patterns, but silence from "go vet" is not a guarantee that the code is valid.

+

(1) Conversion of a *T1 to Pointer to *T2.

+

Provided that T2 is no larger than T1 and that the two share an equivalent memory layout, this conversion allows reinterpreting data of one type as data of another type. An example is the implementation of math.Float64bits:

+
func Float64bits(f float64) uint64 {
+	return *(*uint64)(unsafe.Pointer(&f))
+}
+

(2) Conversion of a Pointer to a uintptr (but not back to Pointer).

+

Converting a Pointer to a uintptr produces the memory address of the value pointed at, as an integer. The usual use for such a uintptr is to print it.

+

Conversion of a uintptr back to Pointer is not valid in general.

+

A uintptr is an integer, not a reference. Converting a Pointer to a uintptr creates an integer value with no pointer semantics. Even if a uintptr holds the address of some object, the garbage collector will not update that uintptr's value if the object moves, nor will that uintptr keep the object from being reclaimed.

+

The remaining patterns enumerate the only valid conversions from uintptr to Pointer.

+

(3) Conversion of a Pointer to a uintptr and back, with arithmetic.

+

If p points into an allocated object, it can be advanced through the object by conversion to uintptr, addition of an offset, and conversion back to Pointer.

+
p = unsafe.Pointer(uintptr(p) + offset)
+

The most common use of this pattern is to access fields in a struct or elements of an array:

+
// equivalent to f := unsafe.Pointer(&s.f)
+f := unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.f))
+
+// equivalent to e := unsafe.Pointer(&x[i])
+e := unsafe.Pointer(uintptr(unsafe.Pointer(&x[0])) + i*unsafe.Sizeof(x[0]))
+

It is valid both to add and to subtract offsets from a pointer in this way. It is also valid to use &^ to round pointers, usually for alignment. In all cases, the result must continue to point into the original allocated object.

+

Unlike in C, it is not valid to advance a pointer just beyond the end of its original allocation:

+
// INVALID: end points outside allocated space.
+var s thing
+end = unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + unsafe.Sizeof(s))
+
+// INVALID: end points outside allocated space.
+b := make([]byte, n)
+end = unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(n))
+

Note that both conversions must appear in the same expression, with only the intervening arithmetic between them:

+
// INVALID: uintptr cannot be stored in variable
+// before conversion back to Pointer.
+u := uintptr(p)
+p = unsafe.Pointer(u + offset)
+

Note that the pointer must point into an allocated object, so it may not be nil.

+
// INVALID: conversion of nil pointer
+u := unsafe.Pointer(nil)
+p := unsafe.Pointer(uintptr(u) + offset)
+

(4) Conversion of a Pointer to a uintptr when calling syscall.Syscall.

+

The Syscall functions in package syscall pass their uintptr arguments directly to the operating system, which then may, depending on the details of the call, reinterpret some of them as pointers. That is, the system call implementation is implicitly converting certain arguments back from uintptr to pointer.

+

If a pointer argument must be converted to uintptr for use as an argument, that conversion must appear in the call expression itself:

+
syscall.Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(n))
+

The compiler handles a Pointer converted to a uintptr in the argument list of a call to a function implemented in assembly by arranging that the referenced allocated object, if any, is retained and not moved until the call completes, even though from the types alone it would appear that the object is no longer needed during the call.

+

For the compiler to recognize this pattern, the conversion must appear in the argument list:

+
// INVALID: uintptr cannot be stored in variable
+// before implicit conversion back to Pointer during system call.
+u := uintptr(unsafe.Pointer(p))
+syscall.Syscall(SYS_READ, uintptr(fd), u, uintptr(n))
+

(5) Conversion of the result of reflect.Value.Pointer or reflect.Value.UnsafeAddr from uintptr to Pointer.

+

Package reflect's Value methods named Pointer and UnsafeAddr return type uintptr instead of unsafe.Pointer to keep callers from changing the result to an arbitrary type without first importing "unsafe". However, this means that the result is fragile and must be converted to Pointer immediately after making the call, in the same expression:

+
p := (*int)(unsafe.Pointer(reflect.ValueOf(new(int)).Pointer()))
+

As in the cases above, it is invalid to store the result before the conversion:

+
// INVALID: uintptr cannot be stored in variable
+// before conversion back to Pointer.
+u := reflect.ValueOf(new(int)).Pointer()
+p := (*int)(unsafe.Pointer(u))
+

(6) Conversion of a reflect.SliceHeader or reflect.StringHeader Data field to or from Pointer.

+

As in the previous case, the reflect data structures SliceHeader and StringHeader declare the field Data as a uintptr to keep callers from changing the result to an arbitrary type without first importing "unsafe". However, this means that SliceHeader and StringHeader are only valid when interpreting the content of an actual slice or string value.

+
var s string
+hdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) // case 1
+hdr.Data = uintptr(unsafe.Pointer(p))              // case 6 (this case)
+hdr.Len = n
+

In this usage hdr.Data is really an alternate way to refer to the underlying pointer in the string header, not a uintptr variable itself.

+

In general, reflect.SliceHeader and reflect.StringHeader should be used only as *reflect.SliceHeader and *reflect.StringHeader pointing at actual slices or strings, never as plain structs. A program should not declare or allocate variables of these struct types.

+
// INVALID: a directly-declared header will not hold Data as a reference.
+var hdr reflect.StringHeader
+hdr.Data = uintptr(unsafe.Pointer(p))
+hdr.Len = n
+s := *(*string)(unsafe.Pointer(&hdr)) // p possibly already lost
+
type Pointer *ArbitraryType

func Add

func Add(ptr Pointer, len IntegerType) Pointer

The function Add adds len to ptr and returns the updated pointer Pointer(uintptr(ptr) + uintptr(len)). The len argument must be of integer type or an untyped constant. A constant len argument must be representable by a value of type int; if it is an untyped constant it is given type int. The rules for valid uses of Pointer still apply.

+

+ © Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
+ http://golang.org/pkg/unsafe/ +

+
-- cgit v1.2.3