diff --git a/index.html b/index.html deleted file mode 100644 index 587f5d5..0000000 --- a/index.html +++ /dev/null @@ -1 +0,0 @@ -Temp diff --git a/lib/godoc/godocs.js b/lib/godoc/godocs.js new file mode 100644 index 0000000..ec9f37a --- /dev/null +++ b/lib/godoc/godocs.js @@ -0,0 +1,571 @@ +// Copyright 2012 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. + +/* A little code to ease navigation of these documents. + * + * On window load we: + * + Bind search box hint placeholder show/hide events (bindSearchEvents) + * + Generate a table of contents (generateTOC) + * + Bind foldable sections (bindToggles) + * + Bind links to foldable sections (bindToggleLinks) + */ + +(function() { +'use strict'; + +// Mobile-friendly topbar menu +$(function() { + var menu = $('#menu'); + var menuButton = $('#menu-button'); + var menuButtonArrow = $('#menu-button-arrow'); + menuButton.click(function(event) { + menu.toggleClass('menu-visible'); + menuButtonArrow.toggleClass('vertical-flip'); + event.preventDefault(); + return false; + }); +}); + +function bindSearchEvents() { + + var search = $('#search'); + if (search.length === 0) { + return; // no search box + } + + function clearInactive() { + if (search.is('.inactive')) { + search.val(''); + search.removeClass('inactive'); + } + } + + function restoreInactive() { + if (search.val() !== '') { + return; + } + search.val(search.attr('placeholder')); + search.addClass('inactive'); + } + + search.on('focus', clearInactive); + search.on('blur', restoreInactive); + + restoreInactive(); +} + +/* Generates a table of contents: looks for h2 and h3 elements and generates + * links. "Decorates" the element with id=="nav" with this table of contents. + */ +function generateTOC() { + if ($('#manual-nav').length > 0) { + return; + } + + var nav = $('#nav'); + if (nav.length === 0) { + return; + } + + var toc_items = []; + $(nav).nextAll('h2, h3').each(function() { + var node = this; + if (node.id == '') + node.id = 'tmp_' + toc_items.length; + var link = $('').attr('href', '#' + node.id).text($(node).text()); + var item; + if ($(node).is('h2')) { + item = $('
'); + } else { // h3 + item = $(''); + } + item.append(link); + toc_items.push(item); + }); + if (toc_items.length <= 1) { + return; + } + + var dl1 = $(''+ + 'Your download should begin shortly. '+ + 'If it does not, click this link.
'); + message.find('a').attr('href', download); + message.insertAfter('#nav'); + + window.location = download; +} + +$(document).ready(function() { + bindSearchEvents(); + generateTOC(); + bindToggles(".toggle"); + bindToggles(".toggleVisible"); + bindToggleLinks(".exampleLink", "example_"); + bindToggleLinks(".overviewLink", ""); + bindToggleLinks(".examplesLink", ""); + bindToggleLinks(".indexLink", ""); + setupDropdownPlayground(); + setupInlinePlayground(); + fixFocus(); + setupTypeInfo(); + setupCallgraphs(); + toggleHash(); + personalizeInstallInstructions(); + + // godoc.html defines window.initFuncs in the tag, and root.html and + // codewalk.js push their on-page-ready functions to the list. + // We execute those functions here, to avoid loading jQuery until the page + // content is loaded. + for (var i = 0; i < window.initFuncs.length; i++) window.initFuncs[i](); +}); + +// -- analysis --------------------------------------------------------- + +// escapeHTML returns HTML for s, with metacharacters quoted. +// It is safe for use in both elements and attributes +// (unlike the "set innerText, read innerHTML" trick). +function escapeHTML(s) { + return s.replace(/&/g, '&'). + replace(/\"/g, '"'). + replace(/\'/g, '''). + replace(//g, '>'); +} + +// makeAnchor returns HTML for an element, given an anchorJSON object. +function makeAnchor(json) { + var html = escapeHTML(json.Text); + if (json.Href != "") { + html = "" + html + ""; + } + return html; +} + +function showLowFrame(html) { + var lowframe = document.getElementById('lowframe'); + lowframe.style.height = "200px"; + lowframe.innerHTML = "" + html + "
\n" + + "" + escapeHTML(data.Callee) + "
:" + escapeHTML(caller.Func) + "
";
+ var sites = caller.Sites;
+ if (sites != null && sites.length > 0) {
+ html += " at line ";
+ for (var j = 0; j < sites.length; j++) {
+ if (j > 0) {
+ html += ", ";
+ }
+ html += "" + makeAnchor(sites[j]) + "
";
+ }
+ }
+ html += "" + makeAnchor(data.Callees[i]) + "
" + data.Name + "
: " +
+ " (size=" + data.Size + ", align=" + data.Align + ")" + escapeHTML(group.Descr) + "
";
+ for (var j = 0; j < group.Facts.length; j++) {
+ var fact = group.Facts[j];
+ var y = "" + makeAnchor(fact.Other) + "
";
+ if (fact.ByKind != null) {
+ html += escapeHTML(fact.ByKind) + " type " + y + " implements " + x;
+ } else {
+ html += x + " implements " + y;
+ }
+ html += "" + makeAnchor(info.Methods[i]) + "
" + escapeHTML(ops[i].Fn) + "
t |
Name | +Synopsis | +
---|---|
.. | +|
+ aes + | ++ Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197. + | +
+ 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. + | +
+ ecdsa + | ++ Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-3. + | +
+ elliptic + | ++ Package elliptic implements several standard 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 pseudorandom 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. + | +
+ sha1 + | ++ Package sha1 implements the SHA1 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. + | +
+ x509 + | ++ Package x509 parses X.509-encoded keys and certificates. + | +
+ pkix + | ++ Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP. + | +
const BlockSize = 64
+ +The blocksize of MD5 in bytes. +
+ + +const Size = 16
+ +The size of an MD5 checksum in bytes. +
+ + + + + + + +func New() hash.Hash+
+New returns a new hash.Hash computing the MD5 checksum. +
+ +▹ Example
+func Sum(data []byte) [Size]byte+
+Sum returns the MD5 checksum of the data. +
+ +▹ Example
+var Reader io.Reader+
+Reader is a global, shared instance of a cryptographically +strong pseudo-random generator. +
++On Unix-like systems, Reader reads from /dev/urandom. +On Linux, Reader uses getrandom(2) if available, /dev/urandom otherwise. +On Windows systems, Reader uses the CryptGenRandom API. +
+ + + + + + +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(rand io.Reader, bits int) (p *big.Int, err error)+
+Prime returns a number, p, of the given size, such that p is prime +with high probability. +Prime will return error for any error returned by rand.Read or if bits < 2. +
+ + + + + + + +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
+type Cipher struct {
+ // contains filtered or unexported fields
+}
+ +A Cipher is an instance of RC4 using a particular key. +
+ + + + + + + + + + + + +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 (c *Cipher) Reset()+
+Reset zeros the key data so that it will no longer appear in the +process's memory. +
+ + + + + + +func (c *Cipher) XORKeyStream(dst, src []byte)+
+XORKeyStream sets dst to the result of XORing src with the key stream. +Dst and src may be the same slice but otherwise should not overlap. +
+ + + + + + + + +type KeySizeError int+ + + + + + + + + + + + + + +
func (k KeySizeError) Error() string+ + + + + + + + + + +
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 +)+ + + + +
var ErrDecryption = errors.New("crypto/rsa: decryption error")+
+ErrDecryption represents a failure to decrypt a message. +It is deliberately vague to avoid adaptive attacks. +
+ + +var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA public key size")+
+ErrMessageTooLong is returned when attempting to encrypt a message which is +too large for the size of the public key. +
+ + +var ErrVerification = errors.New("crypto/rsa: verification error")+
+ErrVerification represents a failure to verify a signature. +It is deliberately vague to avoid adaptive attacks. +
+ + + + + + +func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) (msg []byte, err error)+
+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, if not nil, is used to blind the private-key operation +and avoid timing side-channel attacks. Blinding is purely internal to this +function – the random data need not match that used when encrypting. +
++The label parameter must match the value given when encrypting. See +EncryptOAEP for details. +
+ +▹ Example
+func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out []byte, err error)+
+DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS#1 v1.5. +If rand != nil, it uses RSA blinding to avoid timing side-channel attacks. +
++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(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) (err error)+
+DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS#1 v1.5. +If rand != nil, it uses RSA blinding to avoid timing side-channel attacks. +It 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. +This will remove any possibility that an attacker can learn any information +about the plaintext. +See “Chosen Ciphertext Attacks Against Protocols Based on the RSA +Encryption Standard PKCS #1”, Daniel Bleichenbacher, Advances in Cryptology +(Crypto '98). +
++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 defeats the point of this +function. Using at least a 16-byte key will protect against this attack. +
+ +▹ Example
+func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err 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. +
++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 decrypt 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 less +twice the hash length plus 2. +
+ +▹ Example
+func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, err 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 rand parameter is used as a source of entropy to ensure that encrypting +the same message twice doesn't result in the same ciphertext. +
++WARNING: use of this function to encrypt plaintexts other than session keys +is dangerous. Use RSA OAEP in new protocols. +
+ + + + + + + +func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) (s []byte, err 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. +
++If rand is not nil then RSA blinding will be used to avoid timing side-channel attacks. +
++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
+func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte, opts *PSSOptions) (s []byte, err error)+
+SignPSS calculates the signature of hashed using RSASSA-PSS [1]. +Note that hashed 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. +
+ + + + + + + +func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) (err 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
+func VerifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, opts *PSSOptions) error+
+VerifyPSS verifies a PSS 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. The opts argument may be nil, in which case sensible +defaults are used. +
+ + + + + + + + +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). +}+
+CRTValue contains the precomputed Chinese remainder theorem values. +
+ + + + + + + + + + + + + + + + +type OAEPOptions struct { + // Hash is the hash function that will be used when generating the mask. + Hash crypto.Hash + // Label is an arbitrary byte string that must be equal to the value + // used when encrypting. + Label []byte +}+
+OAEPOptions is an interface for passing options to OAEP 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 +}+
+PKCS1v15DecrypterOpts is for passing options to PKCS#1 v1.5 decryption using +the crypto.Decrypter interface. +
+ + + + + + + + + + + + + + + + +type PSSOptions struct { + // SaltLength controls the length of the salt used in the PSS + // signature. It can either be a number of bytes, or one of the special + // PSSSaltLength constants. + SaltLength int + + // Hash, if not zero, overrides the hash function passed to SignPSS. + // This is the only way to specify the hash function when using the + // crypto.Signer interface. + Hash crypto.Hash +}+
+PSSOptions contains options for creating and verifying PSS signatures. +
+ + + + + + + + + + + + + + +func (pssOpts *PSSOptions) HashFunc() crypto.Hash+
+HashFunc returns pssOpts.Hash so that PSSOptions implements +crypto.SignerOpts. +
+ + + + + + + + +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. + CRTValues []CRTValue +}+ + + + + + + + + + + + + + + + +
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 private + // operations, if available. + Precomputed PrecomputedValues +}+
+A PrivateKey represents an RSA key +
+ + + + + + + + + + + + +func GenerateKey(random io.Reader, bits int) (priv *PrivateKey, err error)+
+GenerateKey generates an RSA keypair of the given bit size using the +random source random (for example, crypto/rand.Reader). +
+ + + + + +func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *PrivateKey, err error)+
+GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit +size and the given random source, as suggested in [1]. 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. +
++Table 1 in [2] suggests maximum numbers of primes for a given size. +
++[1] US patent 4405829 (1972, expired) +[2] http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf +
+ + + + + + + +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 (priv *PrivateKey) Precompute()+
+Precompute performs some calculations that speed up private key operations +in the future. +
+ + + + + + +func (priv *PrivateKey) Public() crypto.PublicKey+
+Public returns the public key corresponding to priv. +
+ + + + + + +func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error)+
+Sign signs msg 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. This method is intended 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. +
+ + + + + + +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 struct { + N *big.Int // modulus + E int // public exponent +}+
+A PublicKey represents the public part of an RSA key. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +const BlockSize = 64
+ +The blocksize of SHA1 in bytes. +
+ + +const Size = 20
+ +The size of a SHA1 checksum in bytes. +
+ + + + + + + +func New() hash.Hash+
+New returns a new hash.Hash computing the SHA1 checksum. +
+ +▹ Example
+func Sum(data []byte) [Size]byte+
+Sum returns the SHA1 checksum of the data. +
+ +▹ Example
+const BlockSize = 64
+ +The blocksize of SHA256 and SHA224 in bytes. +
+ + +const Size = 32
+ +The size of a SHA256 checksum in bytes. +
+ + +const Size224 = 28
+ +The size of a SHA224 checksum in bytes. +
+ + + + + + + +func New() hash.Hash+
+New returns a new hash.Hash computing the SHA256 checksum. +
+ + + + + + + +func New224() hash.Hash+
+New224 returns a new hash.Hash computing the SHA224 checksum. +
+ + + + + + + +func Sum224(data []byte) (sum224 [Size224]byte)+
+Sum224 returns the SHA224 checksum of the data. +
+ + + + + + + +func Sum256(data []byte) [Size]byte+
+Sum256 returns the SHA256 checksum of the data. +
+ + + + + + + + + + + + + + + + + + +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() hash.Hash+
+New returns a new hash.Hash computing the SHA-512 checksum. +
+ + + + + + + +func New384() hash.Hash+
+New384 returns a new hash.Hash computing the SHA-384 checksum. +
+ + + + + + + +func New512_224() hash.Hash+
+New512_224 returns a new hash.Hash computing the SHA-512/224 checksum. +
+ + + + + + + +func New512_256() hash.Hash+
+New512_256 returns a new hash.Hash computing the SHA-512/256 checksum. +
+ + + + + + + +func Sum384(data []byte) (sum384 [Size384]byte)+
+Sum384 returns the SHA384 checksum of the data. +
+ + + + + + + +func Sum512(data []byte) [Size]byte+
+Sum512 returns the SHA512 checksum of the data. +
+ + + + + + + +func Sum512_224(data []byte) (sum224 [Size224]byte)+
+Sum512_224 returns the Sum512/224 checksum of the data. +
+ + + + + + + +func Sum512_256(data []byte) (sum256 [Size256]byte)+
+Sum512_256 returns the Sum512/256 checksum of the data. +
+ + + + + + + + + + + + + + + + + + +func ConstantTimeByteEq(x, y uint8) int+
+ConstantTimeByteEq returns 1 if x == y and 0 otherwise. +
+ + + + + + + +func ConstantTimeCompare(x, y []byte) int+
+ConstantTimeCompare returns 1 iff the two slices, x +and y, have equal contents. The time taken is a function of the length of +the slices and is independent of the contents. +
+ + + + + + + +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(x, y int32) int+
+ConstantTimeEq returns 1 if x == y and 0 otherwise. +
+ + + + + + + +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(v, x, y int) int+
+ConstantTimeSelect returns x if v is 1 and y if v is 0. +Its behavior is undefined if v takes any other value. +
+ + + + + + + + + + + + + + + + + + +const ( + 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_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_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_FALLBACK_SCSV isn't a standard cipher suite but an indicator + // that the client is doing version fallback. See + // https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00. + TLS_FALLBACK_SCSV uint16 = 0x5600 +)+
+A list of the possible cipher suite ids. Taken from +http://www.iana.org/assignments/tls-parameters/tls-parameters.xml +
+ + +const ( + VersionSSL30 = 0x0300 + VersionTLS10 = 0x0301 + VersionTLS11 = 0x0302 + VersionTLS12 = 0x0303 +)+ + + + + + + +
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(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. +
+ + + + + + + + +type Certificate struct { + Certificate [][]byte + // PrivateKey contains the private key corresponding to the public key + // in Leaf. For a server, this must implement crypto.Signer and/or + // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client + // (performing client authentication), this must be a crypto.Signer + // with an RSA or ECDSA PublicKey. + PrivateKey crypto.PrivateKey + // 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 + // Leaf is the parsed form of the leaf certificate, which may be + // initialized using x509.ParseCertificate to reduce per-handshake + // processing for TLS clients doing client authentication. If nil, the + // leaf certificate will be parsed as needed. + Leaf *x509.Certificate +}+
+A Certificate is a chain of one or more certificates, leaf first. +
+ + + + + + + + + + + + +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. On successful return, +Certificate.Leaf will be nil because the parsed form of the certificate is +not retained. +
+ + + + + +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. +
+ + + + + + + + + +type ClientAuthType int+
+ClientAuthType declares the policy the server will follow for +TLS Client Authentication. +
+ + + +const ( + NoClientCert ClientAuthType = iota + RequestClientCert + RequireAnyClientCert + VerifyClientCertIfGiven + RequireAndVerifyClientCert +)+ + + + + + + + + + + + + + + +
type ClientHelloInfo struct { + // CipherSuites lists the CipherSuites supported by the client (e.g. + // TLS_RSA_WITH_RC4_128_SHA). + 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 + // http://tools.ietf.org/html/rfc4366#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 + // http://tools.ietf.org/html/rfc4492#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 + // http://tools.ietf.org/html/rfc4492#section-5.1.2). + SupportedPoints []uint8 +}+
+ClientHelloInfo contains information from a ClientHello message in order to +guide certificate selection in the GetCertificate callback. +
+ + + + + + + + + + + + + + + + +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. + Put(sessionKey string, cs *ClientSessionState) +}+
+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. +
+ + + + + + + + + + + + +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 struct {
+ // contains filtered or unexported fields
+}
+ +ClientSessionState contains the state needed by clients to resume TLS +sessions. +
+ + + + + + + + + + + + + + + + +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. + // Server configurations must include at least one certificate + // or else set GetCertificate. + 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. + // See Config.BuildNameToCertificate + // The nil value causes the first element of Certificates to be used + // for all connections. + 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 + // first element of Certificates will be used. + GetCertificate func(clientHello *ClientHelloInfo) (*Certificate, error) + + // 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. + 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, TLS accepts any certificate + // presented by the server and any host name in that certificate. + // In this mode, TLS is susceptible to man-in-the-middle attacks. + // This should be used only for testing. + InsecureSkipVerify bool + + // CipherSuites is a list of supported cipher suites. If CipherSuites + // is nil, TLS uses a list of suites supported by the implementation. + CipherSuites []uint16 + + // PreferServerCipherSuites controls whether the server selects the + // client's most preferred ciphersuite, or the server's most preferred + // ciphersuite. If true then the server's preference, as expressed in + // the order of elements in CipherSuites, is used. + PreferServerCipherSuites bool + + // SessionTicketsDisabled may be set to true to disable session ticket + // (resumption) support. + SessionTicketsDisabled bool + + // SessionTicketKey is used by TLS servers to provide session + // resumption. See RFC 5077. If zero, it will be filled with + // random data before the first server handshake. + // + // If multiple servers are terminating connections for the same host + // they should all have the same SessionTicketKey. If the + // SessionTicketKey leaks, previously recorded and future TLS + // connections using that key are compromised. + SessionTicketKey [32]byte + + // SessionCache is a cache of ClientSessionState entries for TLS session + // resumption. + ClientSessionCache ClientSessionCache + + // MinVersion contains the minimum SSL/TLS version that is acceptable. + // If zero, then TLS 1.0 is taken as the minimum. + MinVersion uint16 + + // MaxVersion contains the maximum SSL/TLS version that is acceptable. + // If zero, then the maximum version supported by this package is used, + // which is currently TLS 1.2. + MaxVersion uint16 + + // CurvePreferences contains the elliptic curves that will be used in + // an ECDHE handshake, in preference order. If empty, the default will + // be used. + CurvePreferences []CurveID + // contains filtered or unexported fields +}+
+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. +
+ + + + + + + + + + + + + + +func (c *Config) BuildNameToCertificate()+
+BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate +from the CommonName and SubjectAlternateName fields of each of the leaf +certificates. +
+ + + + + + +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. +
+ + + + + + + + +type Conn struct {
+ // contains filtered or unexported fields
+}
+ +A Conn represents a secured connection. +It implements the net.Conn interface. +
+ + + + + + + + + + + + +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(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
+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. +
+ + + + + +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 (c *Conn) Close() error+
+Close closes the connection. +
+ + + + + + +func (c *Conn) ConnectionState() ConnectionState+
+ConnectionState returns basic TLS details about the connection. +
+ + + + + + +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 Read or Write will call it automatically. +
+ + + + + + +func (c *Conn) LocalAddr() net.Addr+
+LocalAddr returns the local network address. +
+ + + + + + +func (c *Conn) OCSPResponse() []byte+
+OCSPResponse returns the stapled OCSP response from the TLS server, if +any. (Only valid for client connections.) +
+ + + + + + +func (c *Conn) Read(b []byte) (n int, err error)+
+Read can be made to time out and return a net.Error with Timeout() == true +after a fixed time limit; see SetDeadline and SetReadDeadline. +
+ + + + + + +func (c *Conn) RemoteAddr() net.Addr+
+RemoteAddr returns the remote network address. +
+ + + + + + +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 Read and 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 (c *Conn) SetReadDeadline(t time.Time) error+
+SetReadDeadline sets the read deadline on the underlying connection. +A zero value for t means Read will not time out. +
+ + + + + + +func (c *Conn) SetWriteDeadline(t time.Time) error+
+SetWriteDeadline sets the write deadline on the underlying connection. +A zero value for t means 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 (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 (c *Conn) Write(b []byte) (int, error)+
+Write writes data to the connection. +
+ + + + + + + + +type ConnectionState struct { + Version uint16 // TLS version used by the connection (e.g. VersionTLS12) + HandshakeComplete bool // TLS handshake is complete + DidResume bool // connection resumes a previous TLS connection + CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...) + NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos) + NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server + ServerName string // server name requested by client, if any (server side only) + PeerCertificates []*x509.Certificate // certificate chain presented by remote peer + VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates + SignedCertificateTimestamps [][]byte // SCTs from the server, if any + OCSPResponse []byte // stapled OCSP response from server, if any + + // TLSUnique contains the "tls-unique" channel binding value (see RFC + // 5929, section 3). For resumed sessions this value will be nil + // because resumption does not include enough context (see + // https://secure-resumption.com/#channelbindings). This will change in + // future versions of Go once the TLS master-secret fix has been + // standardized and implemented. + TLSUnique []byte +}+
+ConnectionState records basic TLS details about the connection. +
+ + + + + + + + + + + + + + + + +type CurveID uint16+
+CurveID is the type of a TLS identifier for an elliptic curve. See +http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8 +
+ + + +const ( + CurveP256 CurveID = 23 + CurveP384 CurveID = 24 + CurveP521 CurveID = 25 +)+ + + + + + + + + + + + + + + +
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 +}+
+RecordHeaderError results when a TLS record header is invalid. +
+ + + + + + + + + + + + + + +func (e RecordHeaderError) Error() string+ + + + + + + + + + +
var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")+
+ErrUnsupportedAlgorithm results from attempting to perform an operation that +involves algorithms that are not currently implemented. +
+ + +var IncorrectPasswordError = errors.New("x509: decryption password incorrect")+
+IncorrectPasswordError is returned when an incorrect password is detected. +
+ + + + + + +func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error)+
+CreateCertificate creates a new certificate based on a template. The +following members of template are used: SerialNumber, Subject, NotBefore, +NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid, +IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical, +PermittedDNSDomains, SignatureAlgorithm. +
++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 +signee and priv is the private key of the signer. +
++The returned slice is the certificate in DER encoding. +
++All keys types that are implemented via crypto.Signer are supported (This +includes *rsa.PublicKey and *ecdsa.PublicKey.) +
+ + + + + + + +func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error)+
+CreateCertificateRequest creates a new certificate based on a template. The +following members of template are used: Subject, Attributes, +SignatureAlgorithm, Extensions, DNSNames, EmailAddresses, and IPAddresses. +The private key is the private key of the signer. +
++The returned slice is the certificate request in DER encoding. +
++All keys types that are implemented via crypto.Signer are supported (This +includes *rsa.PublicKey and *ecdsa.PublicKey.) +
+ + + + + + + +func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)+
+DecryptPEMBlock takes a password encrypted PEM block 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 encrypted-PEM 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. +
+ + + + + + + +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. +
+ + + + + + + +func IsEncryptedPEMBlock(b *pem.Block) bool+
+IsEncryptedPEMBlock returns if the PEM block is password encrypted. +
+ + + + + + + +func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error)+
+MarshalECPrivateKey marshals an EC private key into ASN.1, DER format. +
+ + + + + + + +func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte+
+MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form. +
+ + + + + + + +func MarshalPKIXPublicKey(pub interface{}) ([]byte, error)+
+MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format. +
+ + + + + + + +func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err 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. +
+ + + + + + + +func ParseCertificates(asn1Data []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 ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error)+
+ParseDERCRL parses a DER encoded CRL from the given bytes. +
+ + + + + + + +func ParseECPrivateKey(der []byte) (key *ecdsa.PrivateKey, err error)+
+ParseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure. +
+ + + + + + + +func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err error)+
+ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form. +
+ + + + + + + +func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error)+
+ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key. See +http://www.rsa.com/rsalabs/node.asp?id=2130 and RFC5208. +
+ + + + + + + +func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error)+
+ParsePKIXPublicKey parses a DER encoded public key. These values are +typically found in PEM blocks with "BEGIN PUBLIC KEY". +
+ + + + + + + + +type CertPool struct {
+ // contains filtered or unexported fields
+}
+ +CertPool is a set of certificates. +
+ + + + + + + + + + + + +func NewCertPool() *CertPool+
+NewCertPool returns a new, empty CertPool. +
+ + + + + + + +func (s *CertPool) AddCert(cert *Certificate)+
+AddCert adds a certificate to a pool. +
+ + + + + + +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 (s *CertPool) Subjects() (res [][]byte)+
+Subjects returns a list of the DER-encoded subjects of +all of the certificates in the pool. +
+ + + + + + + + +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 interface{} + + 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 + + // 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 + + // 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 + + ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages. + UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package. + + BasicConstraintsValid bool // if true then the next two fields are valid. + IsCA bool + 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 + + SubjectKeyId []byte + AuthorityKeyId []byte + + // RFC 5280, 4.2.2.1 (Authority Information Access) + OCSPServer []string + IssuingCertificateURL []string + + // Subject Alternate Name values + DNSNames []string + EmailAddresses []string + IPAddresses []net.IP + + // Name constraints + PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical. + PermittedDNSDomains []string + + // CRL Distribution Points + CRLDistributionPoints []string + + PolicyIdentifiers []asn1.ObjectIdentifier +}+
+A Certificate represents an X.509 certificate. +
+ + + + + + + + + + + + +func ParseCertificate(asn1Data []byte) (*Certificate, error)+
+ParseCertificate parses a single certificate from the given ASN.1 DER data. +
+ + + + + + + +func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error)+
+CheckCRLSignature checks that the signature in crl is from c. +
+ + + + + + +func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error)+
+CheckSignature verifies that signature is a valid signature over signed from +c's public key. +
+ + + + + + +func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error)+
+CheckSignatureFrom verifies that the signature on c is a valid signature +from parent. +
+ + + + + + +func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, 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. +
+ + + + + + +func (c *Certificate) Equal(other *Certificate) bool+ + + + + + +
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 and system roots are unavailable the returned error +will be of type SystemRootsError. +
++WARNING: this doesn't do any revocation checking. +
+ + +▹ Example
+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. +
+ + + + + + + + +type CertificateInvalidError struct { + Cert *Certificate + Reason InvalidReason +}+
+CertificateInvalidError results when an odd error occurs. Users of this +library probably want to handle all these errors uniformly. +
+ + + + + + + + + + + + + + +func (e CertificateInvalidError) Error() string+ + + + + + + + +
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 interface{} + + Subject pkix.Name + + // Attributes is the dried husk of a bug and shouldn't be used. + Attributes []pkix.AttributeTypeAndValueSET + + // Extensions contains raw X.509 extensions. 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 + // marshaled CSR. 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 when parsing CSRs, see + // Extensions. + ExtraExtensions []pkix.Extension + + // Subject Alternate Name values. + DNSNames []string + EmailAddresses []string + IPAddresses []net.IP +}+
+CertificateRequest represents a PKCS #10, certificate signature request. +
+ + + + + + + + + + + + +func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)+
+ParseCertificateRequest parses a single certificate request from the +given ASN.1 DER data. +
+ + + + + + + +func (c *CertificateRequest) CheckSignature() (err error)+
+CheckSignature verifies that the signature on c is a valid signature +
+ + + + + + + + +type ConstraintViolationError struct{}+
+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. +
+ + + + + + + + + + + + + + +func (ConstraintViolationError) Error() string+ + + + + + + + +
type ExtKeyUsage int+
+ExtKeyUsage represents an extended set of actions that are valid for a given key. +Each of the ExtKeyUsage* constants define a unique action. +
+ + + +const ( + ExtKeyUsageAny ExtKeyUsage = iota + ExtKeyUsageServerAuth + ExtKeyUsageClientAuth + ExtKeyUsageCodeSigning + ExtKeyUsageEmailProtection + ExtKeyUsageIPSECEndSystem + ExtKeyUsageIPSECTunnel + ExtKeyUsageIPSECUser + ExtKeyUsageTimeStamping + ExtKeyUsageOCSPSigning + ExtKeyUsageMicrosoftServerGatedCrypto + ExtKeyUsageNetscapeServerGatedCrypto +)+ + + + + + + + + + + + + + + +
type HostnameError struct { + Certificate *Certificate + Host string +}+
+HostnameError results when the set of authorized names doesn't match the +requested name. +
+ + + + + + + + + + + + + + +func (h HostnameError) Error() string+ + + + + + + + +
type InsecureAlgorithmError SignatureAlgorithm+
+An InsecureAlgorithmError +
+ + + + + + + + + + + + + + +func (e InsecureAlgorithmError) Error() string+ + + + + + + + +
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 include the name + // being checked. + 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 +)+ + + + + + + + + + + + + + + +
type KeyUsage int+
+KeyUsage represents the set of actions that are valid for a given key. It's +a bitmap of the KeyUsage* constants. +
+ + + +const ( + KeyUsageDigitalSignature KeyUsage = 1 << iota + KeyUsageContentCommitment + KeyUsageKeyEncipherment + KeyUsageDataEncipherment + KeyUsageKeyAgreement + KeyUsageCertSign + KeyUsageCRLSign + KeyUsageEncipherOnly + KeyUsageDecipherOnly +)+ + + + + + + + + + + + + + + +
type PEMCipher int+ + + +
const ( + PEMCipherDES PEMCipher + PEMCipher3DES + PEMCipherAES128 + PEMCipherAES192 + PEMCipherAES256 +)+
+Possible values for the EncryptPEMBlock encryption algorithm. +
+ + + + + + + + + + + + + + + +type PublicKeyAlgorithm int+ + + +
const ( + UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota + RSA + DSA + ECDSA +)+ + + + + + + + + + + + + + + +
type SignatureAlgorithm int+ + + +
const ( + UnknownSignatureAlgorithm SignatureAlgorithm = iota + MD2WithRSA + MD5WithRSA + SHA1WithRSA + SHA256WithRSA + SHA384WithRSA + SHA512WithRSA + DSAWithSHA1 + DSAWithSHA256 + ECDSAWithSHA1 + ECDSAWithSHA256 + ECDSAWithSHA384 + ECDSAWithSHA512 +)+ + + + + + + + + + + + + +
func (algo SignatureAlgorithm) String() string+ + + + + + + + +
type SystemRootsError struct{}+
+SystemRootsError results when we fail to load the system root certificates. +
+ + + + + + + + + + + + + + +func (SystemRootsError) Error() string+ + + + + + + + +
type UnhandledCriticalExtension struct{}+ + + + + + + + + + + + + + +
func (h UnhandledCriticalExtension) Error() string+ + + + + + + + +
type UnknownAuthorityError struct {
+ // contains filtered or unexported fields
+}
+ +UnknownAuthorityError results when the certificate issuer is unknown +
+ + + + + + + + + + + + + + +func (e UnknownAuthorityError) Error() string+ + + + + + + + +
type VerifyOptions struct { + DNSName string + Intermediates *CertPool + Roots *CertPool // if nil, the system roots are used + CurrentTime time.Time // if zero, the current time is used + // KeyUsage specifies which Extended Key Usage values are acceptable. + // An empty list means ExtKeyUsageServerAuth. Key usage is considered a + // constraint down the chain which mirrors Windows CryptoAPI behaviour, + // but not the spec. To accept any key usage, include ExtKeyUsageAny. + KeyUsages []ExtKeyUsage +}+
+VerifyOptions contains parameters for Certificate.Verify. It's a structure +because other PKIX verification APIs have ended up needing many options. +
+ + + + + + + + + + + + + + + + + + + + + + + + +type AlgorithmIdentifier struct { + Algorithm asn1.ObjectIdentifier + Parameters asn1.RawValue `asn1:"optional"` +}+
+AlgorithmIdentifier represents the ASN.1 structure of the same name. See RFC +5280, section 4.1.1.2. +
+ + + + + + + + + + + + + + + + +type AttributeTypeAndValue struct { + Type asn1.ObjectIdentifier + Value interface{} +}+
+AttributeTypeAndValue mirrors the ASN.1 structure of the same name in +http://tools.ietf.org/html/rfc5280#section-4.1.2.4 +
+ + + + + + + + + + + + + + + + +type AttributeTypeAndValueSET struct { + Type asn1.ObjectIdentifier + Value [][]AttributeTypeAndValue `asn1:"set"` +}+
+AttributeTypeAndValueSET represents a set of ASN.1 sequences of +AttributeTypeAndValue sequences from RFC 2986 (PKCS #10). +
+ + + + + + + + + + + + + + + + +type CertificateList struct { + TBSCertList TBSCertificateList + SignatureAlgorithm AlgorithmIdentifier + SignatureValue asn1.BitString +}+
+CertificateList represents the ASN.1 structure of the same name. See RFC +5280, section 5.1. Use Certificate.CheckCRLSignature to verify the +signature. +
+ + + + + + + + + + + + + + +func (certList *CertificateList) HasExpired(now time.Time) bool+
+HasExpired reports whether now is past the expiry time of certList. +
+ + + + + + + + +type Extension struct { + Id asn1.ObjectIdentifier + Critical bool `asn1:"optional"` + Value []byte +}+
+Extension represents the ASN.1 structure of the same name. See RFC +5280, section 4.2. +
+ + + + + + + + + + + + + + + + +type Name struct { + Country, Organization, OrganizationalUnit []string + Locality, Province []string + StreetAddress, PostalCode []string + SerialNumber, CommonName string + + Names []AttributeTypeAndValue + ExtraNames []AttributeTypeAndValue +}+
+Name represents an X.509 distinguished name. This only includes the common +elements of a DN. When parsing, all elements are stored in Names and +non-standard elements can be extracted from there. When marshaling, elements +in ExtraNames are appended and override other values with the same OID. +
+ + + + + + + + + + + + + + +func (n *Name) FillFromRDNSequence(rdns *RDNSequence)+ + + + + + +
func (n Name) ToRDNSequence() (ret RDNSequence)+ + + + + + + + +
type RDNSequence []RelativeDistinguishedNameSET+ + + + + + + + + + + + + + + + +
type RelativeDistinguishedNameSET []AttributeTypeAndValue+ + + + + + + + + + + + + + + + +
type RevokedCertificate struct { + SerialNumber *big.Int + RevocationTime time.Time + Extensions []Extension `asn1:"optional"` +}+
+RevokedCertificate represents the ASN.1 structure of the same name. See RFC +5280, section 5.1. +
+ + + + + + + + + + + + + + + + +type TBSCertificateList struct { + Raw asn1.RawContent + Version int `asn1:"optional,default:1"` + Signature AlgorithmIdentifier + Issuer RDNSequence + ThisUpdate time.Time + NextUpdate time.Time `asn1:"optional"` + RevokedCertificates []RevokedCertificate `asn1:"optional"` + Extensions []Extension `asn1:"tag:0,optional,explicit"` +}+
+TBSCertificateList represents the ASN.1 structure of the same name. See RFC +5280, section 5.1. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +var Bool boolType
+ +Bool is a ValueConverter that converts input values to bools. +
++The conversion rules are: +
+- booleans are returned unchanged +- for integer types, + 1 is true + 0 is false, + other integers are an error +- for strings and []byte, same rules as strconv.ParseBool +- all other types are an error ++ + +
var DefaultParameterConverter defaultConverter
+ +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, +and strings to []byte. If the argument is a nil pointer, +ConvertValue returns a nil Value. If the argument is a non-nil +pointer, it is dereferenced and ConvertValue is called +recursively. Other types are an error. +
+ + +var ErrBadConn = errors.New("driver: bad connection")+
+ErrBadConn should be returned by a driver to signal to the sql +package that a driver.Conn is in a bad state (such as the server +having earlier closed the connection) and the 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. +
+ + +var ErrSkip = errors.New("driver: skip fast-path; continue as if unimplemented")+
+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 Int32 int32Type
+ +Int32 is a ValueConverter that converts input values to int64, +respecting the limits of an int32 value. +
+ + +var ResultNoRows noRows
+ +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 String stringType
+ +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). +
+ + + + + + +func IsScanValue(v interface{}) bool+
+IsScanValue reports whether v is a valid Value scan type. +Unlike IsValue, IsScanValue does not permit the string type. +
+ + + + + + + +func IsValue(v interface{}) bool+
+IsValue reports whether v is a valid Value parameter type. +Unlike IsScanValue, IsValue permits the string type. +
+ + + + + + + + +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 +}+
+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. +
+ + + + + + + + + + + + + + + + +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. + Close() error + + // Begin starts and returns a new transaction. + Begin() (Tx, error) +}+
+Conn is a connection to a database. It is not used concurrently +by multiple goroutines. +
++Conn is assumed to be stateful. +
+ + + + + + + + + + + + + + + + +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) +}+
+Driver is the interface that must be implemented by a database +driver. +
+ + + + + + + + + + + + + + + + +type Execer interface { + Exec(query string, args []Value) (Result, error) +}+
+Execer is an optional interface that may be implemented by a Conn. +
++If a Conn does not implement Execer, the sql package's DB.Exec will +first prepare a query, execute the statement, and then close the +statement. +
++Exec may return ErrSkip. +
+ + + + + + + + + + + + + + + + +type NotNull struct { + Converter ValueConverter +}+
+NotNull is a type that implements ValueConverter by disallowing nil +values but otherwise delegating to another ValueConverter. +
+ + + + + + + + + + + + + + +func (n NotNull) ConvertValue(v interface{}) (Value, error)+ + + + + + + + +
type Null struct { + Converter ValueConverter +}+
+Null is a type that implements ValueConverter by allowing nil +values but otherwise delegating to another ValueConverter. +
+ + + + + + + + + + + + + + +func (n Null) ConvertValue(v interface{}) (Value, error)+ + + + + + + + +
type Queryer interface { + Query(query string, args []Value) (Rows, error) +}+
+Queryer is an optional interface that may be implemented by a Conn. +
++If a Conn does not implement Queryer, the sql package's DB.Query will +first prepare a query, execute the statement, and then close the +statement. +
++Query may return ErrSkip. +
+ + + + + + + + + + + + + + + + +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) +}+
+Result is the result of a query execution. +
+ + + + + + + + + + + + + + + + +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. + // + // The dest slice may be populated only with + // a driver Value type, but excluding string. + // All string values must be converted to []byte. + // + // Next should return io.EOF when there are no more rows. + Next(dest []Value) error +}+
+Rows is an iterator over an executed query's results. +
+ + + + + + + + + + + + + + + + +type RowsAffected int64+
+RowsAffected implements Result for an INSERT or UPDATE operation +which mutates a number of rows. +
+ + + + + + + + + + + + + + +func (RowsAffected) LastInsertId() (int64, error)+ + + + + + +
func (v RowsAffected) RowsAffected() (int64, error)+ + + + + + + + +
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. + 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. + Exec(args []Value) (Result, error) + + // Query executes a query that may return rows, such as a + // SELECT. + Query(args []Value) (Rows, error) +}+
+Stmt is a prepared statement. It is bound to a Conn and not +used by multiple goroutines concurrently. +
+ + + + + + + + + + + + + + + + +type Tx interface { + Commit() error + Rollback() error +}+
+Tx is a transaction. +
+ + + + + + + + + + + + + + + + +type Value interface{}+
+Value is a value that drivers must be able to handle. +It is either nil or an instance of one of these types: +
+int64 +float64 +bool +[]byte +string [*] everywhere except from Rows.Next. +time.Time ++ + + + + + + + + + + + + + + + +
type ValueConverter interface { + // ConvertValue converts a value to a driver Value. + ConvertValue(v interface{}) (Value, error) +}+
+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: +
+* converting from the Value types as provided by the sql package + into a database table's specific column type and making sure it + fits, such as making sure a particular int64 fits in a + table's uint16 column. + +* converting a value as given from the database into one of the + driver Value types. + +* by the sql package, for converting from a driver's Value type + to a user's type in a scan. ++ + + + + + + + + + + + + + + + +
type Valuer interface { + // Value returns a driver Value. + Value() (Value, error) +}+
+Valuer is the interface providing the Value method. +
++Types implementing Valuer interface are able to convert +themselves to a driver Value. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +var ErrNoRows = errors.New("sql: no rows in result set")+
+ErrNoRows is returned by Scan when QueryRow doesn't return a +row. In such a case, QueryRow returns a placeholder *Row value that +defers this error until a Scan. +
+ + +var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back")+ + + + + + +
func Drivers() []string+
+Drivers returns a sorted list of the names of the registered drivers. +
+ + + + + + + +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 DB struct {
+ // contains filtered or unexported fields
+}
+ +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 only be reliably +observed within a transaction. Once DB.Begin is called, the +returned Tx is bound to a single connection. Once Commit or +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 SetMaxIdleConns. +
+ + + + + + + + + + + + +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 +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 (db *DB) Begin() (*Tx, error)+
+Begin starts a transaction. The isolation level is dependent on +the driver. +
+ + + + + + +func (db *DB) Close() error+
+Close closes the database, releasing any open resources. +
++It is rare to Close a DB, as the DB handle is meant to be +long-lived and shared between many goroutines. +
+ + + + + + +func (db *DB) Driver() driver.Driver+
+Driver returns the database's underlying driver. +
+ + + + + + +func (db *DB) Exec(query string, args ...interface{}) (Result, error)+
+Exec executes a query without returning any rows. +The args are for any placeholder parameters in the query. +
+ + + + + + +func (db *DB) Ping() error+
+Ping verifies a connection to the database is still alive, +establishing a connection if necessary. +
+ + + + + + +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 Close method +when the statement is no longer needed. +
+ + + + + + +func (db *DB) Query(query string, args ...interface{}) (*Rows, error)+
+Query executes a query that returns rows, typically a SELECT. +The args are for any placeholder parameters in the query. +
+ + +▹ Example
+func (db *DB) QueryRow(query string, args ...interface{}) *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. +
+ + +▹ Example
+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 reused forever. +
+ + + + + + +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. +
+ + + + + + +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 *DB) Stats() DBStats+
+Stats returns database statistics. +
+ + + + + + + + +type DBStats struct { + // OpenConnections is the number of open connections to the database. + OpenConnections int +}+
+DBStats contains database statistics. +
+ + + + + + + + + + + + + + + + +type NullBool struct { + Bool bool + Valid bool // Valid is true if Bool is not NULL +}+
+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. +
+ + + + + + + + + + + + + + +func (n *NullBool) Scan(value interface{}) error+
+Scan implements the Scanner interface. +
+ + + + + + +func (n NullBool) Value() (driver.Value, error)+
+Value implements the driver Valuer interface. +
+ + + + + + + + +type NullFloat64 struct { + Float64 float64 + Valid bool // Valid is true if Float64 is not NULL +}+
+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. +
+ + + + + + + + + + + + + + +func (n *NullFloat64) Scan(value interface{}) error+
+Scan implements the Scanner interface. +
+ + + + + + +func (n NullFloat64) Value() (driver.Value, error)+
+Value implements the driver Valuer interface. +
+ + + + + + + + +type NullInt64 struct { + Int64 int64 + Valid bool // Valid is true if Int64 is not NULL +}+
+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. +
+ + + + + + + + + + + + + + +func (n *NullInt64) Scan(value interface{}) error+
+Scan implements the Scanner interface. +
+ + + + + + +func (n NullInt64) Value() (driver.Value, error)+
+Value implements the driver Valuer interface. +
+ + + + + + + + +type NullString struct { + String string + Valid bool // Valid is true if String is not NULL +}+
+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 +} ++ + + + + + + + + + + + + + +
func (ns *NullString) Scan(value interface{}) error+
+Scan implements the Scanner interface. +
+ + + + + + +func (ns NullString) Value() (driver.Value, error)+
+Value implements the driver Valuer interface. +
+ + + + + + + + +type RawBytes []byte+
+RawBytes is a byte slice that holds a reference to memory owned by +the database itself. After a Scan into a RawBytes, the slice is only +valid until the next call to Next, Scan, or Close. +
+ + + + + + + + + + + + + + + + +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) +}+
+A Result summarizes an executed SQL command. +
+ + + + + + + + + + + + + + + + +type Row struct {
+ // contains filtered or unexported fields
+}
+ +Row is the result of calling QueryRow to select a single row. +
+ + + + + + + + + + + + + + +func (r *Row) Scan(dest ...interface{}) 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 struct {
+ // contains filtered or unexported fields
+}
+ +Rows is the result of a query. Its cursor starts before the first row +of the result set. Use Next to advance through the rows: +
+rows, err := db.Query("SELECT ...") +... +defer rows.Close() +for rows.Next() { + var id int + var name string + err = rows.Scan(&id, &name) + ... +} +err = rows.Err() // get any error encountered during iteration +... ++ + + + + + + + + + + + + + +
func (rs *Rows) Close() error+
+Close closes the Rows, preventing further enumeration. If Next returns +false, the Rows are closed automatically and it will suffice to check the +result of Err. Close is idempotent and does not affect the result of Err. +
+ + + + + + +func (rs *Rows) Columns() ([]string, error)+
+Columns returns the column names. +Columns returns an error if the rows are closed, or if the rows +are from QueryRow and there was a deferred error. +
+ + + + + + +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 Close. +
+ + + + + + +func (rs *Rows) Next() bool+
+Next prepares the next result row for reading with the Scan method. It +returns true on success, or false if there is no next result row or an error +happened while preparing it. Err should be consulted to distinguish between +the two cases. +
++Every call to Scan, even the first one, must be preceded by a call to Next. +
+ + + + + + +func (rs *Rows) Scan(dest ...interface{}) 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 +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.Format3339Nano 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. +
+ + + + + + + + +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 can not be stored + // without loss of information. + Scan(src interface{}) error +}+
+Scanner is an interface used by Scan. +
+ + + + + + + + + + + + + + + + +type Stmt struct {
+ // contains filtered or unexported fields
+}
+ +Stmt is a prepared statement. +A Stmt is safe for concurrent use by multiple goroutines. +
+ + + + + + + + + + + + + + +func (s *Stmt) Close() error+
+Close closes the statement. +
+ + + + + + +func (s *Stmt) Exec(args ...interface{}) (Result, error)+
+Exec executes a prepared statement with the given arguments and +returns a Result summarizing the effect of the statement. +
+ + + + + + +func (s *Stmt) Query(args ...interface{}) (*Rows, error)+
+Query executes a prepared query statement with the given arguments +and returns the query results as a *Rows. +
+ + + + + + +func (s *Stmt) QueryRow(args ...interface{}) *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's Scan will return ErrNoRows. +Otherwise, the *Row's Scan scans the first selected row and discards +the rest. +
++Example usage: +
+var name string +err := nameByUseridStmt.QueryRow(id).Scan(&name) ++ + + + + + + + +
type Tx struct {
+ // contains filtered or unexported fields
+}
+ +Tx is an in-progress database transaction. +
++A transaction must end with a call to Commit or Rollback. +
++After a call to Commit or Rollback, all operations on the +transaction fail with ErrTxDone. +
++The statements prepared for a transaction by calling +the transaction's Prepare or Stmt methods are closed +by the call to Commit or Rollback. +
+ + + + + + + + + + + + + + +func (tx *Tx) Commit() error+
+Commit commits the transaction. +
+ + + + + + +func (tx *Tx) Exec(query string, args ...interface{}) (Result, error)+
+Exec executes a query that doesn't return rows. +For example: an INSERT and UPDATE. +
+ + + + + + +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 can no longer +be used once the transaction has been committed or rolled back. +
++To use an existing prepared statement on this transaction, see Tx.Stmt. +
+ + + + + + +func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error)+
+Query executes a query that returns rows, typically a SELECT. +
+ + + + + + +func (tx *Tx) QueryRow(query string, args ...interface{}) *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. +
+ + + + + + +func (tx *Tx) Rollback() error+
+Rollback aborts the transaction. +
+ + + + + + +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 can no longer +be used once the transaction has been committed or rolled back. +
+ + + + + + + + + + + + + + + + +const ( + TagBoolean = 1 + TagInteger = 2 + TagBitString = 3 + TagOctetString = 4 + TagOID = 6 + TagEnum = 10 + TagUTF8String = 12 + TagSequence = 16 + TagSet = 17 + TagPrintableString = 19 + TagT61String = 20 + TagIA5String = 22 + TagUTCTime = 23 + TagGeneralizedTime = 24 + TagGeneralString = 27 +)+
+ASN.1 tags represent the type of the following object. +
+ + +const ( + ClassUniversal = 0 + ClassApplication = 1 + ClassContextSpecific = 2 + ClassPrivate = 3 +)+
+ASN.1 class types represent the namespace of the tag. +
+ + + + + + + +func Marshal(val interface{}) ([]byte, error)+
+Marshal returns the ASN.1 encoding of val. +
++In addition to the struct tags recognised by Unmarshal, the following can be +used: +
+ia5: causes strings to be marshaled as ASN.1, IA5 strings +omitempty: causes empty slices to be skipped +printable: causes strings to be marshaled as ASN.1, PrintableString strings. +utf8: causes strings to be marshaled as ASN.1, UTF8 strings ++ + + + + + + +
func Unmarshal(b []byte, val interface{}) (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. +
++An ASN.1 INTEGER can be written to an int, int32, int64, +or *big.Int (from the math/big package). +If the encoded value does not fit in the Go type, +Unmarshal returns a parse error. +
++An ASN.1 BIT STRING can be written to a BitString. +
++An ASN.1 OCTET STRING can be written to a []byte. +
++An ASN.1 OBJECT IDENTIFIER can be written to an +ObjectIdentifier. +
++An ASN.1 ENUMERATED can be written to an Enumerated. +
++An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time. +
++An ASN.1 PrintableString or IA5String can be written to a string. +
++Any of the above ASN.1 values can be written to an interface{}. +The value stored in the interface has the corresponding Go type. +For integers, that type is int64. +
++An ASN.1 SEQUENCE OF x or SET OF x can be written +to a slice if an x can be written to the slice's element type. +
++An ASN.1 SEQUENCE or SET can be written to a struct +if each of the elements in the sequence can be +written to the corresponding element in the struct. +
++The following tags on struct fields have special meaning to Unmarshal: +
+application specifies that a APPLICATION tag is used +default:x sets the default value for optional integer fields +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 ++
+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 type name of a slice element ends with "SET" then it's treated as if +the "set" tag was set on it. 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(b []byte, val interface{}, 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 struct { + Bytes []byte // bits packed into bytes. + BitLength int // length in bits. +}+
+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. +
+ + + + + + + + + + + + + + +func (b BitString) At(i int) int+
+At returns the bit at the given index. If the index is out of range it +returns false. +
+ + + + + + +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 int+
+An Enumerated is represented as a plain int. +
+ + + + + + + + + + + + + + + + +type Flag bool+
+A Flag accepts any data and is set to true if present. +
+ + + + + + + + + + + + + + + + +type ObjectIdentifier []int+
+An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER. +
+ + + + + + + + + + + + + + +func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool+
+Equal reports whether oi and other represent the same identifier. +
+ + + + + + +func (oi ObjectIdentifier) String() string+ + + + + + + + +
type RawContent []byte+
+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 RawValue struct { + Class, Tag int + IsCompound bool + Bytes []byte + FullBytes []byte // includes the tag and length +}+
+A RawValue represents an undecoded ASN.1 object. +
+ + + + + + + + + + + + + + + + +type StructuralError struct { + Msg string +}+
+A StructuralError suggests that the ASN.1 data is valid, but the Go type +which is receiving it doesn't match. +
+ + + + + + + + + + + + + + +func (e StructuralError) Error() string+ + + + + + + + +
type SyntaxError struct { + Msg string +}+
+A SyntaxError suggests that the ASN.1 data is invalid. +
+ + + + + + + + + + + + + + +func (e SyntaxError) Error() string+ + + + + + + + + + + + + + + + + + +
func Compact(dst *bytes.Buffer, src []byte) error+
+Compact appends to dst the JSON-encoded src with +insignificant space characters elided. +
+ + + + + + + +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. +
+ + + + + + + +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
+func Marshal(v interface{}) ([]byte, error)+
+Marshal returns the JSON encoding of v. +
++Marshal traverses the value v recursively. +If an encountered value implements the Marshaler interface +and is not a nil pointer, Marshal calls its MarshalJSON method +to produce JSON. If no MarshalJSON method is present but the +value implements encoding.TextMarshaler instead, Marshal calls +its MarshalText method. +The nil pointer exception is not strictly necessary +but mimics a similar, necessary exception in the behavior of +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. +
++String values encode as JSON strings coerced to valid UTF-8, +replacing invalid bytes with the Unicode replacement rune. +The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" +to keep some browsers from misinterpreting JSON output as HTML. +Ampersand "&" is also escaped to "\u0026" for the same reason. +
++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 object. +
++Struct values encode as JSON objects. Each exported struct field +becomes a member of the object unless +
+- the field's tag is "-", or +- the field is empty and its tag specifies the "omitempty" option. ++
+The empty values are false, 0, any +nil pointer or interface value, and any array, slice, map, or string of +length zero. The object's default key string is the struct field name +but can be specified in the struct field's tag value. The "json" key in +the struct field's tag value is the key name, followed by an optional comma +and options. Examples: +
+// Field is ignored by this package. +Field int `json:"-"` + +// 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"` ++
+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, dollar signs, percent signs, hyphens, +underscores and slashes. +
++Anonymous 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 be string; the map keys are used as JSON object +keys, 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 object. +
++Interface values encode as the value contained in the interface. +A nil interface value encodes as the null JSON object. +
++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 infinite recursion. +
+ +▹ Example
+func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)+
+MarshalIndent is like Marshal but applies Indent to format the output. +
+ + + + + + + +func Unmarshal(data []byte, v interface{}) error+
+Unmarshal parses the JSON-encoded data and stores the result +in the value pointed to by v. +
++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 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. +Unmarshal will only set exported fields of the struct. +
++To unmarshal JSON into an interface value, +Unmarshal stores one of these in the interface value: +
+bool, for JSON booleans +float64, for JSON numbers +string, for JSON strings +[]interface{}, for JSON arrays +map[string]interface{}, for JSON objects +nil for JSON null ++
+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 string-keyed 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. +
++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. +
++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
+type Decoder struct {
+ // contains filtered or unexported fields
+}
+ +A Decoder reads and decodes JSON objects from an input stream. +
+ + + + + + +▹ Example
+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 (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 Decode. +
+ + + + + + +func (dec *Decoder) Decode(v interface{}) 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)
+func (dec *Decoder) More() bool+
+More reports whether there is another element in the +current array or object being parsed. +
+ + + + + + +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
+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 rune+
+A Delim is a JSON array or object delimiter, one of [ ] { or }. +
+ + + + + + + + + + + + + + +func (d Delim) String() string+ + + + + + + + +
type Encoder struct {
+ // contains filtered or unexported fields
+}
+ +An Encoder writes JSON objects to an output stream. +
+ + + + + + + + + + + + +func NewEncoder(w io.Writer) *Encoder+
+NewEncoder returns a new encoder that writes to w. +
+ + + + + + + +func (enc *Encoder) Encode(v interface{}) 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. +
+ + + + + + + + +type InvalidUTF8Error struct { + S string // the whole string value that caused the error +}+
+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. +This error is no longer generated but is kept for backwards compatibility +with programs that might mention it. +
+ + + + + + + + + + + + + + +func (e *InvalidUTF8Error) Error() string+ + + + + + + + +
type InvalidUnmarshalError struct { + Type reflect.Type +}+
+An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. +(The argument to Unmarshal must be a non-nil pointer.) +
+ + + + + + + + + + + + + + +func (e *InvalidUnmarshalError) Error() string+ + + + + + + + +
type Marshaler interface { + MarshalJSON() ([]byte, error) +}+
+Marshaler is the interface implemented by objects that +can marshal themselves into valid JSON. +
+ + + + + + + + + + + + + + + + +type MarshalerError struct { + Type reflect.Type + Err error +}+ + + + + + + + + + + + + + +
func (e *MarshalerError) Error() string+ + + + + + + + +
type Number string+
+A Number represents a JSON number literal. +
+ + + + + + + + + + + + + + +func (n Number) Float64() (float64, error)+
+Float64 returns the number as a float64. +
+ + + + + + +func (n Number) Int64() (int64, error)+
+Int64 returns the number as an int64. +
+ + + + + + +func (n Number) String() string+
+String returns the literal text of the number. +
+ + + + + + + + +type RawMessage []byte+
+RawMessage is a raw encoded JSON object. +It implements Marshaler and Unmarshaler and can +be used to delay JSON decoding or precompute a JSON encoding. +
+ + + + + + +▹ Example
+func (m *RawMessage) MarshalJSON() ([]byte, error)+
+MarshalJSON returns *m as the JSON encoding of m. +
+ + + + + + +func (m *RawMessage) UnmarshalJSON(data []byte) error+
+UnmarshalJSON sets *m to a copy of data. +
+ + + + + + + + +type SyntaxError struct { + Offset int64 // error occurred after reading Offset bytes + // contains filtered or unexported fields +}+
+A SyntaxError is a description of a JSON syntax error. +
+ + + + + + + + + + + + + + +func (e *SyntaxError) Error() string+ + + + + + + + +
type Token interface{}+
+A Token holds a value of one of these types: +
+Delim, for the four JSON delimiters [ ] { } +bool, for JSON booleans +float64, for JSON numbers +Number, for JSON numbers +string, for JSON string literals +nil, for JSON null ++ + + + + + + + + + + + + + + + +
type UnmarshalFieldError struct { + Key string + Type reflect.Type + Field reflect.StructField +}+
+An UnmarshalFieldError describes a JSON object key that +led to an unexported (and therefore unwritable) struct field. +(No longer used; kept for compatibility.) +
+ + + + + + + + + + + + + + +func (e *UnmarshalFieldError) Error() string+ + + + + + + + +
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 +}+
+An UnmarshalTypeError describes a JSON value that was +not appropriate for a value of a specific Go type. +
+ + + + + + + + + + + + + + +func (e *UnmarshalTypeError) Error() string+ + + + + + + + +
type Unmarshaler interface { + UnmarshalJSON([]byte) error +}+
+Unmarshaler is the interface implemented by objects +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. +
+ + + + + + + + + + + + + + + + +type UnsupportedTypeError struct { + Type reflect.Type +}+
+An UnsupportedTypeError is returned by Marshal when attempting +to encode an unsupported value type. +
+ + + + + + + + + + + + + + +func (e *UnsupportedTypeError) Error() string+ + + + + + + + +
type UnsupportedValueError struct { + Value reflect.Value + Str string +}+ + + + + + + + + + + + + + +
func (e *UnsupportedValueError) Error() string+ + + + + + + + + + + + + + + + + + +
func Encode(out io.Writer, b *Block) error+ + + + + + + +
func EncodeToMemory(b *Block) []byte+ + + + + + + + +
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. +}+
+A Block represents a PEM encoded structure. +
++The encoded form is: +
+-----BEGIN Type----- +Headers +base64-encoded Bytes +-----END Type----- ++
+where Headers is a possibly empty sequence of Key: Value lines. +
+ + + + + + + + + + + + +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. +
+ + + + + + + + + + + + + + + + + + + +const ( + // 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" +)+ + + + +
var HTMLAutoClose = htmlAutoClose
+ +HTMLAutoClose is the set of HTML elements that +should be considered to close automatically. +
+ + +var HTMLEntity = htmlEntity
+ +HTMLEntity is an entity map containing translations for the +standard HTML entity characters. +
+ + + + + + +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(w io.Writer, s []byte) error+
+EscapeText writes to w the properly escaped XML equivalent +of the plain text data s. +
+ + + + + + + +func Marshal(v interface{}) ([]byte, error)+
+Marshal returns the XML encoding of v. +
++Marshal handles an array or slice by marshalling each of the elements. +Marshal handles a pointer by marshalling the value it points at or, if the +pointer is nil, by writing nothing. Marshal handles an interface value by +marshalling 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 tag on the XMLName field, if the data is a struct +- the value of the XMLName field of type xml.Name +- the tag of the struct field used to obtain the data +- the name of the struct field used to obtain the data +- the name of the marshalled type ++
+The XML element for a struct contains marshalled elements for each of the +exported fields of the struct, with these exceptions: +
+- the XMLName field, described above, is omitted. +- a field with tag "-" is omitted. +- a field with tag "name,attr" becomes an attribute with + the given name in the XML element. +- a field with tag ",attr" becomes an attribute with the + field name in the XML element. +- a field with tag ",chardata" is written as character data, + not as an XML element. +- a field with tag ",cdata" is written as character data + wrapped in one or more <![CDATA[ ... ]]> tags, not as an XML element. +- a field with tag ",innerxml" is written verbatim, not subject + to the usual marshalling procedure. +- a field with tag ",comment" is written as an XML comment, not + subject to the usual marshalling procedure. It must not contain + the "--" string within it. +- a field with a tag including the "omitempty" option is omitted + if the field value is empty. The empty values are false, 0, any + nil pointer or interface value, and any array, slice, map, or + string of length zero. +- an anonymous struct field is handled as if the fields of its + value were part of the outer struct. ++
+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. +
++See MarshalIndent for an example. +
++Marshal will return an error if asked to marshal a channel, function, or map. +
+ + + + + + + +func MarshalIndent(v interface{}, 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
+func Unmarshal(data []byte, v interface{}) 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 the struct has a field of type []byte or string with tag + ",innerxml", Unmarshal accumulates the raw XML nested inside the + element in that field. The rest of the rules still apply. + +* If the struct has a field named XMLName of type xml.Name, + Unmarshal records the element name in that field. + +* If the XMLName field has an associated tag of the form + "name" or "namespace-URL name", the XML element must have + the given name (and, optionally, name space) or else Unmarshal + returns an error. + +* If the XML element has an attribute whose name matches a + struct field name with an associated tag containing ",attr" or + the explicit name in a struct field tag of the form "name,attr", + Unmarshal records the attribute value in that field. + +* If the XML element contains character data, that data is + accumulated in the first struct field that has tag ",chardata". + The struct field may have type []byte or string. + If there is no such field, the character data is discarded. + +* If the XML element contains comments, they are accumulated in + the first struct field that has tag ",comment". The struct + field may have type []byte or string. If there is no such + field, the comments are discarded. + +* If the XML element contains a sub-element whose name matches + the prefix of a tag formatted as "a" or "a>b>c", unmarshal + will descend into the XML structure looking for elements with the + given names, and will map the innermost elements to that struct + field. A tag starting with ">" is equivalent to one starting + with the field name followed by ">". + +* If the XML element contains a sub-element whose name matches + a struct field's XMLName tag and the struct field has no + explicit name tag as per the previous rule, unmarshal maps + the sub-element to that struct field. + +* If the XML element contains a sub-element whose name matches a + field without any mode flags (",attr", ",chardata", etc), Unmarshal + maps the sub-element to that struct field. + +* If the XML element contains a sub-element that hasn't matched any + of the above rules and the struct has a field with tag ",any", + unmarshal maps the sub-element to that struct field. + +* An anonymous struct field is handled as if the fields of its + value were part of the outer struct. + +* A struct field with tag "-" is never unmarshalled into. ++
+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 XML element to a slice by extending the length of +the slice and mapping the element 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. +
++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. +
++Unmarshal maps an XML element to an xml.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. +
+ +▹ Example
+type Attr struct { + Name Name + Value string +}+
+An Attr represents an attribute in an XML element (Name=Value). +
+ + + + + + + + + + + + + + + + +type CharData []byte+
+A CharData represents XML character data (raw text), +in which XML escape sequences have been replaced by +the characters they represent. +
+ + + + + + + + + + + + + + +func (c CharData) Copy() CharData+ + + + + + + + +
type Comment []byte+
+A Comment represents an XML comment of the form <!--comment-->. +The bytes do not include the <!-- and --> comment markers. +
+ + + + + + + + + + + + + + +func (c Comment) Copy() Comment+ + + + + + + + +
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 = HTMLAutoClose; + // d.Entity = 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 + // 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 + // contains filtered or unexported fields +}+
+A Decoder represents an XML parser reading a particular input stream. +The parser assumes that its input is encoded in UTF-8. +
+ + + + + + + + + + + + +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 (d *Decoder) Decode(v interface{}) error+
+Decode works like xml.Unmarshal, except it reads the decoder +stream to find the start element. +
+ + + + + + +func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error+
+DecodeElement works like xml.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 (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 (d *Decoder) RawToken() (Token, error)+
+RawToken is like Token but does not verify that +start and end elements match and does not translate +name space prefixes to their corresponding URLs. +
+ + + + + + +func (d *Decoder) Skip() error+
+Skip reads tokens until it has consumed the end element +matching the most recent start element already consumed. +It recurs if it encounters a start element, so it can be used to +skip nested structures. +It returns nil if it finds an end element matching the start +element; otherwise it returns an error describing the problem. +
+ + + + + + +func (d *Decoder) Token() (t Token, err 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. +
++Token implements XML name spaces as described by +http://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 []byte+
+A Directive represents an XML directive of the form <!text>. +The bytes do not include the <! and > markers. +
+ + + + + + + + + + + + + + +func (d Directive) Copy() Directive+ + + + + + + + +
type Encoder struct {
+ // contains filtered or unexported fields
+}
+ +An Encoder writes XML data to an output stream. +
+ + + + + + +▹ Example
+func NewEncoder(w io.Writer) *Encoder+
+NewEncoder returns a new encoder that writes to w. +
+ + + + + + + +func (enc *Encoder) Encode(v interface{}) 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 Flush before returning. +
+ + + + + + +func (enc *Encoder) EncodeElement(v interface{}, 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 Flush before returning. +
+ + + + + + +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 Flush, because usually it is part of a larger operation +such as Encode or 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 (enc *Encoder) Flush() error+
+Flush flushes any buffered XML to the underlying writer. +See the EncodeToken documentation for details about when it is necessary. +
+ + + + + + +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 struct { + Name Name +}+
+An EndElement represents an XML end element. +
+ + + + + + + + + + + + + + + + +type Marshaler interface { + MarshalXML(e *Encoder, start StartElement) error +}+
+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 MarshalerAttr interface { + MarshalXMLAttr(name Name) (Attr, error) +}+
+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 Name struct { + Space, Local string +}+
+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 ProcInst struct { + Target string + Inst []byte +}+
+A ProcInst represents an XML processing instruction of the form <?target inst?> +
+ + + + + + + + + + + + + + +func (p ProcInst) Copy() ProcInst+ + + + + + + + +
type StartElement struct { + Name Name + Attr []Attr +}+
+A StartElement represents an XML start element. +
+ + + + + + + + + + + + + + +func (e StartElement) Copy() StartElement+ + + + + + +
func (e StartElement) End() EndElement+
+End returns the corresponding XML end element. +
+ + + + + + + + +type SyntaxError struct { + Msg string + Line int +}+
+A SyntaxError represents a syntax error in the XML input stream. +
+ + + + + + + + + + + + + + +func (e *SyntaxError) Error() string+ + + + + + + + +
type TagPathError struct { + Struct reflect.Type + Field1, Tag1 string + Field2, Tag2 string +}+
+A TagPathError represents an error in the unmarshalling process +caused by the use of field tags with conflicting paths. +
+ + + + + + + + + + + + + + +func (e *TagPathError) Error() string+ + + + + + + + +
type Token interface{}+
+A Token is an interface holding one of the token types: +StartElement, EndElement, CharData, Comment, ProcInst, or Directive. +
+ + + + + + + + + + + + +func CopyToken(t Token) Token+
+CopyToken returns a copy of a Token. +
+ + + + + + + + + +type UnmarshalError string+
+An UnmarshalError represents an error in the unmarshalling process. +
+ + + + + + + + + + + + + + +func (e UnmarshalError) Error() string+ + + + + + + + +
type Unmarshaler interface { + UnmarshalXML(d *Decoder, start StartElement) error +}+
+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 UnmarshalerAttr interface { + UnmarshalXMLAttr(attr Attr) error +}+
+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 UnsupportedTypeError struct { + Type reflect.Type +}+
+A MarshalXMLError is returned when Marshal encounters a type +that cannot be converted into XML. +
+ + + + + + + + + + + + + + +func (e *UnsupportedTypeError) Error() string+ + + + + + + + + + +
▹ Example
+func New(text string) error+
+New returns an error that formats as the given text. +
+ +▹ Example
+▹ Example (Errorf)
+▹ Example
+var CommandLine = NewFlagSet(os.Args[0], ExitOnError)+
+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 ErrHelp = errors.New("flag: help requested")+
+ErrHelp is the error returned if the -help or -h flag is invoked +but no such flag is defined. +
+ + +var Usage = func() { + fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) + PrintDefaults() +}+
+Usage prints to standard error a usage message documenting all defined command-line flags. +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. +
+ + + + + + +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() []string+
+Args returns the non-flag command-line arguments. +
+ + + + + + + +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 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(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(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(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(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 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(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(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(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() int+
+NArg is the number of arguments remaining after flags have been processed. +
+ + + + + + + +func NFlag() int+
+NFlag returns the number of command-line flags that have been set. +
+ + + + + + + +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() bool+
+Parsed reports whether the command-line flags have been parsed. +
+ + + + + + + +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. ++ + + + + + + +
func Set(name, value string) error+
+Set sets the value of the named command-line flag. +
+ + + + + + + +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(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 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(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(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(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(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(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(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(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 int+
+ErrorHandling defines how FlagSet.Parse behaves if the parse fails. +
+ + + +const ( + ContinueOnError ErrorHandling = iota // Return a descriptive error. + ExitOnError // Call os.Exit(2). + PanicOnError // Call panic with a descriptive error. +)+
+These constants cause FlagSet.Parse to behave as described if the parse fails. +
+ + + + + + + + + + + + + + + +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 +}+
+A Flag represents the state of a flag. +
+ + + + + + + + + + + + +func Lookup(name string) *Flag+
+Lookup returns the Flag structure of the named command-line flag, +returning nil if none exists. +
+ + + + + + + + + +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. + Usage func() + // contains filtered or unexported fields +}+
+A FlagSet represents a set of defined flags. The zero value of a FlagSet +has no name and has ContinueOnError error handling. +
+ + + + + + + + + + + + +func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet+
+NewFlagSet returns a new, empty flag set with the specified name and +error handling property. +
+ + + + + + + +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 (f *FlagSet) Args() []string+
+Args returns the non-flag arguments. +
+ + + + + + +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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (f *FlagSet) Lookup(name string) *Flag+
+Lookup returns the Flag structure of the named flag, returning nil if none exists. +
+ + + + + + +func (f *FlagSet) NArg() int+
+NArg is the number of arguments remaining after flags have been processed. +
+ + + + + + +func (f *FlagSet) NFlag() int+
+NFlag returns the number of flags that have been set. +
+ + + + + + +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 (f *FlagSet) Parsed() bool+
+Parsed reports whether f.Parse has been called. +
+ + + + + + +func (f *FlagSet) PrintDefaults()+
+PrintDefaults prints to standard error the default values of all +defined command-line flags in the set. See the documentation for +the global function PrintDefaults for more information. +
+ + + + + + +func (f *FlagSet) Set(name, value string) error+
+Set sets the value of the named flag. +
+ + + + + + +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 (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 (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 (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 (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 (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 (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 (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 (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 (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 interface { + Value + Get() interface{} +}+
+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. +
+ + + + + + + + + + + + + + + + +type Value interface { + String() string + Set(string) error +}+
+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. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +func Errorf(format string, a ...interface{}) error+
+Errorf formats according to a format specifier and returns the string +as a value that satisfies error. +
+ + + + + + + +func Fprint(w io.Writer, a ...interface{}) (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. +
+ + + + + + + +func Fprintf(w io.Writer, format string, a ...interface{}) (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. +
+ + + + + + + +func Fprintln(w io.Writer, a ...interface{}) (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. +
+ + + + + + + +func Fscan(r io.Reader, a ...interface{}) (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(r io.Reader, format string, a ...interface{}) (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. +
+ + + + + + + +func Fscanln(r io.Reader, a ...interface{}) (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. +
+ + + + + + + +func Print(a ...interface{}) (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. +
+ + + + + + + +func Printf(format string, a ...interface{}) (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. +
+ + + + + + + +func Println(a ...interface{}) (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. +
+ + + + + + + +func Scan(a ...interface{}) (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(format string, a ...interface{}) (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(a ...interface{}) (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(a ...interface{}) 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. +
+ + + + + + + +func Sprintf(format string, a ...interface{}) string+
+Sprintf formats according to a format specifier and returns the resulting string. +
+ + + + + + + +func Sprintln(a ...interface{}) 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. +
+ + + + + + + +func Sscan(str string, a ...interface{}) (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(str string, format string, a ...interface{}) (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. +
+ + + + + + + +func Sscanln(str string, a ...interface{}) (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 interface { + Format(f State, c rune) +}+
+Formatter is the interface implemented by values with a custom formatter. +The implementation of Format may call Sprint(f) or Fprint(f) etc. +to generate its output. +
+ + + + + + + + + + + + + + + + +type GoStringer interface { + GoString() string +}+
+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 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) +}+
+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 Scanner interface { + Scan(state ScanState, verb rune) error +}+
+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 State interface { + // Write is the function to call to emit formatted output to be printed. + Write(b []byte) (ret 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 +}+
+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 Stringer interface { + String() string +}+
+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. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +▹ Example
+func NodeName(s *Selection) string+
+NodeName returns the node name of the first element in the selection. +It tries to behave in a similar way as the DOM's nodeName property +(https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName). +
++Go's net/html package defines the following node types, listed with +the corresponding returned value from this function: +
+ErrorNode : #error +TextNode : #text +DocumentNode : #document +ElementNode : the element's tag name +CommentNode : #comment +DoctypeNode : the name of the document type ++ + + + + + + +
func OuterHtml(s *Selection) (string, error)+
+OuterHtml returns the outer HTML rendering of the first item in +the selection - that is, the HTML including the first element's +tag and attributes. +
++Unlike InnerHtml, this is a function and not a method on the Selection, +because this is not a jQuery method (in javascript-land, this is +a property provided by the DOM). +
+ + + + + + + + +type Document struct { + *Selection + Url *url.URL + // contains filtered or unexported fields +}+
+Document represents an HTML document to be manipulated. Unlike jQuery, which +is loaded as part of a DOM document, and thus acts upon its containing +document, GoQuery doesn't know which HTML document to act upon. So it needs +to be told, and that's what the Document class is for. It holds the root +document node to manipulate, and can make selections on this document. +
+ + + + + + + + + + + + +func CloneDocument(doc *Document) *Document+
+CloneDocument creates a deep-clone of a document. +
+ + + + + +func NewDocument(url string) (*Document, error)+
+NewDocument is a Document constructor that takes a string URL as argument. +It loads the specified document, parses it, and stores the root Document +node, ready to be manipulated. +
+ + + + + +func NewDocumentFromNode(root *html.Node) *Document+
+NewDocumentFromNode is a Document constructor that takes a root html Node +as argument. +
+ + + + + +func NewDocumentFromReader(r io.Reader) (*Document, error)+
+NewDocumentFromReader returns a Document from a generic reader. +It returns an error as second value if the reader's data cannot be parsed +as html. It does *not* check if the reader is also an io.Closer, so the +provided reader is never closed by this call, it is the responsibility +of the caller to close it if required. +
+ + + + + +func NewDocumentFromResponse(res *http.Response) (*Document, error)+
+NewDocumentFromResponse is another Document constructor that takes an http response as argument. +It loads the specified response's document, parses it, and stores the root Document +node, ready to be manipulated. The response's body is closed on return. +
+ + + + + + + + + +type Matcher interface { + Match(*html.Node) bool + MatchAll(*html.Node) []*html.Node + Filter([]*html.Node) []*html.Node +}+
+Matcher is an interface that defines the methods to match +HTML nodes against a compiled selector string. Cascadia's +Selector implements this interface. +
+ + + + + + + + + + + + + + + + +type Selection struct { + Nodes []*html.Node + // contains filtered or unexported fields +}+
+Selection represents a collection of nodes matching some criteria. The +initial Selection can be created by using Document.Find, and then +manipulated using the jQuery-like chainable syntax and methods. +
+ + + + + + + + + + + + + + +func (s *Selection) Add(selector string) *Selection+
+Add adds the selector string's matching nodes to those in the current +selection and returns a new Selection object. +The selector string is run in the context of the document of the current +Selection object. +
+ + + + + + +func (s *Selection) AddClass(class ...string) *Selection+
+AddClass adds the given class(es) to each element in the set of matched elements. +Multiple class names can be specified, separated by a space or via multiple arguments. +
+ + + + + + +func (s *Selection) AddMatcher(m Matcher) *Selection+
+AddMatcher adds the matcher's matching nodes to those in the current +selection and returns a new Selection object. +The matcher is run in the context of the document of the current +Selection object. +
+ + + + + + +func (s *Selection) AddNodes(nodes ...*html.Node) *Selection+
+AddNodes adds the specified nodes to those in the +current selection and returns a new Selection object. +
+ + + + + + +func (s *Selection) AddSelection(sel *Selection) *Selection+
+AddSelection adds the specified Selection object's nodes to those in the +current selection and returns a new Selection object. +
+ + + + + + +func (s *Selection) After(selector string) *Selection+
+After applies the selector from the root document and inserts the matched elements +after the elements in the set of matched elements. +
++If one of the matched elements in the selection is not currently in the +document, it's impossible to insert nodes after it, so it will be ignored. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) AfterHtml(html string) *Selection+
+AfterHtml parses the html and inserts it after the set of matched elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) AfterMatcher(m Matcher) *Selection+
+AfterMatcher applies the matcher from the root document and inserts the matched elements +after the elements in the set of matched elements. +
++If one of the matched elements in the selection is not currently in the +document, it's impossible to insert nodes after it, so it will be ignored. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) AfterNodes(ns ...*html.Node) *Selection+
+AfterNodes inserts the nodes after each element in the set of matched elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) AfterSelection(sel *Selection) *Selection+
+AfterSelection inserts the elements in the selection after each element in the set of matched +elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) AndSelf() *Selection+
+AndSelf adds the previous set of elements on the stack to the current set. +It returns a new Selection object containing the current Selection combined +with the previous one. +
+ + + + + + +func (s *Selection) Append(selector string) *Selection+
+Append appends the elements specified by the selector to the end of each element +in the set of matched elements, following those rules: +
++1) The selector is applied to the root document. +
++2) Elements that are part of the document will be moved to the new location. +
++3) If there are multiple locations to append to, cloned nodes will be +appended to all target locations except the last one, which will be moved +as noted in (2). +
+ + + + + + +func (s *Selection) AppendHtml(html string) *Selection+
+AppendHtml parses the html and appends it to the set of matched elements. +
+ + + + + + +func (s *Selection) AppendMatcher(m Matcher) *Selection+
+AppendMatcher appends the elements specified by the matcher to the end of each element +in the set of matched elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) AppendNodes(ns ...*html.Node) *Selection+
+AppendNodes appends the specified nodes to each node in the set of matched elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) AppendSelection(sel *Selection) *Selection+
+AppendSelection appends the elements in the selection to the end of each element +in the set of matched elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) Attr(attrName string) (val string, exists bool)+
+Attr gets the specified attribute's value for the first element in the +Selection. To get the value for each element individually, use a looping +construct such as Each or Map method. +
+ + + + + + +func (s *Selection) AttrOr(attrName, defaultValue string) string+
+AttrOr works like Attr but returns default value if attribute is not present. +
+ + + + + + +func (s *Selection) Before(selector string) *Selection+
+Before inserts the matched elements before each element in the set of matched elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) BeforeHtml(html string) *Selection+
+BeforeHtml parses the html and inserts it before the set of matched elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) BeforeMatcher(m Matcher) *Selection+
+BeforeMatcher inserts the matched elements before each element in the set of matched elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) BeforeNodes(ns ...*html.Node) *Selection+
+BeforeNodes inserts the nodes before each element in the set of matched elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) BeforeSelection(sel *Selection) *Selection+
+BeforeSelection inserts the elements in the selection before each element in the set of matched +elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) Children() *Selection+
+Children gets the child elements of each element in the Selection. +It returns a new Selection object containing these elements. +
+ + + + + + +func (s *Selection) ChildrenFiltered(selector string) *Selection+
+ChildrenFiltered gets the child elements of each element in the Selection, +filtered by the specified selector. It returns a new +Selection object containing these elements. +
+ + + + + + +func (s *Selection) ChildrenMatcher(m Matcher) *Selection+
+ChildrenMatcher gets the child elements of each element in the Selection, +filtered by the specified matcher. It returns a new +Selection object containing these elements. +
+ + + + + + +func (s *Selection) Clone() *Selection+
+Clone creates a deep copy of the set of matched nodes. The new nodes will not be +attached to the document. +
+ + + + + + +func (s *Selection) Closest(selector string) *Selection+
+Closest gets the first element that matches the selector by testing the +element itself and traversing up through its ancestors in the DOM tree. +
+ + + + + + +func (s *Selection) ClosestMatcher(m Matcher) *Selection+
+ClosestMatcher gets the first element that matches the matcher by testing the +element itself and traversing up through its ancestors in the DOM tree. +
+ + + + + + +func (s *Selection) ClosestNodes(nodes ...*html.Node) *Selection+
+ClosestNodes gets the first element that matches one of the nodes by testing the +element itself and traversing up through its ancestors in the DOM tree. +
+ + + + + + +func (s *Selection) ClosestSelection(sel *Selection) *Selection+
+ClosestSelection gets the first element that matches one of the nodes in the +Selection by testing the element itself and traversing up through its ancestors +in the DOM tree. +
+ + + + + + +func (s *Selection) Contains(n *html.Node) bool+
+Contains returns true if the specified Node is within, +at any depth, one of the nodes in the Selection object. +It is NOT inclusive, to behave like jQuery's implementation, and +unlike Javascript's .contains, so if the contained +node is itself in the selection, it returns false. +
+ + + + + + +func (s *Selection) Contents() *Selection+
+Contents gets the children of each element in the Selection, +including text and comment nodes. It returns a new Selection object +containing these elements. +
+ + + + + + +func (s *Selection) ContentsFiltered(selector string) *Selection+
+ContentsFiltered gets the children of each element in the Selection, +filtered by the specified selector. It returns a new Selection +object containing these elements. Since selectors only act on Element nodes, +this function is an alias to ChildrenFiltered unless the selector is empty, +in which case it is an alias to Contents. +
+ + + + + + +func (s *Selection) ContentsMatcher(m Matcher) *Selection+
+ContentsMatcher gets the children of each element in the Selection, +filtered by the specified matcher. It returns a new Selection +object containing these elements. Since matchers only act on Element nodes, +this function is an alias to ChildrenMatcher. +
+ + + + + + +func (s *Selection) Each(f func(int, *Selection)) *Selection+
+Each iterates over a Selection object, executing a function for each +matched element. It returns the current Selection object. The function +f is called for each element in the selection with the index of the +element in that selection starting at 0, and a *Selection that contains +only that element. +
+ + + + + + +func (s *Selection) EachWithBreak(f func(int, *Selection) bool) *Selection+
+EachWithBreak iterates over a Selection object, executing a function for each +matched element. It is identical to Each except that it is possible to break +out of the loop by returning false in the callback function. It returns the +current Selection object. +
+ + + + + + +func (s *Selection) Empty() *Selection+
+Empty removes all children nodes from the set of matched elements. +It returns the children nodes in a new Selection. +
+ + + + + + +func (s *Selection) End() *Selection+
+End ends the most recent filtering operation in the current chain and +returns the set of matched elements to its previous state. +
+ + + + + + +func (s *Selection) Eq(index int) *Selection+
+Eq reduces the set of matched elements to the one at the specified index. +If a negative index is given, it counts backwards starting at the end of the +set. It returns a new Selection object, and an empty Selection object if the +index is invalid. +
+ + + + + + +func (s *Selection) Filter(selector string) *Selection+
+Filter reduces the set of matched elements to those that match the selector string. +It returns a new Selection object for this subset of matching elements. +
+ + + + + + +func (s *Selection) FilterFunction(f func(int, *Selection) bool) *Selection+
+FilterFunction reduces the set of matched elements to those that pass the function's test. +It returns a new Selection object for this subset of elements. +
+ + + + + + +func (s *Selection) FilterMatcher(m Matcher) *Selection+
+FilterMatcher reduces the set of matched elements to those that match +the given matcher. It returns a new Selection object for this subset +of matching elements. +
+ + + + + + +func (s *Selection) FilterNodes(nodes ...*html.Node) *Selection+
+FilterNodes reduces the set of matched elements to those that match the specified nodes. +It returns a new Selection object for this subset of elements. +
+ + + + + + +func (s *Selection) FilterSelection(sel *Selection) *Selection+
+FilterSelection reduces the set of matched elements to those that match a +node in the specified Selection object. +It returns a new Selection object for this subset of elements. +
+ + + + + + +func (s *Selection) Find(selector string) *Selection+
+Find gets the descendants of each element in the current set of matched +elements, filtered by a selector. It returns a new Selection object +containing these matched elements. +
+ + + + + + +func (s *Selection) FindMatcher(m Matcher) *Selection+
+FindMatcher gets the descendants of each element in the current set of matched +elements, filtered by the matcher. It returns a new Selection object +containing these matched elements. +
+ + + + + + +func (s *Selection) FindNodes(nodes ...*html.Node) *Selection+
+FindNodes gets the descendants of each element in the current +Selection, filtered by some nodes. It returns a new Selection object +containing these matched elements. +
+ + + + + + +func (s *Selection) FindSelection(sel *Selection) *Selection+
+FindSelection gets the descendants of each element in the current +Selection, filtered by a Selection. It returns a new Selection object +containing these matched elements. +
+ + + + + + +func (s *Selection) First() *Selection+
+First reduces the set of matched elements to the first in the set. +It returns a new Selection object, and an empty Selection object if the +the selection is empty. +
+ + + + + + +func (s *Selection) Get(index int) *html.Node+
+Get retrieves the underlying node at the specified index. +Get without parameter is not implemented, since the node array is available +on the Selection object. +
+ + + + + + +func (s *Selection) Has(selector string) *Selection+
+Has reduces the set of matched elements to those that have a descendant +that matches the selector. +It returns a new Selection object with the matching elements. +
+ + + + + + +func (s *Selection) HasClass(class string) bool+
+HasClass determines whether any of the matched elements are assigned the +given class. +
+ + + + + + +func (s *Selection) HasMatcher(m Matcher) *Selection+
+HasMatcher reduces the set of matched elements to those that have a descendant +that matches the matcher. +It returns a new Selection object with the matching elements. +
+ + + + + + +func (s *Selection) HasNodes(nodes ...*html.Node) *Selection+
+HasNodes reduces the set of matched elements to those that have a +descendant that matches one of the nodes. +It returns a new Selection object with the matching elements. +
+ + + + + + +func (s *Selection) HasSelection(sel *Selection) *Selection+
+HasSelection reduces the set of matched elements to those that have a +descendant that matches one of the nodes of the specified Selection object. +It returns a new Selection object with the matching elements. +
+ + + + + + +func (s *Selection) Html() (ret string, e error)+
+Html gets the HTML contents of the first element in the set of matched +elements. It includes text and comment nodes. +
+ + + + + + +func (s *Selection) Index() int+
+Index returns the position of the first element within the Selection object +relative to its sibling elements. +
+ + + + + + +func (s *Selection) IndexMatcher(m Matcher) int+
+IndexMatcher returns the position of the first element within the +Selection object relative to the elements matched by the matcher, or -1 if +not found. +
+ + + + + + +func (s *Selection) IndexOfNode(node *html.Node) int+
+IndexOfNode returns the position of the specified node within the Selection +object, or -1 if not found. +
+ + + + + + +func (s *Selection) IndexOfSelection(sel *Selection) int+
+IndexOfSelection returns the position of the first node in the specified +Selection object within this Selection object, or -1 if not found. +
+ + + + + + +func (s *Selection) IndexSelector(selector string) int+
+IndexSelector returns the position of the first element within the +Selection object relative to the elements matched by the selector, or -1 if +not found. +
+ + + + + + +func (s *Selection) Intersection(sel *Selection) *Selection+
+Intersection is an alias for FilterSelection. +
+ + + + + + +func (s *Selection) Is(selector string) bool+
+Is checks the current matched set of elements against a selector and +returns true if at least one of these elements matches. +
+ + + + + + +func (s *Selection) IsFunction(f func(int, *Selection) bool) bool+
+IsFunction checks the current matched set of elements against a predicate and +returns true if at least one of these elements matches. +
+ + + + + + +func (s *Selection) IsMatcher(m Matcher) bool+
+IsMatcher checks the current matched set of elements against a matcher and +returns true if at least one of these elements matches. +
+ + + + + + +func (s *Selection) IsNodes(nodes ...*html.Node) bool+
+IsNodes checks the current matched set of elements against the specified nodes +and returns true if at least one of these elements matches. +
+ + + + + + +func (s *Selection) IsSelection(sel *Selection) bool+
+IsSelection checks the current matched set of elements against a Selection object +and returns true if at least one of these elements matches. +
+ + + + + + +func (s *Selection) Last() *Selection+
+Last reduces the set of matched elements to the last in the set. +It returns a new Selection object, and an empty Selection object if +the selection is empty. +
+ + + + + + +func (s *Selection) Length() int+
+Length returns the number of elements in the Selection object. +
+ + + + + + +func (s *Selection) Map(f func(int, *Selection) string) (result []string)+
+Map passes each element in the current matched set through a function, +producing a slice of string holding the returned values. The function +f is called for each element in the selection with the index of the +element in that selection starting at 0, and a *Selection that contains +only that element. +
+ + + + + + +func (s *Selection) Next() *Selection+
+Next gets the immediately following sibling of each element in the +Selection. It returns a new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) NextAll() *Selection+
+NextAll gets all the following siblings of each element in the +Selection. It returns a new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) NextAllFiltered(selector string) *Selection+
+NextAllFiltered gets all the following siblings of each element in the +Selection filtered by a selector. It returns a new Selection object +containing the matched elements. +
+ + + + + + +func (s *Selection) NextAllMatcher(m Matcher) *Selection+
+NextAllMatcher gets all the following siblings of each element in the +Selection filtered by a matcher. It returns a new Selection object +containing the matched elements. +
+ + + + + + +func (s *Selection) NextFiltered(selector string) *Selection+
+NextFiltered gets the immediately following sibling of each element in the +Selection filtered by a selector. It returns a new Selection object +containing the matched elements. +
+ + + + + + +func (s *Selection) NextFilteredUntil(filterSelector, untilSelector string) *Selection+
+NextFilteredUntil is like NextUntil, with the option to filter +the results based on a selector string. +It returns a new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) NextFilteredUntilMatcher(filter, until Matcher) *Selection+
+NextFilteredUntilMatcher is like NextUntilMatcher, with the option to filter +the results based on a matcher. +It returns a new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) NextFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection+
+NextFilteredUntilNodes is like NextUntilNodes, with the +option to filter the results based on a selector string. It returns a new +Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) NextFilteredUntilSelection(filterSelector string, sel *Selection) *Selection+
+NextFilteredUntilSelection is like NextUntilSelection, with the +option to filter the results based on a selector string. It returns a new +Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) NextMatcher(m Matcher) *Selection+
+NextMatcher gets the immediately following sibling of each element in the +Selection filtered by a matcher. It returns a new Selection object +containing the matched elements. +
+ + + + + + +func (s *Selection) NextMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection+
+NextMatcherUntilNodes is like NextUntilNodes, with the +option to filter the results based on a matcher. It returns a new +Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) NextMatcherUntilSelection(filter Matcher, sel *Selection) *Selection+
+NextMatcherUntilSelection is like NextUntilSelection, with the +option to filter the results based on a matcher. It returns a new +Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) NextUntil(selector string) *Selection+
+NextUntil gets all following siblings of each element up to but not +including the element matched by the selector. It returns a new Selection +object containing the matched elements. +
+ + + + + + +func (s *Selection) NextUntilMatcher(m Matcher) *Selection+
+NextUntilMatcher gets all following siblings of each element up to but not +including the element matched by the matcher. It returns a new Selection +object containing the matched elements. +
+ + + + + + +func (s *Selection) NextUntilNodes(nodes ...*html.Node) *Selection+
+NextUntilNodes gets all following siblings of each element up to but not +including the element matched by the nodes. It returns a new Selection +object containing the matched elements. +
+ + + + + + +func (s *Selection) NextUntilSelection(sel *Selection) *Selection+
+NextUntilSelection gets all following siblings of each element up to but not +including the element matched by the Selection. It returns a new Selection +object containing the matched elements. +
+ + + + + + +func (s *Selection) Not(selector string) *Selection+
+Not removes elements from the Selection that match the selector string. +It returns a new Selection object with the matching elements removed. +
+ + + + + + +func (s *Selection) NotFunction(f func(int, *Selection) bool) *Selection+
+NotFunction removes elements from the Selection that pass the function's test. +It returns a new Selection object with the matching elements removed. +
+ + + + + + +func (s *Selection) NotMatcher(m Matcher) *Selection+
+NotMatcher removes elements from the Selection that match the given matcher. +It returns a new Selection object with the matching elements removed. +
+ + + + + + +func (s *Selection) NotNodes(nodes ...*html.Node) *Selection+
+NotNodes removes elements from the Selection that match the specified nodes. +It returns a new Selection object with the matching elements removed. +
+ + + + + + +func (s *Selection) NotSelection(sel *Selection) *Selection+
+NotSelection removes elements from the Selection that match a node in the specified +Selection object. It returns a new Selection object with the matching elements removed. +
+ + + + + + +func (s *Selection) Parent() *Selection+
+Parent gets the parent of each element in the Selection. It returns a +new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) ParentFiltered(selector string) *Selection+
+ParentFiltered gets the parent of each element in the Selection filtered by a +selector. It returns a new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) ParentMatcher(m Matcher) *Selection+
+ParentMatcher gets the parent of each element in the Selection filtered by a +matcher. It returns a new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) Parents() *Selection+
+Parents gets the ancestors of each element in the current Selection. It +returns a new Selection object with the matched elements. +
+ + + + + + +func (s *Selection) ParentsFiltered(selector string) *Selection+
+ParentsFiltered gets the ancestors of each element in the current +Selection. It returns a new Selection object with the matched elements. +
+ + + + + + +func (s *Selection) ParentsFilteredUntil(filterSelector, untilSelector string) *Selection+
+ParentsFilteredUntil is like ParentsUntil, with the option to filter the +results based on a selector string. It returns a new Selection +object containing the matched elements. +
+ + + + + + +func (s *Selection) ParentsFilteredUntilMatcher(filter, until Matcher) *Selection+
+ParentsFilteredUntilMatcher is like ParentsUntilMatcher, with the option to filter the +results based on a matcher. It returns a new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) ParentsFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection+
+ParentsFilteredUntilNodes is like ParentsUntilNodes, with the +option to filter the results based on a selector string. It returns a new +Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) ParentsFilteredUntilSelection(filterSelector string, sel *Selection) *Selection+
+ParentsFilteredUntilSelection is like ParentsUntilSelection, with the +option to filter the results based on a selector string. It returns a new +Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) ParentsMatcher(m Matcher) *Selection+
+ParentsMatcher gets the ancestors of each element in the current +Selection. It returns a new Selection object with the matched elements. +
+ + + + + + +func (s *Selection) ParentsMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection+
+ParentsMatcherUntilNodes is like ParentsUntilNodes, with the +option to filter the results based on a matcher. It returns a new +Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) ParentsMatcherUntilSelection(filter Matcher, sel *Selection) *Selection+
+ParentsMatcherUntilSelection is like ParentsUntilSelection, with the +option to filter the results based on a matcher. It returns a new +Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) ParentsUntil(selector string) *Selection+
+ParentsUntil gets the ancestors of each element in the Selection, up to but +not including the element matched by the selector. It returns a new Selection +object containing the matched elements. +
+ + + + + + +func (s *Selection) ParentsUntilMatcher(m Matcher) *Selection+
+ParentsUntilMatcher gets the ancestors of each element in the Selection, up to but +not including the element matched by the matcher. It returns a new Selection +object containing the matched elements. +
+ + + + + + +func (s *Selection) ParentsUntilNodes(nodes ...*html.Node) *Selection+
+ParentsUntilNodes gets the ancestors of each element in the Selection, +up to but not including the specified nodes. It returns a +new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) ParentsUntilSelection(sel *Selection) *Selection+
+ParentsUntilSelection gets the ancestors of each element in the Selection, +up to but not including the elements in the specified Selection. It returns a +new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) Prepend(selector string) *Selection+
+Prepend prepends the elements specified by the selector to each element in +the set of matched elements, following the same rules as Append. +
+ + + + + + +func (s *Selection) PrependHtml(html string) *Selection+
+PrependHtml parses the html and prepends it to the set of matched elements. +
+ + + + + + +func (s *Selection) PrependMatcher(m Matcher) *Selection+
+PrependMatcher prepends the elements specified by the matcher to each +element in the set of matched elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) PrependNodes(ns ...*html.Node) *Selection+
+PrependNodes prepends the specified nodes to each node in the set of +matched elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) PrependSelection(sel *Selection) *Selection+
+PrependSelection prepends the elements in the selection to each element in +the set of matched elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) Prev() *Selection+
+Prev gets the immediately preceding sibling of each element in the +Selection. It returns a new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) PrevAll() *Selection+
+PrevAll gets all the preceding siblings of each element in the +Selection. It returns a new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) PrevAllFiltered(selector string) *Selection+
+PrevAllFiltered gets all the preceding siblings of each element in the +Selection filtered by a selector. It returns a new Selection object +containing the matched elements. +
+ + + + + + +func (s *Selection) PrevAllMatcher(m Matcher) *Selection+
+PrevAllMatcher gets all the preceding siblings of each element in the +Selection filtered by a matcher. It returns a new Selection object +containing the matched elements. +
+ + + + + + +func (s *Selection) PrevFiltered(selector string) *Selection+
+PrevFiltered gets the immediately preceding sibling of each element in the +Selection filtered by a selector. It returns a new Selection object +containing the matched elements. +
+ + + + + + +func (s *Selection) PrevFilteredUntil(filterSelector, untilSelector string) *Selection+
+PrevFilteredUntil is like PrevUntil, with the option to filter +the results based on a selector string. +It returns a new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) PrevFilteredUntilMatcher(filter, until Matcher) *Selection+
+PrevFilteredUntilMatcher is like PrevUntilMatcher, with the option to filter +the results based on a matcher. +It returns a new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) PrevFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection+
+PrevFilteredUntilNodes is like PrevUntilNodes, with the +option to filter the results based on a selector string. It returns a new +Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) PrevFilteredUntilSelection(filterSelector string, sel *Selection) *Selection+
+PrevFilteredUntilSelection is like PrevUntilSelection, with the +option to filter the results based on a selector string. It returns a new +Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) PrevMatcher(m Matcher) *Selection+
+PrevMatcher gets the immediately preceding sibling of each element in the +Selection filtered by a matcher. It returns a new Selection object +containing the matched elements. +
+ + + + + + +func (s *Selection) PrevMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection+
+PrevMatcherUntilNodes is like PrevUntilNodes, with the +option to filter the results based on a matcher. It returns a new +Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) PrevMatcherUntilSelection(filter Matcher, sel *Selection) *Selection+
+PrevMatcherUntilSelection is like PrevUntilSelection, with the +option to filter the results based on a matcher. It returns a new +Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) PrevUntil(selector string) *Selection+
+PrevUntil gets all preceding siblings of each element up to but not +including the element matched by the selector. It returns a new Selection +object containing the matched elements. +
+ + + + + + +func (s *Selection) PrevUntilMatcher(m Matcher) *Selection+
+PrevUntilMatcher gets all preceding siblings of each element up to but not +including the element matched by the matcher. It returns a new Selection +object containing the matched elements. +
+ + + + + + +func (s *Selection) PrevUntilNodes(nodes ...*html.Node) *Selection+
+PrevUntilNodes gets all preceding siblings of each element up to but not +including the element matched by the nodes. It returns a new Selection +object containing the matched elements. +
+ + + + + + +func (s *Selection) PrevUntilSelection(sel *Selection) *Selection+
+PrevUntilSelection gets all preceding siblings of each element up to but not +including the element matched by the Selection. It returns a new Selection +object containing the matched elements. +
+ + + + + + +func (s *Selection) Remove() *Selection+
+Remove removes the set of matched elements from the document. +It returns the same selection, now consisting of nodes not in the document. +
+ + + + + + +func (s *Selection) RemoveAttr(attrName string) *Selection+
+RemoveAttr removes the named attribute from each element in the set of matched elements. +
+ + + + + + +func (s *Selection) RemoveClass(class ...string) *Selection+
+RemoveClass removes the given class(es) from each element in the set of matched elements. +Multiple class names can be specified, separated by a space or via multiple arguments. +If no class name is provided, all classes are removed. +
+ + + + + + +func (s *Selection) RemoveFiltered(selector string) *Selection+
+RemoveFiltered removes the set of matched elements by selector. +It returns the Selection of removed nodes. +
+ + + + + + +func (s *Selection) RemoveMatcher(m Matcher) *Selection+
+RemoveMatcher removes the set of matched elements. +It returns the Selection of removed nodes. +
+ + + + + + +func (s *Selection) ReplaceWith(selector string) *Selection+
+ReplaceWith replaces each element in the set of matched elements with the +nodes matched by the given selector. +It returns the removed elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) ReplaceWithHtml(html string) *Selection+
+ReplaceWithHtml replaces each element in the set of matched elements with +the parsed HTML. +It returns the removed elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) ReplaceWithMatcher(m Matcher) *Selection+
+ReplaceWithMatcher replaces each element in the set of matched elements with +the nodes matched by the given Matcher. +It returns the removed elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) ReplaceWithNodes(ns ...*html.Node) *Selection+
+ReplaceWithNodes replaces each element in the set of matched elements with +the given nodes. +It returns the removed elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) ReplaceWithSelection(sel *Selection) *Selection+
+ReplaceWithSelection replaces each element in the set of matched elements with +the nodes from the given Selection. +It returns the removed elements. +
++This follows the same rules as Selection.Append. +
+ + + + + + +func (s *Selection) SetAttr(attrName, val string) *Selection+
+SetAttr sets the given attribute on each element in the set of matched elements. +
+ + + + + + +func (s *Selection) Siblings() *Selection+
+Siblings gets the siblings of each element in the Selection. It returns +a new Selection object containing the matched elements. +
+ + + + + + +func (s *Selection) SiblingsFiltered(selector string) *Selection+
+SiblingsFiltered gets the siblings of each element in the Selection +filtered by a selector. It returns a new Selection object containing the +matched elements. +
+ + + + + + +func (s *Selection) SiblingsMatcher(m Matcher) *Selection+
+SiblingsMatcher gets the siblings of each element in the Selection +filtered by a matcher. It returns a new Selection object containing the +matched elements. +
+ + + + + + +func (s *Selection) Size() int+
+Size is an alias for Length. +
+ + + + + + +func (s *Selection) Slice(start, end int) *Selection+
+Slice reduces the set of matched elements to a subset specified by a range +of indices. +
+ + + + + + +func (s *Selection) Text() string+
+Text gets the combined text contents of each element in the set of matched +elements, including their descendants. +
+ + + + + + +func (s *Selection) ToggleClass(class ...string) *Selection+
+ToggleClass adds or removes the given class(es) for each element in the set of matched elements. +Multiple class names can be specified, separated by a space or via multiple arguments. +
+ + + + + + +func (s *Selection) Union(sel *Selection) *Selection+
+Union is an alias for AddSelection. +
+ + + + + + +func (s *Selection) Unwrap() *Selection+
+Unwrap removes the parents of the set of matched elements, leaving the matched +elements (and their siblings, if any) in their place. +It returns the original selection. +
+ + + + + + +func (s *Selection) Wrap(selector string) *Selection+
+Wrap wraps each element in the set of matched elements inside the first +element matched by the given selector. The matched child is cloned before +being inserted into the document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapAll(selector string) *Selection+
+WrapAll wraps a single HTML structure, matched by the given selector, around +all elements in the set of matched elements. The matched child is cloned +before being inserted into the document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapAllHtml(html string) *Selection+
+WrapAllHtml wraps the given HTML structure around all elements in the set of +matched elements. The matched child is cloned before being inserted into the +document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapAllMatcher(m Matcher) *Selection+
+WrapAllMatcher wraps a single HTML structure, matched by the given Matcher, +around all elements in the set of matched elements. The matched child is +cloned before being inserted into the document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapAllNode(n *html.Node) *Selection+
+WrapAllNode wraps the given node around the first element in the Selection, +making all other nodes in the Selection children of the given node. The node +is cloned before being inserted into the document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapAllSelection(sel *Selection) *Selection+
+WrapAllSelection wraps a single HTML structure, the first node of the given +Selection, around all elements in the set of matched elements. The matched +child is cloned before being inserted into the document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapHtml(html string) *Selection+
+WrapHtml wraps each element in the set of matched elements inside the inner- +most child of the given HTML. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapInner(selector string) *Selection+
+WrapInner wraps an HTML structure, matched by the given selector, around the +content of element in the set of matched elements. The matched child is +cloned before being inserted into the document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapInnerHtml(html string) *Selection+
+WrapInnerHtml wraps an HTML structure, matched by the given selector, around +the content of element in the set of matched elements. The matched child is +cloned before being inserted into the document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapInnerMatcher(m Matcher) *Selection+
+WrapInnerMatcher wraps an HTML structure, matched by the given selector, +around the content of element in the set of matched elements. The matched +child is cloned before being inserted into the document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapInnerNode(n *html.Node) *Selection+
+WrapInnerNode wraps an HTML structure, matched by the given selector, around +the content of element in the set of matched elements. The matched child is +cloned before being inserted into the document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapInnerSelection(sel *Selection) *Selection+
+WrapInnerSelection wraps an HTML structure, matched by the given selector, +around the content of element in the set of matched elements. The matched +child is cloned before being inserted into the document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapMatcher(m Matcher) *Selection+
+WrapMatcher wraps each element in the set of matched elements inside the +first element matched by the given matcher. The matched child is cloned +before being inserted into the document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapNode(n *html.Node) *Selection+
+WrapNode wraps each element in the set of matched elements inside the inner- +most child of the given node. The given node is copied before being inserted +into the document. +
++It returns the original set of elements. +
+ + + + + + +func (s *Selection) WrapSelection(sel *Selection) *Selection+
+WrapSelection wraps each element in the set of matched elements inside the +first element in the given Selection. The element is cloned before being +inserted into the document. +
++It returns the original set of elements. +
+ + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ logrus + | ++ Package logrus is a structured logger for Go, completely API compatible with the standard library logger. + | +
+ examples + | ++ + | +
+ basic + | ++ + | +
+ hook + | ++ + | +
+ hooks + | ++ + | +
+ syslog + | ++ + | +
+ test + | ++ + | +
type SyslogHook struct { + Writer *syslog.Writer + SyslogNetwork string + SyslogRaddr string +}+
+SyslogHook to send logs via syslog. +
+ + + + + + + + + + + + +func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error)+
+Creates a hook to be added to an instance of logger. This is called with +`hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_DEBUG, "")` +`if err == nil { log.Hooks.Add(hook) }` +
+ + + + + + + +func (hook *SyslogHook) Fire(entry *logrus.Entry) error+ + + + + + +
func (hook *SyslogHook) Levels() []logrus.Level+ + + + + + + + + + + + + + + + + + +
func NewNullLogger() (*logrus.Logger, *Hook)+
+Creates a discarding logger and installs the test hook. +
+ + + + + + + + +type Hook struct { + Entries []*logrus.Entry +}+
+test.Hook is a hook designed for dealing with logs in test scenarios. +
+ + + + + + + + + + + + +func NewGlobal() *Hook+
+Installs a test hook for the global logger. +
+ + + + + +func NewLocal(logger *logrus.Logger) *Hook+
+Installs a test hook for a given local logger. +
+ + + + + + + +func (t *Hook) Fire(e *logrus.Entry) error+ + + + + + +
func (t *Hook) LastEntry() (l *logrus.Entry)+
+LastEntry returns the last entry that was logged or nil. +
+ + + + + + +func (t *Hook) Levels() []logrus.Level+ + + + + + +
func (t *Hook) Reset()+
+Reset removes all Entries from this test hook. +
+ + + + + + + + + + + + + + + + + + +const DefaultTimestampFormat = time.RFC3339+ + + + +
var AllLevels = []Level{ + PanicLevel, + FatalLevel, + ErrorLevel, + WarnLevel, + InfoLevel, + DebugLevel, +}+
+A constant exposing all logging levels +
+ + +var ErrorKey = "error"
+ +Defines the key when adding errors using WithError. +
+ + + + + + +func AddHook(hook Hook)+
+AddHook adds a hook to the standard logger hooks. +
+ + + + + + + +func Debug(args ...interface{})+
+Debug logs a message at level Debug on the standard logger. +
+ + + + + + + +func Debugf(format string, args ...interface{})+
+Debugf logs a message at level Debug on the standard logger. +
+ + + + + + + +func Debugln(args ...interface{})+
+Debugln logs a message at level Debug on the standard logger. +
+ + + + + + + +func Error(args ...interface{})+
+Error logs a message at level Error on the standard logger. +
+ + + + + + + +func Errorf(format string, args ...interface{})+
+Errorf logs a message at level Error on the standard logger. +
+ + + + + + + +func Errorln(args ...interface{})+
+Errorln logs a message at level Error on the standard logger. +
+ + + + + + + +func Exit(code int)+
+Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code) +
+ + + + + + + +func Fatal(args ...interface{})+
+Fatal logs a message at level Fatal on the standard logger. +
+ + + + + + + +func Fatalf(format string, args ...interface{})+
+Fatalf logs a message at level Fatal on the standard logger. +
+ + + + + + + +func Fatalln(args ...interface{})+
+Fatalln logs a message at level Fatal on the standard logger. +
+ + + + + + + +func Info(args ...interface{})+
+Info logs a message at level Info on the standard logger. +
+ + + + + + + +func Infof(format string, args ...interface{})+
+Infof logs a message at level Info on the standard logger. +
+ + + + + + + +func Infoln(args ...interface{})+
+Infoln logs a message at level Info on the standard logger. +
+ + + + + + + +func IsTerminal() bool+
+IsTerminal returns true if stderr's file descriptor is a terminal. +
+ + + + + + + +func Panic(args ...interface{})+
+Panic logs a message at level Panic on the standard logger. +
+ + + + + + + +func Panicf(format string, args ...interface{})+
+Panicf logs a message at level Panic on the standard logger. +
+ + + + + + + +func Panicln(args ...interface{})+
+Panicln logs a message at level Panic on the standard logger. +
+ + + + + + + +func Print(args ...interface{})+
+Print logs a message at level Info on the standard logger. +
+ + + + + + + +func Printf(format string, args ...interface{})+
+Printf logs a message at level Info on the standard logger. +
+ + + + + + + +func Println(args ...interface{})+
+Println logs a message at level Info on the standard logger. +
+ + + + + + + +func RegisterExitHandler(handler func())+
+RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke +all handlers. The handlers will also be invoked when any Fatal log entry is +made. +
++This method is useful when a caller wishes to use logrus to log a fatal +message but also needs to gracefully shutdown. An example usecase could be +closing database connections, or sending a alert that the application is +closing. +
+ + + + + + + +func SetFormatter(formatter Formatter)+
+SetFormatter sets the standard logger formatter. +
+ + + + + + + +func SetLevel(level Level)+
+SetLevel sets the standard logger level. +
+ + + + + + + +func SetOutput(out io.Writer)+
+SetOutput sets the standard logger output. +
+ + + + + + + +func Warn(args ...interface{})+
+Warn logs a message at level Warn on the standard logger. +
+ + + + + + + +func Warnf(format string, args ...interface{})+
+Warnf logs a message at level Warn on the standard logger. +
+ + + + + + + +func Warning(args ...interface{})+
+Warning logs a message at level Warn on the standard logger. +
+ + + + + + + +func Warningf(format string, args ...interface{})+
+Warningf logs a message at level Warn on the standard logger. +
+ + + + + + + +func Warningln(args ...interface{})+
+Warningln logs a message at level Warn on the standard logger. +
+ + + + + + + +func Warnln(args ...interface{})+
+Warnln logs a message at level Warn on the standard logger. +
+ + + + + + + + +type Entry struct { + Logger *Logger + + // Contains all the fields set by the user. + Data Fields + + // Time at which the log entry was created + Time time.Time + + // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic + Level Level + + // Message passed to Debug, Info, Warn, Error, Fatal or Panic + Message string +}+
+An entry is the final or intermediate Logrus logging entry. It contains all +the fields passed with WithField{,s}. It's finally logged when Debug, Info, +Warn, Error, Fatal or Panic is called on it. These objects can be reused and +passed around as much as you wish to avoid field duplication. +
+ + + + + + + + + + + + +func NewEntry(logger *Logger) *Entry+ + + + + +
func WithError(err error) *Entry+
+WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. +
+ + + + + +func WithField(key string, value interface{}) *Entry+
+WithField creates an entry from the standard logger and adds a field to +it. If you want multiple fields, use `WithFields`. +
++Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +or Panic on the Entry it returns. +
+ + + + + +func WithFields(fields Fields) *Entry+
+WithFields creates an entry from the standard logger and adds multiple +fields to it. This is simply a helper for `WithField`, invoking it +once for each field. +
++Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +or Panic on the Entry it returns. +
+ + + + + + + +func (entry *Entry) Debug(args ...interface{})+ + + + + + +
func (entry *Entry) Debugf(format string, args ...interface{})+ + + + + + +
func (entry *Entry) Debugln(args ...interface{})+ + + + + + +
func (entry *Entry) Error(args ...interface{})+ + + + + + +
func (entry *Entry) Errorf(format string, args ...interface{})+ + + + + + +
func (entry *Entry) Errorln(args ...interface{})+ + + + + + +
func (entry *Entry) Fatal(args ...interface{})+ + + + + + +
func (entry *Entry) Fatalf(format string, args ...interface{})+ + + + + + +
func (entry *Entry) Fatalln(args ...interface{})+ + + + + + +
func (entry *Entry) Info(args ...interface{})+ + + + + + +
func (entry *Entry) Infof(format string, args ...interface{})+ + + + + + +
func (entry *Entry) Infoln(args ...interface{})+ + + + + + +
func (entry *Entry) Panic(args ...interface{})+ + + + + + +
func (entry *Entry) Panicf(format string, args ...interface{})+ + + + + + +
func (entry *Entry) Panicln(args ...interface{})+ + + + + + +
func (entry *Entry) Print(args ...interface{})+ + + + + + +
func (entry *Entry) Printf(format string, args ...interface{})+ + + + + + +
func (entry *Entry) Println(args ...interface{})+ + + + + + +
func (entry *Entry) Reader() (*bytes.Buffer, error)+
+Returns a reader for the entry, which is a proxy to the formatter. +
+ + + + + + +func (entry *Entry) String() (string, error)+
+Returns the string representation from the reader and ultimately the +formatter. +
+ + + + + + +func (entry *Entry) Warn(args ...interface{})+ + + + + + +
func (entry *Entry) Warnf(format string, args ...interface{})+ + + + + + +
func (entry *Entry) Warning(args ...interface{})+ + + + + + +
func (entry *Entry) Warningf(format string, args ...interface{})+ + + + + + +
func (entry *Entry) Warningln(args ...interface{})+ + + + + + +
func (entry *Entry) Warnln(args ...interface{})+ + + + + + +
func (entry *Entry) WithError(err error) *Entry+
+Add an error as single field (using the key defined in ErrorKey) to the Entry. +
+ + + + + + +func (entry *Entry) WithField(key string, value interface{}) *Entry+
+Add a single field to the Entry. +
+ + + + + + +func (entry *Entry) WithFields(fields Fields) *Entry+
+Add a map of fields to the Entry. +
+ + + + + + + + +type FieldLogger interface { + WithField(key string, value interface{}) *Entry + WithFields(fields Fields) *Entry + WithError(err error) *Entry + + Debugf(format string, args ...interface{}) + Infof(format string, args ...interface{}) + Printf(format string, args ...interface{}) + Warnf(format string, args ...interface{}) + Warningf(format string, args ...interface{}) + Errorf(format string, args ...interface{}) + Fatalf(format string, args ...interface{}) + Panicf(format string, args ...interface{}) + + Debug(args ...interface{}) + Info(args ...interface{}) + Print(args ...interface{}) + Warn(args ...interface{}) + Warning(args ...interface{}) + Error(args ...interface{}) + Fatal(args ...interface{}) + Panic(args ...interface{}) + + Debugln(args ...interface{}) + Infoln(args ...interface{}) + Println(args ...interface{}) + Warnln(args ...interface{}) + Warningln(args ...interface{}) + Errorln(args ...interface{}) + Fatalln(args ...interface{}) + Panicln(args ...interface{}) +}+
+The FieldLogger interface generalizes the Entry and Logger types +
+ + + + + + + + + + + + + + + + +type Fields map[string]interface{}+
+Fields type, used to pass to `WithFields`. +
+ + + + + + + + + + + + + + + + +type Formatter interface { + Format(*Entry) ([]byte, error) +}+
+The Formatter interface is used to implement a custom Formatter. It takes an +`Entry`. It exposes all the fields, including the default ones: +
++* `entry.Data["msg"]`. The message passed from Info, Warn, Error .. +* `entry.Data["time"]`. The timestamp. +* `entry.Data["level"]. The level the entry was logged at. +
++Any additional fields added with `WithField` or `WithFields` are also in +`entry.Data`. Format is expected to return an array of bytes which are then +logged to `logger.Out`. +
+ + + + + + + + + + + + + + + + +type Hook interface { + Levels() []Level + Fire(*Entry) error +}+
+A hook to be fired when logging on the logging levels returned from +`Levels()` on your implementation of the interface. Note that this is not +fired in a goroutine or a channel with workers, you should handle such +functionality yourself if your call is non-blocking and you don't wish for +the logging calls for levels returned from `Levels()` to block. +
+ + + + + + + + + + + + + + + + +type JSONFormatter struct { + // TimestampFormat sets the format used for marshaling timestamps. + TimestampFormat string +}+ + + + + + + + + + + + + + +
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error)+ + + + + + + + +
type Level uint8+
+Level type +
+ + + +const ( + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel Level = iota + // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel +)+
+These are the different logging levels. You can set the logging level to log +on your instance of logger, obtained with `logrus.New()`. +
+ + + + + + + + + + + +func GetLevel() Level+
+GetLevel returns the standard logger level. +
+ + + + + +func ParseLevel(lvl string) (Level, error)+
+ParseLevel takes a string level and returns the Logrus log level constant. +
+ + + + + + + +func (level Level) String() string+
+Convert the Level to a string. E.g. PanicLevel becomes "panic". +
+ + + + + + + + +type LevelHooks map[Level][]Hook+
+Internal type for storing the hooks on a logger instance. +
+ + + + + + + + + + + + + + +func (hooks LevelHooks) Add(hook Hook)+
+Add a hook to an instance of logger. This is called with +`log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. +
+ + + + + + +func (hooks LevelHooks) Fire(level Level, entry *Entry) error+
+Fire all the hooks for the passed level. Used by `entry.log` to fire +appropriate hooks for a log entry. +
+ + + + + + + + +type Logger struct { + // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a + // file, or leave it default which is `os.Stderr`. You can also set this to + // something more adventorous, such as logging to Kafka. + Out io.Writer + // Hooks for the logger instance. These allow firing events based on logging + // levels and log entries. For example, to send errors to an error tracking + // service, log to StatsD or dump the core on fatal errors. + Hooks LevelHooks + // All log entries pass through the formatter before logged to Out. The + // included formatters are `TextFormatter` and `JSONFormatter` for which + // TextFormatter is the default. In development (when a TTY is attached) it + // logs with colors, but to a file it wouldn't. You can easily implement your + // own that implements the `Formatter` interface, see the `README` or included + // formatters for examples. + Formatter Formatter + // The logging level the logger should log at. This is typically (and defaults + // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be + // logged. `logrus.Debug` is useful in + Level Level + // contains filtered or unexported fields +}+ + + + + + + + + + + + +
func New() *Logger+
+Creates a new logger. Configuration should be set by changing `Formatter`, +`Out` and `Hooks` directly on the default logger instance. You can also just +instantiate your own: +
+var log = &Logger{ + Out: os.Stderr, + Formatter: new(JSONFormatter), + Hooks: make(LevelHooks), + Level: logrus.DebugLevel, +} ++
+It's recommended to make this a global instance called `log`. +
+ + + + + +func StandardLogger() *Logger+ + + + + + + +
func (logger *Logger) Debug(args ...interface{})+ + + + + + +
func (logger *Logger) Debugf(format string, args ...interface{})+ + + + + + +
func (logger *Logger) Debugln(args ...interface{})+ + + + + + +
func (logger *Logger) Error(args ...interface{})+ + + + + + +
func (logger *Logger) Errorf(format string, args ...interface{})+ + + + + + +
func (logger *Logger) Errorln(args ...interface{})+ + + + + + +
func (logger *Logger) Fatal(args ...interface{})+ + + + + + +
func (logger *Logger) Fatalf(format string, args ...interface{})+ + + + + + +
func (logger *Logger) Fatalln(args ...interface{})+ + + + + + +
func (logger *Logger) Info(args ...interface{})+ + + + + + +
func (logger *Logger) Infof(format string, args ...interface{})+ + + + + + +
func (logger *Logger) Infoln(args ...interface{})+ + + + + + +
func (logger *Logger) Panic(args ...interface{})+ + + + + + +
func (logger *Logger) Panicf(format string, args ...interface{})+ + + + + + +
func (logger *Logger) Panicln(args ...interface{})+ + + + + + +
func (logger *Logger) Print(args ...interface{})+ + + + + + +
func (logger *Logger) Printf(format string, args ...interface{})+ + + + + + +
func (logger *Logger) Println(args ...interface{})+ + + + + + +
func (logger *Logger) Warn(args ...interface{})+ + + + + + +
func (logger *Logger) Warnf(format string, args ...interface{})+ + + + + + +
func (logger *Logger) Warning(args ...interface{})+ + + + + + +
func (logger *Logger) Warningf(format string, args ...interface{})+ + + + + + +
func (logger *Logger) Warningln(args ...interface{})+ + + + + + +
func (logger *Logger) Warnln(args ...interface{})+ + + + + + +
func (logger *Logger) WithError(err error) *Entry+
+Add an error as single field to the log entry. All it does is call +`WithError` for the given `error`. +
+ + + + + + +func (logger *Logger) WithField(key string, value interface{}) *Entry+
+Adds a field to the log entry, note that it doesn't log until you call +Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry. +If you want multiple fields, use `WithFields`. +
+ + + + + + +func (logger *Logger) WithFields(fields Fields) *Entry+
+Adds a struct of fields to the log entry. All it does is call `WithField` for +each `Field`. +
+ + + + + + +func (logger *Logger) Writer() *io.PipeWriter+ + + + + + +
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter+ + + + + + + + +
type StdLogger interface { + Print(...interface{}) + Printf(string, ...interface{}) + Println(...interface{}) + + Fatal(...interface{}) + Fatalf(string, ...interface{}) + Fatalln(...interface{}) + + Panic(...interface{}) + Panicf(string, ...interface{}) + Panicln(...interface{}) +}+
+StdLogger is what your logrus-enabled library should take, that way +it'll accept a stdlib logger and a logrus logger. There's no standard +interface, this is the closest we get, unfortunately. +
+ + + + + + + + + + + + + + + + +type Termios syscall.Termios+ + + + + + + + + + + + + + + + +
type TextFormatter struct { + // Set to true to bypass checking for a TTY before outputting colors. + ForceColors bool + + // Force disabling colors. + DisableColors bool + + // Disable timestamp logging. useful when output is redirected to logging + // system that already adds timestamps. + DisableTimestamp bool + + // Enable logging the full timestamp when a TTY is attached instead of just + // the time passed since beginning of execution. + FullTimestamp bool + + // TimestampFormat to use for display when a full timestamp is printed + TimestampFormat string + + // The fields are sorted by default for a consistent output. For applications + // that log extremely frequently and don't use the JSON formatter this may not + // be desired. + DisableSorting bool +}+ + + + + + + + + + + + + + +
func (f *TextFormatter) Format(entry *Entry) ([]byte, error)+ + + + + + + + + + + + + + + + +
type Selector func(*html.Node) bool+
+A Selector is a function which tells whether a node matches or not. +
+ + + + + + + + + + + + +func Compile(sel string) (Selector, error)+
+Compile parses a selector and returns, if successful, a Selector object +that can be used to match against html.Node objects. +
+ + + + + +func MustCompile(sel string) Selector+
+MustCompile is like Compile, but panics instead of returning an error. +
+ + + + + + + +func (s Selector) Filter(nodes []*html.Node) (result []*html.Node)+
+Filter returns the nodes in nodes that match the selector. +
+ + + + + + +func (s Selector) Match(n *html.Node) bool+
+Match returns true if the node matches the selector. +
+ + + + + + +func (s Selector) MatchAll(n *html.Node) []*html.Node+
+MatchAll returns a slice of the nodes that match the selector, +from n and its children. +
+ + + + + + +func (s Selector) MatchFirst(n *html.Node) *html.Node+
+MatchFirst returns the first node that matches s, from n and its children. +
+ + + + + + + + + + + + + + + + +const ( + // AssigneeAutomatic represents the value of the "Assignee: Automatic" of JIRA + AssigneeAutomatic = "-1" +)+ + + + + + + +
func CheckResponse(r *http.Response) error+
+CheckResponse checks the API response for errors, and returns them if present. +A response is considered an error if it has a status code outside the 200 range. +The caller is responsible to analyze the response body. +The body can contain JSON (if the error is intended) or xml (sometimes JIRA just failes). +
+ + + + + + + + +type Attachment struct { + Self string `json:"self,omitempty"` + ID string `json:"id,omitempty"` + Filename string `json:"filename,omitempty"` + Author *User `json:"author,omitempty"` + Created string `json:"created,omitempty"` + Size int `json:"size,omitempty"` + MimeType string `json:"mimeType,omitempty"` + Content string `json:"content,omitempty"` + Thumbnail string `json:"thumbnail,omitempty"` +}+
+Attachment represents a JIRA attachment +
+ + + + + + + + + + + + + + + + +type AuthenticationService struct {
+ // contains filtered or unexported fields
+}
+ +AuthenticationService handles authentication for the JIRA instance / API. +
++JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#authentication +
+ + + + + + + + + + + + + + +func (s *AuthenticationService) AcquireSessionCookie(username, password string) (bool, error)+
+AcquireSessionCookie creates a new session for a user in JIRA. +Once a session has been successfully created it can be used to access any of JIRA's remote APIs and also the web UI by passing the appropriate HTTP Cookie header. +The header will by automatically applied to every API request. +Note that it is generally preferrable to use HTTP BASIC authentication with the REST API. +However, this resource may be used to mimic the behaviour of JIRA's log-in page (e.g. to display log-in errors to a user). +
++JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#auth/1/session +
+ + + + + + +func (s *AuthenticationService) Authenticated() bool+
+Authenticated reports if the current Client has an authenticated session with JIRA +
+ + + + + + + + +type AvatarUrls struct { + Four8X48 string `json:"48x48,omitempty"` + Two4X24 string `json:"24x24,omitempty"` + One6X16 string `json:"16x16,omitempty"` + Three2X32 string `json:"32x32,omitempty"` +}+
+AvatarUrls represents different dimensions of avatars / images +
+ + + + + + + + + + + + + + + + +type Board struct { + ID int `json:"id,omitempty"` + Self string `json:"self,omitempty"` + Name string `json:"name,omitempty"` + Type string `json:"type,omitempty"` + FilterID int `json:"filterId,omitempty"` +}+
+Board represents a JIRA agile board +
+ + + + + + + + + + + + + + + + +type BoardListOptions struct { + // BoardType filters results to boards of the specified type. + // Valid values: scrum, kanban. + BoardType string `url:"boardType,omitempty"` + // Name filters results to boards that match or partially match the specified name. + Name string `url:"name,omitempty"` + // ProjectKeyOrID filters results to boards that are relevant to a project. + // Relevance meaning that the JQL filter defined in board contains a reference to a project. + ProjectKeyOrID string `url:"projectKeyOrId,omitempty"` + + SearchOptions +}+
+BoardListOptions specifies the optional parameters to the BoardService.GetList +
+ + + + + + + + + + + + + + + + +type BoardService struct {
+ // contains filtered or unexported fields
+}
+ +BoardService handles Agile Boards for the JIRA instance / API. +
++JIRA API docs: https://docs.atlassian.com/jira-software/REST/server/ +
+ + + + + + + + + + + + + + +func (s *BoardService) CreateBoard(board *Board) (*Board, *Response, error)+
+CreateBoard creates a new board. Board name, type and filter Id is required. +name - Must be less than 255 characters. +type - Valid values: scrum, kanban +filterId - Id of a filter that the user has permissions to view. +Note, if the user does not have the 'Create shared objects' permission and tries to create a shared board, a private +board will be created instead (remember that board sharing depends on the filter sharing). +
++JIRA API docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-createBoard +
+ + + + + + +func (s *BoardService) DeleteBoard(boardID int) (*Board, *Response, error)+
+DeleteBoard will delete an agile board. +
++JIRA API docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-deleteBoard +
+ + + + + + +func (s *BoardService) GetAllBoards(opt *BoardListOptions) (*BoardsList, *Response, error)+
+GetAllBoards will returns all boards. This only includes boards that the user has permission to view. +
++JIRA API docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-getAllBoards +
+ + + + + + +func (s *BoardService) GetAllSprints(boardID string) ([]Sprint, *Response, error)+
+GetAllSprints will returns all sprints from a board, for a given board Id. +This only includes sprints that the user has permission to view. +
++JIRA API docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board/{boardId}/sprint +
+ + + + + + +func (s *BoardService) GetBoard(boardID int) (*Board, *Response, error)+
+GetBoard will returns the board for the given boardID. +This board will only be returned if the user has permission to view it. +
++JIRA API docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-getBoard +
+ + + + + + + + +type BoardsList struct { + MaxResults int `json:"maxResults"` + StartAt int `json:"startAt"` + Total int `json:"total"` + IsLast bool `json:"isLast"` + Values []Board `json:"values"` +}+
+BoardsList reflects a list of agile boards +
+ + + + + + + + + + + + + + + + +type Client struct { + + // Services used for talking to different parts of the JIRA API. + Authentication *AuthenticationService + Issue *IssueService + Project *ProjectService + Board *BoardService + Sprint *SprintService + // contains filtered or unexported fields +}+
+A Client manages communication with the JIRA API. +
+ + + + + + + + + + + + +func NewClient(httpClient *http.Client, baseURL string) (*Client, error)+
+NewClient returns a new JIRA API client. +If a nil httpClient is provided, http.DefaultClient will be used. +To use API methods which require authentication you can follow the preferred solution and +provide an http.Client that will perform the authentication for you with OAuth and HTTP Basic (such as that provided by the golang.org/x/oauth2 library). +As an alternative you can use Session Cookie based authentication provided by this package as well. +See https://docs.atlassian.com/jira/REST/latest/#authentication +baseURL is the HTTP endpoint of your JIRA instance and should always be specified with a trailing slash. +
+ + + + + + + +func (c *Client) Do(req *http.Request, v interface{}) (*Response, error)+
+Do sends an API request and returns the API response. +The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. +
+ + + + + + +func (c *Client) GetBaseURL() url.URL+
+GetBaseURL will return you the Base URL. +This is the same URL as in the NewClient constructor +
+ + + + + + +func (c *Client) NewMultiPartRequest(method, urlStr string, buf *bytes.Buffer) (*http.Request, error)+
+NewMultiPartRequest creates an API request including a multi-part file. +A relative URL can be provided in urlStr, in which case it is resolved relative to the baseURL of the Client. +Relative URLs should always be specified without a preceding slash. +If specified, the value pointed to by buf is a multipart form. +
+ + + + + + +func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)+
+NewRequest creates an API request. +A relative URL can be provided in urlStr, in which case it is resolved relative to the baseURL of the Client. +Relative URLs should always be specified without a preceding slash. +If specified, the value pointed to by body is JSON encoded and included as the request body. +
+ + + + + + + + +type Comment struct { + ID string `json:"id,omitempty"` + Self string `json:"self,omitempty"` + Name string `json:"name,omitempty"` + Author User `json:"author,omitempty"` + Body string `json:"body,omitempty"` + UpdateAuthor User `json:"updateAuthor,omitempty"` + Updated string `json:"updated,omitempty"` + Created string `json:"created,omitempty"` + Visibility CommentVisibility `json:"visibility,omitempty"` +}+
+Comment represents a comment by a person to an issue in JIRA. +
+ + + + + + + + + + + + + + + + +type CommentVisibility struct { + Type string `json:"type,omitempty"` + Value string `json:"value,omitempty"` +}+
+CommentVisibility represents he visibility of a comment. +E.g. Type could be "role" and Value "Administrators" +
+ + + + + + + + + + + + + + + + +type Comments struct { + Comments []*Comment `json:"comments,omitempty"` +}+
+Comments represents a list of Comment. +
+ + + + + + + + + + + + + + + + +type Component struct { + Self string `json:"self,omitempty"` + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` +}+
+Component represents a "component" of a JIRA issue. +Components can be user defined in every JIRA instance. +
+ + + + + + + + + + + + + + + + +type CreateTransitionPayload struct { + Transition TransitionPayload `json:"transition"` +}+
+CreateTransitionPayload is used for creating new issue transitions +
+ + + + + + + + + + + + + + + + +type CustomFields map[string]string+
+CustomFields represents custom fields of JIRA +This can heavily differ between JIRA instances +
+ + + + + + + + + + + + + + + + +type Epic struct { + ID int `json:"id"` + Key string `json:"key"` + Self string `json:"self"` + Name string `json:"name"` + Summary string `json:"summary"` + Done bool `json:"done"` +}+
+Epic represents the epic to which an issue is associated +Not that this struct does not process the returned "color" value +
+ + + + + + + + + + + + + + + + +type FixVersion struct { + Archived *bool `json:"archived,omitempty"` + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + ProjectID int `json:"projectId,omitempty"` + ReleaseDate string `json:"releaseDate,omitempty"` + Released *bool `json:"released,omitempty"` + Self string `json:"self,omitempty"` + UserReleaseDate string `json:"userReleaseDate,omitempty"` +}+
+FixVersion represents a software release in which an issue is fixed. +
+ + + + + + + + + + + + + + + + +type Issue struct { + Expand string `json:"expand,omitempty"` + ID string `json:"id,omitempty"` + Self string `json:"self,omitempty"` + Key string `json:"key,omitempty"` + Fields *IssueFields `json:"fields,omitempty"` +}+
+Issue represents a JIRA issue. +
+ + + + + + + + + + + + + + + + +type IssueFields struct { + // TODO Missing fields + // * "timespent": null, + // * "aggregatetimespent": null, + // * "workratio": -1, + // * "lastViewed": null, + // * "timeestimate": null, + // * "aggregatetimeoriginalestimate": null, + // * "timeoriginalestimate": null, + // * "timetracking": {}, + // * "aggregatetimeestimate": null, + // * "environment": null, + // * "duedate": null, + Type IssueType `json:"issuetype"` + Project Project `json:"project,omitempty"` + Resolution *Resolution `json:"resolution,omitempty"` + Priority *Priority `json:"priority,omitempty"` + Resolutiondate string `json:"resolutiondate,omitempty"` + Created string `json:"created,omitempty"` + Watches *Watches `json:"watches,omitempty"` + Assignee *User `json:"assignee,omitempty"` + Updated string `json:"updated,omitempty"` + Description string `json:"description,omitempty"` + Summary string `json:"summary"` + Creator *User `json:"Creator,omitempty"` + Reporter *User `json:"reporter,omitempty"` + Components []*Component `json:"components,omitempty"` + Status *Status `json:"status,omitempty"` + Progress *Progress `json:"progress,omitempty"` + AggregateProgress *Progress `json:"aggregateprogress,omitempty"` + Worklog *Worklog `json:"worklog,omitempty"` + IssueLinks []*IssueLink `json:"issuelinks,omitempty"` + Comments *Comments `json:"comment,omitempty"` + FixVersions []*FixVersion `json:"fixVersions,omitempty"` + Labels []string `json:"labels,omitempty"` + Subtasks []*Subtasks `json:"subtasks,omitempty"` + Attachments []*Attachment `json:"attachment,omitempty"` + Epic *Epic `json:"epic,omitempty"` +}+
+IssueFields represents single fields of a JIRA issue. +Every JIRA issue has several fields attached. +
+ + + + + + + + + + + + + + + + +type IssueLink struct { + ID string `json:"id,omitempty"` + Self string `json:"self,omitempty"` + Type IssueLinkType `json:"type"` + OutwardIssue *Issue `json:"outwardIssue"` + InwardIssue *Issue `json:"inwardIssue"` + Comment *Comment `json:"comment,omitempty"` +}+
+IssueLink represents a link between two issues in JIRA. +
+ + + + + + + + + + + + + + + + +type IssueLinkType struct { + ID string `json:"id,omitempty"` + Self string `json:"self,omitempty"` + Name string `json:"name"` + Inward string `json:"inward"` + Outward string `json:"outward"` +}+
+IssueLinkType represents a type of a link between to issues in JIRA. +Typical issue link types are "Related to", "Duplicate", "Is blocked by", etc. +
+ + + + + + + + + + + + + + + + +type IssueService struct {
+ // contains filtered or unexported fields
+}
+ +IssueService handles Issues for the JIRA instance / API. +
++JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issue +
+ + + + + + + + + + + + + + +func (s *IssueService) AddComment(issueID string, comment *Comment) (*Comment, *Response, error)+
+AddComment adds a new comment to issueID. +
++JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issue-addComment +
+ + + + + + +func (s *IssueService) AddLink(issueLink *IssueLink) (*Response, error)+
+AddLink adds a link between two issues. +
++JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issueLink +
+ + + + + + +func (s *IssueService) Create(issue *Issue) (*Issue, *Response, error)+
+Create creates an issue or a sub-task from a JSON representation. +Creating a sub-task is similar to creating a regular issue, with two important differences: +The issueType field must correspond to a sub-task issue type and you must provide a parent field in the issue create request containing the id or key of the parent issue. +
++JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issue-createIssues +
+ + + + + + +func (s *IssueService) DoTransition(ticketID, transitionID string) (*Response, error)+
+DoTransition performs a transition on an issue. +When performing the transition you can update or set other issue fields. +
++JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issue-doTransition +
+ + + + + + +func (s *IssueService) DownloadAttachment(attachmentID string) (*Response, error)+
+DownloadAttachment returns a Response of an attachment for a given attachmentID. +The attachment is in the Response.Body of the response. +This is an io.ReadCloser. +The caller should close the resp.Body. +
+ + + + + + +func (s *IssueService) Get(issueID string) (*Issue, *Response, error)+
+Get returns a full representation of the issue for the given issue key. +JIRA will attempt to identify the issue by the issueIdOrKey path parameter. +This can be an issue id, or an issue key. +If the issue cannot be found via an exact match, JIRA will also look for the issue in a case-insensitive way, or by looking to see if the issue was moved. +
++JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issue-getIssue +
+ + + + + + +func (s *IssueService) GetCustomFields(issueID string) (CustomFields, *Response, error)+
+GetCustomFields returns a map of customfield_* keys with string values +
+ + + + + + +func (s *IssueService) GetTransitions(id string) ([]Transition, *Response, error)+
+GetTransitions gets a list of the transitions possible for this issue by the current user, +along with fields that are required and their types. +
++JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issue-getTransitions +
+ + + + + + +func (s *IssueService) PostAttachment(attachmentID string, r io.Reader, attachmentName string) (*[]Attachment, *Response, error)+
+PostAttachment uploads r (io.Reader) as an attachment to a given attachmentID +
+ + + + + + +func (s *IssueService) Search(jql string, options *SearchOptions) ([]Issue, *Response, error)+
+Search will search for tickets according to the jql +
++JIRA API docs: https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-query-issues +
+ + + + + + + + +type IssueType struct { + Self string `json:"self,omitempty"` + ID string `json:"id,omitempty"` + Description string `json:"description,omitempty"` + IconURL string `json:"iconUrl,omitempty"` + Name string `json:"name,omitempty"` + Subtask bool `json:"subtask,omitempty"` + AvatarID int `json:"avatarId,omitempty"` +}+
+IssueType represents a type of a JIRA issue. +Typical types are "Request", "Bug", "Story", ... +
+ + + + + + + + + + + + + + + + +type IssuesInSprintResult struct { + Issues []Issue `json:"issues"` +}+
+IssuesInSprintResult represents a wrapper struct for search result +
+ + + + + + + + + + + + + + + + +type IssuesWrapper struct { + Issues []string `json:"issues"` +}+
+IssuesWrapper represents a wrapper struct for moving issues to sprint +
+ + + + + + + + + + + + + + + + +type Priority struct { + Self string `json:"self,omitempty"` + IconURL string `json:"iconUrl,omitempty"` + Name string `json:"name,omitempty"` + ID string `json:"id,omitempty"` +}+
+Priority represents a priority of a JIRA issue. +Typical types are "Normal", "Moderate", "Urgent", ... +
+ + + + + + + + + + + + + + + + +type Progress struct { + Progress int `json:"progress"` + Total int `json:"total"` +}+
+Progress represents the progress of a JIRA issue. +
+ + + + + + + + + + + + + + + + +type Project struct { + Expand string `json:"expand,omitempty"` + Self string `json:"self,omitempty"` + ID string `json:"id,omitempty"` + Key string `json:"key,omitempty"` + Description string `json:"description,omitempty"` + Lead User `json:"lead,omitempty"` + Components []ProjectComponent `json:"components,omitempty"` + IssueTypes []IssueType `json:"issueTypes,omitempty"` + URL string `json:"url,omitempty"` + Email string `json:"email,omitempty"` + AssigneeType string `json:"assigneeType,omitempty"` + Versions []Version `json:"versions,omitempty"` + Name string `json:"name,omitempty"` + Roles struct { + Developers string `json:"Developers,omitempty"` + } `json:"roles,omitempty"` + AvatarUrls AvatarUrls `json:"avatarUrls,omitempty"` + ProjectCategory ProjectCategory `json:"projectCategory,omitempty"` +}+
+Project represents a JIRA Project. +
+ + + + + + + + + + + + + + + + +type ProjectCategory struct { + Self string `json:"self"` + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` +}+
+ProjectCategory represents a single project category +
+ + + + + + + + + + + + + + + + +type ProjectComponent struct { + Self string `json:"self"` + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Lead User `json:"lead"` + AssigneeType string `json:"assigneeType"` + Assignee User `json:"assignee"` + RealAssigneeType string `json:"realAssigneeType"` + RealAssignee User `json:"realAssignee"` + IsAssigneeTypeValid bool `json:"isAssigneeTypeValid"` + Project string `json:"project"` + ProjectID int `json:"projectId"` +}+
+ProjectComponent represents a single component of a project +
+ + + + + + + + + + + + + + + + +type ProjectList []struct { + Expand string `json:"expand"` + Self string `json:"self"` + ID string `json:"id"` + Key string `json:"key"` + Name string `json:"name"` + AvatarUrls AvatarUrls `json:"avatarUrls"` + ProjectTypeKey string `json:"projectTypeKey"` + ProjectCategory ProjectCategory `json:"projectCategory,omitempty"` +}+
+ProjectList represent a list of Projects +
+ + + + + + + + + + + + + + + + +type ProjectService struct {
+ // contains filtered or unexported fields
+}
+ +ProjectService handles projects for the JIRA instance / API. +
++JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/project +
+ + + + + + + + + + + + + + +func (s *ProjectService) Get(projectID string) (*Project, *Response, error)+
+Get returns a full representation of the project for the given issue key. +JIRA will attempt to identify the project by the projectIdOrKey path parameter. +This can be an project id, or an project key. +
++JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/project-getProject +
+ + + + + + +func (s *ProjectService) GetList() (*ProjectList, *Response, error)+
+GetList gets all projects form JIRA +
++JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/project-getAllProjects +
+ + + + + + + + +type Resolution struct { + Self string `json:"self"` + ID string `json:"id"` + Description string `json:"description"` + Name string `json:"name"` +}+
+Resolution represents a resolution of a JIRA issue. +Typical types are "Fixed", "Suspended", "Won't Fix", ... +
+ + + + + + + + + + + + + + + + +type Response struct { + *http.Response + + StartAt int + MaxResults int + Total int +}+
+Response represents JIRA API response. It wraps http.Response returned from +API and provides information about paging. +
+ + + + + + + + + + + + + + + + +type SearchOptions struct { + // StartAt: The starting index of the returned projects. Base index: 0. + StartAt int `url:"startAt,omitempty"` + // MaxResults: The maximum number of projects to return per page. Default: 50. + MaxResults int `url:"maxResults,omitempty"` +}+
+SearchOptions specifies the optional parameters to various List methods that +support pagination. +Pagination is used for the JIRA REST APIs to conserve server resources and limit +response size for resources that return potentially large collection of items. +A request to a pages API will result in a values array wrapped in a JSON object with some paging metadata +Default Pagination options +
+ + + + + + + + + + + + + + + + +type Session struct { + Self string `json:"self,omitempty"` + Name string `json:"name,omitempty"` + Session struct { + Name string `json:"name"` + Value string `json:"value"` + } `json:"session,omitempty"` + LoginInfo struct { + FailedLoginCount int `json:"failedLoginCount"` + LoginCount int `json:"loginCount"` + LastFailedLoginTime string `json:"lastFailedLoginTime"` + PreviousLoginTime string `json:"previousLoginTime"` + } `json:"loginInfo"` + Cookies []*http.Cookie +}+
+Session represents a Session JSON response by the JIRA API. +
+ + + + + + + + + + + + + + + + +type Sprint struct { + ID int `json:"id"` + Name string `json:"name"` + CompleteDate *time.Time `json:"completeDate"` + EndDate *time.Time `json:"endDate"` + StartDate *time.Time `json:"startDate"` + OriginBoardID int `json:"originBoardId"` + Self string `json:"self"` + State string `json:"state"` +}+
+Sprint represents a sprint on JIRA agile board +
+ + + + + + + + + + + + + + + + +type SprintService struct {
+ // contains filtered or unexported fields
+}
+ +SprintService handles sprints in JIRA Agile API. +See https://docs.atlassian.com/jira-software/REST/cloud/ +
+ + + + + + + + + + + + + + +func (s *SprintService) GetIssuesForSprint(sprintID int) ([]Issue, *Response, error)+
+GetIssuesForSprint returns all issues in a sprint, for a given sprint Id. +This only includes issues that the user has permission to view. +By default, the returned issues are ordered by rank. +
+JIRA API Docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/sprint-getIssuesForSprint ++ + + + + + +
func (s *SprintService) MoveIssuesToSprint(sprintID int, issueIDs []string) (*Response, error)+
+MoveIssuesToSprint moves issues to a sprint, for a given sprint Id. +Issues can only be moved to open or active sprints. +The maximum number of issues that can be moved in one operation is 50. +
++JIRA API docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/sprint-moveIssuesToSprint +
+ + + + + + + + +type Status struct { + Self string `json:"self"` + Description string `json:"description"` + IconURL string `json:"iconUrl"` + Name string `json:"name"` + ID string `json:"id"` + StatusCategory StatusCategory `json:"statusCategory"` +}+
+Status represents the current status of a JIRA issue. +Typical status are "Open", "In Progress", "Closed", ... +Status can be user defined in every JIRA instance. +
+ + + + + + + + + + + + + + + + +type StatusCategory struct { + Self string `json:"self"` + ID int `json:"id"` + Name string `json:"name"` + Key string `json:"key"` + ColorName string `json:"colorName"` +}+
+StatusCategory represents the category a status belongs to. +Those categories can be user defined in every JIRA instance. +
+ + + + + + + + + + + + + + + + +type Subtasks struct { + ID string `json:"id"` + Key string `json:"key"` + Self string `json:"self"` + Fields IssueFields `json:"fields"` +}+
+Subtasks represents all issues of a parent issue. +
+ + + + + + + + + + + + + + + + +type Time time.Time+
+Time represents the Time definition of JIRA as a time.Time of go +
+ + + + + + + + + + + + + + +func (t *Time) UnmarshalJSON(b []byte) error+
+UnmarshalJSON will transform the JIRA time into a time.Time +during the transformation of the JIRA JSON response +
+ + + + + + + + +type Transition struct { + ID string `json:"id"` + Name string `json:"name"` + Fields map[string]TransitionField `json:"fields"` +}+
+Transition represents an issue transition in JIRA +
+ + + + + + + + + + + + + + + + +type TransitionField struct { + Required bool `json:"required"` +}+
+TransitionField represents the value of one Transistion +
+ + + + + + + + + + + + + + + + +type TransitionPayload struct { + ID string `json:"id"` +}+
+TransitionPayload represents the request payload of Transistion calls like DoTransition +
+ + + + + + + + + + + + + + + + +type User struct { + Self string `json:"self,omitempty"` + Name string `json:"name,omitempty"` + Key string `json:"key,omitempty"` + EmailAddress string `json:"emailAddress,omitempty"` + AvatarUrls AvatarUrls `json:"avatarUrls,omitempty"` + DisplayName string `json:"displayName,omitempty"` + Active bool `json:"active,omitempty"` + TimeZone string `json:"timeZone,omitempty"` +}+
+User represents a user who is this JIRA issue assigned to. +
+ + + + + + + + + + + + + + + + +type Version struct { + Self string `json:"self"` + ID string `json:"id"` + Name string `json:"name"` + Archived bool `json:"archived"` + Released bool `json:"released"` + ReleaseDate string `json:"releaseDate"` + UserReleaseDate string `json:"userReleaseDate"` + ProjectID int `json:"projectId"` // Unlike other IDs, this is returned as a number +}+
+Version represents a single release version of a project +
+ + + + + + + + + + + + + + + + +type Watches struct { + Self string `json:"self,omitempty"` + WatchCount int `json:"watchCount,omitempty"` + IsWatching bool `json:"isWatching,omitempty"` +}+
+Watches represents a type of how many user are "observing" a JIRA issue to track the status / updates. +
+ + + + + + + + + + + + + + + + +type Worklog struct { + StartAt int `json:"startAt"` + MaxResults int `json:"maxResults"` + Total int `json:"total"` + Worklogs []WorklogRecord `json:"worklogs"` +}+
+Worklog represents the work log of a JIRA issue. +One Worklog contains zero or n WorklogRecords +JIRA Wiki: https://confluence.atlassian.com/jira/logging-work-on-an-issue-185729605.html +
+ + + + + + + + + + + + + + + + +type WorklogRecord struct { + Self string `json:"self"` + Author User `json:"author"` + UpdateAuthor User `json:"updateAuthor"` + Comment string `json:"comment"` + Created Time `json:"created"` + Updated Time `json:"updated"` + Started Time `json:"started"` + TimeSpent string `json:"timeSpent"` + TimeSpentSeconds int `json:"timeSpentSeconds"` + ID string `json:"id"` + IssueID string `json:"issueId"` +}+
+WorklogRecord represents one entry of a Worklog +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +▹ Example (MergeMultipleStreams)
+▹ Example (Simple)
+▹ Example (Window)
+type Sample struct { + Value float64 `json:",string"` + Width float64 `json:",string"` + Delta float64 `json:",string"` +}+
+Sample holds an observed value and meta information for compression. JSON +tags have been added for convenience. +
+ + + + + + + + + + + + + + + + +type Samples []Sample+
+Samples represents a slice of samples. It implements sort.Interface. +
+ + + + + + + + + + + + + + +func (a Samples) Len() int+ + + + + + +
func (a Samples) Less(i, j int) bool+ + + + + + +
func (a Samples) Swap(i, j int)+ + + + + + + + +
type Stream struct {
+ // contains filtered or unexported fields
+}
+ +Stream computes quantiles for a stream of float64s. It is not thread-safe by +design. Take care when using across multiple goroutines. +
+ + + + + + + + + + + + +func NewHighBiased(epsilon float64) *Stream+
+NewHighBiased returns an initialized Stream for high-biased quantiles +(e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but +error guarantees can still be given even for the higher ranks of the data +distribution. +
++The provided epsilon is a relative error, i.e. the true quantile of a value +returned by a query is guaranteed to be within 1-(1±Epsilon)*(1-Quantile). +
++See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error +properties. +
+ + + + + +func NewLowBiased(epsilon float64) *Stream+
+NewLowBiased returns an initialized Stream for low-biased quantiles +(e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but +error guarantees can still be given even for the lower ranks of the data +distribution. +
++The provided epsilon is a relative error, i.e. the true quantile of a value +returned by a query is guaranteed to be within (1±Epsilon)*Quantile. +
++See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error +properties. +
+ + + + + +func NewTargeted(targets map[float64]float64) *Stream+
+NewTargeted returns an initialized Stream concerned with a particular set of +quantile values that are supplied a priori. Knowing these a priori reduces +space and computation time. The targets map maps the desired quantiles to +their absolute errors, i.e. the true quantile of a value returned by a query +is guaranteed to be within (Quantile±Epsilon). +
++See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties. +
+ + + + + + + +func (s *Stream) Count() int+
+Count returns the total number of samples observed in the stream +since initialization. +
+ + + + + + +func (s *Stream) Insert(v float64)+
+Insert inserts v into the stream. +
+ + + + + + +func (s *Stream) Merge(samples Samples)+
+Merge merges samples into the underlying streams samples. This is handy when +merging multiple streams from separate threads, database shards, etc. +
++ATTENTION: This method is broken and does not yield correct results. The +underlying algorithm is not capable of merging streams correctly. +
+ + + + + + +func (s *Stream) Query(q float64) float64+
+Query returns the computed qth percentiles value. If s was created with +NewTargeted, and q is not in the set of quantiles provided a priori, Query +will return an unspecified result. +
+ + + + + + +func (s *Stream) Reset()+
+Reset reinitializes and clears the list reusing the samples buffer memory. +
+ + + + + + +func (s *Stream) Samples() Samples+
+Samples returns stream samples held by s. +
+ + + + + + + + + + + + + + + + + + +const DefaultTimeout = 100 * time.Millisecond+
+DefaultTimeout is the default socket read/write timeout. +
+ + + + +var ( + // ErrCacheMiss means that a Get failed because the item wasn't present. + ErrCacheMiss = errors.New("memcache: cache miss") + + // ErrCASConflict means that a CompareAndSwap call failed due to the + // cached value being modified between the Get and the CompareAndSwap. + // If the cached value was simply evicted rather than replaced, + // ErrNotStored will be returned instead. + ErrCASConflict = errors.New("memcache: compare-and-swap conflict") + + // ErrNotStored means that a conditional write operation (i.e. Add or + // CompareAndSwap) failed because the condition was not satisfied. + ErrNotStored = errors.New("memcache: item not stored") + + // ErrServer means that a server error occurred. + ErrServerError = errors.New("memcache: server error") + + // ErrNoStats means that no statistics were available. + ErrNoStats = errors.New("memcache: no statistics available") + + // ErrMalformedKey is returned when an invalid key is used. + // Keys must be at maximum 250 bytes long, ASCII, and not + // contain whitespace or control characters. + ErrMalformedKey = errors.New("malformed: key is too long or contains invalid characters") + + // ErrNoServers is returned when no servers are configured or available. + ErrNoServers = errors.New("memcache: no servers configured or available") +)+ + + + + + + +
type Client struct { + // Timeout specifies the socket read/write timeout. + // If zero, DefaultTimeout is used. + Timeout time.Duration + // contains filtered or unexported fields +}+
+Client is a memcache client. +It is safe for unlocked use by multiple concurrent goroutines. +
+ + + + + + + + + + + + +func New(server ...string) *Client+
+New returns a memcache client using the provided server(s) +with equal weight. If a server is listed multiple times, +it gets a proportional amount of weight. +
+ + + + + +func NewFromSelector(ss ServerSelector) *Client+
+NewFromSelector returns a new Client using the provided ServerSelector. +
+ + + + + + + +func (c *Client) Add(item *Item) error+
+Add writes the given item, if no value already exists for its +key. ErrNotStored is returned if that condition is not met. +
+ + + + + + +func (c *Client) CompareAndSwap(item *Item) error+
+CompareAndSwap writes the given item that was previously returned +by Get, if the value was neither modified or evicted between the +Get and the CompareAndSwap calls. The item's Key should not change +between calls but all other item fields may differ. ErrCASConflict +is returned if the value was modified in between the +calls. ErrNotStored is returned if the value was evicted in between +the calls. +
+ + + + + + +func (c *Client) Decrement(key string, delta uint64) (newValue uint64, err error)+
+Decrement atomically decrements key by delta. The return value is +the new value after being decremented or an error. If the value +didn't exist in memcached the error is ErrCacheMiss. The value in +memcached must be an decimal number, or an error will be returned. +On underflow, the new value is capped at zero and does not wrap +around. +
+ + + + + + +func (c *Client) Delete(key string) error+
+Delete deletes the item with the provided key. The error ErrCacheMiss is +returned if the item didn't already exist in the cache. +
+ + + + + + +func (c *Client) DeleteAll() error+
+DeleteAll deletes all items in the cache. +
+ + + + + + +func (c *Client) FlushAll() error+ + + + + + +
func (c *Client) Get(key string) (item *Item, err error)+
+Get gets the item for the given key. ErrCacheMiss is returned for a +memcache cache miss. The key must be at most 250 bytes in length. +
+ + + + + + +func (c *Client) GetMulti(keys []string) (map[string]*Item, error)+
+GetMulti is a batch version of Get. The returned map from keys to +items may have fewer elements than the input slice, due to memcache +cache misses. Each key must be at most 250 bytes in length. +If no error is returned, the returned map will also be non-nil. +
+ + + + + + +func (c *Client) Increment(key string, delta uint64) (newValue uint64, err error)+
+Increment atomically increments key by delta. The return value is +the new value after being incremented or an error. If the value +didn't exist in memcached the error is ErrCacheMiss. The value in +memcached must be an decimal number, or an error will be returned. +On 64-bit overflow, the new value wraps around. +
+ + + + + + +func (c *Client) Replace(item *Item) error+
+Replace writes the given item, but only if the server *does* +already hold data for this key +
+ + + + + + +func (c *Client) Set(item *Item) error+
+Set writes the given item, unconditionally. +
+ + + + + + +func (c *Client) Touch(key string, seconds int32) (err error)+
+Touch updates the expiry for the given key. The seconds parameter is either +a Unix timestamp or, if seconds is less than 1 month, the number of seconds +into the future at which time the item will expire. ErrCacheMiss is returned if the +key is not in the cache. The key must be at most 250 bytes in length. +
+ + + + + + + + +type ConnectTimeoutError struct { + Addr net.Addr +}+
+ConnectTimeoutError is the error type used when it takes +too long to connect to the desired host. This level of +detail can generally be ignored. +
+ + + + + + + + + + + + + + +func (cte *ConnectTimeoutError) Error() string+ + + + + + + + +
type Item struct { + // Key is the Item's key (250 bytes maximum). + Key string + + // Value is the Item's value. + Value []byte + + // Flags are server-opaque flags whose semantics are entirely + // up to the app. + Flags uint32 + + // Expiration is the cache expiration time, in seconds: either a relative + // time from now (up to 1 month), or an absolute Unix epoch time. + // Zero means the Item has no expiration time. + Expiration int32 + // contains filtered or unexported fields +}+
+Item is an item to be got or stored in a memcached server. +
+ + + + + + + + + + + + + + + + +type ServerList struct {
+ // contains filtered or unexported fields
+}
+ +ServerList is a simple ServerSelector. Its zero value is usable. +
+ + + + + + + + + + + + + + +func (ss *ServerList) Each(f func(net.Addr) error) error+
+Each iterates over each server calling the given function +
+ + + + + + +func (ss *ServerList) PickServer(key string) (net.Addr, error)+ + + + + + +
func (ss *ServerList) SetServers(servers ...string) error+
+SetServers changes a ServerList's set of servers at runtime and is +safe for concurrent use by multiple goroutines. +
++Each server is given equal weight. A server is given more weight +if it's listed multiple times. +
++SetServers returns an error if any of the server names fail to +resolve. No attempt is made to connect to the server. If any error +is returned, no changes are made to the ServerList. +
+ + + + + + + + +type ServerSelector interface { + // PickServer returns the server address that a given item + // should be shared onto. + PickServer(key string) (net.Addr, error) + Each(func(net.Addr) error) error +}+
+ServerSelector is the interface that selects a memcache server +as a function of the item's key. +
++All ServerSelector implementations must be safe for concurrent use +by multiple goroutines. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ gomemcache + | ++ + | +
+ memcache + | ++ Package memcache provides a client for the memcached cache server. + | +
const ( + DefaultInitialInterval = 500 * time.Millisecond + DefaultRandomizationFactor = 0.5 + DefaultMultiplier = 1.5 + DefaultMaxInterval = 60 * time.Second + DefaultMaxElapsedTime = 15 * time.Minute +)+
+Default values for ExponentialBackOff. +
+ + +const Stop time.Duration = -1+
+Indicates that no more retries should be made for use in NextBackOff(). +
+ + + + +var SystemClock = systemClock{}
+ +SystemClock implements Clock interface that uses time.Now(). +
+ + + + + + +func Retry(o Operation, b BackOff) error+
+Retry the operation o until it does not return error or BackOff stops. +o is guaranteed to be run at least once. +It is the caller's responsibility to reset b after Retry returns. +
++Retry sleeps the goroutine for the duration returned by BackOff after a +failed operation returns. +
+ +▹ Example
+func RetryNotify(operation Operation, b BackOff, notify Notify) error+
+RetryNotify calls notify function with the error and wait duration +for each failed attempt before sleep. +
+ + + + + + + + +type BackOff interface { + // NextBackOff returns the duration to wait before retrying the operation, + // or backoff.Stop to indicate that no more retries should be made. + // + // Example usage: + // + // duration := backoff.NextBackOff(); + // if (duration == backoff.Stop) { + // // Do not retry operation. + // } else { + // // Sleep for duration and retry operation. + // } + // + NextBackOff() time.Duration + + // Reset to initial state. + Reset() +}+
+BackOff is a backoff policy for retrying an operation. +
+ + + + + + + + + + + + + + + + +type Clock interface { + Now() time.Time +}+
+Clock is an interface that returns current time for BackOff. +
+ + + + + + + + + + + + + + + + +type ConstantBackOff struct { + Interval time.Duration +}+
+ConstantBackOff is a backoff policy that always returns the same backoff delay. +This is in contrast to an exponential backoff policy, +which returns a delay that grows longer as you call NextBackOff() over and over again. +
+ + + + + + + + + + + + +func NewConstantBackOff(d time.Duration) *ConstantBackOff+ + + + + + + +
func (b *ConstantBackOff) NextBackOff() time.Duration+ + + + + + +
func (b *ConstantBackOff) Reset()+ + + + + + + + +
type ExponentialBackOff struct { + InitialInterval time.Duration + RandomizationFactor float64 + Multiplier float64 + MaxInterval time.Duration + // After MaxElapsedTime the ExponentialBackOff stops. + // It never stops if MaxElapsedTime == 0. + MaxElapsedTime time.Duration + Clock Clock + // contains filtered or unexported fields +}+
+ExponentialBackOff is a backoff implementation that increases the backoff +period for each retry attempt using a randomization function that grows exponentially. +
++NextBackOff() is calculated using the following formula: +
+randomized interval = + RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor]) ++
+In other words NextBackOff() will range between the randomization factor +percentage below and above the retry interval. +
++For example, given the following parameters: +
+RetryInterval = 2 +RandomizationFactor = 0.5 +Multiplier = 2 ++
+the actual backoff period used in the next retry attempt will range between 1 and 3 seconds, +multiplied by the exponential, that is, between 2 and 6 seconds. +
++Note: MaxInterval caps the RetryInterval and not the randomized interval. +
++If the time elapsed since an ExponentialBackOff instance is created goes past the +MaxElapsedTime, then the method NextBackOff() starts returning backoff.Stop. +
++The elapsed time can be reset by calling Reset(). +
++Example: Given the following default arguments, for 10 tries the sequence will be, +and assuming we go over the MaxElapsedTime on the 10th try: +
+Request # RetryInterval (seconds) Randomized Interval (seconds) + + 1 0.5 [0.25, 0.75] + 2 0.75 [0.375, 1.125] + 3 1.125 [0.562, 1.687] + 4 1.687 [0.8435, 2.53] + 5 2.53 [1.265, 3.795] + 6 3.795 [1.897, 5.692] + 7 5.692 [2.846, 8.538] + 8 8.538 [4.269, 12.807] + 9 12.807 [6.403, 19.210] +10 19.210 backoff.Stop ++
+Note: Implementation is not thread-safe. +
+ + + + + + + + + + + + +func NewExponentialBackOff() *ExponentialBackOff+
+NewExponentialBackOff creates an instance of ExponentialBackOff using default values. +
+ + + + + + + +func (b *ExponentialBackOff) GetElapsedTime() time.Duration+
+GetElapsedTime returns the elapsed time since an ExponentialBackOff instance +is created and is reset when Reset() is called. +
++The elapsed time is computed using time.Now().UnixNano(). +
+ + + + + + +func (b *ExponentialBackOff) NextBackOff() time.Duration+
+NextBackOff calculates the next backoff interval using the formula: +
+Randomized interval = RetryInterval +/- (RandomizationFactor * RetryInterval) ++ + + + + + +
func (b *ExponentialBackOff) Reset()+
+Reset the interval back to the initial retry interval and restarts the timer. +
+ + + + + + + + +type Notify func(error, time.Duration)+
+Notify is a notify-on-error function. It receives an operation error and +backoff delay if the operation failed (with an error). +
++NOTE that if the backoff policy stated to stop retrying, +the notify function isn't called. +
+ + + + + + + + + + + + + + + + +type Operation func() error+
+An Operation is executing by Retry() or RetryNotify(). +The operation will be retried using a backoff policy if it returns an error. +
+ + + + + + + + + + + + + + + + +type StopBackOff struct{}+
+StopBackOff is a fixed backoff policy that always returns backoff.Stop for +NextBackOff(), meaning that the operation should never be retried. +
+ + + + + + + + + + + + + + +func (b *StopBackOff) NextBackOff() time.Duration+ + + + + + +
func (b *StopBackOff) Reset()+ + + + + + + + +
type Ticker struct { + C <-chan time.Time + // contains filtered or unexported fields +}+
+Ticker holds a channel that delivers `ticks' of a clock at times reported by a BackOff. +
++Ticks will continue to arrive when the previous operation is still running, +so operations that take a while to fail could run in quick succession. +
+ + + + + + +▹ Example
+func NewTicker(b BackOff) *Ticker+
+NewTicker returns a new Ticker containing a channel that will send the time at times +specified by the BackOff argument. Ticker is guaranteed to tick at least once. +The channel is closed when Stop method is called or BackOff stops. +
+ + + + + + + +func (t *Ticker) Stop()+
+Stop turns off a ticker. After Stop, no more ticks will be sent. +
+ + + + + + + + +type ZeroBackOff struct{}+
+ZeroBackOff is a fixed backoff policy whose backoff time is always zero, +meaning that the operation is retried immediately without waiting, indefinitely. +
+ + + + + + + + + + + + + + +func (b *ZeroBackOff) NextBackOff() time.Duration+ + + + + + +
func (b *ZeroBackOff) Reset()+ + + + + + + + + + + + + + + + + + +
func ApplyInputSourceValues(context *cli.Context, inputSourceContext InputSourceContext, flags []cli.Flag) error+
+ApplyInputSourceValues iterates over all provided flags and +executes ApplyInputSourceValue on flags implementing the +FlagInputSourceExtension interface to initialize these flags +to an alternate input source. +
+ + + + + + + +func InitInputSource(flags []cli.Flag, createInputSource func() (InputSourceContext, error)) cli.BeforeFunc+
+InitInputSource is used to to setup an InputSourceContext on a cli.Command Before method. It will create a new +input source based on the func provided. If there is no error it will then apply the new input source to any flags +that are supported by the input source +
+ + + + + + + +func InitInputSourceWithContext(flags []cli.Flag, createInputSource func(context *cli.Context) (InputSourceContext, error)) cli.BeforeFunc+
+InitInputSourceWithContext is used to to setup an InputSourceContext on a cli.Command Before method. It will create a new +input source based on the func provided with potentially using existing cli.Context values to initialize itself. If there is +no error it will then apply the new input source to any flags that are supported by the input source +
+ + + + + + + +func NewTomlSourceFromFlagFunc(flagFileName string) func(context *cli.Context) (InputSourceContext, error)+
+NewTomlSourceFromFlagFunc creates a new TOML InputSourceContext from a provided flag name and source context. +
+ + + + + + + +func NewYamlSourceFromFlagFunc(flagFileName string) func(context *cli.Context) (InputSourceContext, error)+
+NewYamlSourceFromFlagFunc creates a new Yaml InputSourceContext from a provided flag name and source context. +
+ + + + + + + + +type BoolFlag struct { + cli.BoolFlag + // contains filtered or unexported fields +}+
+BoolFlag is the flag type that wraps cli.BoolFlag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewBoolFlag(fl cli.BoolFlag) *BoolFlag+
+NewBoolFlag creates a new BoolFlag +
+ + + + + + + +func (f *BoolFlag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped BoolFlag.Apply +
+ + + + + + +func (f *BoolFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error+
+ApplyInputSourceValue applies a Bool value to the flagSet if required +
+ + + + + + + + +type BoolTFlag struct { + cli.BoolTFlag + // contains filtered or unexported fields +}+
+BoolTFlag is the flag type that wraps cli.BoolTFlag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewBoolTFlag(fl cli.BoolTFlag) *BoolTFlag+
+NewBoolTFlag creates a new BoolTFlag +
+ + + + + + + +func (f *BoolTFlag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped BoolTFlag.Apply +
+ + + + + + +func (f *BoolTFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error+
+ApplyInputSourceValue applies a BoolT value to the flagSet if required +
+ + + + + + + + +type DurationFlag struct { + cli.DurationFlag + // contains filtered or unexported fields +}+
+DurationFlag is the flag type that wraps cli.DurationFlag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewDurationFlag(fl cli.DurationFlag) *DurationFlag+
+NewDurationFlag creates a new DurationFlag +
+ + + + + + + +func (f *DurationFlag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped DurationFlag.Apply +
+ + + + + + +func (f *DurationFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error+
+ApplyInputSourceValue applies a Duration value to the flagSet if required +
+ + + + + + + + +type FlagInputSourceExtension interface { + cli.Flag + ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error +}+
+FlagInputSourceExtension is an extension interface of cli.Flag that +allows a value to be set on the existing parsed flags. +
+ + + + + + + + + + + + + + + + +type Float64Flag struct { + cli.Float64Flag + // contains filtered or unexported fields +}+
+Float64Flag is the flag type that wraps cli.Float64Flag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewFloat64Flag(fl cli.Float64Flag) *Float64Flag+
+NewFloat64Flag creates a new Float64Flag +
+ + + + + + + +func (f *Float64Flag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped Float64Flag.Apply +
+ + + + + + +func (f *Float64Flag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error+
+ApplyInputSourceValue applies a Float64 value to the flagSet if required +
+ + + + + + + + +type GenericFlag struct { + cli.GenericFlag + // contains filtered or unexported fields +}+
+GenericFlag is the flag type that wraps cli.GenericFlag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewGenericFlag(fl cli.GenericFlag) *GenericFlag+
+NewGenericFlag creates a new GenericFlag +
+ + + + + + + +func (f *GenericFlag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped GenericFlag.Apply +
+ + + + + + +func (f *GenericFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error+
+ApplyInputSourceValue applies a generic value to the flagSet if required +
+ + + + + + + + +type InputSourceContext interface { + Int(name string) (int, error) + Duration(name string) (time.Duration, error) + Float64(name string) (float64, error) + String(name string) (string, error) + StringSlice(name string) ([]string, error) + IntSlice(name string) ([]int, error) + Generic(name string) (cli.Generic, error) + Bool(name string) (bool, error) + BoolT(name string) (bool, error) +}+
+InputSourceContext is an interface used to allow +other input sources to be implemented as needed. +
+ + + + + + + + + + + + +func NewTomlSourceFromFile(file string) (InputSourceContext, error)+
+NewTomlSourceFromFile creates a new TOML InputSourceContext from a filepath. +
+ + + + + +func NewYamlSourceFromFile(file string) (InputSourceContext, error)+
+NewYamlSourceFromFile creates a new Yaml InputSourceContext from a filepath. +
+ + + + + + + + + +type Int64Flag struct { + cli.Int64Flag + // contains filtered or unexported fields +}+
+Int64Flag is the flag type that wraps cli.Int64Flag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewInt64Flag(fl cli.Int64Flag) *Int64Flag+
+NewInt64Flag creates a new Int64Flag +
+ + + + + + + +func (f *Int64Flag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped Int64Flag.Apply +
+ + + + + + + + +type Int64SliceFlag struct { + cli.Int64SliceFlag + // contains filtered or unexported fields +}+
+Int64SliceFlag is the flag type that wraps cli.Int64SliceFlag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewInt64SliceFlag(fl cli.Int64SliceFlag) *Int64SliceFlag+
+NewInt64SliceFlag creates a new Int64SliceFlag +
+ + + + + + + +func (f *Int64SliceFlag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped Int64SliceFlag.Apply +
+ + + + + + + + +type IntFlag struct { + cli.IntFlag + // contains filtered or unexported fields +}+
+IntFlag is the flag type that wraps cli.IntFlag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewIntFlag(fl cli.IntFlag) *IntFlag+
+NewIntFlag creates a new IntFlag +
+ + + + + + + +func (f *IntFlag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped IntFlag.Apply +
+ + + + + + +func (f *IntFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error+
+ApplyInputSourceValue applies a int value to the flagSet if required +
+ + + + + + + + +type IntSliceFlag struct { + cli.IntSliceFlag + // contains filtered or unexported fields +}+
+IntSliceFlag is the flag type that wraps cli.IntSliceFlag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewIntSliceFlag(fl cli.IntSliceFlag) *IntSliceFlag+
+NewIntSliceFlag creates a new IntSliceFlag +
+ + + + + + + +func (f *IntSliceFlag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped IntSliceFlag.Apply +
+ + + + + + +func (f *IntSliceFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error+
+ApplyInputSourceValue applies a IntSlice value if required +
+ + + + + + + + +type MapInputSource struct {
+ // contains filtered or unexported fields
+}
+ +MapInputSource implements InputSourceContext to return +data from the map that is loaded. +
+ + + + + + + + + + + + + + +func (fsm *MapInputSource) Bool(name string) (bool, error)+
+Bool returns an bool from the map otherwise returns false +
+ + + + + + +func (fsm *MapInputSource) BoolT(name string) (bool, error)+
+BoolT returns an bool from the map otherwise returns true +
+ + + + + + +func (fsm *MapInputSource) Duration(name string) (time.Duration, error)+
+Duration returns a duration from the map if it exists otherwise returns 0 +
+ + + + + + +func (fsm *MapInputSource) Float64(name string) (float64, error)+
+Float64 returns an float64 from the map if it exists otherwise returns 0 +
+ + + + + + +func (fsm *MapInputSource) Generic(name string) (cli.Generic, error)+
+Generic returns an cli.Generic from the map if it exists otherwise returns nil +
+ + + + + + +func (fsm *MapInputSource) Int(name string) (int, error)+
+Int returns an int from the map if it exists otherwise returns 0 +
+ + + + + + +func (fsm *MapInputSource) IntSlice(name string) ([]int, error)+
+IntSlice returns an []int from the map if it exists otherwise returns nil +
+ + + + + + +func (fsm *MapInputSource) String(name string) (string, error)+
+String returns a string from the map if it exists otherwise returns an empty string +
+ + + + + + +func (fsm *MapInputSource) StringSlice(name string) ([]string, error)+
+StringSlice returns an []string from the map if it exists otherwise returns nil +
+ + + + + + + + +type StringFlag struct { + cli.StringFlag + // contains filtered or unexported fields +}+
+StringFlag is the flag type that wraps cli.StringFlag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewStringFlag(fl cli.StringFlag) *StringFlag+
+NewStringFlag creates a new StringFlag +
+ + + + + + + +func (f *StringFlag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped StringFlag.Apply +
+ + + + + + +func (f *StringFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error+
+ApplyInputSourceValue applies a String value to the flagSet if required +
+ + + + + + + + +type StringSliceFlag struct { + cli.StringSliceFlag + // contains filtered or unexported fields +}+
+StringSliceFlag is the flag type that wraps cli.StringSliceFlag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewStringSliceFlag(fl cli.StringSliceFlag) *StringSliceFlag+
+NewStringSliceFlag creates a new StringSliceFlag +
+ + + + + + + +func (f *StringSliceFlag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped StringSliceFlag.Apply +
+ + + + + + +func (f *StringSliceFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error+
+ApplyInputSourceValue applies a StringSlice value to the flagSet if required +
+ + + + + + + + +type Uint64Flag struct { + cli.Uint64Flag + // contains filtered or unexported fields +}+
+Uint64Flag is the flag type that wraps cli.Uint64Flag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewUint64Flag(fl cli.Uint64Flag) *Uint64Flag+
+NewUint64Flag creates a new Uint64Flag +
+ + + + + + + +func (f *Uint64Flag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped Uint64Flag.Apply +
+ + + + + + + + +type UintFlag struct { + cli.UintFlag + // contains filtered or unexported fields +}+
+UintFlag is the flag type that wraps cli.UintFlag to allow +for other values to be specified +
+ + + + + + + + + + + + +func NewUintFlag(fl cli.UintFlag) *UintFlag+
+NewUintFlag creates a new UintFlag +
+ + + + + + + +func (f *UintFlag) Apply(set *flag.FlagSet)+
+Apply saves the flagSet for later usage calls, then calls the +wrapped UintFlag.Apply +
+ + + + + + + + + + + + + + + + + + +var AppHelpTemplate = `NAME:
+ {{.Name}} - {{.Usage}}
+
+USAGE:
+ {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}
+ {{if .Version}}{{if not .HideVersion}}
+VERSION:
+ {{.Version}}
+ {{end}}{{end}}{{if len .Authors}}
+AUTHOR(S):
+ {{range .Authors}}{{.}}{{end}}
+ {{end}}{{if .VisibleCommands}}
+COMMANDS:{{range .VisibleCategories}}{{if .Name}}
+ {{.Name}}:{{end}}{{range .VisibleCommands}}
+ {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}
+{{end}}{{end}}{{if .VisibleFlags}}
+GLOBAL OPTIONS:
+ {{range .VisibleFlags}}{{.}}
+ {{end}}{{end}}{{if .Copyright}}
+COPYRIGHT:
+ {{.Copyright}}
+ {{end}}
+`
+ +AppHelpTemplate is the text template for the Default help topic. +cli.go uses text/template to render templates. You can +render custom help text by setting this variable. +
+ + +var BashCompletionFlag = BoolFlag{ + Name: "generate-bash-completion", + Hidden: true, +}+
+BashCompletionFlag enables bash-completion for all commands and subcommands +
+ + +var CommandHelpTemplate = `NAME:
+ {{.HelpName}} - {{.Usage}}
+
+USAGE:
+ {{.HelpName}}{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{if .Category}}
+
+CATEGORY:
+ {{.Category}}{{end}}{{if .Description}}
+
+DESCRIPTION:
+ {{.Description}}{{end}}{{if .VisibleFlags}}
+
+OPTIONS:
+ {{range .VisibleFlags}}{{.}}
+ {{end}}{{end}}
+`
+ +CommandHelpTemplate is the text template for the command help topic. +cli.go uses text/template to render templates. You can +render custom help text by setting this variable. +
+ + +var ErrWriter io.Writer = os.Stderr+
+ErrWriter is used to write errors to the user. This can be anything +implementing the io.Writer interface and defaults to os.Stderr. +
+ + +var HelpFlag = BoolFlag{ + Name: "help, h", + Usage: "show help", +}+
+HelpFlag prints the help for all commands and subcommands +Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand +unless HideHelp is set to true) +
+ + +var HelpPrinter helpPrinter = printHelp
+ +HelpPrinter is a function that writes the help output. If not set a default +is used. The function signature is: +func(w io.Writer, templ string, data interface{}) +
+ + +var OsExiter = os.Exit+
+OsExiter is the function used when the app exits. If not set defaults to os.Exit. +
+ + +var SubcommandHelpTemplate = `NAME:
+ {{.HelpName}} - {{.Usage}}
+
+USAGE:
+ {{.HelpName}} command{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}
+
+COMMANDS:{{range .VisibleCategories}}{{if .Name}}
+ {{.Name}}:{{end}}{{range .VisibleCommands}}
+ {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}
+{{end}}{{if .VisibleFlags}}
+OPTIONS:
+ {{range .VisibleFlags}}{{.}}
+ {{end}}{{end}}
+`
+ +SubcommandHelpTemplate is the text template for the subcommand help topic. +cli.go uses text/template to render templates. You can +render custom help text by setting this variable. +
+ + +var VersionFlag = BoolFlag{ + Name: "version, v", + Usage: "print the version", +}+
+VersionFlag prints the version for the application +
+ + +var VersionPrinter = printVersion
+ +VersionPrinter prints the version for the App +
+ + + + + + +func DefaultAppComplete(c *Context)+
+DefaultAppComplete prints the list of subcommands as the default app completion method +
+ + + + + + + +func HandleAction(action interface{}, context *Context) (err error)+
+HandleAction uses ✧✧✧reflection✧✧✧ to figure out if the given Action is an +ActionFunc, a func with the legacy signature for Action, or some other +invalid thing. If it's an ActionFunc or a func with the legacy signature for +Action, the func is run! +
+ + + + + + + +func HandleExitCoder(err error)+
+HandleExitCoder checks if the error fulfills the ExitCoder interface, and if +so prints the error to stderr (if it is non-empty) and calls OsExiter with the +given exit code. If the given error is a MultiError, then this func is +called on all members of the Errors slice. +
+ + + + + + + +func ShowAppHelp(c *Context) error+
+ShowAppHelp is an action that displays the help. +
+ + + + + + + +func ShowCommandCompletions(ctx *Context, command string)+
+ShowCommandCompletions prints the custom completions for a given command +
+ + + + + + + +func ShowCommandHelp(ctx *Context, command string) error+
+ShowCommandHelp prints help for the given command +
+ + + + + + + +func ShowCompletions(c *Context)+
+ShowCompletions prints the lists of commands within a given context +
+ + + + + + + +func ShowSubcommandHelp(c *Context) error+
+ShowSubcommandHelp prints help for the given subcommand +
+ + + + + + + +func ShowVersion(c *Context)+
+ShowVersion prints the version number of the App +
+ + + + + + + + +type ActionFunc func(*Context) error+
+ActionFunc is the action to execute when no subcommands are specified +
+ + + + + + + + + + + + + + + + +type AfterFunc func(*Context) error+
+AfterFunc is an action to execute after any subcommands are run, but after the +subcommand has finished it is run even if Action() panics +
+ + + + + + + + + + + + + + + + +type App struct { + // The name of the program. Defaults to path.Base(os.Args[0]) + Name string + // Full name of command for help, defaults to Name + HelpName string + // Description of the program. + Usage string + // Text to override the USAGE section of help + UsageText string + // Description of the program argument format. + ArgsUsage string + // Version of the program + Version string + // List of commands to execute + Commands []Command + // List of flags to parse + Flags []Flag + // Boolean to enable bash completion commands + EnableBashCompletion bool + // Boolean to hide built-in help command + HideHelp bool + // Boolean to hide built-in version flag and the VERSION section of help + HideVersion bool + + // An action to execute when the bash-completion flag is set + BashComplete BashCompleteFunc + // An action to execute before any subcommands are run, but after the context is ready + // If a non-nil error is returned, no subcommands are run + Before BeforeFunc + // An action to execute after any subcommands are run, but after the subcommand has finished + // It is run even if Action() panics + After AfterFunc + + // The action to execute when no subcommands are specified + // Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}` + // *Note*: support for the deprecated `Action` signature will be removed in a future version + Action interface{} + + // Execute this function if the proper command cannot be found + CommandNotFound CommandNotFoundFunc + // Execute this function if an usage error occurs + OnUsageError OnUsageErrorFunc + // Compilation date + Compiled time.Time + // List of all authors who contributed + Authors []Author + // Copyright of the binary if any + Copyright string + // Name of Author (Note: Use App.Authors, this is deprecated) + Author string + // Email of Author (Note: Use App.Authors, this is deprecated) + Email string + // Writer writer to write output to + Writer io.Writer + // ErrWriter writes error output + ErrWriter io.Writer + // Other custom info + Metadata map[string]interface{} + // contains filtered or unexported fields +}+
+App is the main structure of a cli application. It is recommended that +an app be created with the cli.NewApp() function +
+ + + + + + + + + + + + +func NewApp() *App+
+NewApp creates a new cli Application with some reasonable defaults for Name, +Usage, Version and Action. +
+ + + + + + + +func (a *App) Categories() CommandCategories+
+Categories returns a slice containing all the categories with the commands they contain +
+ + + + + + +func (a *App) Command(name string) *Command+
+Command returns the named command on App. Returns nil if the command does not exist +
+ + + + + + +func (a *App) Run(arguments []string) (err error)+
+Run is the entry point to the cli app. Parses the arguments slice and routes +to the proper flag/args combination +
+ + +▹ Example
+▹ Example (BashComplete)
+▹ Example (Help)
+▹ Example (Subcommand)
+func (a *App) RunAndExitOnError()+
+RunAndExitOnError calls .Run() and exits non-zero if an error was returned +
++Deprecated: instead you should return an error that fulfills cli.ExitCoder +to cli.App.Run. This will cause the application to exit with the given eror +code in the cli.ExitCoder +
+ + + + + + +func (a *App) RunAsSubcommand(ctx *Context) (err error)+
+RunAsSubcommand invokes the subcommand given the context, parses ctx.Args() to +generate command-specific flags +
+ + + + + + +func (a *App) Setup()+
+Setup runs initialization code to ensure all data structures are ready for +`Run` or inspection prior to `Run`. It is internally called by `Run`, but +will return early if setup has already happened. +
+ + + + + + +func (a *App) VisibleCategories() []*CommandCategory+
+VisibleCategories returns a slice of categories and commands that are +Hidden=false +
+ + + + + + +func (a *App) VisibleCommands() []Command+
+VisibleCommands returns a slice of the Commands with Hidden=false +
+ + + + + + +func (a *App) VisibleFlags() []Flag+
+VisibleFlags returns a slice of the Flags with Hidden=false +
+ + + + + + + + +type Args []string+
+Args contains apps console arguments +
+ + + + + + + + + + + + + + +func (a Args) First() string+
+First returns the first argument, or else a blank string +
+ + + + + + +func (a Args) Get(n int) string+
+Get returns the nth argument, or else a blank string +
+ + + + + + +func (a Args) Present() bool+
+Present checks if there are any arguments present +
+ + + + + + +func (a Args) Swap(from, to int) error+
+Swap swaps arguments at the given indexes +
+ + + + + + +func (a Args) Tail() []string+
+Tail returns the rest of the arguments (not the first one) +or else an empty string slice +
+ + + + + + + + +type Author struct { + Name string // The Authors name + Email string // The Authors email +}+
+Author represents someone who has contributed to a cli project. +
+ + + + + + + + + + + + + + +func (a Author) String() string+
+String makes Author comply to the Stringer interface, to allow an easy print in the templating process +
+ + + + + + + + +type BashCompleteFunc func(*Context)+
+BashCompleteFunc is an action to execute when the bash-completion flag is set +
+ + + + + + + + + + + + + + + + +type BeforeFunc func(*Context) error+
+BeforeFunc is an action to execute before any subcommands are run, but after +the context is ready if a non-nil error is returned, no subcommands are run +
+ + + + + + + + + + + + + + + + +type BoolFlag struct { + Name string + Usage string + EnvVar string + Hidden bool + Destination *bool +}+
+BoolFlag is a flag with type bool +
+ + + + + + + + + + + + + + +func (f BoolFlag) Apply(set *flag.FlagSet)+
+Apply populates the flag given the flag set and environment +
+ + + + + + +func (f BoolFlag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f BoolFlag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + +type BoolTFlag struct { + Name string + Usage string + EnvVar string + Hidden bool + Destination *bool +}+
+BoolTFlag is a flag with type bool that is true by default +
+ + + + + + + + + + + + + + +func (f BoolTFlag) Apply(set *flag.FlagSet)+
+Apply populates the flag given the flag set and environment +
+ + + + + + +func (f BoolTFlag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f BoolTFlag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + +type Command struct { + // The name of the command + Name string + // short name of the command. Typically one character (deprecated, use `Aliases`) + ShortName string + // A list of aliases for the command + Aliases []string + // A short description of the usage of this command + Usage string + // Custom text to show on USAGE section of help + UsageText string + // A longer explanation of how the command works + Description string + // A short description of the arguments of this command + ArgsUsage string + // The category the command is part of + Category string + // The function to call when checking for bash command completions + BashComplete BashCompleteFunc + // An action to execute before any sub-subcommands are run, but after the context is ready + // If a non-nil error is returned, no sub-subcommands are run + Before BeforeFunc + // An action to execute after any subcommands are run, but after the subcommand has finished + // It is run even if Action() panics + After AfterFunc + // The function to call when this command is invoked + Action interface{} + + // Execute this function if a usage error occurs. + OnUsageError OnUsageErrorFunc + // List of child commands + Subcommands Commands + // List of flags to parse + Flags []Flag + // Treat all flags as normal arguments if true + SkipFlagParsing bool + // Skip argument reordering which attempts to move flags before arguments, + // but only works if all flags appear after all arguments. This behavior was + // removed n version 2 since it only works under specific conditions so we + // backport here by exposing it as an option for compatibility. + SkipArgReorder bool + // Boolean to hide built-in help command + HideHelp bool + // Boolean to hide this command from help or completion + Hidden bool + + // Full name of command for help, defaults to full command name, including parent commands. + HelpName string + // contains filtered or unexported fields +}+
+Command is a subcommand for a cli.App. +
+ + + + + + + + + + + + + + +func (c Command) FullName() string+
+FullName returns the full name of the command. +For subcommands this ensures that parent commands are part of the command path +
+ + + + + + +func (c Command) HasName(name string) bool+
+HasName returns true if Command.Name or Command.ShortName matches given name +
+ + + + + + +func (c Command) Names() []string+
+Names returns the names including short names and aliases. +
+ + + + + + +func (c Command) Run(ctx *Context) (err error)+
+Run invokes the command given the context, parses ctx.Args() to generate command-specific flags +
+ + + + + + +func (c Command) VisibleFlags() []Flag+
+VisibleFlags returns a slice of the Flags with Hidden=false +
+ + + + + + + + +type CommandCategories []*CommandCategory+
+CommandCategories is a slice of *CommandCategory. +
+ + + + + + + + + + + + + + +func (c CommandCategories) AddCommand(category string, command Command) CommandCategories+
+AddCommand adds a command to a category. +
+ + + + + + +func (c CommandCategories) Len() int+ + + + + + +
func (c CommandCategories) Less(i, j int) bool+ + + + + + +
func (c CommandCategories) Swap(i, j int)+ + + + + + + + +
type CommandCategory struct { + Name string + Commands Commands +}+
+CommandCategory is a category containing commands. +
+ + + + + + + + + + + + + + +func (c *CommandCategory) VisibleCommands() []Command+
+VisibleCommands returns a slice of the Commands with Hidden=false +
+ + + + + + + + +type CommandNotFoundFunc func(*Context, string)+
+CommandNotFoundFunc is executed if the proper command cannot be found +
+ + + + + + + + + + + + + + + + +type Commands []Command+
+Commands is a slice of Command +
+ + + + + + + + + + + + + + + + +type Context struct { + App *App + Command Command + // contains filtered or unexported fields +}+
+Context is a type that is passed through to +each Handler action in a cli application. Context +can be used to retrieve context-specific Args and +parsed command-line options. +
+ + + + + + + + + + + + +func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context+
+NewContext creates a new context. For use in when invoking an App or Command action. +
+ + + + + + + +func (c *Context) Args() Args+
+Args returns the command line arguments associated with the context. +
+ + + + + + +func (c *Context) Bool(name string) bool+
+Bool looks up the value of a local BoolFlag, returns +false if not found +
+ + + + + + +func (c *Context) BoolT(name string) bool+
+BoolT looks up the value of a local BoolTFlag, returns +false if not found +
+ + + + + + +func (c *Context) Duration(name string) time.Duration+
+Duration looks up the value of a local DurationFlag, returns +0 if not found +
+ + + + + + +func (c *Context) FlagNames() (names []string)+
+FlagNames returns a slice of flag names used in this context. +
+ + + + + + +func (c *Context) Float64(name string) float64+
+Float64 looks up the value of a local Float64Flag, returns +0 if not found +
+ + + + + + +func (c *Context) Generic(name string) interface{}+
+Generic looks up the value of a local GenericFlag, returns +nil if not found +
+ + + + + + +func (c *Context) GlobalBool(name string) bool+
+GlobalBool looks up the value of a global BoolFlag, returns +false if not found +
+ + + + + + +func (c *Context) GlobalBoolT(name string) bool+
+GlobalBoolT looks up the value of a global BoolTFlag, returns +false if not found +
+ + + + + + +func (c *Context) GlobalDuration(name string) time.Duration+
+GlobalDuration looks up the value of a global DurationFlag, returns +0 if not found +
+ + + + + + +func (c *Context) GlobalFlagNames() (names []string)+
+GlobalFlagNames returns a slice of global flag names used by the app. +
+ + + + + + +func (c *Context) GlobalFloat64(name string) float64+
+GlobalFloat64 looks up the value of a global Float64Flag, returns +0 if not found +
+ + + + + + +func (c *Context) GlobalGeneric(name string) interface{}+
+GlobalGeneric looks up the value of a global GenericFlag, returns +nil if not found +
+ + + + + + +func (c *Context) GlobalInt(name string) int+
+GlobalInt looks up the value of a global IntFlag, returns +0 if not found +
+ + + + + + +func (c *Context) GlobalInt64(name string) int64+
+GlobalInt64 looks up the value of a global Int64Flag, returns +0 if not found +
+ + + + + + +func (c *Context) GlobalInt64Slice(name string) []int64+
+GlobalInt64Slice looks up the value of a global Int64SliceFlag, returns +nil if not found +
+ + + + + + +func (c *Context) GlobalIntSlice(name string) []int+
+GlobalIntSlice looks up the value of a global IntSliceFlag, returns +nil if not found +
+ + + + + + +func (c *Context) GlobalIsSet(name string) bool+
+GlobalIsSet determines if the global flag was actually set +
+ + + + + + +func (c *Context) GlobalSet(name, value string) error+
+GlobalSet sets a context flag to a value on the global flagset +
+ + + + + + +func (c *Context) GlobalString(name string) string+
+GlobalString looks up the value of a global StringFlag, returns +"" if not found +
+ + + + + + +func (c *Context) GlobalStringSlice(name string) []string+
+GlobalStringSlice looks up the value of a global StringSliceFlag, returns +nil if not found +
+ + + + + + +func (c *Context) GlobalUint(name string) uint+
+GlobalUint looks up the value of a global UintFlag, returns +0 if not found +
+ + + + + + +func (c *Context) GlobalUint64(name string) uint64+
+GlobalUint64 looks up the value of a global Uint64Flag, returns +0 if not found +
+ + + + + + +func (c *Context) Int(name string) int+
+Int looks up the value of a local IntFlag, returns +0 if not found +
+ + + + + + +func (c *Context) Int64(name string) int64+
+Int64 looks up the value of a local Int64Flag, returns +0 if not found +
+ + + + + + +func (c *Context) Int64Slice(name string) []int64+
+Int64Slice looks up the value of a local Int64SliceFlag, returns +nil if not found +
+ + + + + + +func (c *Context) IntSlice(name string) []int+
+IntSlice looks up the value of a local IntSliceFlag, returns +nil if not found +
+ + + + + + +func (c *Context) IsSet(name string) bool+
+IsSet determines if the flag was actually set +
+ + + + + + +func (c *Context) NArg() int+
+NArg returns the number of the command line arguments. +
+ + + + + + +func (c *Context) NumFlags() int+
+NumFlags returns the number of flags set +
+ + + + + + +func (c *Context) Parent() *Context+
+Parent returns the parent context, if any +
+ + + + + + +func (c *Context) Set(name, value string) error+
+Set sets a context flag to a value. +
+ + + + + + +func (c *Context) String(name string) string+
+String looks up the value of a local StringFlag, returns +"" if not found +
+ + + + + + +func (c *Context) StringSlice(name string) []string+
+StringSlice looks up the value of a local StringSliceFlag, returns +nil if not found +
+ + + + + + +func (c *Context) Uint(name string) uint+
+Uint looks up the value of a local UintFlag, returns +0 if not found +
+ + + + + + +func (c *Context) Uint64(name string) uint64+
+Uint64 looks up the value of a local Uint64Flag, returns +0 if not found +
+ + + + + + + + +type DurationFlag struct { + Name string + Usage string + EnvVar string + Hidden bool + Value time.Duration + Destination *time.Duration +}+
+DurationFlag is a flag with type time.Duration (see https://golang.org/pkg/time/#ParseDuration) +
+ + + + + + + + + + + + + + +func (f DurationFlag) Apply(set *flag.FlagSet)+
+Apply populates the flag given the flag set and environment +
+ + + + + + +func (f DurationFlag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f DurationFlag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + +type ExitCoder interface { + error + ExitCode() int +}+
+ExitCoder is the interface checked by `App` and `Command` for a custom exit +code +
+ + + + + + + + + + + + + + + + +type ExitError struct {
+ // contains filtered or unexported fields
+}
+ +ExitError fulfills both the builtin `error` interface and `ExitCoder` +
+ + + + + + + + + + + + +func NewExitError(message string, exitCode int) *ExitError+
+NewExitError makes a new *ExitError +
+ + + + + + + +func (ee *ExitError) Error() string+
+Error returns the string message, fulfilling the interface required by +`error` +
+ + + + + + +func (ee *ExitError) ExitCode() int+
+ExitCode returns the exit code, fulfilling the interface required by +`ExitCoder` +
+ + + + + + + + +type Flag interface { + fmt.Stringer + // Apply Flag settings to the given flag set + Apply(*flag.FlagSet) + GetName() string +}+
+Flag is a common interface related to parsing flags in cli. +For more advanced flag parsing techniques, it is recommended that +this interface be implemented. +
+ + + + + + + + + + + + + + + + +type FlagStringFunc func(Flag) string+
+FlagStringFunc is used by the help generation to display a flag, which is +expected to be a single line. +
+ + + + + +var FlagStringer FlagStringFunc = stringifyFlag+
+FlagStringer converts a flag definition to a string. This is used by help +to display a flag. +
+ + + + + + + + + + + + + +type Float64Flag struct { + Name string + Usage string + EnvVar string + Hidden bool + Value float64 + Destination *float64 +}+
+Float64Flag is a flag with type float64 +
+ + + + + + + + + + + + + + +func (f Float64Flag) Apply(set *flag.FlagSet)+
+Apply populates the flag given the flag set and environment +
+ + + + + + +func (f Float64Flag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f Float64Flag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + +type Generic interface { + Set(value string) error + String() string +}+
+Generic is a generic parseable type identified by a specific flag +
+ + + + + + + + + + + + + + + + +type GenericFlag struct { + Name string + Usage string + EnvVar string + Hidden bool + Value Generic +}+
+GenericFlag is a flag with type Generic +
+ + + + + + + + + + + + + + +func (f GenericFlag) Apply(set *flag.FlagSet)+
+Apply takes the flagset and calls Set on the generic flag with the value +provided by the user for parsing by the flag +
+ + + + + + +func (f GenericFlag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f GenericFlag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + +type Int64Flag struct { + Name string + Usage string + EnvVar string + Hidden bool + Value int64 + Destination *int64 +}+
+Int64Flag is a flag with type int64 +
+ + + + + + + + + + + + + + +func (f Int64Flag) Apply(set *flag.FlagSet)+
+Apply populates the flag given the flag set and environment +
+ + + + + + +func (f Int64Flag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f Int64Flag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + +type Int64Slice []int64+
+Int64Slice is an opaque type for []int to satisfy flag.Value +
+ + + + + + + + + + + + + + +func (f *Int64Slice) Set(value string) error+
+Set parses the value into an integer and appends it to the list of values +
+ + + + + + +func (f *Int64Slice) String() string+
+String returns a readable representation of this value (for usage defaults) +
+ + + + + + +func (f *Int64Slice) Value() []int64+
+Value returns the slice of ints set by this flag +
+ + + + + + + + +type Int64SliceFlag struct { + Name string + Usage string + EnvVar string + Hidden bool + Value *Int64Slice +}+
+Int64SliceFlag is a flag with type *Int64Slice +
+ + + + + + + + + + + + + + +func (f Int64SliceFlag) Apply(set *flag.FlagSet)+
+Apply populates the flag given the flag set and environment +
+ + + + + + +func (f Int64SliceFlag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f Int64SliceFlag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + +type IntFlag struct { + Name string + Usage string + EnvVar string + Hidden bool + Value int + Destination *int +}+
+IntFlag is a flag with type int +
+ + + + + + + + + + + + + + +func (f IntFlag) Apply(set *flag.FlagSet)+
+Apply populates the flag given the flag set and environment +
+ + + + + + +func (f IntFlag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f IntFlag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + +type IntSlice []int+
+IntSlice is an opaque type for []int to satisfy flag.Value +
+ + + + + + + + + + + + + + +func (f *IntSlice) Set(value string) error+
+Set parses the value into an integer and appends it to the list of values +
+ + + + + + +func (f *IntSlice) String() string+
+String returns a readable representation of this value (for usage defaults) +
+ + + + + + +func (f *IntSlice) Value() []int+
+Value returns the slice of ints set by this flag +
+ + + + + + + + +type IntSliceFlag struct { + Name string + Usage string + EnvVar string + Hidden bool + Value *IntSlice +}+
+IntSliceFlag is a flag with type *IntSlice +
+ + + + + + + + + + + + + + +func (f IntSliceFlag) Apply(set *flag.FlagSet)+
+Apply populates the flag given the flag set and environment +
+ + + + + + +func (f IntSliceFlag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f IntSliceFlag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + +type MultiError struct { + Errors []error +}+
+MultiError is an error that wraps multiple errors. +
+ + + + + + + + + + + + +func NewMultiError(err ...error) MultiError+
+NewMultiError creates a new MultiError. Pass in one or more errors. +
+ + + + + + + +func (m MultiError) Error() string+
+Error implents the error interface. +
+ + + + + + + + +type OnUsageErrorFunc func(context *Context, err error, isSubcommand bool) error+
+OnUsageErrorFunc is executed if an usage error occurs. This is useful for displaying +customized usage error messages. This function is able to replace the +original error messages. If this function is not set, the "Incorrect usage" +is displayed and the execution is interrupted. +
+ + + + + + + + + + + + + + + + +type StringFlag struct { + Name string + Usage string + EnvVar string + Hidden bool + Value string + Destination *string +}+
+StringFlag is a flag with type string +
+ + + + + + + + + + + + + + +func (f StringFlag) Apply(set *flag.FlagSet)+
+Apply populates the flag given the flag set and environment +
+ + + + + + +func (f StringFlag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f StringFlag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + +type StringSlice []string+
+StringSlice is an opaque type for []string to satisfy flag.Value +
+ + + + + + + + + + + + + + +func (f *StringSlice) Set(value string) error+
+Set appends the string value to the list of values +
+ + + + + + +func (f *StringSlice) String() string+
+String returns a readable representation of this value (for usage defaults) +
+ + + + + + +func (f *StringSlice) Value() []string+
+Value returns the slice of strings set by this flag +
+ + + + + + + + +type StringSliceFlag struct { + Name string + Usage string + EnvVar string + Hidden bool + Value *StringSlice +}+
+StringSliceFlag is a flag with type *StringSlice +
+ + + + + + + + + + + + + + +func (f StringSliceFlag) Apply(set *flag.FlagSet)+
+Apply populates the flag given the flag set and environment +
+ + + + + + +func (f StringSliceFlag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f StringSliceFlag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + +type Uint64Flag struct { + Name string + Usage string + EnvVar string + Hidden bool + Value uint64 + Destination *uint64 +}+
+Uint64Flag is a flag with type uint64 +
+ + + + + + + + + + + + + + +func (f Uint64Flag) Apply(set *flag.FlagSet)+
+Apply populates the flag given the flag set and environment +
+ + + + + + +func (f Uint64Flag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f Uint64Flag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + +type UintFlag struct { + Name string + Usage string + EnvVar string + Hidden bool + Value uint + Destination *uint +}+
+UintFlag is a flag with type uint +
+ + + + + + + + + + + + + + +func (f UintFlag) Apply(set *flag.FlagSet)+
+Apply populates the flag given the flag set and environment +
+ + + + + + +func (f UintFlag) GetName() string+
+GetName returns the name of the flag +
+ + + + + + +func (f UintFlag) String() string+
+String returns a readable representation of this value +(for usage defaults) +
+ + + + + + + + + + + + + + + + +func Bool(v bool) *bool+
+Bool returns a new pointer to the given bool value. +
+ + + + + + + +func Float(v float64) *float64+
+Float returns a new pointer to the given float64 value. +
+ + + + + + + + +type APIError struct { + Errors []ErrorDetail `json:"errors"` +}+
+APIError represents a Twitter API Error response +https://dev.twitter.com/overview/api/response-codes +
+ + + + + + + + + + + + + + +func (e APIError) Empty() bool+
+Empty returns true if empty. Otherwise, at least 1 error message/code is +present and false is returned. +
+ + + + + + +func (e APIError) Error() string+ + + + + + + + +
type AccountService struct {
+ // contains filtered or unexported fields
+}
+ +AccountService provides a method for account credential verification. +
+ + + + + + + + + + + + + + +func (s *AccountService) VerifyCredentials(params *AccountVerifyParams) (*User, *http.Response, error)+
+VerifyCredentials returns the authorized user if credentials are valid and +returns an error otherwise. +Requires a user auth context. +https://dev.twitter.com/rest/reference/get/account/verify_credentials +
+ + + + + + + + +type AccountVerifyParams struct { + IncludeEntities *bool `url:"include_entities,omitempty"` + SkipStatus *bool `url:"skip_status,omitempty"` + IncludeEmail *bool `url:"include_email,omitempty"` +}+
+AccountVerifyParams are the params for AccountService.VerifyCredentials. +
+ + + + + + + + + + + + + + + + +type BoundingBox struct { + Coordinates [][][2]float64 `json:"coordinates"` + Type string `json:"type"` +}+
+BoundingBox represents the bounding coordinates (longitude, latitutde) +defining the bounds of a box containing a Place entity. +
+ + + + + + + + + + + + + + + + +type Client struct { + + // Twitter API Services + Accounts *AccountService + Statuses *StatusService + Timelines *TimelineService + Users *UserService + Followers *FollowerService + DirectMessages *DirectMessageService + Streams *StreamService + // contains filtered or unexported fields +}+
+Client is a Twitter client for making Twitter API requests. +
+ + + + + + + + + + + + +func NewClient(httpClient *http.Client) *Client+
+NewClient returns a new Client. +
+ + + + + + + + + +type Contributor struct { + ID int64 `json:"id"` + IDStr string `json:"id_str"` + ScreenName string `json:"screen_name"` +}+
+Contributor represents a brief summary of a User identifiers. +
+ + + + + + + + + + + + + + + + +type Coordinates struct { + Coordinates [2]float64 `json:"coordinates"` + Type string `json:"type"` +}+
+Coordinates are pairs of longitude and latitude locations. +
+ + + + + + + + + + + + + + + + +type Demux interface { + Handle(message interface{}) + HandleChan(messages <-chan interface{}) +}+
+A Demux receives interface{} messages individually or from a channel and +sends those messages to one or more outputs determined by the +implementation. +
+ + + + + + + + + + + + + + + + +type DirectMessage struct { + CreatedAt string `json:"created_at"` + Entities *Entities `json:"entities"` + ID int64 `json:"id"` + IDStr string `json:"id_str"` + Recipient *User `json:"recipient"` + RecipientID int64 `json:"recipient_id"` + RecipientScreenName string `json:"recipient_screen_name"` + Sender *User `json:"sender"` + SenderID int64 `json:"sender_id"` + SenderScreenName string `json:"sender_screen_name"` + Text string `json:"text"` +}+
+DirectMessage is a direct message to a single recipient. +
+ + + + + + + + + + + + + + + + +type DirectMessageDestroyParams struct { + ID int64 `url:"id,omitempty"` + IncludeEntities *bool `url:"include_entities,omitempty"` +}+
+DirectMessageDestroyParams are the parameters for DirectMessageService.Destroy +
+ + + + + + + + + + + + + + + + +type DirectMessageGetParams struct { + SinceID int64 `url:"since_id,omitempty"` + MaxID int64 `url:"max_id,omitempty"` + Count int `url:"count,omitempty"` + IncludeEntities *bool `url:"include_entities,omitempty"` + SkipStatus *bool `url:"skip_status,omitempty"` +}+
+DirectMessageGetParams are the parameters for DirectMessageService.Get +
+ + + + + + + + + + + + + + + + +type DirectMessageNewParams struct { + UserID int64 `url:"user_id,omitempty"` + ScreenName string `url:"screen_name,omitempty"` + Text string `url:"text"` +}+
+DirectMessageNewParams are the parameters for DirectMessageService.New +
+ + + + + + + + + + + + + + + + +type DirectMessageSentParams struct { + SinceID int64 `url:"since_id,omitempty"` + MaxID int64 `url:"max_id,omitempty"` + Count int `url:"count,omitempty"` + Page int `url:"page,omitempty"` + IncludeEntities *bool `url:"include_entities,omitempty"` +}+
+DirectMessageSentParams are the parameters for DirectMessageService.Sent +
+ + + + + + + + + + + + + + + + +type DirectMessageService struct {
+ // contains filtered or unexported fields
+}
+ +DirectMessageService provides methods for accessing Twitter direct message +API endpoints. +
+ + + + + + + + + + + + + + +func (s *DirectMessageService) Destroy(id int64, params *DirectMessageDestroyParams) (*DirectMessage, *http.Response, error)+
+Destroy deletes the Direct Message with the given id and returns it if +successful. +Requires a user auth context with DM scope. +https://dev.twitter.com/rest/reference/post/direct_messages/destroy +
+ + + + + + +func (s *DirectMessageService) Get(params *DirectMessageGetParams) ([]DirectMessage, *http.Response, error)+
+Get returns recent Direct Messages received by the authenticated user. +Requires a user auth context with DM scope. +https://dev.twitter.com/rest/reference/get/direct_messages +
+ + + + + + +func (s *DirectMessageService) New(params *DirectMessageNewParams) (*DirectMessage, *http.Response, error)+
+New sends a new Direct Message to a specified user as the authenticated +user. +Requires a user auth context with DM scope. +https://dev.twitter.com/rest/reference/post/direct_messages/new +
+ + + + + + +func (s *DirectMessageService) Sent(params *DirectMessageSentParams) ([]DirectMessage, *http.Response, error)+
+Sent returns recent Direct Messages sent by the authenticated user. +Requires a user auth context with DM scope. +https://dev.twitter.com/rest/reference/get/direct_messages/sent +
+ + + + + + +func (s *DirectMessageService) Show(id int64) (*DirectMessage, *http.Response, error)+
+Show returns the requested Direct Message. +Requires a user auth context with DM scope. +https://dev.twitter.com/rest/reference/get/direct_messages/show +
+ + + + + + + + +type Entities struct { + Hashtags []HashtagEntity `json:"hashtags"` + Media []MediaEntity `json:"media"` + Urls []URLEntity `json:"urls"` + UserMentions []MentionEntity `json:"user_mentions"` +}+
+Entities represent metadata and context info parsed from Twitter components. +https://dev.twitter.com/overview/api/entities +TODO: symbols +
+ + + + + + + + + + + + + + + + +type ErrorDetail struct { + Message string `json:"message"` + Code int `json:"code"` +}+
+ErrorDetail represents an individual item in an APIError. +
+ + + + + + + + + + + + + + + + +type Event struct { + Event string `json:"event"` + CreatedAt string `json:"created_at"` + Target *User `json:"target"` + Source *User `json:"source"` + // TODO: add List or deprecate it + TargetObject *Tweet `json:"target_object"` +}+
+Event is a non-Tweet notification message (e.g. like, retweet, follow). +https://dev.twitter.com/streaming/overview/messages-types#Events_event +
+ + + + + + + + + + + + + + + + +type ExtendedEntity struct { + Media []MediaEntity `json:"media"` +}+
+ExtendedEntity contains media information. +https://dev.twitter.com/overview/api/entities-in-twitter-objects#extended_entities +
+ + + + + + + + + + + + + + + + +type FollowerIDParams struct { + UserID int64 `url:"user_id,omitempty"` + ScreenName string `url:"screen_name,omitempty"` + Cursor int64 `url:"cursor,omitempty"` + Count int `url:"count,omitempty"` +}+
+FollowerIDParams are the parameters for FollowerService.Ids +
+ + + + + + + + + + + + + + + + +type FollowerIDs struct { + IDs []int64 `json:"ids"` + NextCursor int64 `json:"next_cursor"` + NextCursorStr string `json:"next_cursor_str"` + PreviousCursor int64 `json:"previous_cursor"` + PreviousCursorStr string `json:"previous_cursor_str"` +}+
+FollowerIDs is a cursored collection of follower ids. +
+ + + + + + + + + + + + + + + + +type FollowerListParams struct { + UserID int64 `url:"user_id,omitempty"` + ScreenName string `url:"screen_name,omitempty"` + Cursor int `url:"cursor,omitempty"` + Count int `url:"count,omitempty"` + SkipStatus *bool `url:"skip_status,omitempty"` + IncludeUserEntities *bool `url:"include_user_entities,omitempty"` +}+
+FollowerListParams are the parameters for FollowerService.List +
+ + + + + + + + + + + + + + + + +type FollowerService struct {
+ // contains filtered or unexported fields
+}
+ +FollowerService provides methods for accessing Twitter followers endpoints. +
+ + + + + + + + + + + + + + +func (s *FollowerService) IDs(params *FollowerIDParams) (*FollowerIDs, *http.Response, error)+
+IDs returns a cursored collection of user ids following the specified user. +https://dev.twitter.com/rest/reference/get/followers/ids +
+ + + + + + +func (s *FollowerService) List(params *FollowerListParams) (*Followers, *http.Response, error)+
+List returns a cursored collection of Users following the specified user. +https://dev.twitter.com/rest/reference/get/followers/list +
+ + + + + + + + +type Followers struct { + Users []User `json:"users"` + NextCursor int64 `json:"next_cursor"` + NextCursorStr string `json:"next_cursor_str"` + PreviousCursor int64 `json:"previous_cursor"` + PreviousCursorStr string `json:"previous_cursor_str"` +}+
+Followers is a cursored collection of followers. +
+ + + + + + + + + + + + + + + + +type FriendsList struct { + Friends []int64 `json:"friends"` +}+
+FriendsList is a list of some of a user's friends. +https://dev.twitter.com/streaming/overview/messages-types#friends_list_friends +
+ + + + + + + + + + + + + + + + +type HashtagEntity struct { + Indices Indices `json:"indices"` + Text string `json:"text"` +}+
+HashtagEntity represents a hashtag which has been parsed from text. +
+ + + + + + + + + + + + + + + + +type HomeTimelineParams struct { + Count int `url:"count,omitempty"` + SinceID int64 `url:"since_id,omitempty"` + MaxID int64 `url:"max_id,omitempty"` + TrimUser *bool `url:"trim_user,omitempty"` + ExcludeReplies *bool `url:"exclude_replies,omitempty"` + ContributorDetails *bool `url:"contributor_details,omitempty"` + IncludeEntities *bool `url:"include_entities,omitempty"` +}+
+HomeTimelineParams are the parameters for TimelineService.HomeTimeline. +
+ + + + + + + + + + + + + + + + +type Indices [2]int+
+Indices represent the start and end offsets within text. +
+ + + + + + + + + + + + + + +func (i Indices) End() int+
+End returns the index at which an entity ends, exclusive. +
+ + + + + + +func (i Indices) Start() int+
+Start returns the index at which an entity starts, inclusive. +
+ + + + + + + + +type LocationDeletion struct { + UserID int64 `json:"user_id"` + UserIDStr string `json:"user_id_str"` + UpToStatusID int64 `json:"up_to_status_id"` + UpToStatusIDStr string `json:"up_to_status_id_str"` +}+
+LocationDeletion indicates geolocation data must be stripped from a range +of Tweets. +https://dev.twitter.com/streaming/overview/messages-types#Location_deletion_notices_scrub_geo +
+ + + + + + + + + + + + + + + + +type MediaEntity struct { + URLEntity + ID int64 `json:"id"` + IDStr string `json:"id_str"` + MediaURL string `json:"media_url"` + MediaURLHttps string `json:"media_url_https"` + SourceStatusID int64 `json:"source_status_id"` + SourceStatusIDStr string `json:"source_status_id_str"` + Type string `json:"type"` +}+
+MediaEntity represents media elements associated with a Tweet. +TODO: add Sizes +
+ + + + + + + + + + + + + + + + +type MentionEntity struct { + Indices Indices `json:"indices"` + ID int64 `json:"id"` + IDStr string `json:"id_str"` + Name string `json:"name"` + ScreenName string `json:"screen_name"` +}+
+MentionEntity represents Twitter user mentions parsed from text. +
+ + + + + + + + + + + + + + + + +type MentionTimelineParams struct { + Count int `url:"count,omitempty"` + SinceID int64 `url:"since_id,omitempty"` + MaxID int64 `url:"max_id,omitempty"` + TrimUser *bool `url:"trim_user,omitempty"` + ContributorDetails *bool `url:"contributor_details,omitempty"` + IncludeEntities *bool `url:"include_entities,omitempty"` +}+
+MentionTimelineParams are the parameters for TimelineService.MentionTimeline. +
+ + + + + + + + + + + + + + + + +type OEmbedTweet struct { + URL string `json:"url"` + ProviderURL string `json:"provider_url"` + ProviderName string `json:"provider_name"` + AuthorName string `json:"author_name"` + Version string `json:"version"` + AuthorURL string `json:"author_url"` + Type string `json:"type"` + HTML string `json:"html"` + Height int64 `json:"height"` + Width int64 `json:"width"` + CacheAge string `json:"cache_age"` +}+
+OEmbedTweet represents a Tweet in oEmbed format. +
+ + + + + + + + + + + + + + + + +type Place struct { + Attributes map[string]string `json:"attributes"` + BoundingBox *BoundingBox `json:"bounding_box"` + Country string `json:"country"` + CountryCode string `json:"country_code"` + FullName string `json:"full_name"` + Geometry *BoundingBox `json:"geometry"` + ID string `json:"id"` + Name string `json:"name"` + PlaceType string `json:"place_type"` + Polylines []string `json:"polylines"` + URL string `json:"url"` +}+
+Place represents a Twitter Place / Location +https://dev.twitter.com/overview/api/places +
+ + + + + + + + + + + + + + + + +type RetweetsOfMeTimelineParams struct { + Count int `url:"count,omitempty"` + SinceID int64 `url:"since_id,omitempty"` + MaxID int64 `url:"max_id,omitempty"` + TrimUser *bool `url:"trim_user,omitempty"` + IncludeEntities *bool `url:"include_entities,omitempty"` + IncludeUserEntities *bool `url:"include_user_entities"` +}+
+RetweetsOfMeTimelineParams are the parameters for +TimelineService.RetweetsOfMeTimeline. +
+ + + + + + + + + + + + + + + + +type StallWarning struct { + Code string `json:"code"` + Message string `json:"message"` + PercentFull int `json:"percent_full"` +}+
+StallWarning indicates the client is falling behind in the stream. +https://dev.twitter.com/streaming/overview/messages-types#stall_warnings +
+ + + + + + + + + + + + + + + + +type StatusDeletion struct { + ID int64 `json:"id"` + IDStr string `json:"id_str"` + UserID int64 `json:"user_id"` + UserIDStr string `json:"user_id_str"` +}+
+StatusDeletion indicates that a given Tweet has been deleted. +https://dev.twitter.com/streaming/overview/messages-types#status_deletion_notices_delete +
+ + + + + + + + + + + + + + + + +type StatusDestroyParams struct { + ID int64 `url:"id,omitempty"` + TrimUser *bool `url:"trim_user,omitempty"` +}+
+StatusDestroyParams are the parameters for StatusService.Destroy +
+ + + + + + + + + + + + + + + + +type StatusLookupParams struct { + ID []int64 `url:"id,omitempty,comma"` + TrimUser *bool `url:"trim_user,omitempty"` + IncludeEntities *bool `url:"include_entities,omitempty"` + Map *bool `url:"map,omitempty"` +}+
+StatusLookupParams are the parameters for StatusService.Lookup +
+ + + + + + + + + + + + + + + + +type StatusOEmbedParams struct { + ID int64 `url:"id,omitempty"` + URL string `url:"url,omitempty"` + Align string `url:"align,omitempty"` + MaxWidth int64 `url:"maxwidth,omitempty"` + HideMedia *bool `url:"hide_media,omitempty"` + HideThread *bool `url:"hide_media,omitempty"` + OmitScript *bool `url:"hide_media,omitempty"` + WidgetType string `url:"widget_type,omitempty"` + HideTweet *bool `url:"hide_tweet,omitempty"` +}+
+StatusOEmbedParams are the parameters for StatusService.OEmbed +
+ + + + + + + + + + + + + + + + +type StatusRetweetParams struct { + ID int64 `url:"id,omitempty"` + TrimUser *bool `url:"trim_user,omitempty"` +}+
+StatusRetweetParams are the parameters for StatusService.Retweet +
+ + + + + + + + + + + + + + + + +type StatusService struct {
+ // contains filtered or unexported fields
+}
+ +StatusService provides methods for accessing Twitter status API endpoints. +
+ + + + + + + + + + + + + + +func (s *StatusService) Destroy(id int64, params *StatusDestroyParams) (*Tweet, *http.Response, error)+
+Destroy deletes the Tweet with the given id and returns it if successful. +Requires a user auth context. +https://dev.twitter.com/rest/reference/post/statuses/destroy/%3Aid +
+ + + + + + +func (s *StatusService) Lookup(ids []int64, params *StatusLookupParams) ([]Tweet, *http.Response, error)+
+Lookup returns the requested Tweets as a slice. Combines ids from the +required ids argument and from params.Id. +https://dev.twitter.com/rest/reference/get/statuses/lookup +
+ + + + + + +func (s *StatusService) OEmbed(params *StatusOEmbedParams) (*OEmbedTweet, *http.Response, error)+
+OEmbed returns the requested Tweet in oEmbed format. +https://dev.twitter.com/rest/reference/get/statuses/oembed +
+ + + + + + +func (s *StatusService) Retweet(id int64, params *StatusRetweetParams) (*Tweet, *http.Response, error)+
+Retweet retweets the Tweet with the given id and returns the original Tweet +with embedded retweet details. +Requires a user auth context. +https://dev.twitter.com/rest/reference/post/statuses/retweet/%3Aid +
+ + + + + + +func (s *StatusService) Show(id int64, params *StatusShowParams) (*Tweet, *http.Response, error)+
+Show returns the requested Tweet. +https://dev.twitter.com/rest/reference/get/statuses/show/%3Aid +
+ + + + + + +func (s *StatusService) Update(status string, params *StatusUpdateParams) (*Tweet, *http.Response, error)+
+Update updates the user's status, also known as Tweeting. +Requires a user auth context. +https://dev.twitter.com/rest/reference/post/statuses/update +
+ + + + + + + + +type StatusShowParams struct { + ID int64 `url:"id,omitempty"` + TrimUser *bool `url:"trim_user,omitempty"` + IncludeMyRetweet *bool `url:"include_my_retweet,omitempty"` + IncludeEntities *bool `url:"include_entities,omitempty"` +}+
+StatusShowParams are the parameters for StatusService.Show +
+ + + + + + + + + + + + + + + + +type StatusUpdateParams struct { + Status string `url:"status,omitempty"` + InReplyToStatusID int64 `url:"in_reply_to_status_id,omitempty"` + PossiblySensitive *bool `url:"possibly_sensitive,omitempty"` + Lat *float64 `url:"lat,omitempty"` + Long *float64 `url:"long,omitempty"` + PlaceID string `url:"place_id,omitempty"` + DisplayCoordinates *bool `url:"display_coordinates,omitempty"` + TrimUser *bool `url:"trim_user,omitempty"` + MediaIds []int64 `url:"media_ids,omitempty,comma"` +}+
+StatusUpdateParams are the parameters for StatusService.Update +
+ + + + + + + + + + + + + + + + +type StatusWithheld struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + WithheldInCountries []string `json:"withheld_in_countries"` +}+
+StatusWithheld indicates a Tweet with the given ID, belonging to UserId, +has been withheld in certain countries. +https://dev.twitter.com/streaming/overview/messages-types#withheld_content_notices +
+ + + + + + + + + + + + + + + + +type Stream struct {
+ Messages chan interface{}
+ // contains filtered or unexported fields
+}
+ +Stream maintains a connection to the Twitter Streaming API, receives +messages from the streaming response, and sends them on the Messages +channel from a goroutine. The stream goroutine stops itself if an EOF is +reached or retry errors occur, also closing the Messages channel. +
++The client must Stop() the stream when finished receiving, which will +wait until the stream is properly stopped. +
+ + + + + + + + + + + + + + +func (s *Stream) Stop()+
+Stop signals retry and receiver to stop, closes the Messages channel, and +blocks until done. +
+ + + + + + + + +type StreamDisconnect struct { + Code int64 `json:"code"` + StreamName string `json:"stream_name"` + Reason string `json:"reason"` +}+
+StreamDisconnect indicates the stream has been shutdown for some reason. +https://dev.twitter.com/streaming/overview/messages-types#disconnect_messages +
+ + + + + + + + + + + + + + + + +type StreamFilterParams struct { + FilterLevel string `url:"filter_level,omitempty"` + Follow []string `url:"follow,omitempty,comma"` + Language []string `url:"language,omitempty,comma"` + Locations []string `url:"locations,omitempty,comma"` + StallWarnings *bool `url:"stall_warnings,omitempty"` + Track []string `url:"track,omitempty,comma"` +}+
+StreamFilterParams are parameters for StreamService.Filter. +
+ + + + + + + + + + + + + + + + +type StreamFirehoseParams struct { + Count int `url:"count,omitempty"` + FilterLevel string `url:"filter_level,omitempty"` + Language []string `url:"language,omitempty,comma"` + StallWarnings *bool `url:"stall_warnings,omitempty"` +}+
+StreamFirehoseParams are the parameters for StreamService.Firehose. +
+ + + + + + + + + + + + + + + + +type StreamLimit struct { + Track int64 `json:"track"` +}+
+StreamLimit indicates a stream matched more statuses than its rate limit +allowed. The track number is the number of undelivered matches. +https://dev.twitter.com/streaming/overview/messages-types#limit_notices +
+ + + + + + + + + + + + + + + + +type StreamSampleParams struct { + StallWarnings *bool `url:"stall_warnings,omitempty"` +}+
+StreamSampleParams are the parameters for StreamService.Sample. +
+ + + + + + + + + + + + + + + + +type StreamService struct {
+ // contains filtered or unexported fields
+}
+ +StreamService provides methods for accessing the Twitter Streaming API. +
+ + + + + + + + + + + + + + +func (srv *StreamService) Filter(params *StreamFilterParams) (*Stream, error)+
+Filter returns messages that match one or more filter predicates. +https://dev.twitter.com/streaming/reference/post/statuses/filter +
+ + + + + + +func (srv *StreamService) Firehose(params *StreamFirehoseParams) (*Stream, error)+
+Firehose returns all public messages and statuses. +Requires special permission to access. +https://dev.twitter.com/streaming/reference/get/statuses/firehose +
+ + + + + + +func (srv *StreamService) Sample(params *StreamSampleParams) (*Stream, error)+
+Sample returns a small sample of public stream messages. +https://dev.twitter.com/streaming/reference/get/statuses/sample +
+ + + + + + +func (srv *StreamService) Site(params *StreamSiteParams) (*Stream, error)+
+Site returns messages for a set of users. +Requires special permission to access. +https://dev.twitter.com/streaming/reference/get/site +
+ + + + + + +func (srv *StreamService) User(params *StreamUserParams) (*Stream, error)+
+User returns a stream of messages specific to the authenticated User. +https://dev.twitter.com/streaming/reference/get/user +
+ + + + + + + + +type StreamSiteParams struct { + FilterLevel string `url:"filter_level,omitempty"` + Follow []string `url:"follow,omitempty,comma"` + Language []string `url:"language,omitempty,comma"` + Replies string `url:"replies,omitempty"` + StallWarnings *bool `url:"stall_warnings,omitempty"` + With string `url:"with,omitempty"` +}+
+StreamSiteParams are the parameters for StreamService.Site. +
+ + + + + + + + + + + + + + + + +type StreamUserParams struct { + FilterLevel string `url:"filter_level,omitempty"` + Language []string `url:"language,omitempty,comma"` + Locations []string `url:"locations,omitempty,comma"` + Replies string `url:"replies,omitempty"` + StallWarnings *bool `url:"stall_warnings,omitempty"` + Track []string `url:"track,omitempty,comma"` + With string `url:"with,omitempty"` +}+
+StreamUserParams are the parameters for StreamService.User. +
+ + + + + + + + + + + + + + + + +type SwitchDemux struct { + All func(message interface{}) + Tweet func(tweet *Tweet) + DM func(dm *DirectMessage) + StatusDeletion func(deletion *StatusDeletion) + LocationDeletion func(LocationDeletion *LocationDeletion) + StreamLimit func(limit *StreamLimit) + StatusWithheld func(statusWithheld *StatusWithheld) + UserWithheld func(userWithheld *UserWithheld) + StreamDisconnect func(disconnect *StreamDisconnect) + Warning func(warning *StallWarning) + FriendsList func(friendsList *FriendsList) + Event func(event *Event) + Other func(message interface{}) +}+
+SwitchDemux receives messages and uses a type switch to send each typed +message to a handler function. +
+ + + + + + + + + + + + +func NewSwitchDemux() SwitchDemux+
+NewSwitchDemux returns a new SwitchMux which has NoOp handler functions. +
+ + + + + + + +func (d SwitchDemux) Handle(message interface{})+
+Handle determines the type of a message and calls the corresponding receiver +function with the typed message. All messages are passed to the All func. +Messages with unmatched types are passed to the Other func. +
+ + + + + + +func (d SwitchDemux) HandleChan(messages <-chan interface{})+
+HandleChan receives messages and calls the corresponding receiver function +with the typed message. All messages are passed to the All func. Messages +with unmatched type are passed to the Other func. +
+ + + + + + + + +type TimelineService struct {
+ // contains filtered or unexported fields
+}
+ +TimelineService provides methods for accessing Twitter status timeline +API endpoints. +
+ + + + + + + + + + + + + + +func (s *TimelineService) HomeTimeline(params *HomeTimelineParams) ([]Tweet, *http.Response, error)+
+HomeTimeline returns recent Tweets and retweets from the user and those +users they follow. +Requires a user auth context. +https://dev.twitter.com/rest/reference/get/statuses/home_timeline +
+ + + + + + +func (s *TimelineService) MentionTimeline(params *MentionTimelineParams) ([]Tweet, *http.Response, error)+
+MentionTimeline returns recent Tweet mentions of the authenticated user. +Requires a user auth context. +https://dev.twitter.com/rest/reference/get/statuses/mentions_timeline +
+ + + + + + +func (s *TimelineService) RetweetsOfMeTimeline(params *RetweetsOfMeTimelineParams) ([]Tweet, *http.Response, error)+
+RetweetsOfMeTimeline returns the most recent Tweets by the authenticated +user that have been retweeted by others. +Requires a user auth context. +https://dev.twitter.com/rest/reference/get/statuses/retweets_of_me +
+ + + + + + +func (s *TimelineService) UserTimeline(params *UserTimelineParams) ([]Tweet, *http.Response, error)+
+UserTimeline returns recent Tweets from the specified user. +https://dev.twitter.com/rest/reference/get/statuses/user_timeline +
+ + + + + + + + +type Tweet struct { + Contributors []Contributor `json:"contributors"` + Coordinates *Coordinates `json:"coordinates"` + CreatedAt string `json:"created_at"` + CurrentUserRetweet *TweetIdentifier `json:"current_user_retweet"` + Entities *Entities `json:"entities"` + FavoriteCount int `json:"favorite_count"` + Favorited bool `json:"favorited"` + FilterLevel string `json:"filter_level"` + ID int64 `json:"id"` + IDStr string `json:"id_str"` + InReplyToScreenName string `json:"in_reply_to_screen_name"` + InReplyToStatusID int64 `json:"in_reply_to_status_id"` + InReplyToStatusIDStr string `json:"in_reply_to_status_id_str"` + InReplyToUserID int64 `json:"in_reply_to_user_id"` + InReplyToUserIDStr string `json:"in_reply_to_user_id_str"` + Lang string `json:"lang"` + PossiblySensitive bool `json:"possibly_sensitive"` + RetweetCount int `json:"retweet_count"` + Retweeted bool `json:"retweeted"` + RetweetedStatus *Tweet `json:"retweeted_status"` + Source string `json:"source"` + Scopes map[string]interface{} `json:"scopes"` + Text string `json:"text"` + Place *Place `json:"place"` + Truncated bool `json:"truncated"` + User *User `json:"user"` + WithheldCopyright bool `json:"withheld_copyright"` + WithheldInCountries []string `json:"withheld_in_countries"` + WithheldScope string `json:"withheld_scope"` + ExtendedEntities *ExtendedEntity `json:"extended_entities"` + QuotedStatusID int64 `json:"quoted_status_id"` + QuotedStatusIDStr string `json:"quoted_status_id_str"` + QuotedStatus *Tweet `json:"quoted_status"` +}+
+Tweet represents a Twitter Tweet, previously called a status. +https://dev.twitter.com/overview/api/tweets +Unused or deprecated fields not provided: Geo, Annotations +
+ + + + + + + + + + + + + + + + +type TweetIdentifier struct { + ID int64 `json:"id"` + IDStr string `json:"id_str"` +}+
+TweetIdentifier represents the id by which a Tweet can be identified. +
+ + + + + + + + + + + + + + + + +type URLEntity struct { + Indices Indices `json:"indices"` + DisplayURL string `json:"display_url"` + ExpandedURL string `json:"expanded_url"` + URL string `json:"url"` +}+
+URLEntity represents a URL which has been parsed from text. +
+ + + + + + + + + + + + + + + + +type User struct { + ContributorsEnabled bool `json:"contributors_enabled"` + CreatedAt string `json:"created_at"` + DefaultProfile bool `json:"default_profile"` + DefaultProfileImage bool `json:"default_profile_image"` + Description string `json:"description"` + Email string `json:"email"` + Entities *UserEntities `json:"entities"` + FavouritesCount int `json:"favourites_count"` + FollowRequestSent bool `json:"follow_request_sent"` + Following bool `json:"following"` + FollowersCount int `json:"followers_count"` + FriendsCount int `json:"friends_count"` + GeoEnabled bool `json:"geo_enabled"` + ID int64 `json:"id"` + IDStr string `json:"id_str"` + IsTranslator bool `json:"id_translator"` + Lang string `json:"lang"` + ListedCount int `json:"listed_count"` + Location string `json:"location"` + Name string `json:"name"` + Notifications bool `json:"notifications"` + ProfileBackgroundColor string `json:"profile_background_color"` + ProfileBackgroundImageURL string `json:"profile_background_image_url"` + ProfileBackgroundImageURLHttps string `json:"profile_background_image_url_https"` + ProfileBackgroundTile bool `json:"profile_background_tile"` + ProfileBannerURL string `json:"profile_banner_url"` + ProfileImageURL string `json:"profile_image_url"` + ProfileImageURLHttps string `json:"profile_image_url_https"` + ProfileLinkColor string `json:"profile_link_color"` + ProfileSidebarBorderColor string `json:"profile_sidebar_border_color"` + ProfileSidebarFillColor string `json:"profile_sidebar_fill_color"` + ProfileTextColor string `json:"profile_text_color"` + ProfileUseBackgroundImage bool `json:"profile_use_background_image"` + Protected bool `json:"protected"` + ScreenName string `json:"screen_name"` + ShowAllInlineMedia bool `json:"show_all_inline_media"` + Status *Tweet `json:"status"` + StatusesCount int `json:"statuses_count"` + Timezone string `json:"time_zone"` + URL string `json:"url"` + UtcOffset int `json:"utc_offset"` + Verified bool `json:"verified"` + WithheldInCountries string `json:"withheld_in_countries"` + WithholdScope string `json:"withheld_scope"` +}+
+User represents a Twitter User. +https://dev.twitter.com/overview/api/users +
+ + + + + + + + + + + + + + + + +type UserEntities struct { + URL Entities `json:"url"` + Description Entities `json:"description"` +}+
+UserEntities contain Entities parsed from User url and description fields. +https://dev.twitter.com/overview/api/entities-in-twitter-objects#users +
+ + + + + + + + + + + + + + + + +type UserLookupParams struct { + UserID []int64 `url:"user_id,omitempty,comma"` + ScreenName []string `url:"screen_name,omitempty,comma"` + IncludeEntities *bool `url:"include_entities,omitempty"` // whether 'status' should include entities +}+
+UserLookupParams are the parameters for UserService.Lookup. +
+ + + + + + + + + + + + + + + + +type UserSearchParams struct { + Query string `url:"q,omitempty"` + Page int `url:"page,omitempty"` // 1-based page number + Count int `url:"count,omitempty"` + IncludeEntities *bool `url:"include_entities,omitempty"` // whether 'status' should include entities +}+
+UserSearchParams are the parameters for UserService.Search. +
+ + + + + + + + + + + + + + + + +type UserService struct {
+ // contains filtered or unexported fields
+}
+ +UserService provides methods for accessing Twitter user API endpoints. +
+ + + + + + + + + + + + + + +func (s *UserService) Lookup(params *UserLookupParams) ([]User, *http.Response, error)+
+Lookup returns the requested Users as a slice. +https://dev.twitter.com/rest/reference/get/users/lookup +
+ + + + + + +func (s *UserService) Search(query string, params *UserSearchParams) ([]User, *http.Response, error)+
+Search queries public user accounts. +Requires a user auth context. +https://dev.twitter.com/rest/reference/get/users/search +
+ + + + + + +func (s *UserService) Show(params *UserShowParams) (*User, *http.Response, error)+
+Show returns the requested User. +https://dev.twitter.com/rest/reference/get/users/show +
+ + + + + + + + +type UserShowParams struct { + UserID int64 `url:"user_id,omitempty"` + ScreenName string `url:"screen_name,omitempty"` + IncludeEntities *bool `url:"include_entities,omitempty"` // whether 'status' should include entities +}+
+UserShowParams are the parameters for UserService.Show. +
+ + + + + + + + + + + + + + + + +type UserTimelineParams struct { + UserID int64 `url:"user_id,omitempty"` + ScreenName string `url:"screen_name,omitempty"` + Count int `url:"count,omitempty"` + SinceID int64 `url:"since_id,omitempty"` + MaxID int64 `url:"max_id,omitempty"` + TrimUser *bool `url:"trim_user,omitempty"` + ExcludeReplies *bool `url:"exclude_replies,omitempty"` + ContributorDetails *bool `url:"contributor_details,omitempty"` + IncludeRetweets *bool `url:"include_rts,omitempty"` +}+
+UserTimelineParams are the parameters for TimelineService.UserTimeline. +
+ + + + + + + + + + + + + + + + +type UserWithheld struct { + ID int64 `json:"id"` + WithheldInCountries []string `json:"withheld_in_countries"` +}+
+UserWithheld indicates a User with the given ID has been withheld in +certain countries. +https://dev.twitter.com/streaming/overview/messages-types#withheld_content_notices +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ go-twitter + | ++ + | +
+ twitter + | ++ Package twitter provides a Client for the Twitter API. + | +
+ oauth1 + | ++ Package oauth1 is a Go implementation of the OAuth1 spec RFC 5849. + | +
+ dropbox + | ++ Package dropbox provides constants for using OAuth1 to access Dropbox. + | +
+ examples + | ++ + | +
+ tumblr + | ++ Package tumblr provides constants for using OAuth 1 to access Tumblr. + | +
+ twitter + | ++ Package twitter provides constants for using OAuth1 to access Twitter. + | +
+ sling + | ++ Package sling is a Go HTTP client library for creating and sending API requests. + | +
+ examples + | ++ + | +
var Endpoint = oauth1.Endpoint{ + RequestTokenURL: "https://api.dropbox.com/1/oauth/request_token", + AuthorizeURL: "https://api.dropbox.com/1/oauth/authorize", + AccessTokenURL: "https://api.dropbox.com/1/oauth/access_token", +}+
+Endpoint is Dropbox's OAuth 1 endpoint. +
+ + + + + + + + + + + + + + + + + +var HTTPClient contextKey
+ +HTTPClient is the context key to associate an *http.Client value with +a context. +
+ + +var NoContext = context.TODO()+
+NoContext is the default context to use in most cases. +
+ + + + + + +func NewClient(ctx context.Context, config *Config, token *Token) *http.Client+
+NewClient returns a new http Client which signs requests via OAuth1. +
+ + + + + + + +func ParseAuthorizationCallback(req *http.Request) (requestToken, verifier string, err error)+
+ParseAuthorizationCallback parses an OAuth1 authorization callback request +from a provider server. The oauth_token and oauth_verifier parameters are +parsed to return the request token from earlier in the flow and the +verifier string. +See RFC 5849 2.2 Resource Owner Authorization. +
+ + + + + + + +func PercentEncode(input string) string+
+PercentEncode percent encodes a string according to RFC 3986 2.1. +
+ + + + + + + + +type Config struct { + // Consumer Key (Client Identifier) + ConsumerKey string + // Consumer Secret (Client Shared-Secret) + ConsumerSecret string + // Callback URL + CallbackURL string + // Provider Endpoint specifying OAuth1 endpoint URLs + Endpoint Endpoint + // OAuth1 Signer (defaults to HMAC-SHA1) + Signer Signer +}+
+Config represents an OAuth1 consumer's (client's) key and secret, the +callback URL, and the provider Endpoint to which the consumer corresponds. +
+ + + + + + + + + + + + +func NewConfig(consumerKey, consumerSecret string) *Config+
+NewConfig returns a new Config with the given consumer key and secret. +
+ + + + + + + +func (c *Config) AccessToken(requestToken, requestSecret, verifier string) (accessToken, accessSecret string, err error)+
+AccessToken obtains an access token (token credential) by POSTing a +request (with oauth_token and oauth_verifier in the auth header) to the +Endpoint AccessTokenURL. Returns the access token and secret (token +credentials). +See RFC 5849 2.3 Token Credentials. +
+ + + + + + +func (c *Config) AuthorizationURL(requestToken string) (*url.URL, error)+
+AuthorizationURL accepts a request token and returns the *url.URL to the +Endpoint's authorization page that asks the user (resource owner) for to +authorize the consumer to act on his/her/its behalf. +See RFC 5849 2.2 Resource Owner Authorization. +
+ + + + + + +func (c *Config) Client(ctx context.Context, t *Token) *http.Client+
+Client returns an HTTP client which uses the provided ctx and access Token. +
+ + + + + + +func (c *Config) RequestToken() (requestToken, requestSecret string, err error)+
+RequestToken obtains a Request token and secret (temporary credential) by +POSTing a request (with oauth_callback in the auth header) to the Endpoint +RequestTokenURL. The response body form is validated to ensure +oauth_callback_confirmed is true. Returns the request token and secret +(temporary credentials). +See RFC 5849 2.1 Temporary Credentials. +
+ + + + + + + + +type Endpoint struct { + // Request URL (Temporary Credential Request URI) + RequestTokenURL string + // Authorize URL (Resource Owner Authorization URI) + AuthorizeURL string + // Access Token URL (Token Request URI) + AccessTokenURL string +}+
+Endpoint represents an OAuth1 provider's (server's) request token, +owner authorization, and access token request URLs. +
+ + + + + + + + + + + + + + + + +type HMACSigner struct { + ConsumerSecret string +}+
+HMACSigner signs messages with an HMAC SHA1 digest, using the concatenated +consumer secret and token secret as the key. +
+ + + + + + + + + + + + + + +func (s *HMACSigner) Name() string+
+Name returns the HMAC-SHA1 method. +
+ + + + + + +func (s *HMACSigner) Sign(tokenSecret, message string) (string, error)+
+Sign creates a concatenated consumer and token secret key and calculates +the HMAC digest of the message. Returns the base64 encoded digest bytes. +
+ + + + + + + + +type RSASigner struct { + PrivateKey *rsa.PrivateKey +}+
+RSASigner RSA PKCS1-v1_5 signs SHA1 digests of messages using the given +RSA private key. +
+ + + + + + + + + + + + + + +func (s *RSASigner) Name() string+
+Name returns the RSA-SHA1 method. +
+ + + + + + +func (s *RSASigner) Sign(tokenSecret, message string) (string, error)+
+Sign uses RSA PKCS1-v1_5 to sign a SHA1 digest of the given message. The +tokenSecret is not used with this signing scheme. +
+ + + + + + + + +type Signer interface { + // Name returns the name of the signing method. + Name() string + // Sign signs the message using the given secret key. + Sign(key string, message string) (string, error) +}+
+A Signer signs messages to create signed OAuth1 Requests. +
+ + + + + + + + + + + + + + + + +type Token struct { + Token string + TokenSecret string +}+
+Token is an AccessToken (token credential) which allows a consumer (client) +to access resources from an OAuth1 provider server. +
+ + + + + + + + + + + + +func NewToken(token, tokenSecret string) *Token+
+NewToken returns a new Token with the given token and token secret. +
+ + + + + + + + + +type TokenSource interface { + Token() (*Token, error) +}+
+A TokenSource can return a Token. +
+ + + + + + + + + + + + +func StaticTokenSource(token *Token) TokenSource+
+StaticTokenSource returns a TokenSource which always returns the same Token. +This is appropriate for tokens which do not have a time expiration. +
+ + + + + + + + + +type Transport struct { + // Base is the base RoundTripper used to make HTTP requests. If nil, then + // http.DefaultTransport is used + Base http.RoundTripper + // contains filtered or unexported fields +}+
+Transport is an http.RoundTripper which makes OAuth1 HTTP requests. It +wraps a base RoundTripper and adds an Authorization header using the +token from a TokenSource. +
++Transport is a low-level component, most users should use Config to create +an http.Client instead. +
+ + + + + + + + + + + + + + +func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)+
+RoundTrip authorizes the request with a signed OAuth1 Authorization header +using the auther and TokenSource. +
+ + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ dropbox + | ++ Package dropbox provides constants for using OAuth1 to access Dropbox. + | +
+ examples + | ++ + | +
+ tumblr + | ++ Package tumblr provides constants for using OAuth 1 to access Tumblr. + | +
+ twitter + | ++ Package twitter provides constants for using OAuth1 to access Twitter. + | +
var Endpoint = oauth1.Endpoint{ + RequestTokenURL: "http://www.tumblr.com/oauth/request_token", + AuthorizeURL: "http://www.tumblr.com/oauth/authorize", + AccessTokenURL: "http://www.tumblr.com/oauth/access_token", +}+
+Endpoint is Tumblr's OAuth 1a endpoint. +
+ + + + + + + + + + + + + + + + + +var AuthenticateEndpoint = oauth1.Endpoint{ + RequestTokenURL: "https://api.twitter.com/oauth/request_token", + AuthorizeURL: "https://api.twitter.com/oauth/authenticate", + AccessTokenURL: "https://api.twitter.com/oauth/access_token", +}+
+AuthenticateEndpoint is Twitter's OAuth 1 endpoint which uses the +oauth/authenticate AuthorizeURL redirect. Logged in users who have granted +access are immediately authenticated and redirected to the callback URL. +
+ + +var AuthorizeEndpoint = oauth1.Endpoint{ + RequestTokenURL: "https://api.twitter.com/oauth/request_token", + AuthorizeURL: "https://api.twitter.com/oauth/authorize", + AccessTokenURL: "https://api.twitter.com/oauth/access_token", +}+
+AuthorizeEndpoint is Twitter's OAuth 1 endpoint which uses the +oauth/authorize AuthorizeURL redirect. Note that this requires users who +have granted access previously, to re-grant access at AuthorizeURL. +Prefer AuthenticateEndpoint over AuthorizeEndpoint if you are unsure. +
+ + + + + + + + + + + + + + + + + +type Doer interface { + Do(req *http.Request) (*http.Response, error) +}+
+Doer executes http requests. It is implemented by *http.Client. You can +wrap *http.Client with layers of Doers to form a stack of client-side +middleware. +
+ + + + + + + + + + + + + + + + +type Sling struct {
+ // contains filtered or unexported fields
+}
+ +Sling is an HTTP Request builder and sender. +
+ + + + + + + + + + + + +func New() *Sling+
+New returns a new Sling with an http DefaultClient. +
+ + + + + + + +func (s *Sling) Add(key, value string) *Sling+
+Add adds the key, value pair in Headers, appending values for existing keys +to the key's values. Header keys are canonicalized. +
+ + + + + + +func (s *Sling) Base(rawURL string) *Sling+
+Base sets the rawURL. If you intend to extend the url with Path, +baseUrl should be specified with a trailing slash. +
+ + + + + + +func (s *Sling) Body(body io.Reader) *Sling+
+Body sets the Sling's body. The body value will be set as the Body on new +requests (see Request()). +If the provided body is also an io.Closer, the request Body will be closed +by http.Client methods. +
+ + + + + + +func (s *Sling) BodyForm(bodyForm interface{}) *Sling+
+BodyForm sets the Sling's bodyForm. The value pointed to by the bodyForm +will be url encoded as the Body on new requests (see Request()). +The bodyStruct argument should be a pointer to a url tagged struct. See +https://godoc.org/github.com/google/go-querystring/query for details. +
+ + + + + + +func (s *Sling) BodyJSON(bodyJSON interface{}) *Sling+
+BodyJSON sets the Sling's bodyJSON. The value pointed to by the bodyJSON +will be JSON encoded as the Body on new requests (see Request()). +The bodyJSON argument should be a pointer to a JSON tagged struct. See +https://golang.org/pkg/encoding/json/#MarshalIndent for details. +
+ + + + + + +func (s *Sling) Client(httpClient *http.Client) *Sling+
+Client sets the http Client used to do requests. If a nil client is given, +the http.DefaultClient will be used. +
+ + + + + + +func (s *Sling) Delete(pathURL string) *Sling+
+Delete sets the Sling method to DELETE and sets the given pathURL. +
+ + + + + + +func (s *Sling) Do(req *http.Request, successV, failureV interface{}) (*http.Response, error)+
+Do sends an HTTP request and returns the response. Success responses (2XX) +are JSON decoded into the value pointed to by successV and other responses +are JSON decoded into the value pointed to by failureV. +Any error sending the request or decoding the response is returned. +
+ + + + + + +func (s *Sling) Doer(doer Doer) *Sling+
+Doer sets the custom Doer implementation used to do requests. +If a nil client is given, the http.DefaultClient will be used. +
+ + + + + + +func (s *Sling) Get(pathURL string) *Sling+
+Get sets the Sling method to GET and sets the given pathURL. +
+ + + + + + +func (s *Sling) Head(pathURL string) *Sling+
+Head sets the Sling method to HEAD and sets the given pathURL. +
+ + + + + + +func (s *Sling) New() *Sling+
+New returns a copy of a Sling for creating a new Sling with properties +from a parent Sling. For example, +
+parentSling := sling.New().Client(client).Base("https://api.io/") +fooSling := parentSling.New().Get("foo/") +barSling := parentSling.New().Get("bar/") ++
+fooSling and barSling will both use the same client, but send requests to +https://api.io/foo/ and https://api.io/bar/ respectively. +
++Note that query and body values are copied so if pointer values are used, +mutating the original value will mutate the value within the child Sling. +
+ + + + + + +func (s *Sling) Patch(pathURL string) *Sling+
+Patch sets the Sling method to PATCH and sets the given pathURL. +
+ + + + + + +func (s *Sling) Path(path string) *Sling+
+Path extends the rawURL with the given path by resolving the reference to +an absolute URL. If parsing errors occur, the rawURL is left unmodified. +
+ + + + + + +func (s *Sling) Post(pathURL string) *Sling+
+Post sets the Sling method to POST and sets the given pathURL. +
+ + + + + + +func (s *Sling) Put(pathURL string) *Sling+
+Put sets the Sling method to PUT and sets the given pathURL. +
+ + + + + + +func (s *Sling) QueryStruct(queryStruct interface{}) *Sling+
+QueryStruct appends the queryStruct to the Sling's queryStructs. The value +pointed to by each queryStruct will be encoded as url query parameters on +new requests (see Request()). +The queryStruct argument should be a pointer to a url tagged struct. See +https://godoc.org/github.com/google/go-querystring/query for details. +
+ + + + + + +func (s *Sling) Receive(successV, failureV interface{}) (*http.Response, error)+
+Receive creates a new HTTP request and returns the response. Success +responses (2XX) are JSON decoded into the value pointed to by successV and +other responses are JSON decoded into the value pointed to by failureV. +Any error creating the request, sending it, or decoding the response is +returned. +Receive is shorthand for calling Request and Do. +
+ + + + + + +func (s *Sling) ReceiveSuccess(successV interface{}) (*http.Response, error)+
+ReceiveSuccess creates a new HTTP request and returns the response. Success +responses (2XX) are JSON decoded into the value pointed to by successV. +Any error creating the request, sending it, or decoding a 2XX response +is returned. +
+ + + + + + +func (s *Sling) Request() (*http.Request, error)+
+Request returns a new http.Request created with the Sling properties. +Returns any errors parsing the rawURL, encoding query structs, encoding +the body, or creating the http.Request. +
+ + + + + + +func (s *Sling) Set(key, value string) *Sling+
+Set sets the key, value pair in Headers, replacing existing values +associated with key. Header keys are canonicalized. +
+ + + + + + +func (s *Sling) SetBasicAuth(username, password string) *Sling+
+SetBasicAuth sets the 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. +
+ + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ lrucache + | ++ Package lrucache provides a byte-size-limited implementation of httpcache.Cache that stores data in memory. + | +
+ twotier + | ++ Package twotier provides a wrapper for two httpcache.Cache instances, allowing you to use both a small and fast cache for popular objects and fall back to a larger and slower cache for less popular ones. + | +
type LruCache struct { + MaxSize int64 + MaxAge int64 + // contains filtered or unexported fields +}+
+LruCache is a thread-safe, in-memory httpcache.Cache that evicts the +least recently used entries from memory when either MaxSize (in bytes) +limit would be exceeded or (if set) the entries are older than MaxAge (in +seconds). Use the New constructor to create one. +
+ + + + + + + + + + + + +func New(maxSize int64, maxAge int64) *LruCache+
+New creates an LruCache that will restrict itself to maxSize bytes of +memory. If maxAge > 0, entries will also be expired after maxAge +seconds. +
+ + + + + + + +func (c *LruCache) Delete(key string)+
+Delete removes the value associated with a key. +
+ + + + + + +func (c *LruCache) Get(key string) ([]byte, bool)+
+Get returns the []byte representation of a cached response and a bool +set to true if the key was found. +
+ + + + + + +func (c *LruCache) Set(key string, value []byte)+
+Set stores the []byte representation of a response for a given key. +
+ + + + + + +func (c *LruCache) Size() int64+
+Size returns the estimated current memory usage of LruCache. +
+ + + + + + + + + + + + + + + + +type TwoTier struct {
+ // contains filtered or unexported fields
+}
+ +TwoTier creates a two-tiered cache out of two httpcache.Cache instances. +Reads are favored from first, and writes affect both first and second. +
+ + + + + + + + + + + + +func New(first httpcache.Cache, second httpcache.Cache) *TwoTier+
+New creates a TwoTier. Both first and second must be non-nil. +
+ + + + + + + +func (c *TwoTier) Delete(key string)+
+Delete removes the value associated with a key from both the first and +second tier caches. +
+ + + + + + +func (c *TwoTier) Get(key string) ([]byte, bool)+
+Get returns the []byte representation of a cached response and a bool set +to true if the key was found. It tries the first tier cache, and if +that's not successful, copies the result from the second tier into the +first tier. +
+ + + + + + +func (c *TwoTier) Set(key string, value []byte)+
+Set stores the []byte representation of a response for a given key into +the second tier cache, and deletes the cache entry from the first tier +cache. +
+ + + + + + + + + + + + + + + + + + +▹ Example (Zpop)
+var ErrNil = errors.New("redigo: nil returned")+
+ErrNil indicates that a reply value is nil. +
+ + +var ErrPoolExhausted = errors.New("redigo: connection pool exhausted")+
+ErrPoolExhausted is returned from a pool connection method (Do, Send, +Receive, Flush, Err) when the maximum number of database connections in the +pool has been reached. +
+ + + + + + +func Bool(reply interface{}, err error) (bool, error)+
+Bool is a helper that converts a command reply to a boolean. If err is not +equal to nil, then Bool returns false, err. Otherwise Bool converts the +reply to boolean as follows: +
+Reply type Result +integer value != 0, nil +bulk string strconv.ParseBool(reply) +nil false, ErrNil +other false, error ++ +
▹ Example
+func ByteSlices(reply interface{}, err error) ([][]byte, error)+
+ByteSlices is a helper that converts an array command reply to a [][]byte. +If err is not equal to nil, then ByteSlices returns nil, err. Nil array +items are stay nil. ByteSlices returns an error if an array item is not a +bulk string or nil. +
+ + + + + + + +func Bytes(reply interface{}, err error) ([]byte, error)+
+Bytes is a helper that converts a command reply to a slice of bytes. If err +is not equal to nil, then Bytes returns nil, err. Otherwise Bytes converts +the reply to a slice of bytes as follows: +
+Reply type Result +bulk string reply, nil +simple string []byte(reply), nil +nil nil, ErrNil +other nil, error ++ + + + + + + +
func Float64(reply interface{}, err error) (float64, error)+
+Float64 is a helper that converts a command reply to 64 bit float. If err is +not equal to nil, then Float64 returns 0, err. Otherwise, Float64 converts +the reply to an int as follows: +
+Reply type Result +bulk string parsed reply, nil +nil 0, ErrNil +other 0, error ++ + + + + + + +
func Int(reply interface{}, err error) (int, error)+
+Int is a helper that converts a command reply to an integer. If err is not +equal to nil, then Int returns 0, err. Otherwise, Int converts the +reply to an int as follows: +
+Reply type Result +integer int(reply), nil +bulk string parsed reply, nil +nil 0, ErrNil +other 0, error ++ +
▹ Example
+func Int64(reply interface{}, err error) (int64, error)+
+Int64 is a helper that converts a command reply to 64 bit integer. If err is +not equal to nil, then Int returns 0, err. Otherwise, Int64 converts the +reply to an int64 as follows: +
+Reply type Result +integer reply, nil +bulk string parsed reply, nil +nil 0, ErrNil +other 0, error ++ + + + + + + +
func Int64Map(result interface{}, err error) (map[string]int64, error)+
+Int64Map is a helper that converts an array of strings (alternating key, value) +into a map[string]int64. The HGETALL commands return replies in this format. +Requires an even number of values in result. +
+ + + + + + + +func IntMap(result interface{}, err error) (map[string]int, error)+
+IntMap is a helper that converts an array of strings (alternating key, value) +into a map[string]int. The HGETALL commands return replies in this format. +Requires an even number of values in result. +
+ + + + + + + +func Ints(reply interface{}, err error) ([]int, error)+
+Ints is a helper that converts an array command reply to a []int. If +err is not equal to nil, then Ints returns nil, err. +
+ +▹ Example
+func MultiBulk(reply interface{}, err error) ([]interface{}, error)+
+MultiBulk is a helper that converts an array command reply to a []interface{}. +
++Deprecated: Use Values instead. +
+ + + + + + + +func Scan(src []interface{}, dest ...interface{}) ([]interface{}, error)+
+Scan copies from src to the values pointed at by dest. +
++The values pointed at by dest must be an integer, float, boolean, string, +[]byte, interface{} or slices of these types. Scan uses the standard strconv +package to convert bulk strings to numeric and boolean types. +
++If a dest value is nil, then the corresponding src value is skipped. +
++If a src element is nil, then the corresponding dest value is not modified. +
++To enable easy use of Scan in a loop, Scan returns the slice of src +following the copied values. +
+ +▹ Example
+func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string) error+
+ScanSlice scans src to the slice pointed to by dest. The elements the dest +slice must be integer, float, boolean, string, struct or pointer to struct +values. +
++Struct fields must be integer, float, boolean or string values. All struct +fields are used unless a subset is specified using fieldNames. +
+ +▹ Example
+func ScanStruct(src []interface{}, dest interface{}) error+
+ScanStruct scans alternating names and values from src to a struct. The +HGETALL and CONFIG GET commands return replies in this format. +
++ScanStruct uses exported field names to match values in the response. Use +'redis' field tag to override the name: +
+Field int `redis:"myName"` ++
+Fields with the tag redis:"-" are ignored. +
++Integer, float, boolean, string and []byte fields are supported. Scan uses the +standard strconv package to convert bulk string values to numeric and +boolean types. +
++If a src element is nil, then the corresponding field is not modified. +
+ + + + + + + +func String(reply interface{}, err error) (string, error)+
+String is a helper that converts a command reply to a string. If err is not +equal to nil, then String returns "", err. Otherwise String converts the +reply to a string as follows: +
+Reply type Result +bulk string string(reply), nil +simple string reply, nil +nil "", ErrNil +other "", error ++ +
▹ Example
+func StringMap(result interface{}, err error) (map[string]string, error)+
+StringMap is a helper that converts an array of strings (alternating key, value) +into a map[string]string. The HGETALL and CONFIG GET commands return replies in this format. +Requires an even number of values in result. +
+ + + + + + + +func Strings(reply interface{}, err error) ([]string, error)+
+Strings is a helper that converts an array command reply to a []string. If +err is not equal to nil, then Strings returns nil, err. Nil array items are +converted to "" in the output slice. Strings returns an error if an array +item is not a bulk string or nil. +
+ + + + + + + +func Uint64(reply interface{}, err error) (uint64, error)+
+Uint64 is a helper that converts a command reply to 64 bit integer. If err is +not equal to nil, then Int returns 0, err. Otherwise, Int64 converts the +reply to an int64 as follows: +
+Reply type Result +integer reply, nil +bulk string parsed reply, nil +nil 0, ErrNil +other 0, error ++ + + + + + + +
func Values(reply interface{}, err error) ([]interface{}, error)+
+Values is a helper that converts an array command reply to a []interface{}. +If err is not equal to nil, then Values returns nil, err. Otherwise, Values +converts the reply as follows: +
+Reply type Result +array reply, nil +nil nil, ErrNil +other nil, error ++ + + + + + + + +
type Args []interface{}+
+Args is a helper for constructing command arguments from structured values. +
+ + + + + + +▹ Example
+func (args Args) Add(value ...interface{}) Args+
+Add returns the result of appending value to args. +
+ + + + + + +func (args Args) AddFlat(v interface{}) Args+
+AddFlat returns the result of appending the flattened value of v to args. +
++Maps are flattened by appending the alternating keys and map values to args. +
++Slices are flattened by appending the slice elements to args. +
++Structs are flattened by appending the alternating names and values of +exported fields to args. If v is a nil struct pointer, then nothing is +appended. The 'redis' field tag overrides struct field names. See ScanStruct +for more information on the use of the 'redis' field tag. +
++Other types are appended to args as is. +
+ + + + + + + + +type Conn interface { + // Close closes the connection. + Close() error + + // Err returns a non-nil value if the connection is broken. The returned + // value is either the first non-nil value returned from the underlying + // network connection or a protocol parsing error. Applications should + // close broken connections. + Err() error + + // Do sends a command to the server and returns the received reply. + Do(commandName string, args ...interface{}) (reply interface{}, err error) + + // Send writes the command to the client's output buffer. + Send(commandName string, args ...interface{}) error + + // Flush flushes the output buffer to the Redis server. + Flush() error + + // Receive receives a single reply from the Redis server + Receive() (reply interface{}, err error) +}+
+Conn represents a connection to a Redis server. +
+ + + + + + + + + + + + +func Dial(network, address string, options ...DialOption) (Conn, error)+
+Dial connects to the Redis server at the given network and +address using the specified options. +
+ +▹ Example
+func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error)+
+DialTimeout acts like Dial but takes timeouts for establishing the +connection to the server, writing a command and reading a reply. +
++Deprecated: Use Dial with options instead. +
+ + + + + +func DialURL(rawurl string, options ...DialOption) (Conn, error)+
+DialURL connects to a Redis server at the given URL using the Redis +URI scheme. URLs should follow the draft IANA specification for the +scheme (https://www.iana.org/assignments/uri-schemes/prov/redis). +
+ +▹ Example
+func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn+
+NewConn returns a new Redigo connection for the given net connection. +
+ + + + + +func NewLoggingConn(conn Conn, logger *log.Logger, prefix string) Conn+
+NewLoggingConn returns a logging wrapper around a connection. +
+ + + + + + + + + +type DialOption struct {
+ // contains filtered or unexported fields
+}
+ +DialOption specifies an option for dialing a Redis server. +
+ + + + + + + + + + + + +func DialConnectTimeout(d time.Duration) DialOption+
+DialConnectTimeout specifies the timeout for connecting to the Redis server. +
+ + + + + +func DialDatabase(db int) DialOption+
+DialDatabase specifies the database to select when dialing a connection. +
+ + + + + +func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption+
+DialNetDial specifies a custom dial function for creating TCP +connections. If this option is left out, then net.Dial is +used. DialNetDial overrides DialConnectTimeout. +
+ + + + + +func DialPassword(password string) DialOption+
+DialPassword specifies the password to use when connecting to +the Redis server. +
+ + + + + +func DialReadTimeout(d time.Duration) DialOption+
+DialReadTimeout specifies the timeout for reading a single command reply. +
+ + + + + +func DialWriteTimeout(d time.Duration) DialOption+
+DialWriteTimeout specifies the timeout for writing a single command. +
+ + + + + + + + + +type Error string+
+Error represents an error returned in a command reply. +
+ + + + + + + + + + + + + + +func (err Error) Error() string+ + + + + + + + +
type Message struct { + + // The originating channel. + Channel string + + // The message data. + Data []byte +}+
+Message represents a message notification. +
+ + + + + + + + + + + + + + + + +type PMessage struct { + + // The matched pattern. + Pattern string + + // The originating channel. + Channel string + + // The message data. + Data []byte +}+
+PMessage represents a pmessage notification. +
+ + + + + + + + + + + + + + + + +type Pong struct { + Data string +}+
+Pong represents a pubsub pong notification. +
+ + + + + + + + + + + + + + + + +type Pool struct { + + // Dial is an application supplied function for creating and configuring a + // connection. + // + // The connection returned from Dial must not be in a special state + // (subscribed to pubsub channel, transaction started, ...). + Dial func() (Conn, error) + + // TestOnBorrow is an optional application supplied function for checking + // the health of an idle connection before the connection is used again by + // the application. Argument t is the time that the connection was returned + // to the pool. If the function returns an error, then the connection is + // closed. + TestOnBorrow func(c Conn, t time.Time) error + + // Maximum number of idle connections in the pool. + MaxIdle int + + // Maximum number of connections allocated by the pool at a given time. + // When zero, there is no limit on the number of connections in the pool. + MaxActive int + + // Close connections after remaining idle for this duration. If the value + // is zero, then idle connections are not closed. Applications should set + // the timeout to a value less than the server's timeout. + IdleTimeout time.Duration + + // If Wait is true and the pool is at the MaxActive limit, then Get() waits + // for a connection to be returned to the pool before returning. + Wait bool + // contains filtered or unexported fields +}+
+Pool maintains a pool of connections. The application calls the Get method +to get a connection from the pool and the connection's Close method to +return the connection's resources to the pool. +
++The following example shows how to use a pool in a web application. The +application creates a pool at application startup and makes it available to +request handlers using a global variable. The pool configuration used here +is an example, not a recommendation. +
+func newPool(server, password string) *redis.Pool { + return &redis.Pool{ + MaxIdle: 3, + IdleTimeout: 240 * time.Second, + Dial: func () (redis.Conn, error) { + c, err := redis.Dial("tcp", server) + if err != nil { + return nil, err + } + if _, err := c.Do("AUTH", password); err != nil { + c.Close() + return nil, err + } + return c, err + }, + TestOnBorrow: func(c redis.Conn, t time.Time) error { + if time.Since(t) < time.Minute { + return nil + } + _, err := c.Do("PING") + return err + }, + } +} + +var ( + pool *redis.Pool + redisServer = flag.String("redisServer", ":6379", "") + redisPassword = flag.String("redisPassword", "", "") +) + +func main() { + flag.Parse() + pool = newPool(*redisServer, *redisPassword) + ... +} ++
+A request handler gets a connection from the pool and closes the connection +when the handler is done: +
+func serveHome(w http.ResponseWriter, r *http.Request) { + conn := pool.Get() + defer conn.Close() + .... +} ++ + + + + + + + + + + + +
func NewPool(newFn func() (Conn, error), maxIdle int) *Pool+
+NewPool creates a new pool. +
++Deprecated: Initialize the Pool directory as shown in the example. +
+ + + + + + + +func (p *Pool) ActiveCount() int+
+ActiveCount returns the number of active connections in the pool. +
+ + + + + + +func (p *Pool) Close() error+
+Close releases the resources used by the pool. +
+ + + + + + +func (p *Pool) Get() Conn+
+Get gets a connection. The application must close the returned connection. +This method always returns a valid connection so that applications can defer +error handling to the first use of the connection. If there is an error +getting an underlying connection, then the connection Err, Do, Send, Flush +and Receive methods return that error. +
+ + + + + + + + +type PubSubConn struct { + Conn Conn +}+
+PubSubConn wraps a Conn with convenience methods for subscribers. +
+ + + + + + +▹ Example
+func (c PubSubConn) Close() error+
+Close closes the connection. +
+ + + + + + +func (c PubSubConn) PSubscribe(channel ...interface{}) error+
+PSubscribe subscribes the connection to the given patterns. +
+ + + + + + +func (c PubSubConn) PUnsubscribe(channel ...interface{}) error+
+PUnsubscribe unsubscribes the connection from the given patterns, or from all +of them if none is given. +
+ + + + + + +func (c PubSubConn) Ping(data string) error+
+Ping sends a PING to the server with the specified data. +
+ + + + + + +func (c PubSubConn) Receive() interface{}+
+Receive returns a pushed message as a Subscription, Message, PMessage, Pong +or error. The return value is intended to be used directly in a type switch +as illustrated in the PubSubConn example. +
+ + + + + + +func (c PubSubConn) Subscribe(channel ...interface{}) error+
+Subscribe subscribes the connection to the specified channels. +
+ + + + + + +func (c PubSubConn) Unsubscribe(channel ...interface{}) error+
+Unsubscribe unsubscribes the connection from the given channels, or from all +of them if none is given. +
+ + + + + + + + +type Script struct {
+ // contains filtered or unexported fields
+}
+ +Script encapsulates the source, hash and key count for a Lua script. See +http://redis.io/commands/eval for information on scripts in Redis. +
+ + + + + + +▹ Example
+func NewScript(keyCount int, src string) *Script+
+NewScript returns a new script object. If keyCount is greater than or equal +to zero, then the count is automatically inserted in the EVAL command +argument list. If keyCount is less than zero, then the application supplies +the count as the first value in the keysAndArgs argument to the Do, Send and +SendHash methods. +
+ + + + + + + +func (s *Script) Do(c Conn, keysAndArgs ...interface{}) (interface{}, error)+
+Do evaluates the script. Under the covers, Do optimistically evaluates the +script using the EVALSHA command. If the command fails because the script is +not loaded, then Do evaluates the script using the EVAL command (thus +causing the script to load). +
+ + + + + + +func (s *Script) Load(c Conn) error+
+Load loads the script without evaluating it. +
+ + + + + + +func (s *Script) Send(c Conn, keysAndArgs ...interface{}) error+
+Send evaluates the script without waiting for the reply. +
+ + + + + + +func (s *Script) SendHash(c Conn, keysAndArgs ...interface{}) error+
+SendHash evaluates the script without waiting for the reply. The script is +evaluated with the EVALSHA command. The application must ensure that the +script is loaded by a previous call to Send, Do or Load methods. +
+ + + + + + + + +type Subscription struct { + + // Kind is "subscribe", "unsubscribe", "psubscribe" or "punsubscribe" + Kind string + + // The channel that was changed. + Channel string + + // The current number of subscriptions for connection. + Count int +}+
+Subscription represents a subscribe or unsubscribe notification. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ protobuf + | ++ + | +
+ proto + | ++ Package proto converts data structures to and from the wire format of protocol buffers. + | +
+ proto3_proto + | ++ Package proto3_proto is a generated protocol buffer package. + | +
+ snappy + | ++ Package snappy implements the snappy block-based compression format. + | +
Name | +Synopsis | +
---|---|
.. | +|
+ proto + | ++ Package proto converts data structures to and from the wire format of protocol buffers. + | +
+ proto3_proto + | ++ Package proto3_proto is a generated protocol buffer package. + | +
const ( + WireVarint = 0 + WireFixed64 = 1 + WireBytes = 2 + WireStartGroup = 3 + WireEndGroup = 4 + WireFixed32 = 5 +)+
+Constants that identify the encoding of a value on the wire. +
+ + +const ProtoPackageIsVersion1 = true+
+ProtoPackageIsVersion1 is referenced from generated protocol buffer files +to assert that that code is compatible with this version of the proto package. +
+ + +const ProtoPackageIsVersion2 = true+
+ProtoPackageIsVersion2 is referenced from generated protocol buffer files +to assert that that code is compatible with this version of the proto package. +
+ + + + +var ( + + // ErrNil is the error returned if Marshal is called with nil. + ErrNil = errors.New("proto: Marshal called with nil") + + // ErrTooLarge is the error returned if Marshal is called with a + // message that encodes to >2GB. + ErrTooLarge = errors.New("proto: message encodes to over 2 GB") +)+ + +
var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")+
+ErrInternalBadWireType is returned by generated code when an incorrect +wire type is encountered. It does not get returned to user code. +
+ + +var ErrMissingExtension = errors.New("proto: missing extension")+
+ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. +
+ + + + + + +func Bool(v bool) *bool+
+Bool is a helper routine that allocates a new bool value +to store v and returns a pointer to it. +
+ + + + + + + +func ClearAllExtensions(pb Message)+
+ClearAllExtensions clears all extensions from pb. +
+ + + + + + + +func ClearExtension(pb Message, extension *ExtensionDesc)+
+ClearExtension removes the given extension from pb. +
+ + + + + + + +func CompactText(w io.Writer, pb Message) error+
+CompactText writes a given protocol buffer in compact text format (one line). +
+ + + + + + + +func CompactTextString(pb Message) string+
+CompactTextString is the same as CompactText, but returns the string directly. +
+ + + + + + + +func DecodeVarint(buf []byte) (x uint64, n int)+
+DecodeVarint reads a varint-encoded integer from the slice. +It returns the integer and the number of bytes consumed, or +zero if there is not enough. +This is the format for the +int32, int64, uint32, uint64, bool, and enum +protocol buffer types. +
+ + + + + + + +func EncodeVarint(x uint64) []byte+
+EncodeVarint returns the varint encoding of x. +This is the format for the +int32, int64, uint32, uint64, bool, and enum +protocol buffer types. +Not used by the package itself, but helpful to clients +wishing to use the same encoding. +
+ + + + + + + +func EnumName(m map[int32]string, v int32) string+
+EnumName is a helper function to simplify printing protocol buffer enums +by name. Given an enum map and a value, it returns a useful string. +
+ + + + + + + +func EnumValueMap(enumType string) map[string]int32+
+EnumValueMap returns the mapping from names to integers of the +enum type enumType, or a nil if not found. +
+ + + + + + + +func Equal(a, b Message) bool+
+Equal returns true iff protocol buffers a and b are equal. +The arguments must both be pointers to protocol buffer structs. +
++Equality is defined in this way: +
+- Two messages are equal iff they are the same type, + corresponding fields are equal, unknown field sets + are equal, and extensions sets are equal. +- Two set scalar fields are equal iff their values are equal. + If the fields are of a floating-point type, remember that + NaN != x for all x, including NaN. If the message is defined + in a proto3 .proto file, fields are not "set"; specifically, + zero length proto3 "bytes" fields are equal (nil == {}). +- Two repeated fields are equal iff their lengths are the same, + and their corresponding elements are equal. Note a "bytes" field, + although represented by []byte, is not a repeated field and the + rule for the scalar fields described above applies. +- Two unset fields are equal. +- Two unknown field sets are equal if their current + encoded state is equal. +- Two extension sets are equal iff they have corresponding + elements that are pairwise equal. +- Two map fields are equal iff their lengths are the same, + and they contain the same set of elements. Zero-length map + fields are equal. +- Every other combination of things are not equal. ++
+The return value is undefined if a and b are not protocol buffers. +
+ + + + + + + +func ExtensionDescs(pb Message) ([]*ExtensionDesc, error)+
+ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. +For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing +just the Field field, which defines the extension's field number. +
+ + + + + + + +func FileDescriptor(filename string) []byte+
+FileDescriptor returns the compressed FileDescriptorProto for a .proto file. +
+ + + + + + + +func Float32(v float32) *float32+
+Float32 is a helper routine that allocates a new float32 value +to store v and returns a pointer to it. +
+ + + + + + + +func Float64(v float64) *float64+
+Float64 is a helper routine that allocates a new float64 value +to store v and returns a pointer to it. +
+ + + + + + + +func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error)+
+GetExtension parses and returns the given extension of pb. +If the extension is not present and has no default value it returns ErrMissingExtension. +
+ + + + + + + +func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error)+
+GetExtensions returns a slice of the extensions present in pb that are also listed in es. +The returned slice has the same length as es; missing extensions will appear as nil elements. +
+ + + + + + + +func HasExtension(pb Message, extension *ExtensionDesc) bool+
+HasExtension returns whether the given extension is present in pb. +
+ + + + + + + +func Int(v int) *int32+
+Int is a helper routine that allocates a new int32 value +to store v and returns a pointer to it, but unlike Int32 +its argument value is an int. +
+ + + + + + + +func Int32(v int32) *int32+
+Int32 is a helper routine that allocates a new int32 value +to store v and returns a pointer to it. +
+ + + + + + + +func Int64(v int64) *int64+
+Int64 is a helper routine that allocates a new int64 value +to store v and returns a pointer to it. +
+ + + + + + + +func Marshal(pb Message) ([]byte, error)+
+Marshal takes the protocol buffer +and encodes it into the wire format, returning the data. +
+ + + + + + + +func MarshalMessageSet(exts interface{}) ([]byte, error)+
+MarshalMessageSet encodes the extension map represented by m in the message set wire format. +It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. +
+ + + + + + + +func MarshalMessageSetJSON(exts interface{}) ([]byte, error)+
+MarshalMessageSetJSON encodes the extension map represented by m in JSON format. +It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. +
+ + + + + + + +func MarshalText(w io.Writer, pb Message) error+
+MarshalText writes a given protocol buffer in text format. +The only errors returned are from w. +
+ + + + + + + +func MarshalTextString(pb Message) string+
+MarshalTextString is the same as MarshalText, but returns the string directly. +
+ + + + + + + +func Merge(dst, src Message)+
+Merge merges src into dst. +Required and optional fields that are set in src will be set to that value in dst. +Elements of repeated fields will be appended. +Merge panics if src and dst are not the same type, or if dst is nil. +
+ + + + + + + +func MessageName(x Message) string+
+MessageName returns the fully-qualified proto name for the given message type. +
+ + + + + + + +func MessageType(name string) reflect.Type+
+MessageType returns the message type (pointer to struct) for a named message. +
+ + + + + + + +func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32)+
+RegisterEnum is called from the generated code to install the enum descriptor +maps into the global table to aid parsing text format protocol buffers. +
+ + + + + + + +func RegisterExtension(desc *ExtensionDesc)+
+RegisterExtension is called from the generated code. +
+ + + + + + + +func RegisterFile(filename string, fileDescriptor []byte)+
+RegisterFile is called from generated code and maps from the +full file name of a .proto file to its compressed FileDescriptorProto. +
+ + + + + + + +func RegisterMessageSetType(m Message, fieldNum int32, name string)+
+RegisterMessageSetType is called from the generated code. +
+ + + + + + + +func RegisterType(x Message, name string)+
+RegisterType is called from generated code and maps from the fully qualified +proto name to the type (pointer to struct) of the protocol buffer. +
+ + + + + + + +func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc+
+RegisteredExtensions returns a map of the registered extensions of a +protocol buffer struct, indexed by the extension number. +The argument pb should be a nil pointer to the struct type. +
+ + + + + + + +func SetDefaults(pb Message)+
+SetDefaults sets unset protocol buffer fields to their default values. +It only modifies fields that are both unset and have defined defaults. +It recursively sets default values in any non-nil sub-messages. +
+ + + + + + + +func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error+
+SetExtension sets the specified extension of pb to the specified value. +
+ + + + + + + +func SetRawExtension(base Message, id int32, b []byte)+
+SetRawExtension is for testing only. +
+ + + + + + + +func Size(pb Message) (n int)+
+Size returns the encoded size of a protocol buffer. +
+ + + + + + + +func SizeVarint(x uint64) int+
+SizeVarint returns the varint encoding size of an integer. +
+ + + + + + + +func String(v string) *string+
+String is a helper routine that allocates a new string value +to store v and returns a pointer to it. +
+ + + + + + + +func Uint32(v uint32) *uint32+
+Uint32 is a helper routine that allocates a new uint32 value +to store v and returns a pointer to it. +
+ + + + + + + +func Uint64(v uint64) *uint64+
+Uint64 is a helper routine that allocates a new uint64 value +to store v and returns a pointer to it. +
+ + + + + + + +func Unmarshal(buf []byte, pb Message) error+
+Unmarshal parses the protocol buffer representation in buf and places the +decoded result in pb. If the struct underlying pb does not match +the data in buf, the results can be unpredictable. +
++Unmarshal resets pb before starting to unmarshal, so any +existing data in pb is always removed. Use UnmarshalMerge +to preserve and append to existing data. +
+ + + + + + + +func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error)+
+UnmarshalJSONEnum is a helper function to simplify recovering enum int values +from their JSON-encoded representation. Given a map from the enum's symbolic +names to its int values, and a byte buffer containing the JSON-encoded +value, it returns an int32 that can be cast to the enum type by the caller. +
++The function can deal with both JSON representations, numeric and symbolic. +
+ + + + + + + +func UnmarshalMerge(buf []byte, pb Message) error+
+UnmarshalMerge parses the protocol buffer representation in buf and +writes the decoded result to pb. If the struct underlying pb does not match +the data in buf, the results can be unpredictable. +
++UnmarshalMerge merges into existing data in pb. +Most code should use Unmarshal instead. +
+ + + + + + + +func UnmarshalMessageSet(buf []byte, exts interface{}) error+
+UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. +It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option. +
+ + + + + + + +func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error+
+UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. +It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. +
+ + + + + + + +func UnmarshalText(s string, pb Message) error+
+UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb +before starting to unmarshal, so any existing data in pb is always removed. +If a required field is not set and no other error occurs, +UnmarshalText returns *RequiredNotSetError. +
+ + + + + + + + +type Buffer struct {
+ // contains filtered or unexported fields
+}
+ +A Buffer is a buffer manager for marshaling and unmarshaling +protocol buffers. It may be reused between invocations to +reduce memory usage. It is not necessary to use a Buffer; +the global functions Marshal and Unmarshal create a +temporary Buffer and are fine for most applications. +
+ + + + + + + + + + + + +func NewBuffer(e []byte) *Buffer+
+NewBuffer allocates a new Buffer and initializes its internal data to +the contents of the argument slice. +
+ + + + + + + +func (p *Buffer) Bytes() []byte+
+Bytes returns the contents of the Buffer. +
+ + + + + + +func (p *Buffer) DebugPrint(s string, b []byte)+
+DebugPrint dumps the encoded data in b in a debugging format with a header +including the string s. Used in testing but made available for general debugging. +
+ + + + + + +func (p *Buffer) DecodeFixed32() (x uint64, err error)+
+DecodeFixed32 reads a 32-bit integer from the Buffer. +This is the format for the +fixed32, sfixed32, and float protocol buffer types. +
+ + + + + + +func (p *Buffer) DecodeFixed64() (x uint64, err error)+
+DecodeFixed64 reads a 64-bit integer from the Buffer. +This is the format for the +fixed64, sfixed64, and double protocol buffer types. +
+ + + + + + +func (p *Buffer) DecodeGroup(pb Message) error+
+DecodeGroup reads a tag-delimited group from the Buffer. +
+ + + + + + +func (p *Buffer) DecodeMessage(pb Message) error+
+DecodeMessage reads a count-delimited message from the Buffer. +
+ + + + + + +func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error)+
+DecodeRawBytes reads a count-delimited byte buffer from the Buffer. +This is the format used for the bytes protocol buffer +type and for embedded messages. +
+ + + + + + +func (p *Buffer) DecodeStringBytes() (s string, err error)+
+DecodeStringBytes reads an encoded string from the Buffer. +This is the format used for the proto2 string type. +
+ + + + + + +func (p *Buffer) DecodeVarint() (x uint64, err error)+
+DecodeVarint reads a varint-encoded integer from the Buffer. +This is the format for the +int32, int64, uint32, uint64, bool, and enum +protocol buffer types. +
+ + + + + + +func (p *Buffer) DecodeZigzag32() (x uint64, err error)+
+DecodeZigzag32 reads a zigzag-encoded 32-bit integer +from the Buffer. +This is the format used for the sint32 protocol buffer type. +
+ + + + + + +func (p *Buffer) DecodeZigzag64() (x uint64, err error)+
+DecodeZigzag64 reads a zigzag-encoded 64-bit integer +from the Buffer. +This is the format used for the sint64 protocol buffer type. +
+ + + + + + +func (p *Buffer) EncodeFixed32(x uint64) error+
+EncodeFixed32 writes a 32-bit integer to the Buffer. +This is the format for the +fixed32, sfixed32, and float protocol buffer types. +
+ + + + + + +func (p *Buffer) EncodeFixed64(x uint64) error+
+EncodeFixed64 writes a 64-bit integer to the Buffer. +This is the format for the +fixed64, sfixed64, and double protocol buffer types. +
+ + + + + + +func (p *Buffer) EncodeMessage(pb Message) error+
+EncodeMessage writes the protocol buffer to the Buffer, +prefixed by a varint-encoded length. +
+ + + + + + +func (p *Buffer) EncodeRawBytes(b []byte) error+
+EncodeRawBytes writes a count-delimited byte buffer to the Buffer. +This is the format used for the bytes protocol buffer +type and for embedded messages. +
+ + + + + + +func (p *Buffer) EncodeStringBytes(s string) error+
+EncodeStringBytes writes an encoded string to the Buffer. +This is the format used for the proto2 string type. +
+ + + + + + +func (p *Buffer) EncodeVarint(x uint64) error+
+EncodeVarint writes a varint-encoded integer to the Buffer. +This is the format for the +int32, int64, uint32, uint64, bool, and enum +protocol buffer types. +
+ + + + + + +func (p *Buffer) EncodeZigzag32(x uint64) error+
+EncodeZigzag32 writes a zigzag-encoded 32-bit integer +to the Buffer. +This is the format used for the sint32 protocol buffer type. +
+ + + + + + +func (p *Buffer) EncodeZigzag64(x uint64) error+
+EncodeZigzag64 writes a zigzag-encoded 64-bit integer +to the Buffer. +This is the format used for the sint64 protocol buffer type. +
+ + + + + + +func (p *Buffer) Marshal(pb Message) error+
+Marshal takes the protocol buffer +and encodes it into the wire format, writing the result to the +Buffer. +
+ + + + + + +func (p *Buffer) Reset()+
+Reset resets the Buffer, ready for marshaling a new protocol buffer. +
+ + + + + + +func (p *Buffer) SetBuf(s []byte)+
+SetBuf replaces the internal buffer with the slice, +ready for unmarshaling the contents of the slice. +
+ + + + + + +func (p *Buffer) Unmarshal(pb Message) error+
+Unmarshal parses the protocol buffer representation in the +Buffer and places the decoded result in pb. If the struct +underlying pb does not match the data in the buffer, the results can be +unpredictable. +
++Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. +
+ + + + + + + + +type Extension struct {
+ // contains filtered or unexported fields
+}
+ +Extension represents an extension in a message. +
+ + + + + + + + + + + + + + + + +type ExtensionDesc struct { + ExtendedType Message // nil pointer to the type that is being extended + ExtensionType interface{} // nil pointer to the extension type + Field int32 // field number + Name string // fully-qualified name of extension, for text formatting + Tag string // protobuf tag style +}+
+ExtensionDesc represents an extension specification. +Used in generated code from the protocol compiler. +
+ + + + + + + + + + + + + + + + +type ExtensionRange struct { + Start, End int32 // both inclusive +}+
+ExtensionRange represents a range of message extensions for a protocol buffer. +Used in code generated by the protocol compiler. +
+ + + + + + + + + + + + + + + + +type Marshaler interface { + Marshal() ([]byte, error) +}+
+Marshaler is the interface representing objects that can marshal themselves. +
+ + + + + + + + + + + + + + + + +type Message interface { + Reset() + String() string + ProtoMessage() +}+
+Message is implemented by generated protocol buffer messages. +
+ + + + + + + + + + + + +func Clone(pb Message) Message+
+Clone returns a deep copy of a protocol buffer. +
+ + + + + + + + + +type OneofProperties struct { + Type reflect.Type // pointer to generated struct type for this oneof field + Field int // struct field number of the containing oneof in the message + Prop *Properties +}+
+OneofProperties represents information about a specific field in a oneof. +
+ + + + + + + + + + + + + + + + +type ParseError struct { + Message string + Line int // 1-based line number + Offset int // 0-based byte offset from start of input +}+ + + + + + + + + + + + + + +
func (p *ParseError) Error() string+ + + + + + + + +
type Properties struct { + Name string // name of the field, for error messages + OrigName string // original name before protocol compiler (always set) + JSONName string // name to use for JSON; determined by protoc + Wire string + WireType int + Tag int + Required bool + Optional bool + Repeated bool + Packed bool // relevant for repeated primitives only + Enum string // set for enum types only + + Default string // default value + HasDefault bool // whether an explicit default was provided + // contains filtered or unexported fields +}+
+Properties represents the protocol-specific behavior of a single struct field. +
+ + + + + + + + + + + + + + +func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField)+
+Init populates the properties from a protocol buffer struct tag. +
+ + + + + + +func (p *Properties) Parse(s string)+
+Parse populates p by parsing a string in the protobuf struct field tag style. +
+ + + + + + +func (p *Properties) String() string+
+String formats the properties in the protobuf struct field tag style. +
+ + + + + + + + +type RequiredNotSetError struct {
+ // contains filtered or unexported fields
+}
+ +RequiredNotSetError is the error returned if Marshal is called with +a protocol buffer struct whose required fields have not +all been initialized. It is also the error returned if Unmarshal is +called with an encoded protocol buffer that does not include all the +required fields. +
++When printed, RequiredNotSetError reports the first unset required field in a +message. If the field cannot be precisely determined, it is reported as +"{Unknown}". +
+ + + + + + + + + + + + + + +func (e *RequiredNotSetError) Error() string+ + + + + + + + +
type Stats struct { + Emalloc uint64 // mallocs in encode + Dmalloc uint64 // mallocs in decode + Encode uint64 // number of encodes + Decode uint64 // number of decodes + Chit uint64 // number of cache hits + Cmiss uint64 // number of cache misses + Size uint64 // number of sizes +}+
+Stats records allocation details about the protocol buffer encoders +and decoders. Useful for tuning the library itself. +
+ + + + + + + + + + + + +func GetStats() Stats+
+GetStats returns a copy of the global Stats structure. +
+ + + + + + + + + +type StructProperties struct { + Prop []*Properties // properties for each field + + // OneofTypes contains information about the oneof fields in this message. + // It is keyed by the original name of a field. + OneofTypes map[string]*OneofProperties + // contains filtered or unexported fields +}+
+StructProperties represents properties for all the fields of a struct. +decoderTags and decoderOrigNames should only be used by the decoder. +
+ + + + + + + + + + + + +func GetProperties(t reflect.Type) *StructProperties+
+GetProperties returns the list of properties for the type represented by t. +t must represent a generated struct type of a protocol message. +
+ + + + + + + +func (sp *StructProperties) Len() int+ + + + + + +
func (sp *StructProperties) Less(i, j int) bool+ + + + + + +
func (sp *StructProperties) Swap(i, j int)+ + + + + + + + +
type TextMarshaler struct { + Compact bool // use compact text format (one line). + ExpandAny bool // expand google.protobuf.Any messages of known types +}+
+TextMarshaler is a configurable text format marshaler. +
+ + + + + + + + + + + + + + +func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error+
+Marshal writes a given protocol buffer in text format. +The only errors returned are from w. +
+ + + + + + +func (tm *TextMarshaler) Text(pb Message) string+
+Text is the same as Marshal, but returns the string directly. +
+ + + + + + + + +type Unmarshaler interface { + Unmarshal([]byte) error +}+
+Unmarshaler is the interface representing objects that can +unmarshal themselves. The method should reset the receiver before +decoding starts. The argument points to data that may be +overwritten, so implementations should not keep references to the +buffer. +
+ + + + + + + + + + + + + + + + +type XXX_InternalExtensions struct {
+ // contains filtered or unexported fields
+}
+ +XXX_InternalExtensions is an internal representation of proto extensions. +
++Each generated message struct type embeds an anonymous XXX_InternalExtensions field, +thus gaining the unexported 'extensions' method, which can be called only from the proto package. +
++The methods of XXX_InternalExtensions are not concurrency safe in general, +but calls to logically read-only methods such as has and get may be executed concurrently. +
+ + + + + + + + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ proto3_proto + | ++ Package proto3_proto is a generated protocol buffer package. + | +
var Message_Humour_name = map[int32]string{ + 0: "UNKNOWN", + 1: "PUNS", + 2: "SLAPSTICK", + 3: "BILL_BAILEY", +}+ + +
var Message_Humour_value = map[string]int32{ + "UNKNOWN": 0, + "PUNS": 1, + "SLAPSTICK": 2, + "BILL_BAILEY": 3, +}+ + + + + + + +
type Message struct { + Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Hilarity Message_Humour `protobuf:"varint,2,opt,name=hilarity,enum=proto3_proto.Message_Humour" json:"hilarity,omitempty"` + HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm,json=heightInCm" json:"height_in_cm,omitempty"` + Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"` + ResultCount int64 `protobuf:"varint,7,opt,name=result_count,json=resultCount" json:"result_count,omitempty"` + TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman,json=trueScotsman" json:"true_scotsman,omitempty"` + Score float32 `protobuf:"fixed32,9,opt,name=score" json:"score,omitempty"` + Key []uint64 `protobuf:"varint,5,rep,name=key" json:"key,omitempty"` + ShortKey []int32 `protobuf:"varint,19,rep,name=short_key,json=shortKey" json:"short_key,omitempty"` + Nested *Nested `protobuf:"bytes,6,opt,name=nested" json:"nested,omitempty"` + RFunny []Message_Humour `protobuf:"varint,16,rep,name=r_funny,json=rFunny,enum=proto3_proto.Message_Humour" json:"r_funny,omitempty"` + Terrain map[string]*Nested `protobuf:"bytes,10,rep,name=terrain" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + Proto2Field *testdata.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field,json=proto2Field" json:"proto2_field,omitempty"` + Proto2Value map[string]*testdata.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value,json=proto2Value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + Anything *google_protobuf.Any `protobuf:"bytes,14,opt,name=anything" json:"anything,omitempty"` + ManyThings []*google_protobuf.Any `protobuf:"bytes,15,rep,name=many_things,json=manyThings" json:"many_things,omitempty"` + Submessage *Message `protobuf:"bytes,17,opt,name=submessage" json:"submessage,omitempty"` + Children []*Message `protobuf:"bytes,18,rep,name=children" json:"children,omitempty"` +}+ + + + + + + + + + + + + + +
func (*Message) Descriptor() ([]byte, []int)+ + + + + + +
func (m *Message) GetAnything() *google_protobuf.Any+ + + + + + +
func (m *Message) GetChildren() []*Message+ + + + + + +
func (m *Message) GetManyThings() []*google_protobuf.Any+ + + + + + +
func (m *Message) GetNested() *Nested+ + + + + + +
func (m *Message) GetProto2Field() *testdata.SubDefaults+ + + + + + +
func (m *Message) GetProto2Value() map[string]*testdata.SubDefaults+ + + + + + +
func (m *Message) GetSubmessage() *Message+ + + + + + +
func (m *Message) GetTerrain() map[string]*Nested+ + + + + + +
func (*Message) ProtoMessage()+ + + + + + +
func (m *Message) Reset()+ + + + + + +
func (m *Message) String() string+ + + + + + + + +
type MessageWithMap struct { + ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"` +}+ + + + + + + + + + + + + + +
func (*MessageWithMap) Descriptor() ([]byte, []int)+ + + + + + +
func (m *MessageWithMap) GetByteMapping() map[bool][]byte+ + + + + + +
func (*MessageWithMap) ProtoMessage()+ + + + + + +
func (m *MessageWithMap) Reset()+ + + + + + +
func (m *MessageWithMap) String() string+ + + + + + + + +
type Message_Humour int32+ + + +
const ( + Message_UNKNOWN Message_Humour = 0 + Message_PUNS Message_Humour = 1 + Message_SLAPSTICK Message_Humour = 2 + Message_BILL_BAILEY Message_Humour = 3 +)+ + + + + + + + + + + + + +
func (Message_Humour) EnumDescriptor() ([]byte, []int)+ + + + + + +
func (x Message_Humour) String() string+ + + + + + + + +
type Nested struct { + Bunny string `protobuf:"bytes,1,opt,name=bunny" json:"bunny,omitempty"` + Cute bool `protobuf:"varint,2,opt,name=cute" json:"cute,omitempty"` +}+ + + + + + + + + + + + + + +
func (*Nested) Descriptor() ([]byte, []int)+ + + + + + +
func (*Nested) ProtoMessage()+ + + + + + +
func (m *Nested) Reset()+ + + + + + +
func (m *Nested) String() string+ + + + + + + + + + + + + + + + + + +
const Default_Defaults_F_Bool bool = true+ + +
const Default_Defaults_F_Double float64 = 271828+ + +
const Default_Defaults_F_Fixed32 uint32 = 320+ + +
const Default_Defaults_F_Fixed64 uint64 = 640+ + +
const Default_Defaults_F_Float float32 = 314159+ + +
const Default_Defaults_F_Int32 int32 = 32+ + +
const Default_Defaults_F_Int64 int64 = 64+ + +
const Default_Defaults_F_Sint32 int32 = -32+ + +
const Default_Defaults_F_Sint64 int64 = -64+ + +
const Default_Defaults_F_String string = "hello, \"world!\"\n"+ + +
const Default_Defaults_F_Uint32 uint32 = 3200+ + +
const Default_Defaults_F_Uint64 uint64 = 6400+ + +
const Default_GoTest_F_BoolDefaulted bool = true+ + +
const Default_GoTest_F_DoubleDefaulted float64 = 271828+ + +
const Default_GoTest_F_Fixed32Defaulted uint32 = 320+ + +
const Default_GoTest_F_Fixed64Defaulted uint64 = 640+ + +
const Default_GoTest_F_FloatDefaulted float32 = 314159+ + +
const Default_GoTest_F_Int32Defaulted int32 = 32+ + +
const Default_GoTest_F_Int64Defaulted int64 = 64+ + +
const Default_GoTest_F_Sint32Defaulted int32 = -32+ + +
const Default_GoTest_F_Sint64Defaulted int64 = -64+ + +
const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n"+ + +
const Default_GoTest_F_Uint32Defaulted uint32 = 3200+ + +
const Default_GoTest_F_Uint64Defaulted uint64 = 6400+ + +
const Default_InnerMessage_Port int32 = 4000+ + +
const Default_SubDefaults_N int64 = 7+ + + + +
var Default_Defaults_F_Bytes []byte = []byte("Bignose")+ + +
var Default_Defaults_F_Nan float32 = float32(math.NaN())+ + +
var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1))+ + +
var Default_Defaults_F_Pinf float32 = float32(math.Inf(1))+ + +
var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose")+ + +
var DefaultsMessage_DefaultsEnum_name = map[int32]string{ + 0: "ZERO", + 1: "ONE", + 2: "TWO", +}+ + +
var DefaultsMessage_DefaultsEnum_value = map[string]int32{ + "ZERO": 0, + "ONE": 1, + "TWO": 2, +}+ + +
var Defaults_Color_name = map[int32]string{ + 0: "RED", + 1: "GREEN", + 2: "BLUE", +}+ + +
var Defaults_Color_value = map[string]int32{ + "RED": 0, + "GREEN": 1, + "BLUE": 2, +}+ + +
var E_Complex = &proto.ExtensionDesc{ + ExtendedType: (*OtherMessage)(nil), + ExtensionType: (*ComplexExtension)(nil), + Field: 200, + Name: "testdata.complex", + Tag: "bytes,200,opt,name=complex", +}+ + +
var E_DefaultBool = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*bool)(nil), + Field: 213, + Name: "testdata.default_bool", + Tag: "varint,213,opt,name=default_bool,json=defaultBool,def=1", +}+ + +
var E_DefaultBytes = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: ([]byte)(nil), + Field: 215, + Name: "testdata.default_bytes", + Tag: "bytes,215,opt,name=default_bytes,json=defaultBytes,def=Hello, bytes", +}+ + +
var E_DefaultDouble = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*float64)(nil), + Field: 201, + Name: "testdata.default_double", + Tag: "fixed64,201,opt,name=default_double,json=defaultDouble,def=3.1415", +}+ + +
var E_DefaultEnum = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), + Field: 216, + Name: "testdata.default_enum", + Tag: "varint,216,opt,name=default_enum,json=defaultEnum,enum=testdata.DefaultsMessage_DefaultsEnum,def=1", +}+ + +
var E_DefaultFixed32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint32)(nil), + Field: 209, + Name: "testdata.default_fixed32", + Tag: "fixed32,209,opt,name=default_fixed32,json=defaultFixed32,def=48", +}+ + +
var E_DefaultFixed64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint64)(nil), + Field: 210, + Name: "testdata.default_fixed64", + Tag: "fixed64,210,opt,name=default_fixed64,json=defaultFixed64,def=49", +}+ + +
var E_DefaultFloat = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*float32)(nil), + Field: 202, + Name: "testdata.default_float", + Tag: "fixed32,202,opt,name=default_float,json=defaultFloat,def=3.14", +}+ + +
var E_DefaultInt32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 203, + Name: "testdata.default_int32", + Tag: "varint,203,opt,name=default_int32,json=defaultInt32,def=42", +}+ + +
var E_DefaultInt64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int64)(nil), + Field: 204, + Name: "testdata.default_int64", + Tag: "varint,204,opt,name=default_int64,json=defaultInt64,def=43", +}+ + +
var E_DefaultSfixed32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 211, + Name: "testdata.default_sfixed32", + Tag: "fixed32,211,opt,name=default_sfixed32,json=defaultSfixed32,def=50", +}+ + +
var E_DefaultSfixed64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int64)(nil), + Field: 212, + Name: "testdata.default_sfixed64", + Tag: "fixed64,212,opt,name=default_sfixed64,json=defaultSfixed64,def=51", +}+ + +
var E_DefaultSint32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 207, + Name: "testdata.default_sint32", + Tag: "zigzag32,207,opt,name=default_sint32,json=defaultSint32,def=46", +}+ + +
var E_DefaultSint64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int64)(nil), + Field: 208, + Name: "testdata.default_sint64", + Tag: "zigzag64,208,opt,name=default_sint64,json=defaultSint64,def=47", +}+ + +
var E_DefaultString = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*string)(nil), + Field: 214, + Name: "testdata.default_string", + Tag: "bytes,214,opt,name=default_string,json=defaultString,def=Hello, string", +}+ + +
var E_DefaultUint32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint32)(nil), + Field: 205, + Name: "testdata.default_uint32", + Tag: "varint,205,opt,name=default_uint32,json=defaultUint32,def=44", +}+ + +
var E_DefaultUint64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint64)(nil), + Field: 206, + Name: "testdata.default_uint64", + Tag: "varint,206,opt,name=default_uint64,json=defaultUint64,def=45", +}+ + +
var E_Ext_More = &proto.ExtensionDesc{ + ExtendedType: (*MyMessage)(nil), + ExtensionType: (*Ext)(nil), + Field: 103, + Name: "testdata.Ext.more", + Tag: "bytes,103,opt,name=more", +}+ + +
var E_Ext_Number = &proto.ExtensionDesc{ + ExtendedType: (*MyMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 105, + Name: "testdata.Ext.number", + Tag: "varint,105,opt,name=number", +}+ + +
var E_Ext_Text = &proto.ExtensionDesc{ + ExtendedType: (*MyMessage)(nil), + ExtensionType: (*string)(nil), + Field: 104, + Name: "testdata.Ext.text", + Tag: "bytes,104,opt,name=text", +}+ + +
var E_Greeting = &proto.ExtensionDesc{ + ExtendedType: (*MyMessage)(nil), + ExtensionType: ([]string)(nil), + Field: 106, + Name: "testdata.greeting", + Tag: "bytes,106,rep,name=greeting", +}+ + +
var E_NoDefaultBool = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*bool)(nil), + Field: 113, + Name: "testdata.no_default_bool", + Tag: "varint,113,opt,name=no_default_bool,json=noDefaultBool", +}+ + +
var E_NoDefaultBytes = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: ([]byte)(nil), + Field: 115, + Name: "testdata.no_default_bytes", + Tag: "bytes,115,opt,name=no_default_bytes,json=noDefaultBytes", +}+ + +
var E_NoDefaultDouble = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*float64)(nil), + Field: 101, + Name: "testdata.no_default_double", + Tag: "fixed64,101,opt,name=no_default_double,json=noDefaultDouble", +}+ + +
var E_NoDefaultEnum = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), + Field: 116, + Name: "testdata.no_default_enum", + Tag: "varint,116,opt,name=no_default_enum,json=noDefaultEnum,enum=testdata.DefaultsMessage_DefaultsEnum", +}+ + +
var E_NoDefaultFixed32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint32)(nil), + Field: 109, + Name: "testdata.no_default_fixed32", + Tag: "fixed32,109,opt,name=no_default_fixed32,json=noDefaultFixed32", +}+ + +
var E_NoDefaultFixed64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint64)(nil), + Field: 110, + Name: "testdata.no_default_fixed64", + Tag: "fixed64,110,opt,name=no_default_fixed64,json=noDefaultFixed64", +}+ + +
var E_NoDefaultFloat = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*float32)(nil), + Field: 102, + Name: "testdata.no_default_float", + Tag: "fixed32,102,opt,name=no_default_float,json=noDefaultFloat", +}+ + +
var E_NoDefaultInt32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 103, + Name: "testdata.no_default_int32", + Tag: "varint,103,opt,name=no_default_int32,json=noDefaultInt32", +}+ + +
var E_NoDefaultInt64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int64)(nil), + Field: 104, + Name: "testdata.no_default_int64", + Tag: "varint,104,opt,name=no_default_int64,json=noDefaultInt64", +}+ + +
var E_NoDefaultSfixed32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 111, + Name: "testdata.no_default_sfixed32", + Tag: "fixed32,111,opt,name=no_default_sfixed32,json=noDefaultSfixed32", +}+ + +
var E_NoDefaultSfixed64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int64)(nil), + Field: 112, + Name: "testdata.no_default_sfixed64", + Tag: "fixed64,112,opt,name=no_default_sfixed64,json=noDefaultSfixed64", +}+ + +
var E_NoDefaultSint32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 107, + Name: "testdata.no_default_sint32", + Tag: "zigzag32,107,opt,name=no_default_sint32,json=noDefaultSint32", +}+ + +
var E_NoDefaultSint64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int64)(nil), + Field: 108, + Name: "testdata.no_default_sint64", + Tag: "zigzag64,108,opt,name=no_default_sint64,json=noDefaultSint64", +}+ + +
var E_NoDefaultString = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*string)(nil), + Field: 114, + Name: "testdata.no_default_string", + Tag: "bytes,114,opt,name=no_default_string,json=noDefaultString", +}+ + +
var E_NoDefaultUint32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint32)(nil), + Field: 105, + Name: "testdata.no_default_uint32", + Tag: "varint,105,opt,name=no_default_uint32,json=noDefaultUint32", +}+ + +
var E_NoDefaultUint64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint64)(nil), + Field: 106, + Name: "testdata.no_default_uint64", + Tag: "varint,106,opt,name=no_default_uint64,json=noDefaultUint64", +}+ + +
var E_RComplex = &proto.ExtensionDesc{ + ExtendedType: (*OtherMessage)(nil), + ExtensionType: ([]*ComplexExtension)(nil), + Field: 201, + Name: "testdata.r_complex", + Tag: "bytes,201,rep,name=r_complex,json=rComplex", +}+ + +
var E_X201 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 201, + Name: "testdata.x201", + Tag: "bytes,201,opt,name=x201", +}+ + +
var E_X202 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 202, + Name: "testdata.x202", + Tag: "bytes,202,opt,name=x202", +}+ + +
var E_X203 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 203, + Name: "testdata.x203", + Tag: "bytes,203,opt,name=x203", +}+ + +
var E_X204 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 204, + Name: "testdata.x204", + Tag: "bytes,204,opt,name=x204", +}+ + +
var E_X205 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 205, + Name: "testdata.x205", + Tag: "bytes,205,opt,name=x205", +}+ + +
var E_X206 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 206, + Name: "testdata.x206", + Tag: "bytes,206,opt,name=x206", +}+ + +
var E_X207 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 207, + Name: "testdata.x207", + Tag: "bytes,207,opt,name=x207", +}+ + +
var E_X208 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 208, + Name: "testdata.x208", + Tag: "bytes,208,opt,name=x208", +}+ + +
var E_X209 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 209, + Name: "testdata.x209", + Tag: "bytes,209,opt,name=x209", +}+ + +
var E_X210 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 210, + Name: "testdata.x210", + Tag: "bytes,210,opt,name=x210", +}+ + +
var E_X211 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 211, + Name: "testdata.x211", + Tag: "bytes,211,opt,name=x211", +}+ + +
var E_X212 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 212, + Name: "testdata.x212", + Tag: "bytes,212,opt,name=x212", +}+ + +
var E_X213 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 213, + Name: "testdata.x213", + Tag: "bytes,213,opt,name=x213", +}+ + +
var E_X214 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 214, + Name: "testdata.x214", + Tag: "bytes,214,opt,name=x214", +}+ + +
var E_X215 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 215, + Name: "testdata.x215", + Tag: "bytes,215,opt,name=x215", +}+ + +
var E_X216 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 216, + Name: "testdata.x216", + Tag: "bytes,216,opt,name=x216", +}+ + +
var E_X217 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 217, + Name: "testdata.x217", + Tag: "bytes,217,opt,name=x217", +}+ + +
var E_X218 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 218, + Name: "testdata.x218", + Tag: "bytes,218,opt,name=x218", +}+ + +
var E_X219 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 219, + Name: "testdata.x219", + Tag: "bytes,219,opt,name=x219", +}+ + +
var E_X220 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 220, + Name: "testdata.x220", + Tag: "bytes,220,opt,name=x220", +}+ + +
var E_X221 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 221, + Name: "testdata.x221", + Tag: "bytes,221,opt,name=x221", +}+ + +
var E_X222 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 222, + Name: "testdata.x222", + Tag: "bytes,222,opt,name=x222", +}+ + +
var E_X223 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 223, + Name: "testdata.x223", + Tag: "bytes,223,opt,name=x223", +}+ + +
var E_X224 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 224, + Name: "testdata.x224", + Tag: "bytes,224,opt,name=x224", +}+ + +
var E_X225 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 225, + Name: "testdata.x225", + Tag: "bytes,225,opt,name=x225", +}+ + +
var E_X226 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 226, + Name: "testdata.x226", + Tag: "bytes,226,opt,name=x226", +}+ + +
var E_X227 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 227, + Name: "testdata.x227", + Tag: "bytes,227,opt,name=x227", +}+ + +
var E_X228 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 228, + Name: "testdata.x228", + Tag: "bytes,228,opt,name=x228", +}+ + +
var E_X229 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 229, + Name: "testdata.x229", + Tag: "bytes,229,opt,name=x229", +}+ + +
var E_X230 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 230, + Name: "testdata.x230", + Tag: "bytes,230,opt,name=x230", +}+ + +
var E_X231 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 231, + Name: "testdata.x231", + Tag: "bytes,231,opt,name=x231", +}+ + +
var E_X232 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 232, + Name: "testdata.x232", + Tag: "bytes,232,opt,name=x232", +}+ + +
var E_X233 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 233, + Name: "testdata.x233", + Tag: "bytes,233,opt,name=x233", +}+ + +
var E_X234 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 234, + Name: "testdata.x234", + Tag: "bytes,234,opt,name=x234", +}+ + +
var E_X235 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 235, + Name: "testdata.x235", + Tag: "bytes,235,opt,name=x235", +}+ + +
var E_X236 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 236, + Name: "testdata.x236", + Tag: "bytes,236,opt,name=x236", +}+ + +
var E_X237 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 237, + Name: "testdata.x237", + Tag: "bytes,237,opt,name=x237", +}+ + +
var E_X238 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 238, + Name: "testdata.x238", + Tag: "bytes,238,opt,name=x238", +}+ + +
var E_X239 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 239, + Name: "testdata.x239", + Tag: "bytes,239,opt,name=x239", +}+ + +
var E_X240 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 240, + Name: "testdata.x240", + Tag: "bytes,240,opt,name=x240", +}+ + +
var E_X241 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 241, + Name: "testdata.x241", + Tag: "bytes,241,opt,name=x241", +}+ + +
var E_X242 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 242, + Name: "testdata.x242", + Tag: "bytes,242,opt,name=x242", +}+ + +
var E_X243 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 243, + Name: "testdata.x243", + Tag: "bytes,243,opt,name=x243", +}+ + +
var E_X244 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 244, + Name: "testdata.x244", + Tag: "bytes,244,opt,name=x244", +}+ + +
var E_X245 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 245, + Name: "testdata.x245", + Tag: "bytes,245,opt,name=x245", +}+ + +
var E_X246 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 246, + Name: "testdata.x246", + Tag: "bytes,246,opt,name=x246", +}+ + +
var E_X247 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 247, + Name: "testdata.x247", + Tag: "bytes,247,opt,name=x247", +}+ + +
var E_X248 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 248, + Name: "testdata.x248", + Tag: "bytes,248,opt,name=x248", +}+ + +
var E_X249 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 249, + Name: "testdata.x249", + Tag: "bytes,249,opt,name=x249", +}+ + +
var E_X250 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 250, + Name: "testdata.x250", + Tag: "bytes,250,opt,name=x250", +}+ + +
var FOO_name = map[int32]string{ + 1: "FOO1", +}+ + +
var FOO_value = map[string]int32{ + "FOO1": 1, +}+ + +
var GoTest_KIND_name = map[int32]string{ + 0: "VOID", + 1: "BOOL", + 2: "BYTES", + 3: "FINGERPRINT", + 4: "FLOAT", + 5: "INT", + 6: "STRING", + 7: "TIME", + 8: "TUPLE", + 9: "ARRAY", + 10: "MAP", + 11: "TABLE", + 12: "FUNCTION", +}+ + +
var GoTest_KIND_value = map[string]int32{ + "VOID": 0, + "BOOL": 1, + "BYTES": 2, + "FINGERPRINT": 3, + "FLOAT": 4, + "INT": 5, + "STRING": 6, + "TIME": 7, + "TUPLE": 8, + "ARRAY": 9, + "MAP": 10, + "TABLE": 11, + "FUNCTION": 12, +}+ + +
var MyMessage_Color_name = map[int32]string{ + 0: "RED", + 1: "GREEN", + 2: "BLUE", +}+ + +
var MyMessage_Color_value = map[string]int32{ + "RED": 0, + "GREEN": 1, + "BLUE": 2, +}+ + +
var RepeatedEnum_Color_name = map[int32]string{ + 1: "RED", +}+ + +
var RepeatedEnum_Color_value = map[string]int32{ + "RED": 1, +}+ + + + + + + +
type Communique struct { + MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"` + // This is a oneof, called "union". + // + // Types that are valid to be assigned to Union: + // *Communique_Number + // *Communique_Name + // *Communique_Data + // *Communique_TempC + // *Communique_Col + // *Communique_Msg + Union isCommunique_Union `protobuf_oneof:"union"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*Communique) Descriptor() ([]byte, []int)+ + + + + + +
func (m *Communique) GetCol() MyMessage_Color+ + + + + + +
func (m *Communique) GetData() []byte+ + + + + + +
func (m *Communique) GetMakeMeCry() bool+ + + + + + +
func (m *Communique) GetMsg() *Strings+ + + + + + +
func (m *Communique) GetName() string+ + + + + + +
func (m *Communique) GetNumber() int32+ + + + + + +
func (m *Communique) GetTempC() float64+ + + + + + +
func (m *Communique) GetUnion() isCommunique_Union+ + + + + + +
func (*Communique) ProtoMessage()+ + + + + + +
func (m *Communique) Reset()+ + + + + + +
func (m *Communique) String() string+ + + + + + +
func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{})+
+XXX_OneofFuncs is for the internal use of the proto package. +
+ + + + + + + + +type Communique_Col struct { + Col MyMessage_Color `protobuf:"varint,9,opt,name=col,enum=testdata.MyMessage_Color,oneof"` +}+ + + + + + + + + + + + + + + + +
type Communique_Data struct { + Data []byte `protobuf:"bytes,7,opt,name=data,oneof"` +}+ + + + + + + + + + + + + + + + +
type Communique_Msg struct { + Msg *Strings `protobuf:"bytes,10,opt,name=msg,oneof"` +}+ + + + + + + + + + + + + + + + +
type Communique_Name struct { + Name string `protobuf:"bytes,6,opt,name=name,oneof"` +}+ + + + + + + + + + + + + + + + +
type Communique_Number struct { + Number int32 `protobuf:"varint,5,opt,name=number,oneof"` +}+ + + + + + + + + + + + + + + + +
type Communique_TempC struct { + TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"` +}+ + + + + + + + + + + + + + + + +
type ComplexExtension struct { + First *int32 `protobuf:"varint,1,opt,name=first" json:"first,omitempty"` + Second *int32 `protobuf:"varint,2,opt,name=second" json:"second,omitempty"` + Third []int32 `protobuf:"varint,3,rep,name=third" json:"third,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*ComplexExtension) Descriptor() ([]byte, []int)+ + + + + + +
func (m *ComplexExtension) GetFirst() int32+ + + + + + +
func (m *ComplexExtension) GetSecond() int32+ + + + + + +
func (m *ComplexExtension) GetThird() []int32+ + + + + + +
func (*ComplexExtension) ProtoMessage()+ + + + + + +
func (m *ComplexExtension) Reset()+ + + + + + +
func (m *ComplexExtension) String() string+ + + + + + + + +
type Defaults struct { + // Default-valued fields of all basic types. + // Same as GoTest, but copied here to make testing easier. + F_Bool *bool `protobuf:"varint,1,opt,name=F_Bool,json=fBool,def=1" json:"F_Bool,omitempty"` + F_Int32 *int32 `protobuf:"varint,2,opt,name=F_Int32,json=fInt32,def=32" json:"F_Int32,omitempty"` + F_Int64 *int64 `protobuf:"varint,3,opt,name=F_Int64,json=fInt64,def=64" json:"F_Int64,omitempty"` + F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=fFixed32,def=320" json:"F_Fixed32,omitempty"` + F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=fFixed64,def=640" json:"F_Fixed64,omitempty"` + F_Uint32 *uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=fUint32,def=3200" json:"F_Uint32,omitempty"` + F_Uint64 *uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=fUint64,def=6400" json:"F_Uint64,omitempty"` + F_Float *float32 `protobuf:"fixed32,8,opt,name=F_Float,json=fFloat,def=314159" json:"F_Float,omitempty"` + F_Double *float64 `protobuf:"fixed64,9,opt,name=F_Double,json=fDouble,def=271828" json:"F_Double,omitempty"` + F_String *string `protobuf:"bytes,10,opt,name=F_String,json=fString,def=hello, \"world!\"\n" json:"F_String,omitempty"` + F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=fBytes,def=Bignose" json:"F_Bytes,omitempty"` + F_Sint32 *int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=fSint32,def=-32" json:"F_Sint32,omitempty"` + F_Sint64 *int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=fSint64,def=-64" json:"F_Sint64,omitempty"` + F_Enum *Defaults_Color `protobuf:"varint,14,opt,name=F_Enum,json=fEnum,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"` + // More fields with crazy defaults. + F_Pinf *float32 `protobuf:"fixed32,15,opt,name=F_Pinf,json=fPinf,def=inf" json:"F_Pinf,omitempty"` + F_Ninf *float32 `protobuf:"fixed32,16,opt,name=F_Ninf,json=fNinf,def=-inf" json:"F_Ninf,omitempty"` + F_Nan *float32 `protobuf:"fixed32,17,opt,name=F_Nan,json=fNan,def=nan" json:"F_Nan,omitempty"` + // Sub-message. + Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"` + // Redundant but explicit defaults. + StrZero *string `protobuf:"bytes,19,opt,name=str_zero,json=strZero,def=" json:"str_zero,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*Defaults) Descriptor() ([]byte, []int)+ + + + + + +
func (m *Defaults) GetF_Bool() bool+ + + + + + +
func (m *Defaults) GetF_Bytes() []byte+ + + + + + +
func (m *Defaults) GetF_Double() float64+ + + + + + +
func (m *Defaults) GetF_Enum() Defaults_Color+ + + + + + +
func (m *Defaults) GetF_Fixed32() uint32+ + + + + + +
func (m *Defaults) GetF_Fixed64() uint64+ + + + + + +
func (m *Defaults) GetF_Float() float32+ + + + + + +
func (m *Defaults) GetF_Int32() int32+ + + + + + +
func (m *Defaults) GetF_Int64() int64+ + + + + + +
func (m *Defaults) GetF_Nan() float32+ + + + + + +
func (m *Defaults) GetF_Ninf() float32+ + + + + + +
func (m *Defaults) GetF_Pinf() float32+ + + + + + +
func (m *Defaults) GetF_Sint32() int32+ + + + + + +
func (m *Defaults) GetF_Sint64() int64+ + + + + + +
func (m *Defaults) GetF_String() string+ + + + + + +
func (m *Defaults) GetF_Uint32() uint32+ + + + + + +
func (m *Defaults) GetF_Uint64() uint64+ + + + + + +
func (m *Defaults) GetStrZero() string+ + + + + + +
func (m *Defaults) GetSub() *SubDefaults+ + + + + + +
func (*Defaults) ProtoMessage()+ + + + + + +
func (m *Defaults) Reset()+ + + + + + +
func (m *Defaults) String() string+ + + + + + + + +
type DefaultsMessage struct { + proto.XXX_InternalExtensions `json:"-"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*DefaultsMessage) Descriptor() ([]byte, []int)+ + + + + + +
func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange+ + + + + + +
func (*DefaultsMessage) ProtoMessage()+ + + + + + +
func (m *DefaultsMessage) Reset()+ + + + + + +
func (m *DefaultsMessage) String() string+ + + + + + + + +
type DefaultsMessage_DefaultsEnum int32+ + + +
const ( + DefaultsMessage_ZERO DefaultsMessage_DefaultsEnum = 0 + DefaultsMessage_ONE DefaultsMessage_DefaultsEnum = 1 + DefaultsMessage_TWO DefaultsMessage_DefaultsEnum = 2 +)+ + + + + + + + + + + + + +
func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum+ + + + + + +
func (DefaultsMessage_DefaultsEnum) EnumDescriptor() ([]byte, []int)+ + + + + + +
func (x DefaultsMessage_DefaultsEnum) String() string+ + + + + + +
func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error+ + + + + + + + +
type Defaults_Color int32+ + + +
const ( + Defaults_RED Defaults_Color = 0 + Defaults_GREEN Defaults_Color = 1 + Defaults_BLUE Defaults_Color = 2 +)+ + +
const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN+ + + + + + + + + + + + + +
func (x Defaults_Color) Enum() *Defaults_Color+ + + + + + +
func (Defaults_Color) EnumDescriptor() ([]byte, []int)+ + + + + + +
func (x Defaults_Color) String() string+ + + + + + +
func (x *Defaults_Color) UnmarshalJSON(data []byte) error+ + + + + + + + +
type Empty struct { + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*Empty) Descriptor() ([]byte, []int)+ + + + + + +
func (*Empty) ProtoMessage()+ + + + + + +
func (m *Empty) Reset()+ + + + + + +
func (m *Empty) String() string+ + + + + + + + +
type Ext struct { + Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*Ext) Descriptor() ([]byte, []int)+ + + + + + +
func (m *Ext) GetData() string+ + + + + + +
func (*Ext) ProtoMessage()+ + + + + + +
func (m *Ext) Reset()+ + + + + + +
func (m *Ext) String() string+ + + + + + + + +
type FOO int32+ + + +
const ( + FOO_FOO1 FOO = 1 +)+ + + + + + + + + + + + + +
func (x FOO) Enum() *FOO+ + + + + + +
func (FOO) EnumDescriptor() ([]byte, []int)+ + + + + + +
func (x FOO) String() string+ + + + + + +
func (x *FOO) UnmarshalJSON(data []byte) error+ + + + + + + + +
type FloatingPoint struct { + F *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"` + Exact *bool `protobuf:"varint,2,opt,name=exact" json:"exact,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*FloatingPoint) Descriptor() ([]byte, []int)+ + + + + + +
func (m *FloatingPoint) GetExact() bool+ + + + + + +
func (m *FloatingPoint) GetF() float64+ + + + + + +
func (*FloatingPoint) ProtoMessage()+ + + + + + +
func (m *FloatingPoint) Reset()+ + + + + + +
func (m *FloatingPoint) String() string+ + + + + + + + +
type GoEnum struct { + Foo *FOO `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*GoEnum) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GoEnum) GetFoo() FOO+ + + + + + +
func (*GoEnum) ProtoMessage()+ + + + + + +
func (m *GoEnum) Reset()+ + + + + + +
func (m *GoEnum) String() string+ + + + + + + + +
type GoSkipTest struct { + SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32,json=skipInt32" json:"skip_int32,omitempty"` + SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32,json=skipFixed32" json:"skip_fixed32,omitempty"` + SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64,json=skipFixed64" json:"skip_fixed64,omitempty"` + SkipString *string `protobuf:"bytes,14,req,name=skip_string,json=skipString" json:"skip_string,omitempty"` + Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup,json=skipgroup" json:"skipgroup,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+
+For testing skipping of unrecognized fields. +Numbers are all big, larger than tag numbers in GoTestField, +the message used in the corresponding test. +
+ + + + + + + + + + + + + + +func (*GoSkipTest) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GoSkipTest) GetSkipFixed32() uint32+ + + + + + +
func (m *GoSkipTest) GetSkipFixed64() uint64+ + + + + + +
func (m *GoSkipTest) GetSkipInt32() int32+ + + + + + +
func (m *GoSkipTest) GetSkipString() string+ + + + + + +
func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup+ + + + + + +
func (*GoSkipTest) ProtoMessage()+ + + + + + +
func (m *GoSkipTest) Reset()+ + + + + + +
func (m *GoSkipTest) String() string+ + + + + + + + +
type GoSkipTest_SkipGroup struct { + GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32,json=groupInt32" json:"group_int32,omitempty"` + GroupString *string `protobuf:"bytes,17,req,name=group_string,json=groupString" json:"group_string,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*GoSkipTest_SkipGroup) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32+ + + + + + +
func (m *GoSkipTest_SkipGroup) GetGroupString() string+ + + + + + +
func (*GoSkipTest_SkipGroup) ProtoMessage()+ + + + + + +
func (m *GoSkipTest_SkipGroup) Reset()+ + + + + + +
func (m *GoSkipTest_SkipGroup) String() string+ + + + + + + + +
type GoTest struct { + // Some typical parameters + Kind *GoTest_KIND `protobuf:"varint,1,req,name=Kind,json=kind,enum=testdata.GoTest_KIND" json:"Kind,omitempty"` + Table *string `protobuf:"bytes,2,opt,name=Table,json=table" json:"Table,omitempty"` + Param *int32 `protobuf:"varint,3,opt,name=Param,json=param" json:"Param,omitempty"` + // Required, repeated and optional foreign fields. + RequiredField *GoTestField `protobuf:"bytes,4,req,name=RequiredField,json=requiredField" json:"RequiredField,omitempty"` + RepeatedField []*GoTestField `protobuf:"bytes,5,rep,name=RepeatedField,json=repeatedField" json:"RepeatedField,omitempty"` + OptionalField *GoTestField `protobuf:"bytes,6,opt,name=OptionalField,json=optionalField" json:"OptionalField,omitempty"` + // Required fields of all basic types + F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required,json=fBoolRequired" json:"F_Bool_required,omitempty"` + F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required,json=fInt32Required" json:"F_Int32_required,omitempty"` + F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required,json=fInt64Required" json:"F_Int64_required,omitempty"` + F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required,json=fFixed32Required" json:"F_Fixed32_required,omitempty"` + F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required,json=fFixed64Required" json:"F_Fixed64_required,omitempty"` + F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required,json=fUint32Required" json:"F_Uint32_required,omitempty"` + F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required,json=fUint64Required" json:"F_Uint64_required,omitempty"` + F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required,json=fFloatRequired" json:"F_Float_required,omitempty"` + F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required,json=fDoubleRequired" json:"F_Double_required,omitempty"` + F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required,json=fStringRequired" json:"F_String_required,omitempty"` + F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required,json=fBytesRequired" json:"F_Bytes_required,omitempty"` + F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required,json=fSint32Required" json:"F_Sint32_required,omitempty"` + F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required,json=fSint64Required" json:"F_Sint64_required,omitempty"` + // Repeated fields of all basic types + F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated,json=fBoolRepeated" json:"F_Bool_repeated,omitempty"` + F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated,json=fInt32Repeated" json:"F_Int32_repeated,omitempty"` + F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated,json=fInt64Repeated" json:"F_Int64_repeated,omitempty"` + F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated,json=fFixed32Repeated" json:"F_Fixed32_repeated,omitempty"` + F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated,json=fFixed64Repeated" json:"F_Fixed64_repeated,omitempty"` + F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated,json=fUint32Repeated" json:"F_Uint32_repeated,omitempty"` + F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated,json=fUint64Repeated" json:"F_Uint64_repeated,omitempty"` + F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated,json=fFloatRepeated" json:"F_Float_repeated,omitempty"` + F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated,json=fDoubleRepeated" json:"F_Double_repeated,omitempty"` + F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated,json=fStringRepeated" json:"F_String_repeated,omitempty"` + F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated,json=fBytesRepeated" json:"F_Bytes_repeated,omitempty"` + F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated,json=fSint32Repeated" json:"F_Sint32_repeated,omitempty"` + F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated,json=fSint64Repeated" json:"F_Sint64_repeated,omitempty"` + // Optional fields of all basic types + F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional,json=fBoolOptional" json:"F_Bool_optional,omitempty"` + F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional,json=fInt32Optional" json:"F_Int32_optional,omitempty"` + F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional,json=fInt64Optional" json:"F_Int64_optional,omitempty"` + F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional,json=fFixed32Optional" json:"F_Fixed32_optional,omitempty"` + F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional,json=fFixed64Optional" json:"F_Fixed64_optional,omitempty"` + F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional,json=fUint32Optional" json:"F_Uint32_optional,omitempty"` + F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional,json=fUint64Optional" json:"F_Uint64_optional,omitempty"` + F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional,json=fFloatOptional" json:"F_Float_optional,omitempty"` + F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional,json=fDoubleOptional" json:"F_Double_optional,omitempty"` + F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional,json=fStringOptional" json:"F_String_optional,omitempty"` + F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional,json=fBytesOptional" json:"F_Bytes_optional,omitempty"` + F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional,json=fSint32Optional" json:"F_Sint32_optional,omitempty"` + F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional,json=fSint64Optional" json:"F_Sint64_optional,omitempty"` + // Default-valued fields of all basic types + F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,json=fBoolDefaulted,def=1" json:"F_Bool_defaulted,omitempty"` + F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,json=fInt32Defaulted,def=32" json:"F_Int32_defaulted,omitempty"` + F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,json=fInt64Defaulted,def=64" json:"F_Int64_defaulted,omitempty"` + F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,json=fFixed32Defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"` + F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,json=fFixed64Defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"` + F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,json=fUint32Defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"` + F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,json=fUint64Defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"` + F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,json=fFloatDefaulted,def=314159" json:"F_Float_defaulted,omitempty"` + F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,json=fDoubleDefaulted,def=271828" json:"F_Double_defaulted,omitempty"` + F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,json=fStringDefaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"` + F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,json=fBytesDefaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"` + F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,json=fSint32Defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"` + F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,json=fSint64Defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"` + // Packed repeated fields (no string or bytes). + F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed,json=fBoolRepeatedPacked" json:"F_Bool_repeated_packed,omitempty"` + F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed,json=fInt32RepeatedPacked" json:"F_Int32_repeated_packed,omitempty"` + F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed,json=fInt64RepeatedPacked" json:"F_Int64_repeated_packed,omitempty"` + F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed,json=fFixed32RepeatedPacked" json:"F_Fixed32_repeated_packed,omitempty"` + F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed,json=fFixed64RepeatedPacked" json:"F_Fixed64_repeated_packed,omitempty"` + F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed,json=fUint32RepeatedPacked" json:"F_Uint32_repeated_packed,omitempty"` + F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed,json=fUint64RepeatedPacked" json:"F_Uint64_repeated_packed,omitempty"` + F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed,json=fFloatRepeatedPacked" json:"F_Float_repeated_packed,omitempty"` + F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed,json=fDoubleRepeatedPacked" json:"F_Double_repeated_packed,omitempty"` + F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed,json=fSint32RepeatedPacked" json:"F_Sint32_repeated_packed,omitempty"` + F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed,json=fSint64RepeatedPacked" json:"F_Sint64_repeated_packed,omitempty"` + Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup,json=requiredgroup" json:"requiredgroup,omitempty"` + Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup,json=repeatedgroup" json:"repeatedgroup,omitempty"` + Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup,json=optionalgroup" json:"optionalgroup,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*GoTest) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GoTest) GetF_BoolDefaulted() bool+ + + + + + +
func (m *GoTest) GetF_BoolOptional() bool+ + + + + + +
func (m *GoTest) GetF_BoolRepeated() []bool+ + + + + + +
func (m *GoTest) GetF_BoolRepeatedPacked() []bool+ + + + + + +
func (m *GoTest) GetF_BoolRequired() bool+ + + + + + +
func (m *GoTest) GetF_BytesDefaulted() []byte+ + + + + + +
func (m *GoTest) GetF_BytesOptional() []byte+ + + + + + +
func (m *GoTest) GetF_BytesRepeated() [][]byte+ + + + + + +
func (m *GoTest) GetF_BytesRequired() []byte+ + + + + + +
func (m *GoTest) GetF_DoubleDefaulted() float64+ + + + + + +
func (m *GoTest) GetF_DoubleOptional() float64+ + + + + + +
func (m *GoTest) GetF_DoubleRepeated() []float64+ + + + + + +
func (m *GoTest) GetF_DoubleRepeatedPacked() []float64+ + + + + + +
func (m *GoTest) GetF_DoubleRequired() float64+ + + + + + +
func (m *GoTest) GetF_Fixed32Defaulted() uint32+ + + + + + +
func (m *GoTest) GetF_Fixed32Optional() uint32+ + + + + + +
func (m *GoTest) GetF_Fixed32Repeated() []uint32+ + + + + + +
func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32+ + + + + + +
func (m *GoTest) GetF_Fixed32Required() uint32+ + + + + + +
func (m *GoTest) GetF_Fixed64Defaulted() uint64+ + + + + + +
func (m *GoTest) GetF_Fixed64Optional() uint64+ + + + + + +
func (m *GoTest) GetF_Fixed64Repeated() []uint64+ + + + + + +
func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64+ + + + + + +
func (m *GoTest) GetF_Fixed64Required() uint64+ + + + + + +
func (m *GoTest) GetF_FloatDefaulted() float32+ + + + + + +
func (m *GoTest) GetF_FloatOptional() float32+ + + + + + +
func (m *GoTest) GetF_FloatRepeated() []float32+ + + + + + +
func (m *GoTest) GetF_FloatRepeatedPacked() []float32+ + + + + + +
func (m *GoTest) GetF_FloatRequired() float32+ + + + + + +
func (m *GoTest) GetF_Int32Defaulted() int32+ + + + + + +
func (m *GoTest) GetF_Int32Optional() int32+ + + + + + +
func (m *GoTest) GetF_Int32Repeated() []int32+ + + + + + +
func (m *GoTest) GetF_Int32RepeatedPacked() []int32+ + + + + + +
func (m *GoTest) GetF_Int32Required() int32+ + + + + + +
func (m *GoTest) GetF_Int64Defaulted() int64+ + + + + + +
func (m *GoTest) GetF_Int64Optional() int64+ + + + + + +
func (m *GoTest) GetF_Int64Repeated() []int64+ + + + + + +
func (m *GoTest) GetF_Int64RepeatedPacked() []int64+ + + + + + +
func (m *GoTest) GetF_Int64Required() int64+ + + + + + +
func (m *GoTest) GetF_Sint32Defaulted() int32+ + + + + + +
func (m *GoTest) GetF_Sint32Optional() int32+ + + + + + +
func (m *GoTest) GetF_Sint32Repeated() []int32+ + + + + + +
func (m *GoTest) GetF_Sint32RepeatedPacked() []int32+ + + + + + +
func (m *GoTest) GetF_Sint32Required() int32+ + + + + + +
func (m *GoTest) GetF_Sint64Defaulted() int64+ + + + + + +
func (m *GoTest) GetF_Sint64Optional() int64+ + + + + + +
func (m *GoTest) GetF_Sint64Repeated() []int64+ + + + + + +
func (m *GoTest) GetF_Sint64RepeatedPacked() []int64+ + + + + + +
func (m *GoTest) GetF_Sint64Required() int64+ + + + + + +
func (m *GoTest) GetF_StringDefaulted() string+ + + + + + +
func (m *GoTest) GetF_StringOptional() string+ + + + + + +
func (m *GoTest) GetF_StringRepeated() []string+ + + + + + +
func (m *GoTest) GetF_StringRequired() string+ + + + + + +
func (m *GoTest) GetF_Uint32Defaulted() uint32+ + + + + + +
func (m *GoTest) GetF_Uint32Optional() uint32+ + + + + + +
func (m *GoTest) GetF_Uint32Repeated() []uint32+ + + + + + +
func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32+ + + + + + +
func (m *GoTest) GetF_Uint32Required() uint32+ + + + + + +
func (m *GoTest) GetF_Uint64Defaulted() uint64+ + + + + + +
func (m *GoTest) GetF_Uint64Optional() uint64+ + + + + + +
func (m *GoTest) GetF_Uint64Repeated() []uint64+ + + + + + +
func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64+ + + + + + +
func (m *GoTest) GetF_Uint64Required() uint64+ + + + + + +
func (m *GoTest) GetKind() GoTest_KIND+ + + + + + +
func (m *GoTest) GetOptionalField() *GoTestField+ + + + + + +
func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup+ + + + + + +
func (m *GoTest) GetParam() int32+ + + + + + +
func (m *GoTest) GetRepeatedField() []*GoTestField+ + + + + + +
func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup+ + + + + + +
func (m *GoTest) GetRequiredField() *GoTestField+ + + + + + +
func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup+ + + + + + +
func (m *GoTest) GetTable() string+ + + + + + +
func (*GoTest) ProtoMessage()+ + + + + + +
func (m *GoTest) Reset()+ + + + + + +
func (m *GoTest) String() string+ + + + + + + + +
type GoTestField struct { + Label *string `protobuf:"bytes,1,req,name=Label,json=label" json:"Label,omitempty"` + Type *string `protobuf:"bytes,2,req,name=Type,json=type" json:"Type,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*GoTestField) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GoTestField) GetLabel() string+ + + + + + +
func (m *GoTestField) GetType() string+ + + + + + +
func (*GoTestField) ProtoMessage()+ + + + + + +
func (m *GoTestField) Reset()+ + + + + + +
func (m *GoTestField) String() string+ + + + + + + + +
type GoTestRequiredGroupField struct { + Group *GoTestRequiredGroupField_Group `protobuf:"group,1,req,name=Group,json=group" json:"group,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+
+For testing a group containing a required field. +
+ + + + + + + + + + + + + + +func (*GoTestRequiredGroupField) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GoTestRequiredGroupField) GetGroup() *GoTestRequiredGroupField_Group+ + + + + + +
func (*GoTestRequiredGroupField) ProtoMessage()+ + + + + + +
func (m *GoTestRequiredGroupField) Reset()+ + + + + + +
func (m *GoTestRequiredGroupField) String() string+ + + + + + + + +
type GoTestRequiredGroupField_Group struct { + Field *int32 `protobuf:"varint,2,req,name=Field,json=field" json:"Field,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*GoTestRequiredGroupField_Group) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GoTestRequiredGroupField_Group) GetField() int32+ + + + + + +
func (*GoTestRequiredGroupField_Group) ProtoMessage()+ + + + + + +
func (m *GoTestRequiredGroupField_Group) Reset()+ + + + + + +
func (m *GoTestRequiredGroupField_Group) String() string+ + + + + + + + +
type GoTest_KIND int32+
+An enum, for completeness. +
+ + + +const ( + GoTest_VOID GoTest_KIND = 0 + // Basic types + GoTest_BOOL GoTest_KIND = 1 + GoTest_BYTES GoTest_KIND = 2 + GoTest_FINGERPRINT GoTest_KIND = 3 + GoTest_FLOAT GoTest_KIND = 4 + GoTest_INT GoTest_KIND = 5 + GoTest_STRING GoTest_KIND = 6 + GoTest_TIME GoTest_KIND = 7 + // Groupings + GoTest_TUPLE GoTest_KIND = 8 + GoTest_ARRAY GoTest_KIND = 9 + GoTest_MAP GoTest_KIND = 10 + // Table types + GoTest_TABLE GoTest_KIND = 11 + // Functions + GoTest_FUNCTION GoTest_KIND = 12 +)+ + + + + + + + + + + + + +
func (x GoTest_KIND) Enum() *GoTest_KIND+ + + + + + +
func (GoTest_KIND) EnumDescriptor() ([]byte, []int)+ + + + + + +
func (x GoTest_KIND) String() string+ + + + + + +
func (x *GoTest_KIND) UnmarshalJSON(data []byte) error+ + + + + + + + +
type GoTest_OptionalGroup struct { + RequiredField *string `protobuf:"bytes,91,req,name=RequiredField,json=requiredField" json:"RequiredField,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*GoTest_OptionalGroup) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GoTest_OptionalGroup) GetRequiredField() string+ + + + + + +
func (*GoTest_OptionalGroup) ProtoMessage()+ + + + + + +
func (m *GoTest_OptionalGroup) Reset()+ + + + + + +
func (m *GoTest_OptionalGroup) String() string+ + + + + + + + +
type GoTest_RepeatedGroup struct { + RequiredField *string `protobuf:"bytes,81,req,name=RequiredField,json=requiredField" json:"RequiredField,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*GoTest_RepeatedGroup) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GoTest_RepeatedGroup) GetRequiredField() string+ + + + + + +
func (*GoTest_RepeatedGroup) ProtoMessage()+ + + + + + +
func (m *GoTest_RepeatedGroup) Reset()+ + + + + + +
func (m *GoTest_RepeatedGroup) String() string+ + + + + + + + +
type GoTest_RequiredGroup struct { + RequiredField *string `protobuf:"bytes,71,req,name=RequiredField,json=requiredField" json:"RequiredField,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+
+Required, repeated, and optional groups. +
+ + + + + + + + + + + + + + +func (*GoTest_RequiredGroup) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GoTest_RequiredGroup) GetRequiredField() string+ + + + + + +
func (*GoTest_RequiredGroup) ProtoMessage()+ + + + + + +
func (m *GoTest_RequiredGroup) Reset()+ + + + + + +
func (m *GoTest_RequiredGroup) String() string+ + + + + + + + +
type GroupNew struct { + G *GroupNew_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*GroupNew) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GroupNew) GetG() *GroupNew_G+ + + + + + +
func (*GroupNew) ProtoMessage()+ + + + + + +
func (m *GroupNew) Reset()+ + + + + + +
func (m *GroupNew) String() string+ + + + + + + + +
type GroupNew_G struct { + X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` + Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*GroupNew_G) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GroupNew_G) GetX() int32+ + + + + + +
func (m *GroupNew_G) GetY() int32+ + + + + + +
func (*GroupNew_G) ProtoMessage()+ + + + + + +
func (m *GroupNew_G) Reset()+ + + + + + +
func (m *GroupNew_G) String() string+ + + + + + + + +
type GroupOld struct { + G *GroupOld_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*GroupOld) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GroupOld) GetG() *GroupOld_G+ + + + + + +
func (*GroupOld) ProtoMessage()+ + + + + + +
func (m *GroupOld) Reset()+ + + + + + +
func (m *GroupOld) String() string+ + + + + + + + +
type GroupOld_G struct { + X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*GroupOld_G) Descriptor() ([]byte, []int)+ + + + + + +
func (m *GroupOld_G) GetX() int32+ + + + + + +
func (*GroupOld_G) ProtoMessage()+ + + + + + +
func (m *GroupOld_G) Reset()+ + + + + + +
func (m *GroupOld_G) String() string+ + + + + + + + +
type InnerMessage struct { + Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"` + Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"` + Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*InnerMessage) Descriptor() ([]byte, []int)+ + + + + + +
func (m *InnerMessage) GetConnected() bool+ + + + + + +
func (m *InnerMessage) GetHost() string+ + + + + + +
func (m *InnerMessage) GetPort() int32+ + + + + + +
func (*InnerMessage) ProtoMessage()+ + + + + + +
func (m *InnerMessage) Reset()+ + + + + + +
func (m *InnerMessage) String() string+ + + + + + + + +
type MaxTag struct { + // Maximum possible tag number. + LastField *string `protobuf:"bytes,536870911,opt,name=last_field,json=lastField" json:"last_field,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*MaxTag) Descriptor() ([]byte, []int)+ + + + + + +
func (m *MaxTag) GetLastField() string+ + + + + + +
func (*MaxTag) ProtoMessage()+ + + + + + +
func (m *MaxTag) Reset()+ + + + + + +
func (m *MaxTag) String() string+ + + + + + + + +
type MessageList struct { + Message []*MessageList_Message `protobuf:"group,1,rep,name=Message,json=message" json:"message,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*MessageList) Descriptor() ([]byte, []int)+ + + + + + +
func (m *MessageList) GetMessage() []*MessageList_Message+ + + + + + +
func (*MessageList) ProtoMessage()+ + + + + + +
func (m *MessageList) Reset()+ + + + + + +
func (m *MessageList) String() string+ + + + + + + + +
type MessageList_Message struct { + Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"` + Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*MessageList_Message) Descriptor() ([]byte, []int)+ + + + + + +
func (m *MessageList_Message) GetCount() int32+ + + + + + +
func (m *MessageList_Message) GetName() string+ + + + + + +
func (*MessageList_Message) ProtoMessage()+ + + + + + +
func (m *MessageList_Message) Reset()+ + + + + + +
func (m *MessageList_Message) String() string+ + + + + + + + +
type MessageWithMap struct { + NameMapping map[int32]string `protobuf:"bytes,1,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + MsgMapping map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + ByteMapping map[bool][]byte `protobuf:"bytes,3,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + StrToStr map[string]string `protobuf:"bytes,4,rep,name=str_to_str,json=strToStr" json:"str_to_str,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*MessageWithMap) Descriptor() ([]byte, []int)+ + + + + + +
func (m *MessageWithMap) GetByteMapping() map[bool][]byte+ + + + + + +
func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint+ + + + + + +
func (m *MessageWithMap) GetNameMapping() map[int32]string+ + + + + + +
func (m *MessageWithMap) GetStrToStr() map[string]string+ + + + + + +
func (*MessageWithMap) ProtoMessage()+ + + + + + +
func (m *MessageWithMap) Reset()+ + + + + + +
func (m *MessageWithMap) String() string+ + + + + + + + +
type MoreRepeated struct { + Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"` + BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed,json=boolsPacked" json:"bools_packed,omitempty"` + Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"` + IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed,json=intsPacked" json:"ints_packed,omitempty"` + Int64SPacked []int64 `protobuf:"varint,7,rep,packed,name=int64s_packed,json=int64sPacked" json:"int64s_packed,omitempty"` + Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"` + Fixeds []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*MoreRepeated) Descriptor() ([]byte, []int)+ + + + + + +
func (m *MoreRepeated) GetBools() []bool+ + + + + + +
func (m *MoreRepeated) GetBoolsPacked() []bool+ + + + + + +
func (m *MoreRepeated) GetFixeds() []uint32+ + + + + + +
func (m *MoreRepeated) GetInt64SPacked() []int64+ + + + + + +
func (m *MoreRepeated) GetInts() []int32+ + + + + + +
func (m *MoreRepeated) GetIntsPacked() []int32+ + + + + + +
func (m *MoreRepeated) GetStrings() []string+ + + + + + +
func (*MoreRepeated) ProtoMessage()+ + + + + + +
func (m *MoreRepeated) Reset()+ + + + + + +
func (m *MoreRepeated) String() string+ + + + + + + + +
type MyMessage struct { + Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"` + Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` + Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"` + Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"` + Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"` + Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"` + WeMustGoDeeper *RequiredInnerMessage `protobuf:"bytes,13,opt,name=we_must_go_deeper,json=weMustGoDeeper" json:"we_must_go_deeper,omitempty"` + RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner,json=repInner" json:"rep_inner,omitempty"` + Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"` + Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"` + // This field becomes [][]byte in the generated code. + RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes,json=repBytes" json:"rep_bytes,omitempty"` + Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"` + proto.XXX_InternalExtensions `json:"-"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*MyMessage) Descriptor() ([]byte, []int)+ + + + + + +
func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange+ + + + + + +
func (m *MyMessage) GetBigfloat() float64+ + + + + + +
func (m *MyMessage) GetBikeshed() MyMessage_Color+ + + + + + +
func (m *MyMessage) GetCount() int32+ + + + + + +
func (m *MyMessage) GetInner() *InnerMessage+ + + + + + +
func (m *MyMessage) GetName() string+ + + + + + +
func (m *MyMessage) GetOthers() []*OtherMessage+ + + + + + +
func (m *MyMessage) GetPet() []string+ + + + + + +
func (m *MyMessage) GetQuote() string+ + + + + + +
func (m *MyMessage) GetRepBytes() [][]byte+ + + + + + +
func (m *MyMessage) GetRepInner() []*InnerMessage+ + + + + + +
func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup+ + + + + + +
func (m *MyMessage) GetWeMustGoDeeper() *RequiredInnerMessage+ + + + + + +
func (*MyMessage) ProtoMessage()+ + + + + + +
func (m *MyMessage) Reset()+ + + + + + +
func (m *MyMessage) String() string+ + + + + + + + +
type MyMessageSet struct { + proto.XXX_InternalExtensions `json:"-"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*MyMessageSet) Descriptor() ([]byte, []int)+ + + + + + +
func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange+ + + + + + +
func (m *MyMessageSet) Marshal() ([]byte, error)+ + + + + + +
func (m *MyMessageSet) MarshalJSON() ([]byte, error)+ + + + + + +
func (*MyMessageSet) ProtoMessage()+ + + + + + +
func (m *MyMessageSet) Reset()+ + + + + + +
func (m *MyMessageSet) String() string+ + + + + + +
func (m *MyMessageSet) Unmarshal(buf []byte) error+ + + + + + +
func (m *MyMessageSet) UnmarshalJSON(buf []byte) error+ + + + + + + + +
type MyMessage_Color int32+ + + +
const ( + MyMessage_RED MyMessage_Color = 0 + MyMessage_GREEN MyMessage_Color = 1 + MyMessage_BLUE MyMessage_Color = 2 +)+ + + + + + + + + + + + + +
func (x MyMessage_Color) Enum() *MyMessage_Color+ + + + + + +
func (MyMessage_Color) EnumDescriptor() ([]byte, []int)+ + + + + + +
func (x MyMessage_Color) String() string+ + + + + + +
func (x *MyMessage_Color) UnmarshalJSON(data []byte) error+ + + + + + + + +
type MyMessage_SomeGroup struct { + GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*MyMessage_SomeGroup) Descriptor() ([]byte, []int)+ + + + + + +
func (m *MyMessage_SomeGroup) GetGroupField() int32+ + + + + + +
func (*MyMessage_SomeGroup) ProtoMessage()+ + + + + + +
func (m *MyMessage_SomeGroup) Reset()+ + + + + + +
func (m *MyMessage_SomeGroup) String() string+ + + + + + + + +
type NewMessage struct { + Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` + // This is an int32 in OldMessage. + Num *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+
+NewMessage is wire compatible with OldMessage; +imagine it as a future version. +
+ + + + + + + + + + + + + + +func (*NewMessage) Descriptor() ([]byte, []int)+ + + + + + +
func (m *NewMessage) GetNested() *NewMessage_Nested+ + + + + + +
func (m *NewMessage) GetNum() int64+ + + + + + +
func (*NewMessage) ProtoMessage()+ + + + + + +
func (m *NewMessage) Reset()+ + + + + + +
func (m *NewMessage) String() string+ + + + + + + + +
type NewMessage_Nested struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + FoodGroup *string `protobuf:"bytes,2,opt,name=food_group,json=foodGroup" json:"food_group,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*NewMessage_Nested) Descriptor() ([]byte, []int)+ + + + + + +
func (m *NewMessage_Nested) GetFoodGroup() string+ + + + + + +
func (m *NewMessage_Nested) GetName() string+ + + + + + +
func (*NewMessage_Nested) ProtoMessage()+ + + + + + +
func (m *NewMessage_Nested) Reset()+ + + + + + +
func (m *NewMessage_Nested) String() string+ + + + + + + + +
type NonPackedTest struct { + A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+
+For testing packed/non-packed decoder switching. +A serialized instance of one should be deserializable as the other. +
+ + + + + + + + + + + + + + +func (*NonPackedTest) Descriptor() ([]byte, []int)+ + + + + + +
func (m *NonPackedTest) GetA() []int32+ + + + + + +
func (*NonPackedTest) ProtoMessage()+ + + + + + +
func (m *NonPackedTest) Reset()+ + + + + + +
func (m *NonPackedTest) String() string+ + + + + + + + +
type OldMessage struct { + Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` + Num *int32 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*OldMessage) Descriptor() ([]byte, []int)+ + + + + + +
func (m *OldMessage) GetNested() *OldMessage_Nested+ + + + + + +
func (m *OldMessage) GetNum() int32+ + + + + + +
func (*OldMessage) ProtoMessage()+ + + + + + +
func (m *OldMessage) Reset()+ + + + + + +
func (m *OldMessage) String() string+ + + + + + + + +
type OldMessage_Nested struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*OldMessage_Nested) Descriptor() ([]byte, []int)+ + + + + + +
func (m *OldMessage_Nested) GetName() string+ + + + + + +
func (*OldMessage_Nested) ProtoMessage()+ + + + + + +
func (m *OldMessage_Nested) Reset()+ + + + + + +
func (m *OldMessage_Nested) String() string+ + + + + + + + +
type Oneof struct { + // Types that are valid to be assigned to Union: + // *Oneof_F_Bool + // *Oneof_F_Int32 + // *Oneof_F_Int64 + // *Oneof_F_Fixed32 + // *Oneof_F_Fixed64 + // *Oneof_F_Uint32 + // *Oneof_F_Uint64 + // *Oneof_F_Float + // *Oneof_F_Double + // *Oneof_F_String + // *Oneof_F_Bytes + // *Oneof_F_Sint32 + // *Oneof_F_Sint64 + // *Oneof_F_Enum + // *Oneof_F_Message + // *Oneof_FGroup + // *Oneof_F_Largest_Tag + Union isOneof_Union `protobuf_oneof:"union"` + // Types that are valid to be assigned to Tormato: + // *Oneof_Value + Tormato isOneof_Tormato `protobuf_oneof:"tormato"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*Oneof) Descriptor() ([]byte, []int)+ + + + + + +
func (m *Oneof) GetFGroup() *Oneof_F_Group+ + + + + + +
func (m *Oneof) GetF_Bool() bool+ + + + + + +
func (m *Oneof) GetF_Bytes() []byte+ + + + + + +
func (m *Oneof) GetF_Double() float64+ + + + + + +
func (m *Oneof) GetF_Enum() MyMessage_Color+ + + + + + +
func (m *Oneof) GetF_Fixed32() uint32+ + + + + + +
func (m *Oneof) GetF_Fixed64() uint64+ + + + + + +
func (m *Oneof) GetF_Float() float32+ + + + + + +
func (m *Oneof) GetF_Int32() int32+ + + + + + +
func (m *Oneof) GetF_Int64() int64+ + + + + + +
func (m *Oneof) GetF_Largest_Tag() int32+ + + + + + +
func (m *Oneof) GetF_Message() *GoTestField+ + + + + + +
func (m *Oneof) GetF_Sint32() int32+ + + + + + +
func (m *Oneof) GetF_Sint64() int64+ + + + + + +
func (m *Oneof) GetF_String() string+ + + + + + +
func (m *Oneof) GetF_Uint32() uint32+ + + + + + +
func (m *Oneof) GetF_Uint64() uint64+ + + + + + +
func (m *Oneof) GetTormato() isOneof_Tormato+ + + + + + +
func (m *Oneof) GetUnion() isOneof_Union+ + + + + + +
func (m *Oneof) GetValue() int32+ + + + + + +
func (*Oneof) ProtoMessage()+ + + + + + +
func (m *Oneof) Reset()+ + + + + + +
func (m *Oneof) String() string+ + + + + + +
func (*Oneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{})+
+XXX_OneofFuncs is for the internal use of the proto package. +
+ + + + + + + + +type Oneof_FGroup struct { + FGroup *Oneof_F_Group `protobuf:"group,16,opt,name=F_Group,json=fGroup,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Bool struct { + F_Bool bool `protobuf:"varint,1,opt,name=F_Bool,json=fBool,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Bytes struct { + F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=fBytes,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Double struct { + F_Double float64 `protobuf:"fixed64,9,opt,name=F_Double,json=fDouble,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Enum struct { + F_Enum MyMessage_Color `protobuf:"varint,14,opt,name=F_Enum,json=fEnum,enum=testdata.MyMessage_Color,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Fixed32 struct { + F_Fixed32 uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=fFixed32,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Fixed64 struct { + F_Fixed64 uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=fFixed64,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Float struct { + F_Float float32 `protobuf:"fixed32,8,opt,name=F_Float,json=fFloat,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Group struct { + X *int32 `protobuf:"varint,17,opt,name=x" json:"x,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*Oneof_F_Group) Descriptor() ([]byte, []int)+ + + + + + +
func (m *Oneof_F_Group) GetX() int32+ + + + + + +
func (*Oneof_F_Group) ProtoMessage()+ + + + + + +
func (m *Oneof_F_Group) Reset()+ + + + + + +
func (m *Oneof_F_Group) String() string+ + + + + + + + +
type Oneof_F_Int32 struct { + F_Int32 int32 `protobuf:"varint,2,opt,name=F_Int32,json=fInt32,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Int64 struct { + F_Int64 int64 `protobuf:"varint,3,opt,name=F_Int64,json=fInt64,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Largest_Tag struct { + F_Largest_Tag int32 `protobuf:"varint,536870911,opt,name=F_Largest_Tag,json=fLargestTag,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Message struct { + F_Message *GoTestField `protobuf:"bytes,15,opt,name=F_Message,json=fMessage,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Sint32 struct { + F_Sint32 int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=fSint32,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Sint64 struct { + F_Sint64 int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=fSint64,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_String struct { + F_String string `protobuf:"bytes,10,opt,name=F_String,json=fString,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Uint32 struct { + F_Uint32 uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=fUint32,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_F_Uint64 struct { + F_Uint64 uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=fUint64,oneof"` +}+ + + + + + + + + + + + + + + + +
type Oneof_Value struct { + Value int32 `protobuf:"varint,100,opt,name=value,oneof"` +}+ + + + + + + + + + + + + + + + +
type OtherMessage struct { + Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` + Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` + Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"` + Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"` + proto.XXX_InternalExtensions `json:"-"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*OtherMessage) Descriptor() ([]byte, []int)+ + + + + + +
func (*OtherMessage) ExtensionRangeArray() []proto.ExtensionRange+ + + + + + +
func (m *OtherMessage) GetInner() *InnerMessage+ + + + + + +
func (m *OtherMessage) GetKey() int64+ + + + + + +
func (m *OtherMessage) GetValue() []byte+ + + + + + +
func (m *OtherMessage) GetWeight() float32+ + + + + + +
func (*OtherMessage) ProtoMessage()+ + + + + + +
func (m *OtherMessage) Reset()+ + + + + + +
func (m *OtherMessage) String() string+ + + + + + + + +
type PackedTest struct { + B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*PackedTest) Descriptor() ([]byte, []int)+ + + + + + +
func (m *PackedTest) GetB() []int32+ + + + + + +
func (*PackedTest) ProtoMessage()+ + + + + + +
func (m *PackedTest) Reset()+ + + + + + +
func (m *PackedTest) String() string+ + + + + + + + +
type RepeatedEnum struct { + Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*RepeatedEnum) Descriptor() ([]byte, []int)+ + + + + + +
func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color+ + + + + + +
func (*RepeatedEnum) ProtoMessage()+ + + + + + +
func (m *RepeatedEnum) Reset()+ + + + + + +
func (m *RepeatedEnum) String() string+ + + + + + + + +
type RepeatedEnum_Color int32+ + + +
const ( + RepeatedEnum_RED RepeatedEnum_Color = 1 +)+ + + + + + + + + + + + + +
func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color+ + + + + + +
func (RepeatedEnum_Color) EnumDescriptor() ([]byte, []int)+ + + + + + +
func (x RepeatedEnum_Color) String() string+ + + + + + +
func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error+ + + + + + + + +
type RequiredInnerMessage struct { + LeoFinallyWonAnOscar *InnerMessage `protobuf:"bytes,1,req,name=leo_finally_won_an_oscar,json=leoFinallyWonAnOscar" json:"leo_finally_won_an_oscar,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*RequiredInnerMessage) Descriptor() ([]byte, []int)+ + + + + + +
func (m *RequiredInnerMessage) GetLeoFinallyWonAnOscar() *InnerMessage+ + + + + + +
func (*RequiredInnerMessage) ProtoMessage()+ + + + + + +
func (m *RequiredInnerMessage) Reset()+ + + + + + +
func (m *RequiredInnerMessage) String() string+ + + + + + + + +
type Strings struct { + StringField *string `protobuf:"bytes,1,opt,name=string_field,json=stringField" json:"string_field,omitempty"` + BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field,json=bytesField" json:"bytes_field,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*Strings) Descriptor() ([]byte, []int)+ + + + + + +
func (m *Strings) GetBytesField() []byte+ + + + + + +
func (m *Strings) GetStringField() string+ + + + + + +
func (*Strings) ProtoMessage()+ + + + + + +
func (m *Strings) Reset()+ + + + + + +
func (m *Strings) String() string+ + + + + + + + +
type SubDefaults struct { + N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (*SubDefaults) Descriptor() ([]byte, []int)+ + + + + + +
func (m *SubDefaults) GetN() int64+ + + + + + +
func (*SubDefaults) ProtoMessage()+ + + + + + +
func (m *SubDefaults) Reset()+ + + + + + +
func (m *SubDefaults) String() string+ + + + + + + + + + + + + + + + + + +
var ( + // ErrCorrupt reports that the input is invalid. + ErrCorrupt = errors.New("snappy: corrupt input") + // ErrTooLarge reports that the uncompressed length is too large. + ErrTooLarge = errors.New("snappy: decoded block is too large") + // ErrUnsupported reports that the input isn't supported. + ErrUnsupported = errors.New("snappy: unsupported input") +)+ + + + + + +
func Decode(dst, src []byte) ([]byte, error)+
+Decode returns the decoded form of src. The returned slice may be a sub- +slice of dst if dst was large enough to hold the entire decoded block. +Otherwise, a newly allocated slice will be returned. +
++The dst and src must not overlap. It is valid to pass a nil dst. +
+ + + + + + + +func DecodedLen(src []byte) (int, error)+
+DecodedLen returns the length of the decoded block. +
+ + + + + + + +func Encode(dst, src []byte) []byte+
+Encode returns the encoded form of src. The returned slice may be a sub- +slice of dst if dst was large enough to hold the entire encoded block. +Otherwise, a newly allocated slice will be returned. +
++The dst and src must not overlap. It is valid to pass a nil dst. +
+ + + + + + + +func MaxEncodedLen(srcLen int) int+
+MaxEncodedLen returns the maximum length of a snappy block, given its +uncompressed length. +
++It will return a negative value if srcLen is too large to encode. +
+ + + + + + + + +type Reader struct {
+ // contains filtered or unexported fields
+}
+ +Reader is an io.Reader that can read Snappy-compressed bytes. +
+ + + + + + + + + + + + +func NewReader(r io.Reader) *Reader+
+NewReader returns a new Reader that decompresses from r, using the framing +format described at +https://github.com/google/snappy/blob/master/framing_format.txt +
+ + + + + + + +func (r *Reader) Read(p []byte) (int, error)+
+Read satisfies the io.Reader interface. +
+ + + + + + +func (r *Reader) Reset(reader io.Reader)+
+Reset discards any buffered data, resets all state, and switches the Snappy +reader to read from r. This permits reusing a Reader rather than allocating +a new one. +
+ + + + + + + + +type Writer struct {
+ // contains filtered or unexported fields
+}
+ +Writer is an io.Writer than can write Snappy-compressed bytes. +
+ + + + + + + + + + + + +func NewBufferedWriter(w io.Writer) *Writer+
+NewBufferedWriter returns a new Writer that compresses to w, using the +framing format described at +https://github.com/google/snappy/blob/master/framing_format.txt +
++The Writer returned buffers writes. Users must call Close to guarantee all +data has been forwarded to the underlying io.Writer. They may also call +Flush zero or more times before calling Close. +
+ + + + + +func NewWriter(w io.Writer) *Writer+
+NewWriter returns a new Writer that compresses to w. +
++The Writer returned does not buffer writes. There is no need to Flush or +Close such a Writer. +
++Deprecated: the Writer returned is not suitable for many small writes, only +for few large writes. Use NewBufferedWriter instead, which is efficient +regardless of the frequency and shape of the writes, and remember to Close +that Writer when done. +
+ + + + + + + +func (w *Writer) Close() error+
+Close calls Flush and then closes the Writer. +
+ + + + + + +func (w *Writer) Flush() error+
+Flush flushes the Writer to its underlying io.Writer. +
+ + + + + + +func (w *Writer) Reset(writer io.Writer)+
+Reset discards the writer's state and switches the Snappy writer to write to +w. This permits reusing a Writer rather than allocating a new one. +
+ + + + + + +func (w *Writer) Write(p []byte) (nRet int, errRet error)+
+Write satisfies the io.Writer interface. +
+ + + + + + + + + + + + + + + + + + +const (
+ DefaultFreeListSize = 32
+)
+
+
+
+
+
+
+
+
+ type BTree struct {
+ // contains filtered or unexported fields
+}
+ +BTree is an implementation of a B-Tree. +
++BTree stores Item instances in an ordered structure, allowing easy insertion, +removal, and iteration. +
++Write operations are not safe for concurrent mutation by multiple +goroutines, but Read operations are. +
+ + + + + + +▹ Example
+func New(degree int) *BTree+
+New creates a new B-Tree with the given degree. +
++New(2), for example, will create a 2-3-4 tree (each node contains 1-3 items +and 2-4 children). +
+ + + + + +func NewWithFreeList(degree int, f *FreeList) *BTree+
+NewWithFreeList creates a new B-Tree that uses the given node free list. +
+ + + + + + + +func (t *BTree) Ascend(iterator ItemIterator)+
+Ascend calls the iterator for every value in the tree within the range +[first, last], until iterator returns false. +
+ + + + + + +func (t *BTree) AscendGreaterOrEqual(pivot Item, iterator ItemIterator)+
+AscendGreaterOrEqual calls the iterator for every value in the tree within +the range [pivot, last], until iterator returns false. +
+ + + + + + +func (t *BTree) AscendLessThan(pivot Item, iterator ItemIterator)+
+AscendLessThan calls the iterator for every value in the tree within the range +[first, pivot), until iterator returns false. +
+ + + + + + +func (t *BTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator)+
+AscendRange calls the iterator for every value in the tree within the range +[greaterOrEqual, lessThan), until iterator returns false. +
+ + + + + + +func (t *BTree) Delete(item Item) Item+
+Delete removes an item equal to the passed in item from the tree, returning +it. If no such item exists, returns nil. +
+ + + + + + +func (t *BTree) DeleteMax() Item+
+DeleteMax removes the largest item in the tree and returns it. +If no such item exists, returns nil. +
+ + + + + + +func (t *BTree) DeleteMin() Item+
+DeleteMin removes the smallest item in the tree and returns it. +If no such item exists, returns nil. +
+ + + + + + +func (t *BTree) Descend(iterator ItemIterator)+
+Descend calls the iterator for every value in the tree within the range +[last, first], until iterator returns false. +
+ + + + + + +func (t *BTree) DescendGreaterThan(pivot Item, iterator ItemIterator)+
+DescendGreaterThan calls the iterator for every value in the tree within +the range (pivot, last], until iterator returns false. +
+ + + + + + +func (t *BTree) DescendLessOrEqual(pivot Item, iterator ItemIterator)+
+DescendLessOrEqual calls the iterator for every value in the tree within the range +[pivot, first], until iterator returns false. +
+ + + + + + +func (t *BTree) DescendRange(lessOrEqual, greaterThan Item, iterator ItemIterator)+
+DescendRange calls the iterator for every value in the tree within the range +[lessOrEqual, greaterThan), until iterator returns false. +
+ + + + + + +func (t *BTree) Get(key Item) Item+
+Get looks for the key item in the tree, returning it. It returns nil if +unable to find that item. +
+ + + + + + +func (t *BTree) Has(key Item) bool+
+Has returns true if the given key is in the tree. +
+ + + + + + +func (t *BTree) Len() int+
+Len returns the number of items currently in the tree. +
+ + + + + + +func (t *BTree) Max() Item+
+Max returns the largest item in the tree, or nil if the tree is empty. +
+ + + + + + +func (t *BTree) Min() Item+
+Min returns the smallest item in the tree, or nil if the tree is empty. +
+ + + + + + +func (t *BTree) ReplaceOrInsert(item Item) Item+
+ReplaceOrInsert adds the given item to the tree. If an item in the tree +already equals the given one, it is removed from the tree and returned. +Otherwise, nil is returned. +
++nil cannot be added to the tree (will panic). +
+ + + + + + + + +type FreeList struct {
+ // contains filtered or unexported fields
+}
+ +FreeList represents a free list of btree nodes. By default each +BTree has its own FreeList, but multiple BTrees can share the same +FreeList. +Two Btrees using the same freelist are not safe for concurrent write access. +
+ + + + + + + + + + + + +func NewFreeList(size int) *FreeList+
+NewFreeList creates a new free list. +size is the maximum size of the returned free list. +
+ + + + + + + + + +type Int int+
+Int implements the Item interface for integers. +
+ + + + + + + + + + + + + + +func (a Int) Less(b Item) bool+
+Less returns true if int(a) < int(b). +
+ + + + + + + + +type Item interface { + // Less tests whether the current item is less than the given argument. + // + // This must provide a strict weak ordering. + // If !a.Less(b) && !b.Less(a), we treat this to mean a == b (i.e. we can only + // hold one of either a or b in the tree). + Less(than Item) bool +}+
+Item represents a single object in the tree. +
+ + + + + + + + + + + + + + + + +type ItemIterator func(i Item) bool+
+ItemIterator allows callers of Ascend* to iterate in-order over portions of +the tree. When this function returns false, iteration will stop and the +associated Ascend* function will immediately return. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +const ( + // Tarball specifies an archive in gzipped tar format. + Tarball archiveFormat = "tarball" + + // Zipball specifies an archive in zip format. + Zipball archiveFormat = "zipball" +)+ + +
const ( + // StatusUnprocessableEntity is the status code returned when sending a request with invalid fields. + StatusUnprocessableEntity = 422 +)+ + + + + + + +
func Bool(v bool) *bool+
+Bool is a helper routine that allocates a new bool value +to store v and returns a pointer to it. +
+ + + + + + + +func CheckResponse(r *http.Response) error+
+CheckResponse checks the API response for errors, and returns them if +present. A response is considered an error if it has a status code outside +the 200 range. API error responses are expected to have either no response +body, or a JSON response body that maps to ErrorResponse. Any other +response body will be silently ignored. +
++The error type will be *RateLimitError for rate limit exceeded errors, +and *TwoFactorAuthError for two-factor authentication errors. +
+ + + + + + + +func Int(v int) *int+
+Int is a helper routine that allocates a new int value +to store v and returns a pointer to it. +
+ + + + + + + +func String(v string) *string+
+String is a helper routine that allocates a new string value +to store v and returns a pointer to it. +
+ + + + + + + +func Stringify(message interface{}) string+
+Stringify attempts to create a reasonable string representation of types in +the GitHub library. It does things like resolve pointers to their values +and omits struct fields with nil values. +
+ + + + + + + +func ValidatePayload(r *http.Request, secretKey []byte) (payload []byte, err error)+
+ValidatePayload validates an incoming GitHub Webhook event request +and returns the (JSON) payload. +secretKey is the GitHub Webhook secret message. +
++Example usage: +
+func (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) { + payload, err := github.ValidatePayload(r, s.webhookSecretKey) + if err != nil { ... } + // Process payload... +} ++ + + + + + + + +
type APIMeta struct { + // An Array of IP addresses in CIDR format specifying the addresses + // that incoming service hooks will originate from on GitHub.com. + Hooks []string `json:"hooks,omitempty"` + + // An Array of IP addresses in CIDR format specifying the Git servers + // for GitHub.com. + Git []string `json:"git,omitempty"` + + // Whether authentication with username and password is supported. + // (GitHub Enterprise instances using CAS or OAuth for authentication + // will return false. Features like Basic Authentication with a + // username and password, sudo mode, and two-factor authentication are + // not supported on these servers.) + VerifiablePasswordAuthentication *bool `json:"verifiable_password_authentication,omitempty"` + + // An array of IP addresses in CIDR format specifying the addresses + // which serve GitHub Pages websites. + Pages []string `json:"pages,omitempty"` +}+
+APIMeta represents metadata about the GitHub API. +
+ + + + + + + + + + + + + + + + +type ActivityListStarredOptions struct { + // How to sort the repository list. Possible values are: created, updated, + // pushed, full_name. Default is "full_name". + Sort string `url:"sort,omitempty"` + + // Direction in which to sort repositories. Possible values are: asc, desc. + // Default is "asc" when sort is "full_name", otherwise default is "desc". + Direction string `url:"direction,omitempty"` + + ListOptions +}+
+ActivityListStarredOptions specifies the optional parameters to the +ActivityService.ListStarred method. +
+ + + + + + + + + + + + + + + + +type ActivityService service+
+ActivityService handles communication with the activity related +methods of the GitHub API. +
++GitHub API docs: http://developer.github.com/v3/activity/ +
+ + + + + + + + + + + + + + +func (s *ActivityService) DeleteRepositorySubscription(owner, repo string) (*Response, error)+
+DeleteRepositorySubscription deletes the subscription for the specified +repository for the authenticated user. +
++GitHub API Docs: https://developer.github.com/v3/activity/watching/#delete-a-repository-subscription +
+ + + + + + +func (s *ActivityService) DeleteThreadSubscription(id string) (*Response, error)+
+DeleteThreadSubscription deletes the subscription for the specified thread +for the authenticated user. +
++GitHub API Docs: https://developer.github.com/v3/activity/notifications/#delete-a-thread-subscription +
+ + + + + + +func (s *ActivityService) GetRepositorySubscription(owner, repo string) (*Subscription, *Response, error)+
+GetRepositorySubscription returns the subscription for the specified +repository for the authenticated user. If the authenticated user is not +watching the repository, a nil Subscription is returned. +
++GitHub API Docs: https://developer.github.com/v3/activity/watching/#get-a-repository-subscription +
+ + + + + + +func (s *ActivityService) GetThread(id string) (*Notification, *Response, error)+
+GetThread gets the specified notification thread. +
++GitHub API Docs: https://developer.github.com/v3/activity/notifications/#view-a-single-thread +
+ + + + + + +func (s *ActivityService) GetThreadSubscription(id string) (*Subscription, *Response, error)+
+GetThreadSubscription checks to see if the authenticated user is subscribed +to a thread. +
++GitHub API Docs: https://developer.github.com/v3/activity/notifications/#get-a-thread-subscription +
+ + + + + + +func (s *ActivityService) IsStarred(owner, repo string) (bool, *Response, error)+
+IsStarred checks if a repository is starred by authenticated user. +
++GitHub API docs: https://developer.github.com/v3/activity/starring/#check-if-you-are-starring-a-repository +
+ + + + + + +func (s *ActivityService) ListEvents(opt *ListOptions) ([]*Event, *Response, error)+
+ListEvents drinks from the firehose of all public events across GitHub. +
++GitHub API docs: http://developer.github.com/v3/activity/events/#list-public-events +
+ + + + + + +func (s *ActivityService) ListEventsForOrganization(org string, opt *ListOptions) ([]*Event, *Response, error)+
+ListEventsForOrganization lists public events for an organization. +
++GitHub API docs: http://developer.github.com/v3/activity/events/#list-public-events-for-an-organization +
+ + + + + + +func (s *ActivityService) ListEventsForRepoNetwork(owner, repo string, opt *ListOptions) ([]*Event, *Response, error)+
+ListEventsForRepoNetwork lists public events for a network of repositories. +
++GitHub API docs: http://developer.github.com/v3/activity/events/#list-public-events-for-a-network-of-repositories +
+ + + + + + +func (s *ActivityService) ListEventsPerformedByUser(user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error)+
+ListEventsPerformedByUser lists the events performed by a user. If publicOnly is +true, only public events will be returned. +
++GitHub API docs: http://developer.github.com/v3/activity/events/#list-events-performed-by-a-user +
+ + + + + + +func (s *ActivityService) ListEventsReceivedByUser(user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error)+
+ListEventsReceivedByUser lists the events received by a user. If publicOnly is +true, only public events will be returned. +
++GitHub API docs: http://developer.github.com/v3/activity/events/#list-events-that-a-user-has-received +
+ + + + + + +func (s *ActivityService) ListFeeds() (*Feeds, *Response, error)+
+ListFeeds lists all the feeds available to the authenticated user. +
++GitHub provides several timeline resources in Atom format: +
+Timeline: The GitHub global public timeline +User: The public timeline for any user, using URI template +Current user public: The public timeline for the authenticated user +Current user: The private timeline for the authenticated user +Current user actor: The private timeline for activity created by the + authenticated user +Current user organizations: The private timeline for the organizations + the authenticated user is a member of. ++
+Note: Private feeds are only returned when authenticating via Basic Auth +since current feed URIs use the older, non revocable auth tokens. +
+ + + + + + +func (s *ActivityService) ListIssueEventsForRepository(owner, repo string, opt *ListOptions) ([]*Event, *Response, error)+
+ListIssueEventsForRepository lists issue events for a repository. +
++GitHub API docs: http://developer.github.com/v3/activity/events/#list-issue-events-for-a-repository +
+ + + + + + +func (s *ActivityService) ListNotifications(opt *NotificationListOptions) ([]*Notification, *Response, error)+
+ListNotifications lists all notifications for the authenticated user. +
++GitHub API Docs: https://developer.github.com/v3/activity/notifications/#list-your-notifications +
+ + + + + + +func (s *ActivityService) ListRepositoryEvents(owner, repo string, opt *ListOptions) ([]*Event, *Response, error)+
+ListRepositoryEvents lists events for a repository. +
++GitHub API docs: http://developer.github.com/v3/activity/events/#list-repository-events +
+ + + + + + +func (s *ActivityService) ListRepositoryNotifications(owner, repo string, opt *NotificationListOptions) ([]*Notification, *Response, error)+
+ListRepositoryNotifications lists all notifications in a given repository +for the authenticated user. +
++GitHub API Docs: https://developer.github.com/v3/activity/notifications/#list-your-notifications-in-a-repository +
+ + + + + + +func (s *ActivityService) ListStargazers(owner, repo string, opt *ListOptions) ([]*Stargazer, *Response, error)+
+ListStargazers lists people who have starred the specified repo. +
++GitHub API Docs: https://developer.github.com/v3/activity/starring/#list-stargazers +
+ + + + + + +func (s *ActivityService) ListStarred(user string, opt *ActivityListStarredOptions) ([]*StarredRepository, *Response, error)+
+ListStarred lists all the repos starred by a user. Passing the empty string +will list the starred repositories for the authenticated user. +
++GitHub API docs: http://developer.github.com/v3/activity/starring/#list-repositories-being-starred +
+ + + + + + +func (s *ActivityService) ListUserEventsForOrganization(org, user string, opt *ListOptions) ([]*Event, *Response, error)+
+ListUserEventsForOrganization provides the user’s organization dashboard. You +must be authenticated as the user to view this. +
++GitHub API docs: http://developer.github.com/v3/activity/events/#list-events-for-an-organization +
+ + + + + + +func (s *ActivityService) ListWatched(user string, opt *ListOptions) ([]*Repository, *Response, error)+
+ListWatched lists the repositories the specified user is watching. Passing +the empty string will fetch watched repos for the authenticated user. +
++GitHub API Docs: https://developer.github.com/v3/activity/watching/#list-repositories-being-watched +
+ + + + + + +func (s *ActivityService) ListWatchers(owner, repo string, opt *ListOptions) ([]*User, *Response, error)+
+ListWatchers lists watchers of a particular repo. +
++GitHub API Docs: http://developer.github.com/v3/activity/watching/#list-watchers +
+ + + + + + +func (s *ActivityService) MarkNotificationsRead(lastRead time.Time) (*Response, error)+
+MarkNotificationsRead marks all notifications up to lastRead as read. +
++GitHub API Docs: https://developer.github.com/v3/activity/notifications/#mark-as-read +
+ + + + + + +func (s *ActivityService) MarkRepositoryNotificationsRead(owner, repo string, lastRead time.Time) (*Response, error)+
+MarkRepositoryNotificationsRead marks all notifications up to lastRead in +the specified repository as read. +
++GitHub API Docs: https://developer.github.com/v3/activity/notifications/#mark-notifications-as-read-in-a-repository +
+ + + + + + +func (s *ActivityService) MarkThreadRead(id string) (*Response, error)+
+MarkThreadRead marks the specified thread as read. +
++GitHub API Docs: https://developer.github.com/v3/activity/notifications/#mark-a-thread-as-read +
+ + + + + + +func (s *ActivityService) SetRepositorySubscription(owner, repo string, subscription *Subscription) (*Subscription, *Response, error)+
+SetRepositorySubscription sets the subscription for the specified repository +for the authenticated user. +
++GitHub API Docs: https://developer.github.com/v3/activity/watching/#set-a-repository-subscription +
+ + + + + + +func (s *ActivityService) SetThreadSubscription(id string, subscription *Subscription) (*Subscription, *Response, error)+
+SetThreadSubscription sets the subscription for the specified thread for the +authenticated user. +
++GitHub API Docs: https://developer.github.com/v3/activity/notifications/#set-a-thread-subscription +
+ + + + + + +func (s *ActivityService) Star(owner, repo string) (*Response, error)+
+Star a repository as the authenticated user. +
++GitHub API docs: https://developer.github.com/v3/activity/starring/#star-a-repository +
+ + + + + + +func (s *ActivityService) Unstar(owner, repo string) (*Response, error)+
+Unstar a repository as the authenticated user. +
++GitHub API docs: https://developer.github.com/v3/activity/starring/#unstar-a-repository +
+ + + + + + + + +type Authorization struct { + ID *int `json:"id,omitempty"` + URL *string `json:"url,omitempty"` + Scopes []Scope `json:"scopes,omitempty"` + Token *string `json:"token,omitempty"` + TokenLastEight *string `json:"token_last_eight,omitempty"` + HashedToken *string `json:"hashed_token,omitempty"` + App *AuthorizationApp `json:"app,omitempty"` + Note *string `json:"note,omitempty"` + NoteURL *string `json:"note_url,omitempty"` + UpdateAt *Timestamp `json:"updated_at,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + Fingerprint *string `json:"fingerprint,omitempty"` + + // User is only populated by the Check and Reset methods. + User *User `json:"user,omitempty"` +}+
+Authorization represents an individual GitHub authorization. +
+ + + + + + + + + + + + + + +func (a Authorization) String() string+ + + + + + + + +
type AuthorizationApp struct { + URL *string `json:"url,omitempty"` + Name *string `json:"name,omitempty"` + ClientID *string `json:"client_id,omitempty"` +}+
+AuthorizationApp represents an individual GitHub app (in the context of authorization). +
+ + + + + + + + + + + + + + +func (a AuthorizationApp) String() string+ + + + + + + + +
type AuthorizationRequest struct { + Scopes []Scope `json:"scopes,omitempty"` + Note *string `json:"note,omitempty"` + NoteURL *string `json:"note_url,omitempty"` + ClientID *string `json:"client_id,omitempty"` + ClientSecret *string `json:"client_secret,omitempty"` + Fingerprint *string `json:"fingerprint,omitempty"` +}+
+AuthorizationRequest represents a request to create an authorization. +
+ + + + + + + + + + + + + + +func (a AuthorizationRequest) String() string+ + + + + + + + +
type AuthorizationUpdateRequest struct { + Scopes []string `json:"scopes,omitempty"` + AddScopes []string `json:"add_scopes,omitempty"` + RemoveScopes []string `json:"remove_scopes,omitempty"` + Note *string `json:"note,omitempty"` + NoteURL *string `json:"note_url,omitempty"` + Fingerprint *string `json:"fingerprint,omitempty"` +}+
+AuthorizationUpdateRequest represents a request to update an authorization. +
++Note that for any one update, you must only provide one of the "scopes" +fields. That is, you may provide only one of "Scopes", or "AddScopes", or +"RemoveScopes". +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#update-an-existing-authorization +
+ + + + + + + + + + + + + + +func (a AuthorizationUpdateRequest) String() string+ + + + + + + + +
type AuthorizationsService service+
+AuthorizationsService handles communication with the authorization related +methods of the GitHub API. +
++This service requires HTTP Basic Authentication; it cannot be accessed using +an OAuth token. +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/ +
+ + + + + + + + + + + + + + +func (s *AuthorizationsService) Check(clientID string, token string) (*Authorization, *Response, error)+
+Check if an OAuth token is valid for a specific app. +
++Note that this operation requires the use of BasicAuth, but where the +username is the OAuth application clientID, and the password is its +clientSecret. Invalid tokens will return a 404 Not Found. +
++The returned Authorization.User field will be populated. +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#check-an-authorization +
+ + + + + + +func (s *AuthorizationsService) Create(auth *AuthorizationRequest) (*Authorization, *Response, error)+
+Create a new authorization for the specified OAuth application. +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#create-a-new-authorization +
+ + + + + + +func (s *AuthorizationsService) CreateImpersonation(username string, authReq *AuthorizationRequest) (*Authorization, *Response, error)+
+Create an impersonation OAuth token. +
++This requires admin permissions. With the returned Authorization.Token +you can e.g. create or delete a user's public SSH key. NOTE: creating a +new token automatically revokes an existing one. +
++GitHub API docs: https://developer.github.com/enterprise/2.5/v3/users/administration/#create-an-impersonation-oauth-token +
+ + + + + + +func (s *AuthorizationsService) Delete(id int) (*Response, error)+
+Delete a single authorization. +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#delete-an-authorization +
+ + + + + + +func (s *AuthorizationsService) DeleteGrant(id int) (*Response, error)+
+DeleteGrant deletes an OAuth application grant. Deleting an application's +grant will also delete all OAuth tokens associated with the application for +the user. +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#delete-a-grant +
+ + + + + + +func (s *AuthorizationsService) DeleteImpersonation(username string) (*Response, error)+
+Delete an impersonation OAuth token. +
++NOTE: there can be only one at a time. +
++GitHub API docs: https://developer.github.com/enterprise/2.5/v3/users/administration/#delete-an-impersonation-oauth-token +
+ + + + + + +func (s *AuthorizationsService) Edit(id int, auth *AuthorizationUpdateRequest) (*Authorization, *Response, error)+
+Edit a single authorization. +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#update-an-existing-authorization +
+ + + + + + +func (s *AuthorizationsService) Get(id int) (*Authorization, *Response, error)+
+Get a single authorization. +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-authorization +
+ + + + + + +func (s *AuthorizationsService) GetGrant(id int) (*Grant, *Response, error)+
+GetGrant gets a single OAuth application grant. +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-grant +
+ + + + + + +func (s *AuthorizationsService) GetOrCreateForApp(clientID string, auth *AuthorizationRequest) (*Authorization, *Response, error)+
+GetOrCreateForApp creates a new authorization for the specified OAuth +application, only if an authorization for that application doesn’t already +exist for the user. +
++If a new token is created, the HTTP status code will be "201 Created", and +the returned Authorization.Token field will be populated. If an existing +token is returned, the status code will be "200 OK" and the +Authorization.Token field will be empty. +
++clientID is the OAuth Client ID with which to create the token. +
++GitHub API docs: +- https://developer.github.com/v3/oauth_authorizations/#get-or-create-an-authorization-for-a-specific-app +- https://developer.github.com/v3/oauth_authorizations/#get-or-create-an-authorization-for-a-specific-app-and-fingerprint +
+ + + + + + +func (s *AuthorizationsService) List(opt *ListOptions) ([]*Authorization, *Response, error)+
+List the authorizations for the authenticated user. +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-authorizations +
+ + + + + + +func (s *AuthorizationsService) ListGrants() ([]*Grant, *Response, error)+
+ListGrants lists the set of OAuth applications that have been granted +access to a user's account. This will return one entry for each application +that has been granted access to the account, regardless of the number of +tokens an application has generated for the user. +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-grants +
+ + + + + + +func (s *AuthorizationsService) Reset(clientID string, token string) (*Authorization, *Response, error)+
+Reset is used to reset a valid OAuth token without end user involvement. +Applications must save the "token" property in the response, because changes +take effect immediately. +
++Note that this operation requires the use of BasicAuth, but where the +username is the OAuth application clientID, and the password is its +clientSecret. Invalid tokens will return a 404 Not Found. +
++The returned Authorization.User field will be populated. +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#reset-an-authorization +
+ + + + + + +func (s *AuthorizationsService) Revoke(clientID string, token string) (*Response, error)+
+Revoke an authorization for an application. +
++Note that this operation requires the use of BasicAuth, but where the +username is the OAuth application clientID, and the password is its +clientSecret. Invalid tokens will return a 404 Not Found. +
++GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#revoke-an-authorization-for-an-application +
+ + + + + + + + +type BasicAuthTransport struct { + Username string // GitHub username + Password string // GitHub password + OTP string // one-time password for users with two-factor auth enabled + + // Transport is the underlying HTTP transport to use when making requests. + // It will default to http.DefaultTransport if nil. + Transport http.RoundTripper +}+
+BasicAuthTransport is an http.RoundTripper that authenticates all requests +using HTTP Basic Authentication with the provided username and password. It +additionally supports users who have two-factor authentication enabled on +their GitHub account. +
+ + + + + + + + + + + + + + +func (t *BasicAuthTransport) Client() *http.Client+
+Client returns an *http.Client that makes requests that are authenticated +using HTTP Basic Authentication. +
+ + + + + + +func (t *BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error)+
+RoundTrip implements the RoundTripper interface. +
+ + + + + + + + +type Blob struct { + Content *string `json:"content,omitempty"` + Encoding *string `json:"encoding,omitempty"` + SHA *string `json:"sha,omitempty"` + Size *int `json:"size,omitempty"` + URL *string `json:"url,omitempty"` +}+
+Blob represents a blob object. +
+ + + + + + + + + + + + + + + + +type Branch struct { + Name *string `json:"name,omitempty"` + Commit *Commit `json:"commit,omitempty"` + Protection *Protection `json:"protection,omitempty"` +}+
+Branch represents a repository branch +
+ + + + + + + + + + + + + + + + +type Client struct { + + // Base URL for API requests. Defaults to the public GitHub API, but can be + // set to a domain endpoint to use with GitHub Enterprise. BaseURL should + // always be specified with a trailing slash. + BaseURL *url.URL + + // Base URL for uploading files. + UploadURL *url.URL + + // User agent used when communicating with the GitHub API. + UserAgent string + + // Services used for talking to different parts of the GitHub API. + Activity *ActivityService + Authorizations *AuthorizationsService + Gists *GistsService + Git *GitService + Gitignores *GitignoresService + Issues *IssuesService + Organizations *OrganizationsService + PullRequests *PullRequestsService + Repositories *RepositoriesService + Search *SearchService + Users *UsersService + Licenses *LicensesService + Migrations *MigrationService + Reactions *ReactionsService + // contains filtered or unexported fields +}+
+A Client manages communication with the GitHub API. +
+ + + + + + + + + + + + +func NewClient(httpClient *http.Client) *Client+
+NewClient returns a new GitHub API client. If a nil httpClient is +provided, http.DefaultClient will be used. To use API methods which require +authentication, provide an http.Client that will perform the authentication +for you (such as that provided by the golang.org/x/oauth2 library). +
+ + + + + + + +func (c *Client) APIMeta() (*APIMeta, *Response, error)+
+APIMeta returns information about GitHub.com, the service. Or, if you access +this endpoint on your organization’s GitHub Enterprise installation, this +endpoint provides information about that installation. +
++GitHub API docs: https://developer.github.com/v3/meta/ +
+ + + + + + +func (c *Client) Do(req *http.Request, v interface{}) (*Response, error)+
+Do sends an API request and returns the API response. The API response is +JSON decoded and stored in the value pointed to by v, or returned as an +error if an API error has occurred. If v implements the io.Writer +interface, the raw response body will be written to v, without attempting to +first decode it. If rate limit is exceeded and reset time is in the future, +Do returns *RateLimitError immediately without making a network API call. +
+ + + + + + +func (c *Client) ListEmojis() (map[string]string, *Response, error)+
+ListEmojis returns the emojis available to use on GitHub. +
++GitHub API docs: https://developer.github.com/v3/emojis/ +
+ + + + + + +func (c *Client) ListServiceHooks() ([]*ServiceHook, *Response, error)+
+ListServiceHooks lists all of the available service hooks. +
++GitHub API docs: https://developer.github.com/webhooks/#services +
+ + + + + + +func (c *Client) Markdown(text string, opt *MarkdownOptions) (string, *Response, error)+
+Markdown renders an arbitrary Markdown document. +
++GitHub API docs: https://developer.github.com/v3/markdown/ +
+ + +▹ Example
+func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)+
+NewRequest creates an API request. A relative URL can be provided in urlStr, +in which case it is resolved relative to the BaseURL of the Client. +Relative URLs should always be specified without a preceding slash. If +specified, the value pointed to by body is JSON encoded and included as the +request body. +
+ + + + + + +func (c *Client) NewUploadRequest(urlStr string, reader io.Reader, size int64, mediaType string) (*http.Request, error)+
+NewUploadRequest creates an upload request. A relative URL can be provided in +urlStr, in which case it is resolved relative to the UploadURL of the Client. +Relative URLs should always be specified without a preceding slash. +
+ + + + + + +func (c *Client) Octocat(message string) (string, *Response, error)+
+Octocat returns an ASCII art octocat with the specified message in a speech +bubble. If message is empty, a random zen phrase is used. +
+ + + + + + +func (c *Client) Rate() Rate+
+Rate specifies the current rate limit for the client as determined by the +most recent API call. If the client is used in a multi-user application, +this rate may not always be up-to-date. +
++Deprecated: Use the Response.Rate returned from most recent API call instead. +Call RateLimits() to check the current rate. +
+ + + + + + +func (c *Client) RateLimit() (*Rate, *Response, error)+
+Deprecated: RateLimit is deprecated, use RateLimits instead. +
+ + + + + + +func (c *Client) RateLimits() (*RateLimits, *Response, error)+
+RateLimits returns the rate limits for the current client. +
+ + + + + + +func (c *Client) Zen() (string, *Response, error)+
+Zen returns a random line from The Zen of GitHub. +
++see also: http://warpspire.com/posts/taste/ +
+ + + + + + + + +type CodeResult struct { + Name *string `json:"name,omitempty"` + Path *string `json:"path,omitempty"` + SHA *string `json:"sha,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + Repository *Repository `json:"repository,omitempty"` + TextMatches []TextMatch `json:"text_matches,omitempty"` +}+
+CodeResult represents a single search result. +
+ + + + + + + + + + + + + + +func (c CodeResult) String() string+ + + + + + + + +
type CodeSearchResult struct { + Total *int `json:"total_count,omitempty"` + CodeResults []CodeResult `json:"items,omitempty"` +}+
+CodeSearchResult represents the result of an code search. +
+ + + + + + + + + + + + + + + + +type CombinedStatus struct { + // State is the combined state of the repository. Possible values are: + // failure, pending, or success. + State *string `json:"state,omitempty"` + + Name *string `json:"name,omitempty"` + SHA *string `json:"sha,omitempty"` + TotalCount *int `json:"total_count,omitempty"` + Statuses []RepoStatus `json:"statuses,omitempty"` + + CommitURL *string `json:"commit_url,omitempty"` + RepositoryURL *string `json:"repository_url,omitempty"` +}+
+CombinedStatus represents the combined status of a repository at a particular reference. +
+ + + + + + + + + + + + + + +func (s CombinedStatus) String() string+ + + + + + + + +
type Commit struct { + SHA *string `json:"sha,omitempty"` + Author *CommitAuthor `json:"author,omitempty"` + Committer *CommitAuthor `json:"committer,omitempty"` + Message *string `json:"message,omitempty"` + Tree *Tree `json:"tree,omitempty"` + Parents []Commit `json:"parents,omitempty"` + Stats *CommitStats `json:"stats,omitempty"` + URL *string `json:"url,omitempty"` + Verification *SignatureVerification `json:"verification,omitempty"` + + // CommentCount is the number of GitHub comments on the commit. This + // is only populated for requests that fetch GitHub data like + // Pulls.ListCommits, Repositories.ListCommits, etc. + CommentCount *int `json:"comment_count,omitempty"` +}+
+Commit represents a GitHub commit. +
+ + + + + + + + + + + + + + +func (c Commit) String() string+ + + + + + + + +
type CommitAuthor struct { + Date *time.Time `json:"date,omitempty"` + Name *string `json:"name,omitempty"` + Email *string `json:"email,omitempty"` + + // The following fields are only populated by Webhook events. + Login *string `json:"username,omitempty"` // Renamed for go-github consistency. +}+
+CommitAuthor represents the author or committer of a commit. The commit +author may not correspond to a GitHub User. +
+ + + + + + + + + + + + + + +func (c CommitAuthor) String() string+ + + + + + + + +
type CommitCommentEvent struct { + Comment *RepositoryComment `json:"comment,omitempty"` + + // The following fields are only populated by Webhook events. + Action *string `json:"action,omitempty"` + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+CommitCommentEvent is triggered when a commit comment is created. +The Webhook event name is "commit_comment". +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#commitcommentevent +
+ + + + + + + + + + + + + + + + +type CommitFile struct { + SHA *string `json:"sha,omitempty"` + Filename *string `json:"filename,omitempty"` + Additions *int `json:"additions,omitempty"` + Deletions *int `json:"deletions,omitempty"` + Changes *int `json:"changes,omitempty"` + Status *string `json:"status,omitempty"` + Patch *string `json:"patch,omitempty"` +}+
+CommitFile represents a file modified in a commit. +
+ + + + + + + + + + + + + + +func (c CommitFile) String() string+ + + + + + + + +
type CommitStats struct { + Additions *int `json:"additions,omitempty"` + Deletions *int `json:"deletions,omitempty"` + Total *int `json:"total,omitempty"` +}+
+CommitStats represents the number of additions / deletions from a file in a given RepositoryCommit or GistCommit. +
+ + + + + + + + + + + + + + +func (c CommitStats) String() string+ + + + + + + + +
type CommitsComparison struct { + BaseCommit *RepositoryCommit `json:"base_commit,omitempty"` + MergeBaseCommit *RepositoryCommit `json:"merge_base_commit,omitempty"` + + // Head can be 'behind' or 'ahead' + Status *string `json:"status,omitempty"` + AheadBy *int `json:"ahead_by,omitempty"` + BehindBy *int `json:"behind_by,omitempty"` + TotalCommits *int `json:"total_commits,omitempty"` + + Commits []RepositoryCommit `json:"commits,omitempty"` + + Files []CommitFile `json:"files,omitempty"` +}+
+CommitsComparison is the result of comparing two commits. +See CompareCommits() for details. +
+ + + + + + + + + + + + + + +func (c CommitsComparison) String() string+ + + + + + + + +
type CommitsListOptions struct { + // SHA or branch to start listing Commits from. + SHA string `url:"sha,omitempty"` + + // Path that should be touched by the returned Commits. + Path string `url:"path,omitempty"` + + // Author of by which to filter Commits. + Author string `url:"author,omitempty"` + + // Since when should Commits be included in the response. + Since time.Time `url:"since,omitempty"` + + // Until when should Commits be included in the response. + Until time.Time `url:"until,omitempty"` + + ListOptions +}+
+CommitsListOptions specifies the optional parameters to the +RepositoriesService.ListCommits method. +
+ + + + + + + + + + + + + + + + +type Contributor struct { + Login *string `json:"login,omitempty"` + ID *int `json:"id,omitempty"` + AvatarURL *string `json:"avatar_url,omitempty"` + GravatarID *string `json:"gravatar_id,omitempty"` + URL *string `json:"url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + FollowersURL *string `json:"followers_url,omitempty"` + FollowingURL *string `json:"following_url,omitempty"` + GistsURL *string `json:"gists_url,omitempty"` + StarredURL *string `json:"starred_url,omitempty"` + SubscriptionsURL *string `json:"subscriptions_url,omitempty"` + OrganizationsURL *string `json:"organizations_url,omitempty"` + ReposURL *string `json:"repos_url,omitempty"` + EventsURL *string `json:"events_url,omitempty"` + ReceivedEventsURL *string `json:"received_events_url,omitempty"` + Type *string `json:"type,omitempty"` + SiteAdmin *bool `json:"site_admin"` + Contributions *int `json:"contributions,omitempty"` +}+
+Contributor represents a repository contributor +
+ + + + + + + + + + + + + + + + +type ContributorStats struct { + Author *Contributor `json:"author,omitempty"` + Total *int `json:"total,omitempty"` + Weeks []WeeklyStats `json:"weeks,omitempty"` +}+
+ContributorStats represents a contributor to a repository and their +weekly contributions to a given repo. +
+ + + + + + + + + + + + + + +func (c ContributorStats) String() string+ + + + + + + + +
type CreateEvent struct { + Ref *string `json:"ref,omitempty"` + // RefType is the object that was created. Possible values are: "repository", "branch", "tag". + RefType *string `json:"ref_type,omitempty"` + MasterBranch *string `json:"master_branch,omitempty"` + Description *string `json:"description,omitempty"` + + // The following fields are only populated by Webhook events. + PusherType *string `json:"pusher_type,omitempty"` + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+CreateEvent represents a created repository, branch, or tag. +The Webhook event name is "create". +
++Note: webhooks will not receive this event for created repositories. +Additionally, webhooks will not receive this event for tags if more +than three tags are pushed at once. +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#createevent +
+ + + + + + + + + + + + + + + + +type DeleteEvent struct { + Ref *string `json:"ref,omitempty"` + // RefType is the object that was deleted. Possible values are: "branch", "tag". + RefType *string `json:"ref_type,omitempty"` + + // The following fields are only populated by Webhook events. + PusherType *string `json:"pusher_type,omitempty"` + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+DeleteEvent represents a deleted branch or tag. +The Webhook event name is "delete". +
++Note: webhooks will not receive this event for tags if more than three tags +are deleted at once. +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#deleteevent +
+ + + + + + + + + + + + + + + + +type Deployment struct { + URL *string `json:"url,omitempty"` + ID *int `json:"id,omitempty"` + SHA *string `json:"sha,omitempty"` + Ref *string `json:"ref,omitempty"` + Task *string `json:"task,omitempty"` + Payload json.RawMessage `json:"payload,omitempty"` + Environment *string `json:"environment,omitempty"` + Description *string `json:"description,omitempty"` + Creator *User `json:"creator,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + UpdatedAt *Timestamp `json:"pushed_at,omitempty"` + StatusesURL *string `json:"statuses_url,omitempty"` + RepositoryURL *string `json:"repository_url,omitempty"` +}+
+Deployment represents a deployment in a repo +
+ + + + + + + + + + + + + + + + +type DeploymentEvent struct { + Deployment *Deployment `json:"deployment,omitempty"` + Repo *Repository `json:"repository,omitempty"` + + // The following fields are only populated by Webhook events. + Sender *User `json:"sender,omitempty"` +}+
+DeploymentEvent represents a deployment. +The Webhook event name is "deployment". +
++Events of this type are not visible in timelines, they are only used to trigger hooks. +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#deploymentevent +
+ + + + + + + + + + + + + + + + +type DeploymentRequest struct { + Ref *string `json:"ref,omitempty"` + Task *string `json:"task,omitempty"` + AutoMerge *bool `json:"auto_merge,omitempty"` + RequiredContexts *[]string `json:"required_contexts,omitempty"` + Payload *string `json:"payload,omitempty"` + Environment *string `json:"environment,omitempty"` + Description *string `json:"description,omitempty"` + TransientEnvironment *bool `json:"transient_environment,omitempty"` + ProductionEnvironment *bool `json:"production_environment,omitempty"` +}+
+DeploymentRequest represents a deployment request +
+ + + + + + + + + + + + + + + + +type DeploymentStatus struct { + ID *int `json:"id,omitempty"` + // State is the deployment state. + // Possible values are: "pending", "success", "failure", "error", "inactive". + State *string `json:"state,omitempty"` + Creator *User `json:"creator,omitempty"` + Description *string `json:"description,omitempty"` + TargetURL *string `json:"target_url,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + UpdatedAt *Timestamp `json:"pushed_at,omitempty"` + DeploymentURL *string `json:"deployment_url,omitempty"` + RepositoryURL *string `json:"repository_url,omitempty"` +}+
+DeploymentStatus represents the status of a +particular deployment. +
+ + + + + + + + + + + + + + + + +type DeploymentStatusEvent struct { + Deployment *Deployment `json:"deployment,omitempty"` + DeploymentStatus *DeploymentStatus `json:"deployment_status,omitempty"` + Repo *Repository `json:"repository,omitempty"` + + // The following fields are only populated by Webhook events. + Sender *User `json:"sender,omitempty"` +}+
+DeploymentStatusEvent represents a deployment status. +The Webhook event name is "deployment_status". +
++Events of this type are not visible in timelines, they are only used to trigger hooks. +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#deploymentstatusevent +
+ + + + + + + + + + + + + + + + +type DeploymentStatusRequest struct { + State *string `json:"state,omitempty"` + TargetURL *string `json:"target_url,omitempty"` // Deprecated. Use LogURL instead. + LogURL *string `json:"log_url,omitempty"` + Description *string `json:"description,omitempty"` + EnvironmentURL *string `json:"environment_url,omitempty"` + AutoInactive *bool `json:"auto_inactive,omitempty"` +}+
+DeploymentStatusRequest represents a deployment request +
+ + + + + + + + + + + + + + + + +type DeploymentsListOptions struct { + // SHA of the Deployment. + SHA string `url:"sha,omitempty"` + + // List deployments for a given ref. + Ref string `url:"ref,omitempty"` + + // List deployments for a given task. + Task string `url:"task,omitempty"` + + // List deployments for a given environment. + Environment string `url:"environment,omitempty"` + + ListOptions +}+
+DeploymentsListOptions specifies the optional parameters to the +RepositoriesService.ListDeployments method. +
+ + + + + + + + + + + + + + + + +type EditChange struct { + Title *struct { + From *string `json:"from,omitempty"` + } `json:"title,omitempty"` + Body *struct { + From *string `json:"from,omitempty"` + } `json:"body,omitempty"` +}+
+EditChange represents the changes when an issue, pull request, or comment has +been edited. +
+ + + + + + + + + + + + + + + + +type Error struct { + Resource string `json:"resource"` // resource on which the error occurred + Field string `json:"field"` // field on which the error occurred + Code string `json:"code"` // validation error code + Message string `json:"message"` // Message describing the error. Errors with Code == "custom" will always have this set. +}+
+An Error reports more details on an individual error in an ErrorResponse. +These are the possible validation error codes: +
+missing: + resource does not exist +missing_field: + a required field on a resource has not been set +invalid: + the formatting of a field is invalid +already_exists: + another resource has the same valid as this field +custom: + some resources return this (e.g. github.User.CreateKey()), additional + information is set in the Message field of the Error ++
+GitHub API docs: http://developer.github.com/v3/#client-errors +
+ + + + + + + + + + + + + + +func (e *Error) Error() string+ + + + + + + + +
type ErrorResponse struct { + Response *http.Response // HTTP response that caused this error + Message string `json:"message"` // error message + Errors []Error `json:"errors"` // more detail on individual errors + // Block is only populated on certain types of errors such as code 451. + // See https://developer.github.com/changes/2016-03-17-the-451-status-code-is-now-supported/ + // for more information. + Block *struct { + Reason string `json:"reason,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + } `json:"block,omitempty"` + // Most errors will also include a documentation_url field pointing + // to some content that might help you resolve the error, see + // https://developer.github.com/v3/#client-errors + DocumentationURL string `json:"documentation_url,omitempty"` +}+
+An ErrorResponse reports one or more errors caused by an API request. +
++GitHub API docs: http://developer.github.com/v3/#client-errors +
+ + + + + + + + + + + + + + +func (r *ErrorResponse) Error() string+ + + + + + + + +
type Event struct { + Type *string `json:"type,omitempty"` + Public *bool `json:"public"` + RawPayload *json.RawMessage `json:"payload,omitempty"` + Repo *Repository `json:"repo,omitempty"` + Actor *User `json:"actor,omitempty"` + Org *Organization `json:"org,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + ID *string `json:"id,omitempty"` +}+
+Event represents a GitHub event. +
+ + + + + + + + + + + + + + +func (e *Event) Payload() (payload interface{})+
+Payload returns the parsed event payload. For recognized event types, +a value of the corresponding struct type will be returned. +
+ + + + + + +func (e Event) String() string+ + + + + + + + +
type FeedLink struct { + HRef *string `json:"href,omitempty"` + Type *string `json:"type,omitempty"` +}+
+FeedLink represents a link to a related resource. +
+ + + + + + + + + + + + + + + + +type Feeds struct { + TimelineURL *string `json:"timeline_url,omitempty"` + UserURL *string `json:"user_url,omitempty"` + CurrentUserPublicURL *string `json:"current_user_public_url,omitempty"` + CurrentUserURL *string `json:"current_user_url,omitempty"` + CurrentUserActorURL *string `json:"current_user_actor_url,omitempty"` + CurrentUserOrganizationURL *string `json:"current_user_organization_url,omitempty"` + CurrentUserOrganizationURLs []string `json:"current_user_organization_urls,omitempty"` + Links *struct { + Timeline *FeedLink `json:"timeline,omitempty"` + User *FeedLink `json:"user,omitempty"` + CurrentUserPublic *FeedLink `json:"current_user_public,omitempty"` + CurrentUser *FeedLink `json:"current_user,omitempty"` + CurrentUserActor *FeedLink `json:"current_user_actor,omitempty"` + CurrentUserOrganization *FeedLink `json:"current_user_organization,omitempty"` + CurrentUserOrganizations []FeedLink `json:"current_user_organizations,omitempty"` + } `json:"_links,omitempty"` +}+
+Feeds represents timeline resources in Atom format. +
+ + + + + + + + + + + + + + + + +type ForkEvent struct { + // Forkee is the created repository. + Forkee *Repository `json:"forkee,omitempty"` + + // The following fields are only populated by Webhook events. + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+ForkEvent is triggered when a user forks a repository. +The Webhook event name is "fork". +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#forkevent +
+ + + + + + + + + + + + + + + + +type GPGEmail struct { + Email *string `json:"email,omitempty"` + Verified *bool `json:"verified,omitempty"` +}+
+GPGEmail represents an email address associated to a GPG key. +
+ + + + + + + + + + + + + + + + +type GPGKey struct { + ID *int `json:"id,omitempty"` + PrimaryKeyID *int `json:"primary_key_id,omitempty"` + KeyID *string `json:"key_id,omitempty"` + PublicKey *string `json:"public_key,omitempty"` + Emails []GPGEmail `json:"emails,omitempty"` + Subkeys []GPGKey `json:"subkeys,omitempty"` + CanSign *bool `json:"can_sign,omitempty"` + CanEncryptComms *bool `json:"can_encrypt_comms,omitempty"` + CanEncryptStorage *bool `json:"can_encrypt_storage,omitempty"` + CanCertify *bool `json:"can_certify,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` +}+
+GPGKey represents a GitHub user's public GPG key used to verify GPG signed commits and tags. +
++https://developer.github.com/changes/2016-04-04-git-signing-api-preview/ +
+ + + + + + + + + + + + + + +func (k GPGKey) String() string+
+String stringifies a GPGKey. +
+ + + + + + + + +type Gist struct { + ID *string `json:"id,omitempty"` + Description *string `json:"description,omitempty"` + Public *bool `json:"public,omitempty"` + Owner *User `json:"owner,omitempty"` + Files map[GistFilename]GistFile `json:"files,omitempty"` + Comments *int `json:"comments,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + GitPullURL *string `json:"git_pull_url,omitempty"` + GitPushURL *string `json:"git_push_url,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +}+
+Gist represents a GitHub's gist. +
+ + + + + + + + + + + + + + +func (g Gist) String() string+ + + + + + + + +
type GistComment struct { + ID *int `json:"id,omitempty"` + URL *string `json:"url,omitempty"` + Body *string `json:"body,omitempty"` + User *User `json:"user,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` +}+
+GistComment represents a Gist comment. +
+ + + + + + + + + + + + + + +func (g GistComment) String() string+ + + + + + + + +
type GistCommit struct { + URL *string `json:"url,omitempty"` + Version *string `json:"version,omitempty"` + User *User `json:"user,omitempty"` + ChangeStatus *CommitStats `json:"change_status,omitempty"` + CommitedAt *Timestamp `json:"commited_at,omitempty"` +}+
+GistCommit represents a commit on a gist. +
+ + + + + + + + + + + + + + +func (gc GistCommit) String() string+ + + + + + + + +
type GistFile struct { + Size *int `json:"size,omitempty"` + Filename *string `json:"filename,omitempty"` + RawURL *string `json:"raw_url,omitempty"` + Content *string `json:"content,omitempty"` +}+
+GistFile represents a file on a gist. +
+ + + + + + + + + + + + + + +func (g GistFile) String() string+ + + + + + + + +
type GistFilename string+
+GistFilename represents filename on a gist. +
+ + + + + + + + + + + + + + + + +type GistFork struct { + URL *string `json:"url,omitempty"` + User *User `json:"user,omitempty"` + ID *string `json:"id,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` +}+
+GistFork represents a fork of a gist. +
+ + + + + + + + + + + + + + +func (gf GistFork) String() string+ + + + + + + + +
type GistListOptions struct { + // Since filters Gists by time. + Since time.Time `url:"since,omitempty"` + + ListOptions +}+
+GistListOptions specifies the optional parameters to the +GistsService.List, GistsService.ListAll, and GistsService.ListStarred methods. +
+ + + + + + + + + + + + + + + + +type GistsService service+
+GistsService handles communication with the Gist related +methods of the GitHub API. +
++GitHub API docs: http://developer.github.com/v3/gists/ +
+ + + + + + + + + + + + + + +func (s *GistsService) Create(gist *Gist) (*Gist, *Response, error)+
+Create a gist for authenticated user. +
++GitHub API docs: http://developer.github.com/v3/gists/#create-a-gist +
+ + + + + + +func (s *GistsService) CreateComment(gistID string, comment *GistComment) (*GistComment, *Response, error)+
+CreateComment creates a comment for a gist. +
++GitHub API docs: http://developer.github.com/v3/gists/comments/#create-a-comment +
+ + + + + + +func (s *GistsService) Delete(id string) (*Response, error)+
+Delete a gist. +
++GitHub API docs: http://developer.github.com/v3/gists/#delete-a-gist +
+ + + + + + +func (s *GistsService) DeleteComment(gistID string, commentID int) (*Response, error)+
+DeleteComment deletes a gist comment. +
++GitHub API docs: http://developer.github.com/v3/gists/comments/#delete-a-comment +
+ + + + + + +func (s *GistsService) Edit(id string, gist *Gist) (*Gist, *Response, error)+
+Edit a gist. +
++GitHub API docs: http://developer.github.com/v3/gists/#edit-a-gist +
+ + + + + + +func (s *GistsService) EditComment(gistID string, commentID int, comment *GistComment) (*GistComment, *Response, error)+
+EditComment edits an existing gist comment. +
++GitHub API docs: http://developer.github.com/v3/gists/comments/#edit-a-comment +
+ + + + + + +func (s *GistsService) Fork(id string) (*Gist, *Response, error)+
+Fork a gist. +
++GitHub API docs: http://developer.github.com/v3/gists/#fork-a-gist +
+ + + + + + +func (s *GistsService) Get(id string) (*Gist, *Response, error)+
+Get a single gist. +
++GitHub API docs: http://developer.github.com/v3/gists/#get-a-single-gist +
+ + + + + + +func (s *GistsService) GetComment(gistID string, commentID int) (*GistComment, *Response, error)+
+GetComment retrieves a single comment from a gist. +
++GitHub API docs: http://developer.github.com/v3/gists/comments/#get-a-single-comment +
+ + + + + + +func (s *GistsService) GetRevision(id, sha string) (*Gist, *Response, error)+
+GetRevision gets a specific revision of a gist. +
++GitHub API docs: https://developer.github.com/v3/gists/#get-a-specific-revision-of-a-gist +
+ + + + + + +func (s *GistsService) IsStarred(id string) (bool, *Response, error)+
+IsStarred checks if a gist is starred by authenticated user. +
++GitHub API docs: http://developer.github.com/v3/gists/#check-if-a-gist-is-starred +
+ + + + + + +func (s *GistsService) List(user string, opt *GistListOptions) ([]*Gist, *Response, error)+
+List gists for a user. Passing the empty string will list +all public gists if called anonymously. However, if the call +is authenticated, it will returns all gists for the authenticated +user. +
++GitHub API docs: http://developer.github.com/v3/gists/#list-gists +
+ + + + + + +func (s *GistsService) ListAll(opt *GistListOptions) ([]*Gist, *Response, error)+
+ListAll lists all public gists. +
++GitHub API docs: http://developer.github.com/v3/gists/#list-gists +
+ + + + + + +func (s *GistsService) ListComments(gistID string, opt *ListOptions) ([]*GistComment, *Response, error)+
+ListComments lists all comments for a gist. +
++GitHub API docs: http://developer.github.com/v3/gists/comments/#list-comments-on-a-gist +
+ + + + + + +func (s *GistsService) ListCommits(id string) ([]*GistCommit, *Response, error)+
+ListCommits lists commits of a gist. +
++Github API docs: https://developer.github.com/v3/gists/#list-gist-commits +
+ + + + + + +func (s *GistsService) ListForks(id string) ([]*GistFork, *Response, error)+
+ListForks lists forks of a gist. +
++Github API docs: https://developer.github.com/v3/gists/#list-gist-forks +
+ + + + + + +func (s *GistsService) ListStarred(opt *GistListOptions) ([]*Gist, *Response, error)+
+ListStarred lists starred gists of authenticated user. +
++GitHub API docs: http://developer.github.com/v3/gists/#list-gists +
+ + + + + + +func (s *GistsService) Star(id string) (*Response, error)+
+Star a gist on behalf of authenticated user. +
++GitHub API docs: http://developer.github.com/v3/gists/#star-a-gist +
+ + + + + + +func (s *GistsService) Unstar(id string) (*Response, error)+
+Unstar a gist on a behalf of authenticated user. +
++Github API docs: http://developer.github.com/v3/gists/#unstar-a-gist +
+ + + + + + + + +type GitObject struct { + Type *string `json:"type"` + SHA *string `json:"sha"` + URL *string `json:"url"` +}+
+GitObject represents a Git object. +
+ + + + + + + + + + + + + + +func (o GitObject) String() string+ + + + + + + + +
type GitService service+
+GitService handles communication with the git data related +methods of the GitHub API. +
++GitHub API docs: http://developer.github.com/v3/git/ +
+ + + + + + + + + + + + + + +func (s *GitService) CreateBlob(owner string, repo string, blob *Blob) (*Blob, *Response, error)+
+CreateBlob creates a blob object. +
++GitHub API docs: https://developer.github.com/v3/git/blobs/#create-a-blob +
+ + + + + + +func (s *GitService) CreateCommit(owner string, repo string, commit *Commit) (*Commit, *Response, error)+
+CreateCommit creates a new commit in a repository. +
++The commit.Committer is optional and will be filled with the commit.Author +data if omitted. If the commit.Author is omitted, it will be filled in with +the authenticated user’s information and the current date. +
++GitHub API docs: http://developer.github.com/v3/git/commits/#create-a-commit +
+ + + + + + +func (s *GitService) CreateRef(owner string, repo string, ref *Reference) (*Reference, *Response, error)+
+CreateRef creates a new ref in a repository. +
++GitHub API docs: http://developer.github.com/v3/git/refs/#create-a-reference +
+ + + + + + +func (s *GitService) CreateTag(owner string, repo string, tag *Tag) (*Tag, *Response, error)+
+CreateTag creates a tag object. +
++GitHub API docs: http://developer.github.com/v3/git/tags/#create-a-tag-object +
+ + + + + + +func (s *GitService) CreateTree(owner string, repo string, baseTree string, entries []TreeEntry) (*Tree, *Response, error)+
+CreateTree creates a new tree in a repository. If both a tree and a nested +path modifying that tree are specified, it will overwrite the contents of +that tree with the new path contents and write a new tree out. +
++GitHub API docs: http://developer.github.com/v3/git/trees/#create-a-tree +
+ + + + + + +func (s *GitService) DeleteRef(owner string, repo string, ref string) (*Response, error)+
+DeleteRef deletes a ref from a repository. +
++GitHub API docs: http://developer.github.com/v3/git/refs/#delete-a-reference +
+ + + + + + +func (s *GitService) GetBlob(owner string, repo string, sha string) (*Blob, *Response, error)+
+GetBlob fetchs a blob from a repo given a SHA. +
++GitHub API docs: http://developer.github.com/v3/git/blobs/#get-a-blob +
+ + + + + + +func (s *GitService) GetCommit(owner string, repo string, sha string) (*Commit, *Response, error)+
+GetCommit fetchs the Commit object for a given SHA. +
++GitHub API docs: http://developer.github.com/v3/git/commits/#get-a-commit +
+ + + + + + +func (s *GitService) GetRef(owner string, repo string, ref string) (*Reference, *Response, error)+
+GetRef fetches the Reference object for a given Git ref. +
++GitHub API docs: http://developer.github.com/v3/git/refs/#get-a-reference +
+ + + + + + +func (s *GitService) GetTag(owner string, repo string, sha string) (*Tag, *Response, error)+
+GetTag fetchs a tag from a repo given a SHA. +
++GitHub API docs: http://developer.github.com/v3/git/tags/#get-a-tag +
+ + + + + + +func (s *GitService) GetTree(owner string, repo string, sha string, recursive bool) (*Tree, *Response, error)+
+GetTree fetches the Tree object for a given sha hash from a repository. +
++GitHub API docs: http://developer.github.com/v3/git/trees/#get-a-tree +
+ + + + + + +func (s *GitService) ListRefs(owner, repo string, opt *ReferenceListOptions) ([]*Reference, *Response, error)+
+ListRefs lists all refs in a repository. +
++GitHub API docs: http://developer.github.com/v3/git/refs/#get-all-references +
+ + + + + + +func (s *GitService) UpdateRef(owner string, repo string, ref *Reference, force bool) (*Reference, *Response, error)+
+UpdateRef updates an existing ref in a repository. +
++GitHub API docs: http://developer.github.com/v3/git/refs/#update-a-reference +
+ + + + + + + + +type Gitignore struct { + Name *string `json:"name,omitempty"` + Source *string `json:"source,omitempty"` +}+
+Gitignore represents a .gitignore file as returned by the GitHub API. +
+ + + + + + + + + + + + + + +func (g Gitignore) String() string+ + + + + + + + +
type GitignoresService service+
+GitignoresService provides access to the gitignore related functions in the +GitHub API. +
++GitHub API docs: http://developer.github.com/v3/gitignore/ +
+ + + + + + + + + + + + + + +func (s GitignoresService) Get(name string) (*Gitignore, *Response, error)+
+Get a Gitignore by name. +
++http://developer.github.com/v3/gitignore/#get-a-single-template +
+ + + + + + +func (s GitignoresService) List() ([]string, *Response, error)+
+List all available Gitignore templates. +
++http://developer.github.com/v3/gitignore/#listing-available-templates +
+ + + + + + + + +type GollumEvent struct { + Pages []*Page `json:"pages,omitempty"` + + // The following fields are only populated by Webhook events. + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+GollumEvent is triggered when a Wiki page is created or updated. +The Webhook event name is "gollum". +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#gollumevent +
+ + + + + + + + + + + + + + + + +type Grant struct { + ID *int `json:"id,omitempty"` + URL *string `json:"url,omitempty"` + App *AuthorizationApp `json:"app,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` + Scopes []string `json:"scopes,omitempty"` +}+
+Grant represents an OAuth application that has been granted access to an account. +
+ + + + + + + + + + + + + + +func (g Grant) String() string+ + + + + + + + +
type Hook struct { + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + Name *string `json:"name,omitempty"` + URL *string `json:"url,omitempty"` + Events []string `json:"events,omitempty"` + Active *bool `json:"active,omitempty"` + Config map[string]interface{} `json:"config,omitempty"` + ID *int `json:"id,omitempty"` +}+
+Hook represents a GitHub (web and service) hook for a repository. +
+ + + + + + + + + + + + + + +func (h Hook) String() string+ + + + + + + + +
type Import struct { + // The URL of the originating repository. + VCSURL *string `json:"vcs_url,omitempty"` + // The originating VCS type. Can be one of 'subversion', 'git', + // 'mercurial', or 'tfvc'. Without this parameter, the import job will + // take additional time to detect the VCS type before beginning the + // import. This detection step will be reflected in the response. + VCS *string `json:"vcs,omitempty"` + // VCSUsername and VCSPassword are only used for StartImport calls that + // are importing a password-protected repository. + VCSUsername *string `json:"vcs_username,omitempty"` + VCSPassword *string `json:"vcs_password,omitempty"` + // For a tfvc import, the name of the project that is being imported. + TFVCProject *string `json:"tfvc_project,omitempty"` + + // Describes whether the import has been opted in or out of using Git + // LFS. The value can be 'opt_in', 'opt_out', or 'undecided' if no + // action has been taken. + UseLFS *string `json:"use_lfs,omitempty"` + // Describes whether files larger than 100MB were found during the + // importing step. + HasLargeFiles *bool `json:"has_large_files,omitempty"` + // The total size in gigabytes of files larger than 100MB found in the + // originating repository. + LargeFilesSize *int `json:"large_files_size,omitempty"` + // The total number of files larger than 100MB found in the originating + // repository. To see a list of these files, call LargeFiles. + LargeFilesCount *int `json:"large_files_count,omitempty"` + + // Identifies the current status of an import. An import that does not + // have errors will progress through these steps: + // + // detecting - the "detection" step of the import is in progress + // because the request did not include a VCS parameter. The + // import is identifying the type of source control present at + // the URL. + // importing - the "raw" step of the import is in progress. This is + // where commit data is fetched from the original repository. + // The import progress response will include CommitCount (the + // total number of raw commits that will be imported) and + // Percent (0 - 100, the current progress through the import). + // mapping - the "rewrite" step of the import is in progress. This + // is where SVN branches are converted to Git branches, and + // where author updates are applied. The import progress + // response does not include progress information. + // pushing - the "push" step of the import is in progress. This is + // where the importer updates the repository on GitHub. The + // import progress response will include PushPercent, which is + // the percent value reported by git push when it is "Writing + // objects". + // complete - the import is complete, and the repository is ready + // on GitHub. + // + // If there are problems, you will see one of these in the status field: + // + // auth_failed - the import requires authentication in order to + // connect to the original repository. Make an UpdateImport + // request, and include VCSUsername and VCSPassword. + // error - the import encountered an error. The import progress + // response will include the FailedStep and an error message. + // Contact GitHub support for more information. + // detection_needs_auth - the importer requires authentication for + // the originating repository to continue detection. Make an + // UpdatImport request, and include VCSUsername and + // VCSPassword. + // detection_found_nothing - the importer didn't recognize any + // source control at the URL. + // detection_found_multiple - the importer found several projects + // or repositories at the provided URL. When this is the case, + // the Import Progress response will also include a + // ProjectChoices field with the possible project choices as + // values. Make an UpdateImport request, and include VCS and + // (if applicable) TFVCProject. + Status *string `json:"status,omitempty"` + CommitCount *int `json:"commit_count,omitempty"` + StatusText *string `json:"status_text,omitempty"` + AuthorsCount *int `json:"authors_count,omitempty"` + Percent *int `json:"percent,omitempty"` + PushPercent *int `json:"push_percent,omitempty"` + URL *string `json:"url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + AuthorsURL *string `json:"authors_url,omitempty"` + RepositoryURL *string `json:"repository_url,omitempty"` + Message *string `json:"message,omitempty"` + FailedStep *string `json:"failed_step,omitempty"` + + // Human readable display name, provided when the Import appears as + // part of ProjectChoices. + HumanName *string `json:"human_name,omitempty"` + + // When the importer finds several projects or repositories at the + // provided URLs, this will identify the available choices. Call + // UpdateImport with the selected Import value. + ProjectChoices []Import `json:"project_choices,omitempty"` +}+
+Import represents a repository import request. +
+ + + + + + + + + + + + + + +func (i Import) String() string+ + + + + + + + +
type Issue struct { + ID *int `json:"id,omitempty"` + Number *int `json:"number,omitempty"` + State *string `json:"state,omitempty"` + Title *string `json:"title,omitempty"` + Body *string `json:"body,omitempty"` + User *User `json:"user,omitempty"` + Labels []Label `json:"labels,omitempty"` + Assignee *User `json:"assignee,omitempty"` + Comments *int `json:"comments,omitempty"` + ClosedAt *time.Time `json:"closed_at,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + URL *string `json:"url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + Milestone *Milestone `json:"milestone,omitempty"` + PullRequestLinks *PullRequestLinks `json:"pull_request,omitempty"` + Repository *Repository `json:"repository,omitempty"` + Reactions *Reactions `json:"reactions,omitempty"` + Assignees []*User `json:"assignees,omitempty"` + + // TextMatches is only populated from search results that request text matches + // See: search.go and https://developer.github.com/v3/search/#text-match-metadata + TextMatches []TextMatch `json:"text_matches,omitempty"` +}+
+Issue represents a GitHub issue on a repository. +
+ + + + + + + + + + + + + + +func (i Issue) String() string+ + + + + + + + +
type IssueActivityEvent struct { + Action *string `json:"action,omitempty"` + Issue *Issue `json:"issue,omitempty"` + + // The following fields are only populated by Webhook events. + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+DEPRECATED: IssueActivityEvent represents the payload delivered by Issue webhook +Use IssuesEvent instead. +
+ + + + + + + + + + + + + + + + +type IssueComment struct { + ID *int `json:"id,omitempty"` + Body *string `json:"body,omitempty"` + User *User `json:"user,omitempty"` + Reactions *Reactions `json:"reactions,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + URL *string `json:"url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + IssueURL *string `json:"issue_url,omitempty"` +}+
+IssueComment represents a comment left on an issue. +
+ + + + + + + + + + + + + + +func (i IssueComment) String() string+ + + + + + + + +
type IssueCommentEvent struct { + // Action is the action that was performed on the comment. + // Possible values are: "created", "edited", "deleted". + Action *string `json:"action,omitempty"` + Issue *Issue `json:"issue,omitempty"` + Comment *IssueComment `json:"comment,omitempty"` + + // The following fields are only populated by Webhook events. + Changes *EditChange `json:"changes,omitempty"` + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+IssueCommentEvent is triggered when an issue comment is created on an issue +or pull request. +The Webhook event name is "issue_comment". +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#issuecommentevent +
+ + + + + + + + + + + + + + + + +type IssueEvent struct { + ID *int `json:"id,omitempty"` + URL *string `json:"url,omitempty"` + + // The User that generated this event. + Actor *User `json:"actor,omitempty"` + + // Event identifies the actual type of Event that occurred. Possible + // values are: + // + // closed + // The Actor closed the issue. + // If the issue was closed by commit message, CommitID holds the SHA1 hash of the commit. + // + // merged + // The Actor merged into master a branch containing a commit mentioning the issue. + // CommitID holds the SHA1 of the merge commit. + // + // referenced + // The Actor committed to master a commit mentioning the issue in its commit message. + // CommitID holds the SHA1 of the commit. + // + // reopened, locked, unlocked + // The Actor did that to the issue. + // + // renamed + // The Actor changed the issue title from Rename.From to Rename.To. + // + // mentioned + // Someone unspecified @mentioned the Actor [sic] in an issue comment body. + // + // assigned, unassigned + // The Actor assigned the issue to or removed the assignment from the Assignee. + // + // labeled, unlabeled + // The Actor added or removed the Label from the issue. + // + // milestoned, demilestoned + // The Actor added or removed the issue from the Milestone. + // + // subscribed, unsubscribed + // The Actor subscribed to or unsubscribed from notifications for an issue. + // + // head_ref_deleted, head_ref_restored + // The pull request’s branch was deleted or restored. + // + Event *string `json:"event,omitempty"` + + CreatedAt *time.Time `json:"created_at,omitempty"` + Issue *Issue `json:"issue,omitempty"` + + // Only present on certain events; see above. + Assignee *User `json:"assignee,omitempty"` + CommitID *string `json:"commit_id,omitempty"` + Milestone *Milestone `json:"milestone,omitempty"` + Label *Label `json:"label,omitempty"` + Rename *Rename `json:"rename,omitempty"` +}+
+IssueEvent represents an event that occurred around an Issue or Pull Request. +
+ + + + + + + + + + + + + + + + +type IssueListByRepoOptions struct { + // Milestone limits issues for the specified milestone. Possible values are + // a milestone number, "none" for issues with no milestone, "*" for issues + // with any milestone. + Milestone string `url:"milestone,omitempty"` + + // State filters issues based on their state. Possible values are: open, + // closed, all. Default is "open". + State string `url:"state,omitempty"` + + // Assignee filters issues based on their assignee. Possible values are a + // user name, "none" for issues that are not assigned, "*" for issues with + // any assigned user. + Assignee string `url:"assignee,omitempty"` + + // Creator filters issues based on their creator. + Creator string `url:"creator,omitempty"` + + // Mentioned filters issues to those mentioned a specific user. + Mentioned string `url:"mentioned,omitempty"` + + // Labels filters issues based on their label. + Labels []string `url:"labels,omitempty,comma"` + + // Sort specifies how to sort issues. Possible values are: created, updated, + // and comments. Default value is "created". + Sort string `url:"sort,omitempty"` + + // Direction in which to sort issues. Possible values are: asc, desc. + // Default is "desc". + Direction string `url:"direction,omitempty"` + + // Since filters issues by time. + Since time.Time `url:"since,omitempty"` + + ListOptions +}+
+IssueListByRepoOptions specifies the optional parameters to the +IssuesService.ListByRepo method. +
+ + + + + + + + + + + + + + + + +type IssueListCommentsOptions struct { + // Sort specifies how to sort comments. Possible values are: created, updated. + Sort string `url:"sort,omitempty"` + + // Direction in which to sort comments. Possible values are: asc, desc. + Direction string `url:"direction,omitempty"` + + // Since filters comments by time. + Since time.Time `url:"since,omitempty"` + + ListOptions +}+
+IssueListCommentsOptions specifies the optional parameters to the +IssuesService.ListComments method. +
+ + + + + + + + + + + + + + + + +type IssueListOptions struct { + // Filter specifies which issues to list. Possible values are: assigned, + // created, mentioned, subscribed, all. Default is "assigned". + Filter string `url:"filter,omitempty"` + + // State filters issues based on their state. Possible values are: open, + // closed, all. Default is "open". + State string `url:"state,omitempty"` + + // Labels filters issues based on their label. + Labels []string `url:"labels,comma,omitempty"` + + // Sort specifies how to sort issues. Possible values are: created, updated, + // and comments. Default value is "created". + Sort string `url:"sort,omitempty"` + + // Direction in which to sort issues. Possible values are: asc, desc. + // Default is "desc". + Direction string `url:"direction,omitempty"` + + // Since filters issues by time. + Since time.Time `url:"since,omitempty"` + + ListOptions +}+
+IssueListOptions specifies the optional parameters to the IssuesService.List +and IssuesService.ListByOrg methods. +
+ + + + + + + + + + + + + + + + +type IssueRequest struct { + Title *string `json:"title,omitempty"` + Body *string `json:"body,omitempty"` + Labels *[]string `json:"labels,omitempty"` + Assignee *string `json:"assignee,omitempty"` + State *string `json:"state,omitempty"` + Milestone *int `json:"milestone,omitempty"` + Assignees *[]string `json:"assignees,omitempty"` +}+
+IssueRequest represents a request to create/edit an issue. +It is separate from Issue above because otherwise Labels +and Assignee fail to serialize to the correct JSON. +
+ + + + + + + + + + + + + + + + +type IssuesEvent struct { + // Action is the action that was performed. Possible values are: "assigned", + // "unassigned", "labeled", "unlabeled", "opened", "closed", "reopened", "edited". + Action *string `json:"action,omitempty"` + Issue *Issue `json:"issue,omitempty"` + Assignee *User `json:"assignee,omitempty"` + Label *Label `json:"label,omitempty"` + + // The following fields are only populated by Webhook events. + Changes *EditChange `json:"changes,omitempty"` + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+IssuesEvent is triggered when an issue is assigned, unassigned, labeled, +unlabeled, opened, closed, or reopened. +The Webhook event name is "issues". +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#issuesevent +
+ + + + + + + + + + + + + + + + +type IssuesSearchResult struct { + Total *int `json:"total_count,omitempty"` + Issues []Issue `json:"items,omitempty"` +}+
+IssuesSearchResult represents the result of an issues search. +
+ + + + + + + + + + + + + + + + +type IssuesService service+
+IssuesService handles communication with the issue related +methods of the GitHub API. +
++GitHub API docs: http://developer.github.com/v3/issues/ +
+ + + + + + + + + + + + + + +func (s *IssuesService) AddAssignees(owner, repo string, number int, assignees []string) (*Issue, *Response, error)+
+AddAssignees adds the provided GitHub users as assignees to the issue. +
++GitHub API docs: https://developer.github.com/v3/issues/assignees/#add-assignees-to-an-issue +
+ + + + + + +func (s *IssuesService) AddLabelsToIssue(owner string, repo string, number int, labels []string) ([]*Label, *Response, error)+
+AddLabelsToIssue adds labels to an issue. +
++GitHub API docs: http://developer.github.com/v3/issues/labels/#list-all-labels-for-this-repository +
+ + + + + + +func (s *IssuesService) Create(owner string, repo string, issue *IssueRequest) (*Issue, *Response, error)+
+Create a new issue on the specified repository. +
++GitHub API docs: http://developer.github.com/v3/issues/#create-an-issue +
+ + + + + + +func (s *IssuesService) CreateComment(owner string, repo string, number int, comment *IssueComment) (*IssueComment, *Response, error)+
+CreateComment creates a new comment on the specified issue. +
++GitHub API docs: http://developer.github.com/v3/issues/comments/#create-a-comment +
+ + + + + + +func (s *IssuesService) CreateLabel(owner string, repo string, label *Label) (*Label, *Response, error)+
+CreateLabel creates a new label on the specified repository. +
++GitHub API docs: http://developer.github.com/v3/issues/labels/#create-a-label +
+ + + + + + +func (s *IssuesService) CreateMilestone(owner string, repo string, milestone *Milestone) (*Milestone, *Response, error)+
+CreateMilestone creates a new milestone on the specified repository. +
++GitHub API docs: https://developer.github.com/v3/issues/milestones/#create-a-milestone +
+ + + + + + +func (s *IssuesService) DeleteComment(owner string, repo string, id int) (*Response, error)+
+DeleteComment deletes an issue comment. +
++GitHub API docs: http://developer.github.com/v3/issues/comments/#delete-a-comment +
+ + + + + + +func (s *IssuesService) DeleteLabel(owner string, repo string, name string) (*Response, error)+
+DeleteLabel deletes a label. +
++GitHub API docs: http://developer.github.com/v3/issues/labels/#delete-a-label +
+ + + + + + +func (s *IssuesService) DeleteMilestone(owner string, repo string, number int) (*Response, error)+
+DeleteMilestone deletes a milestone. +
++GitHub API docs: https://developer.github.com/v3/issues/milestones/#delete-a-milestone +
+ + + + + + +func (s *IssuesService) Edit(owner string, repo string, number int, issue *IssueRequest) (*Issue, *Response, error)+
+Edit an issue. +
++GitHub API docs: http://developer.github.com/v3/issues/#edit-an-issue +
+ + + + + + +func (s *IssuesService) EditComment(owner string, repo string, id int, comment *IssueComment) (*IssueComment, *Response, error)+
+EditComment updates an issue comment. +
++GitHub API docs: http://developer.github.com/v3/issues/comments/#edit-a-comment +
+ + + + + + +func (s *IssuesService) EditLabel(owner string, repo string, name string, label *Label) (*Label, *Response, error)+
+EditLabel edits a label. +
++GitHub API docs: http://developer.github.com/v3/issues/labels/#update-a-label +
+ + + + + + +func (s *IssuesService) EditMilestone(owner string, repo string, number int, milestone *Milestone) (*Milestone, *Response, error)+
+EditMilestone edits a milestone. +
++GitHub API docs: https://developer.github.com/v3/issues/milestones/#update-a-milestone +
+ + + + + + +func (s *IssuesService) Get(owner string, repo string, number int) (*Issue, *Response, error)+
+Get a single issue. +
++GitHub API docs: http://developer.github.com/v3/issues/#get-a-single-issue +
+ + + + + + +func (s *IssuesService) GetComment(owner string, repo string, id int) (*IssueComment, *Response, error)+
+GetComment fetches the specified issue comment. +
++GitHub API docs: http://developer.github.com/v3/issues/comments/#get-a-single-comment +
+ + + + + + +func (s *IssuesService) GetEvent(owner, repo string, id int) (*IssueEvent, *Response, error)+
+GetEvent returns the specified issue event. +
++GitHub API docs: https://developer.github.com/v3/issues/events/#get-a-single-event +
+ + + + + + +func (s *IssuesService) GetLabel(owner string, repo string, name string) (*Label, *Response, error)+
+GetLabel gets a single label. +
++GitHub API docs: http://developer.github.com/v3/issues/labels/#get-a-single-label +
+ + + + + + +func (s *IssuesService) GetMilestone(owner string, repo string, number int) (*Milestone, *Response, error)+
+GetMilestone gets a single milestone. +
++GitHub API docs: https://developer.github.com/v3/issues/milestones/#get-a-single-milestone +
+ + + + + + +func (s *IssuesService) IsAssignee(owner, repo, user string) (bool, *Response, error)+
+IsAssignee checks if a user is an assignee for the specified repository. +
++GitHub API docs: http://developer.github.com/v3/issues/assignees/#check-assignee +
+ + + + + + +func (s *IssuesService) List(all bool, opt *IssueListOptions) ([]*Issue, *Response, error)+
+List the issues for the authenticated user. If all is true, list issues +across all the user's visible repositories including owned, member, and +organization repositories; if false, list only owned and member +repositories. +
++GitHub API docs: http://developer.github.com/v3/issues/#list-issues +
+ + + + + + +func (s *IssuesService) ListAssignees(owner, repo string, opt *ListOptions) ([]*User, *Response, error)+
+ListAssignees fetches all available assignees (owners and collaborators) to +which issues may be assigned. +
++GitHub API docs: http://developer.github.com/v3/issues/assignees/#list-assignees +
+ + + + + + +func (s *IssuesService) ListByOrg(org string, opt *IssueListOptions) ([]*Issue, *Response, error)+
+ListByOrg fetches the issues in the specified organization for the +authenticated user. +
++GitHub API docs: http://developer.github.com/v3/issues/#list-issues +
+ + + + + + +func (s *IssuesService) ListByRepo(owner string, repo string, opt *IssueListByRepoOptions) ([]*Issue, *Response, error)+
+ListByRepo lists the issues for the specified repository. +
++GitHub API docs: http://developer.github.com/v3/issues/#list-issues-for-a-repository +
+ + + + + + +func (s *IssuesService) ListComments(owner string, repo string, number int, opt *IssueListCommentsOptions) ([]*IssueComment, *Response, error)+
+ListComments lists all comments on the specified issue. Specifying an issue +number of 0 will return all comments on all issues for the repository. +
++GitHub API docs: http://developer.github.com/v3/issues/comments/#list-comments-on-an-issue +
+ + + + + + +func (s *IssuesService) ListIssueEvents(owner, repo string, number int, opt *ListOptions) ([]*IssueEvent, *Response, error)+
+ListIssueEvents lists events for the specified issue. +
++GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-an-issue +
+ + + + + + +func (s *IssuesService) ListIssueTimeline(owner, repo string, number int, opt *ListOptions) ([]*Timeline, *Response, error)+
+ListIssueTimeline lists events for the specified issue. +
++GitHub API docs: https://developer.github.com/v3/issues/timeline/#list-events-for-an-issue +
+ + + + + + +func (s *IssuesService) ListLabels(owner string, repo string, opt *ListOptions) ([]*Label, *Response, error)+
+ListLabels lists all labels for a repository. +
++GitHub API docs: http://developer.github.com/v3/issues/labels/#list-all-labels-for-this-repository +
+ + + + + + +func (s *IssuesService) ListLabelsByIssue(owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error)+
+ListLabelsByIssue lists all labels for an issue. +
++GitHub API docs: http://developer.github.com/v3/issues/labels/#list-all-labels-for-this-repository +
+ + + + + + +func (s *IssuesService) ListLabelsForMilestone(owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error)+
+ListLabelsForMilestone lists labels for every issue in a milestone. +
++GitHub API docs: http://developer.github.com/v3/issues/labels/#get-labels-for-every-issue-in-a-milestone +
+ + + + + + +func (s *IssuesService) ListMilestones(owner string, repo string, opt *MilestoneListOptions) ([]*Milestone, *Response, error)+
+ListMilestones lists all milestones for a repository. +
++GitHub API docs: https://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository +
+ + + + + + +func (s *IssuesService) ListRepositoryEvents(owner, repo string, opt *ListOptions) ([]*IssueEvent, *Response, error)+
+ListRepositoryEvents lists events for the specified repository. +
++GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-a-repository +
+ + + + + + +func (s *IssuesService) Lock(owner string, repo string, number int) (*Response, error)+
+Lock an issue's conversation. +
++GitHub API docs: https://developer.github.com/v3/issues/#lock-an-issue +
+ + + + + + +func (s *IssuesService) RemoveAssignees(owner, repo string, number int, assignees []string) (*Issue, *Response, error)+
+RemoveAssignees removes the provided GitHub users as assignees from the issue. +
++GitHub API docs: https://developer.github.com/v3/issues/assignees/#remove-assignees-from-an-issue +
+ + + + + + +func (s *IssuesService) RemoveLabelForIssue(owner string, repo string, number int, label string) (*Response, error)+
+RemoveLabelForIssue removes a label for an issue. +
++GitHub API docs: http://developer.github.com/v3/issues/labels/#remove-a-label-from-an-issue +
+ + + + + + +func (s *IssuesService) RemoveLabelsForIssue(owner string, repo string, number int) (*Response, error)+
+RemoveLabelsForIssue removes all labels for an issue. +
++GitHub API docs: http://developer.github.com/v3/issues/labels/#remove-all-labels-from-an-issue +
+ + + + + + +func (s *IssuesService) ReplaceLabelsForIssue(owner string, repo string, number int, labels []string) ([]*Label, *Response, error)+
+ReplaceLabelsForIssue replaces all labels for an issue. +
++GitHub API docs: http://developer.github.com/v3/issues/labels/#replace-all-labels-for-an-issue +
+ + + + + + +func (s *IssuesService) Unlock(owner string, repo string, number int) (*Response, error)+
+Unlock an issue's conversation. +
++GitHub API docs: https://developer.github.com/v3/issues/#unlock-an-issue +
+ + + + + + + + +type Key struct { + ID *int `json:"id,omitempty"` + Key *string `json:"key,omitempty"` + URL *string `json:"url,omitempty"` + Title *string `json:"title,omitempty"` + ReadOnly *bool `json:"read_only,omitempty"` +}+
+Key represents a public SSH key used to authenticate a user or deploy script. +
+ + + + + + + + + + + + + + +func (k Key) String() string+ + + + + + + + +
type Label struct { + URL *string `json:"url,omitempty"` + Name *string `json:"name,omitempty"` + Color *string `json:"color,omitempty"` +}+
+Label represents a GitHub label on an Issue +
+ + + + + + + + + + + + + + +func (l Label) String() string+ + + + + + + + +
type LargeFile struct { + RefName *string `json:"ref_name,omitempty"` + Path *string `json:"path,omitempty"` + OID *string `json:"oid,omitempty"` + Size *int `json:"size,omitempty"` +}+
+LargeFile identifies a file larger than 100MB found during a repository import. +
++GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-large-files +
+ + + + + + + + + + + + + + +func (f LargeFile) String() string+ + + + + + + + +
type License struct { + Key *string `json:"key,omitempty"` + Name *string `json:"name,omitempty"` + URL *string `json:"url,omitempty"` + + HTMLURL *string `json:"html_url,omitempty"` + Featured *bool `json:"featured,omitempty"` + Description *string `json:"description,omitempty"` + Category *string `json:"category,omitempty"` + Implementation *string `json:"implementation,omitempty"` + Required *[]string `json:"required,omitempty"` + Permitted *[]string `json:"permitted,omitempty"` + Forbidden *[]string `json:"forbidden,omitempty"` + Body *string `json:"body,omitempty"` +}+
+License represents an open source license. +
+ + + + + + + + + + + + + + +func (l License) String() string+ + + + + + + + +
type LicensesService service+
+LicensesService handles communication with the license related +methods of the GitHub API. +
++GitHub API docs: http://developer.github.com/v3/pulls/ +
+ + + + + + + + + + + + + + +func (s *LicensesService) Get(licenseName string) (*License, *Response, error)+
+Get extended metadata for one license. +
++GitHub API docs: https://developer.github.com/v3/licenses/#get-an-individual-license +
+ + + + + + +func (s *LicensesService) List() ([]*License, *Response, error)+
+List popular open source licenses. +
++GitHub API docs: https://developer.github.com/v3/licenses/#list-all-licenses +
+ + + + + + + + +type ListContributorsOptions struct { + // Include anonymous contributors in results or not + Anon string `url:"anon,omitempty"` + + ListOptions +}+
+ListContributorsOptions specifies the optional parameters to the +RepositoriesService.ListContributors method. +
+ + + + + + + + + + + + + + + + +type ListMembersOptions struct { + // If true (or if the authenticated user is not an owner of the + // organization), list only publicly visible members. + PublicOnly bool `url:"-"` + + // Filter members returned in the list. Possible values are: + // 2fa_disabled, all. Default is "all". + Filter string `url:"filter,omitempty"` + + // Role filters members returned by their role in the organization. + // Possible values are: + // all - all members of the organization, regardless of role + // admin - organization owners + // member - non-organization members + // + // Default is "all". + Role string `url:"role,omitempty"` + + ListOptions +}+
+ListMembersOptions specifies optional parameters to the +OrganizationsService.ListMembers method. +
+ + + + + + + + + + + + + + + + +type ListOptions struct { + // For paginated result sets, page of results to retrieve. + Page int `url:"page,omitempty"` + + // For paginated result sets, the number of results to include per page. + PerPage int `url:"per_page,omitempty"` +}+
+ListOptions specifies the optional parameters to various List methods that +support pagination. +
+ + + + + + + + + + + + + + + + +type ListOrgMembershipsOptions struct { + // Filter memberships to include only those with the specified state. + // Possible values are: "active", "pending". + State string `url:"state,omitempty"` + + ListOptions +}+
+ListOrgMembershipsOptions specifies optional parameters to the +OrganizationsService.ListOrgMemberships method. +
+ + + + + + + + + + + + + + + + +type MarkdownOptions struct { + // Mode identifies the rendering mode. Possible values are: + // markdown - render a document as plain Markdown, just like + // README files are rendered. + // + // gfm - to render a document as user-content, e.g. like user + // comments or issues are rendered. In GFM mode, hard line breaks are + // always taken into account, and issue and user mentions are linked + // accordingly. + // + // Default is "markdown". + Mode string + + // Context identifies the repository context. Only taken into account + // when rendering as "gfm". + Context string +}+
+MarkdownOptions specifies optional parameters to the Markdown method. +
+ + + + + + + + + + + + + + + + +type Match struct { + Text *string `json:"text,omitempty"` + Indices []int `json:"indices,omitempty"` +}+
+Match represents a single text match. +
+ + + + + + + + + + + + + + + + +type MemberEvent struct { + // Action is the action that was performed. Possible value is: "added". + Action *string `json:"action,omitempty"` + Member *User `json:"member,omitempty"` + + // The following fields are only populated by Webhook events. + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+MemberEvent is triggered when a user is added as a collaborator to a repository. +The Webhook event name is "member". +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#memberevent +
+ + + + + + + + + + + + + + + + +type Membership struct { + URL *string `json:"url,omitempty"` + + // State is the user's status within the organization or team. + // Possible values are: "active", "pending" + State *string `json:"state,omitempty"` + + // Role identifies the user's role within the organization or team. + // Possible values for organization membership: + // member - non-owner organization member + // admin - organization owner + // + // Possible values for team membership are: + // member - a normal member of the team + // maintainer - a team maintainer. Able to add/remove other team + // members, promote other team members to team + // maintainer, and edit the team’s name and description + Role *string `json:"role,omitempty"` + + // For organization membership, the API URL of the organization. + OrganizationURL *string `json:"organization_url,omitempty"` + + // For organization membership, the organization the membership is for. + Organization *Organization `json:"organization,omitempty"` + + // For organization membership, the user the membership is for. + User *User `json:"user,omitempty"` +}+
+Membership represents the status of a user's membership in an organization or team. +
+ + + + + + + + + + + + + + +func (m Membership) String() string+ + + + + + + + +
type MembershipEvent struct { + // Action is the action that was performed. Possible values are: "added", "removed". + Action *string `json:"action,omitempty"` + // Scope is the scope of the membership. Possible value is: "team". + Scope *string `json:"scope,omitempty"` + Member *User `json:"member,omitempty"` + Team *Team `json:"team,omitempty"` + + // The following fields are only populated by Webhook events. + Org *Organization `json:"organization,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+MembershipEvent is triggered when a user is added or removed from a team. +The Webhook event name is "membership". +
++Events of this type are not visible in timelines, they are only used to +trigger organization webhooks. +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#membershipevent +
+ + + + + + + + + + + + + + + + +type Migration struct { + ID *int `json:"id,omitempty"` + GUID *string `json:"guid,omitempty"` + // State is the current state of a migration. + // Possible values are: + // "pending" which means the migration hasn't started yet, + // "exporting" which means the migration is in progress, + // "exported" which means the migration finished successfully, or + // "failed" which means the migration failed. + State *string `json:"state,omitempty"` + // LockRepositories indicates whether repositories are locked (to prevent + // manipulation) while migrating data. + LockRepositories *bool `json:"lock_repositories,omitempty"` + // ExcludeAttachments indicates whether attachments should be excluded from + // the migration (to reduce migration archive file size). + ExcludeAttachments *bool `json:"exclude_attachments,omitempty"` + URL *string `json:"url,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + Repositories []*Repository `json:"repositories,omitempty"` +}+
+Migration represents a GitHub migration (archival). +
+ + + + + + + + + + + + + + +func (m Migration) String() string+ + + + + + + + +
type MigrationOptions struct { + // LockRepositories indicates whether repositories should be locked (to prevent + // manipulation) while migrating data. + LockRepositories bool + + // ExcludeAttachments indicates whether attachments should be excluded from + // the migration (to reduce migration archive file size). + ExcludeAttachments bool +}+
+MigrationOptions specifies the optional parameters to Migration methods. +
+ + + + + + + + + + + + + + + + +type MigrationService service+
+MigrationService provides access to the migration related functions +in the GitHub API. +
++GitHub API docs: https://developer.github.com/v3/migration/ +
+ + + + + + + + + + + + + + +func (s *MigrationService) CancelImport(owner, repo string) (*Response, error)+
+CancelImport stops an import for a repository. +
++GitHub API docs: https://developer.github.com/v3/migration/source_imports/#cancel-an-import +
+ + + + + + +func (s *MigrationService) CommitAuthors(owner, repo string) ([]*SourceImportAuthor, *Response, error)+
+CommitAuthors gets the authors mapped from the original repository. +
++Each type of source control system represents authors in a different way. +For example, a Git commit author has a display name and an email address, +but a Subversion commit author just has a username. The GitHub Importer will +make the author information valid, but the author might not be correct. For +example, it will change the bare Subversion username "hubot" into something +like "hubot <hubot@12341234-abab-fefe-8787-fedcba987654>". +
++This method and MapCommitAuthor allow you to provide correct Git author +information. +
++GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-commit-authors +
+ + + + + + +func (s *MigrationService) DeleteMigration(org string, id int) (*Response, error)+
+DeleteMigration deletes a previous migration archive. +id is the migration ID. +
++GitHub API docs: https://developer.github.com/v3/migration/migrations/#delete-a-migration-archive +
+ + + + + + +func (s *MigrationService) ImportProgress(owner, repo string) (*Import, *Response, error)+
+QueryImport queries for the status and progress of an ongoing repository import. +
++GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-import-progress +
+ + + + + + +func (s *MigrationService) LargeFiles(owner, repo string) ([]*LargeFile, *Response, error)+
+LargeFiles lists files larger than 100MB found during the import. +
++GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-large-files +
+ + + + + + +func (s *MigrationService) ListMigrations(org string) ([]*Migration, *Response, error)+
+ListMigrations lists the most recent migrations. +
++GitHub API docs: https://developer.github.com/v3/migration/migrations/#get-a-list-of-migrations +
+ + + + + + +func (s *MigrationService) MapCommitAuthor(owner, repo string, id int, author *SourceImportAuthor) (*SourceImportAuthor, *Response, error)+
+MapCommitAuthor updates an author's identity for the import. Your +application can continue updating authors any time before you push new +commits to the repository. +
++GitHub API docs: https://developer.github.com/v3/migration/source_imports/#map-a-commit-author +
+ + + + + + +func (s *MigrationService) MigrationArchiveURL(org string, id int) (url string, err error)+
+MigrationArchiveURL fetches a migration archive URL. +id is the migration ID. +
++GitHub API docs: https://developer.github.com/v3/migration/migrations/#download-a-migration-archive +
+ + + + + + +func (s *MigrationService) MigrationStatus(org string, id int) (*Migration, *Response, error)+
+MigrationStatus gets the status of a specific migration archive. +id is the migration ID. +
++GitHub API docs: https://developer.github.com/v3/migration/migrations/#get-the-status-of-a-migration +
+ + + + + + +func (s *MigrationService) SetLFSPreference(owner, repo string, in *Import) (*Import, *Response, error)+
+SetLFSPreference sets whether imported repositories should use Git LFS for +files larger than 100MB. Only the UseLFS field on the provided Import is +used. +
++GitHub API docs: https://developer.github.com/v3/migration/source_imports/#set-git-lfs-preference +
+ + + + + + +func (s *MigrationService) StartImport(owner, repo string, in *Import) (*Import, *Response, error)+
+StartImport initiates a repository import. +
++GitHub API docs: https://developer.github.com/v3/migration/source_imports/#start-an-import +
+ + + + + + +func (s *MigrationService) StartMigration(org string, repos []string, opt *MigrationOptions) (*Migration, *Response, error)+
+StartMigration starts the generation of a migration archive. +repos is a slice of repository names to migrate. +
++GitHub API docs: https://developer.github.com/v3/migration/migrations/#start-a-migration +
+ + + + + + +func (s *MigrationService) UnlockRepo(org string, id int, repo string) (*Response, error)+
+UnlockRepo unlocks a repository that was locked for migration. +id is the migration ID. +You should unlock each migrated repository and delete them when the migration +is complete and you no longer need the source data. +
++GitHub API docs: https://developer.github.com/v3/migration/migrations/#unlock-a-repository +
+ + + + + + +func (s *MigrationService) UpdateImport(owner, repo string, in *Import) (*Import, *Response, error)+
+UpdateImport initiates a repository import. +
++GitHub API docs: https://developer.github.com/v3/migration/source_imports/#update-existing-import +
+ + + + + + + + +type Milestone struct { + URL *string `json:"url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + LabelsURL *string `json:"labels_url,omitempty"` + ID *int `json:"id,omitempty"` + Number *int `json:"number,omitempty"` + State *string `json:"state,omitempty"` + Title *string `json:"title,omitempty"` + Description *string `json:"description,omitempty"` + Creator *User `json:"creator,omitempty"` + OpenIssues *int `json:"open_issues,omitempty"` + ClosedIssues *int `json:"closed_issues,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + ClosedAt *time.Time `json:"closed_at,omitempty"` + DueOn *time.Time `json:"due_on,omitempty"` +}+
+Milestone represents a Github repository milestone. +
+ + + + + + + + + + + + + + +func (m Milestone) String() string+ + + + + + + + +
type MilestoneListOptions struct { + // State filters milestones based on their state. Possible values are: + // open, closed. Default is "open". + State string `url:"state,omitempty"` + + // Sort specifies how to sort milestones. Possible values are: due_date, completeness. + // Default value is "due_date". + Sort string `url:"sort,omitempty"` + + // Direction in which to sort milestones. Possible values are: asc, desc. + // Default is "asc". + Direction string `url:"direction,omitempty"` + + ListOptions +}+
+MilestoneListOptions specifies the optional parameters to the +IssuesService.ListMilestones method. +
+ + + + + + + + + + + + + + + + +type NewPullRequest struct { + Title *string `json:"title,omitempty"` + Head *string `json:"head,omitempty"` + Base *string `json:"base,omitempty"` + Body *string `json:"body,omitempty"` + Issue *int `json:"issue,omitempty"` +}+
+NewPullRequest represents a new pull request to be created. +
+ + + + + + + + + + + + + + + + +type Notification struct { + ID *string `json:"id,omitempty"` + Repository *Repository `json:"repository,omitempty"` + Subject *NotificationSubject `json:"subject,omitempty"` + + // Reason identifies the event that triggered the notification. + // + // GitHub API Docs: https://developer.github.com/v3/activity/notifications/#notification-reasons + Reason *string `json:"reason,omitempty"` + + Unread *bool `json:"unread,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + LastReadAt *time.Time `json:"last_read_at,omitempty"` + URL *string `json:"url,omitempty"` +}+
+Notification identifies a GitHub notification for a user. +
+ + + + + + + + + + + + + + + + +type NotificationListOptions struct { + All bool `url:"all,omitempty"` + Participating bool `url:"participating,omitempty"` + Since time.Time `url:"since,omitempty"` + Before time.Time `url:"before,omitempty"` + + ListOptions +}+
+NotificationListOptions specifies the optional parameters to the +ActivityService.ListNotifications method. +
+ + + + + + + + + + + + + + + + +type NotificationSubject struct { + Title *string `json:"title,omitempty"` + URL *string `json:"url,omitempty"` + LatestCommentURL *string `json:"latest_comment_url,omitempty"` + Type *string `json:"type,omitempty"` +}+
+NotificationSubject identifies the subject of a notification. +
+ + + + + + + + + + + + + + + + +type Organization struct { + Login *string `json:"login,omitempty"` + ID *int `json:"id,omitempty"` + AvatarURL *string `json:"avatar_url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + Name *string `json:"name,omitempty"` + Company *string `json:"company,omitempty"` + Blog *string `json:"blog,omitempty"` + Location *string `json:"location,omitempty"` + Email *string `json:"email,omitempty"` + PublicRepos *int `json:"public_repos,omitempty"` + PublicGists *int `json:"public_gists,omitempty"` + Followers *int `json:"followers,omitempty"` + Following *int `json:"following,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + TotalPrivateRepos *int `json:"total_private_repos,omitempty"` + OwnedPrivateRepos *int `json:"owned_private_repos,omitempty"` + PrivateGists *int `json:"private_gists,omitempty"` + DiskUsage *int `json:"disk_usage,omitempty"` + Collaborators *int `json:"collaborators,omitempty"` + BillingEmail *string `json:"billing_email,omitempty"` + Type *string `json:"type,omitempty"` + Plan *Plan `json:"plan,omitempty"` + + // API URLs + URL *string `json:"url,omitempty"` + EventsURL *string `json:"events_url,omitempty"` + MembersURL *string `json:"members_url,omitempty"` + PublicMembersURL *string `json:"public_members_url,omitempty"` + ReposURL *string `json:"repos_url,omitempty"` +}+
+Organization represents a GitHub organization account. +
+ + + + + + + + + + + + + + +func (o Organization) String() string+ + + + + + + + +
type OrganizationAddTeamMembershipOptions struct { + // Role specifies the role the user should have in the team. Possible + // values are: + // member - a normal member of the team + // maintainer - a team maintainer. Able to add/remove other team + // members, promote other team members to team + // maintainer, and edit the team’s name and description + // + // Default value is "member". + Role string `json:"role,omitempty"` +}+
+OrganizationAddTeamMembershipOptions does stuff specifies the optional +parameters to the OrganizationsService.AddTeamMembership method. +
+ + + + + + + + + + + + + + + + +type OrganizationAddTeamRepoOptions struct { + // Permission specifies the permission to grant the team on this repository. + // Possible values are: + // pull - team members can pull, but not push to or administer this repository + // push - team members can pull and push, but not administer this repository + // admin - team members can pull, push and administer this repository + // + // If not specified, the team's permission attribute will be used. + Permission string `json:"permission,omitempty"` +}+
+OrganizationAddTeamRepoOptions specifies the optional parameters to the +OrganizationsService.AddTeamRepo method. +
+ + + + + + + + + + + + + + + + +type OrganizationListTeamMembersOptions struct { + // Role filters members returned by their role in the team. Possible + // values are "all", "member", "maintainer". Default is "all". + Role string `url:"role,omitempty"` + + ListOptions +}+
+OrganizationListTeamMembersOptions specifies the optional parameters to the +OrganizationsService.ListTeamMembers method. +
+ + + + + + + + + + + + + + + + +type OrganizationsListOptions struct { + // Since filters Organizations by ID. + Since int `url:"since,omitempty"` + + ListOptions +}+
+OrganizationsListOptions specifies the optional parameters to the +OrganizationsService.ListAll method. +
+ + + + + + + + + + + + + + + + +type OrganizationsService service+
+OrganizationsService provides access to the organization related functions +in the GitHub API. +
++GitHub API docs: http://developer.github.com/v3/orgs/ +
+ + + + + + + + + + + + + + +func (s *OrganizationsService) AddTeamMembership(team int, user string, opt *OrganizationAddTeamMembershipOptions) (*Membership, *Response, error)+
+AddTeamMembership adds or invites a user to a team. +
++In order to add a membership between a user and a team, the authenticated +user must have 'admin' permissions to the team or be an owner of the +organization that the team is associated with. +
++If the user is already a part of the team's organization (meaning they're on +at least one other team in the organization), this endpoint will add the +user to the team. +
++If the user is completely unaffiliated with the team's organization (meaning +they're on none of the organization's teams), this endpoint will send an +invitation to the user via email. This newly-created membership will be in +the "pending" state until the user accepts the invitation, at which point +the membership will transition to the "active" state and the user will be +added as a member of the team. +
++GitHub API docs: https://developer.github.com/v3/orgs/teams/#add-team-membership +
+ + + + + + +func (s *OrganizationsService) AddTeamRepo(team int, owner string, repo string, opt *OrganizationAddTeamRepoOptions) (*Response, error)+
+AddTeamRepo adds a repository to be managed by the specified team. The +specified repository must be owned by the organization to which the team +belongs, or a direct fork of a repository owned by the organization. +
++GitHub API docs: http://developer.github.com/v3/orgs/teams/#add-team-repo +
+ + + + + + +func (s *OrganizationsService) ConcealMembership(org, user string) (*Response, error)+
+ConcealMembership conceals a user's membership in an organization. +
++GitHub API docs: http://developer.github.com/v3/orgs/members/#conceal-a-users-membership +
+ + + + + + +func (s *OrganizationsService) CreateHook(org string, hook *Hook) (*Hook, *Response, error)+
+CreateHook creates a Hook for the specified org. +Name and Config are required fields. +
++GitHub API docs: https://developer.github.com/v3/orgs/hooks/#create-a-hook +
+ + + + + + +func (s *OrganizationsService) CreateTeam(org string, team *Team) (*Team, *Response, error)+
+CreateTeam creates a new team within an organization. +
++GitHub API docs: http://developer.github.com/v3/orgs/teams/#create-team +
+ + + + + + +func (s *OrganizationsService) DeleteHook(org string, id int) (*Response, error)+
+DeleteHook deletes a specified Hook. +
++GitHub API docs: https://developer.github.com/v3/orgs/hooks/#delete-a-hook +
+ + + + + + +func (s *OrganizationsService) DeleteTeam(team int) (*Response, error)+
+DeleteTeam deletes a team. +
++GitHub API docs: http://developer.github.com/v3/orgs/teams/#delete-team +
+ + + + + + +func (s *OrganizationsService) Edit(name string, org *Organization) (*Organization, *Response, error)+
+Edit an organization. +
++GitHub API docs: http://developer.github.com/v3/orgs/#edit-an-organization +
+ + + + + + +func (s *OrganizationsService) EditHook(org string, id int, hook *Hook) (*Hook, *Response, error)+
+EditHook updates a specified Hook. +
++GitHub API docs: https://developer.github.com/v3/orgs/hooks/#edit-a-hook +
+ + + + + + +func (s *OrganizationsService) EditOrgMembership(user, org string, membership *Membership) (*Membership, *Response, error)+
+EditOrgMembership edits the membership for user in specified organization. +Passing an empty string for user will edit the membership for the +authenticated user. +
++GitHub API docs: https://developer.github.com/v3/orgs/members/#add-or-update-organization-membership +GitHub API docs: https://developer.github.com/v3/orgs/members/#edit-your-organization-membership +
+ + + + + + +func (s *OrganizationsService) EditTeam(id int, team *Team) (*Team, *Response, error)+
+EditTeam edits a team. +
++GitHub API docs: http://developer.github.com/v3/orgs/teams/#edit-team +
+ + + + + + +func (s *OrganizationsService) Get(org string) (*Organization, *Response, error)+
+Get fetches an organization by name. +
++GitHub API docs: http://developer.github.com/v3/orgs/#get-an-organization +
+ + + + + + +func (s *OrganizationsService) GetHook(org string, id int) (*Hook, *Response, error)+
+GetHook returns a single specified Hook. +
++GitHub API docs: https://developer.github.com/v3/orgs/hooks/#get-single-hook +
+ + + + + + +func (s *OrganizationsService) GetOrgMembership(user, org string) (*Membership, *Response, error)+
+GetOrgMembership gets the membership for a user in a specified organization. +Passing an empty string for user will get the membership for the +authenticated user. +
++GitHub API docs: https://developer.github.com/v3/orgs/members/#get-organization-membership +GitHub API docs: https://developer.github.com/v3/orgs/members/#get-your-organization-membership +
+ + + + + + +func (s *OrganizationsService) GetTeam(team int) (*Team, *Response, error)+
+GetTeam fetches a team by ID. +
++GitHub API docs: http://developer.github.com/v3/orgs/teams/#get-team +
+ + + + + + +func (s *OrganizationsService) GetTeamMembership(team int, user string) (*Membership, *Response, error)+
+GetTeamMembership returns the membership status for a user in a team. +
++GitHub API docs: https://developer.github.com/v3/orgs/teams/#get-team-membership +
+ + + + + + +func (s *OrganizationsService) IsMember(org, user string) (bool, *Response, error)+
+IsMember checks if a user is a member of an organization. +
++GitHub API docs: http://developer.github.com/v3/orgs/members/#check-membership +
+ + + + + + +func (s *OrganizationsService) IsPublicMember(org, user string) (bool, *Response, error)+
+IsPublicMember checks if a user is a public member of an organization. +
++GitHub API docs: http://developer.github.com/v3/orgs/members/#check-public-membership +
+ + + + + + +func (s *OrganizationsService) IsTeamMember(team int, user string) (bool, *Response, error)+
+IsTeamMember checks if a user is a member of the specified team. +
++GitHub API docs: http://developer.github.com/v3/orgs/teams/#get-team-member +
+ + + + + + +func (s *OrganizationsService) IsTeamRepo(team int, owner string, repo string) (*Repository, *Response, error)+
+IsTeamRepo checks if a team manages the specified repository. If the +repository is managed by team, a Repository is returned which includes the +permissions team has for that repo. +
++GitHub API docs: https://developer.github.com/v3/orgs/teams/#check-if-a-team-manages-a-repository +
+ + + + + + +func (s *OrganizationsService) List(user string, opt *ListOptions) ([]*Organization, *Response, error)+
+List the organizations for a user. Passing the empty string will list +organizations for the authenticated user. +
++GitHub API docs: http://developer.github.com/v3/orgs/#list-user-organizations +
+ + + + + + +func (s *OrganizationsService) ListAll(opt *OrganizationsListOptions) ([]*Organization, *Response, error)+
+ListAll lists all organizations, in the order that they were created on GitHub. +
++Note: Pagination is powered exclusively by the since parameter. To continue +listing the next set of organizations, use the ID of the last-returned organization +as the opts.Since parameter for the next call. +
++GitHub API docs: https://developer.github.com/v3/orgs/#list-all-organizations +
+ + + + + + +func (s *OrganizationsService) ListHooks(org string, opt *ListOptions) ([]*Hook, *Response, error)+
+ListHooks lists all Hooks for the specified organization. +
++GitHub API docs: https://developer.github.com/v3/orgs/hooks/#list-hooks +
+ + + + + + +func (s *OrganizationsService) ListMembers(org string, opt *ListMembersOptions) ([]*User, *Response, error)+
+ListMembers lists the members for an organization. If the authenticated +user is an owner of the organization, this will return both concealed and +public members, otherwise it will only return public members. +
++GitHub API docs: http://developer.github.com/v3/orgs/members/#members-list +
+ + + + + + +func (s *OrganizationsService) ListOrgMemberships(opt *ListOrgMembershipsOptions) ([]*Membership, *Response, error)+
+ListOrgMemberships lists the organization memberships for the authenticated user. +
++GitHub API docs: https://developer.github.com/v3/orgs/members/#list-your-organization-memberships +
+ + + + + + +func (s *OrganizationsService) ListTeamMembers(team int, opt *OrganizationListTeamMembersOptions) ([]*User, *Response, error)+
+ListTeamMembers lists all of the users who are members of the specified +team. +
++GitHub API docs: http://developer.github.com/v3/orgs/teams/#list-team-members +
+ + + + + + +func (s *OrganizationsService) ListTeamRepos(team int, opt *ListOptions) ([]*Repository, *Response, error)+
+ListTeamRepos lists the repositories that the specified team has access to. +
++GitHub API docs: http://developer.github.com/v3/orgs/teams/#list-team-repos +
+ + + + + + +func (s *OrganizationsService) ListTeams(org string, opt *ListOptions) ([]*Team, *Response, error)+
+ListTeams lists all of the teams for an organization. +
++GitHub API docs: http://developer.github.com/v3/orgs/teams/#list-teams +
+ + + + + + +func (s *OrganizationsService) ListUserTeams(opt *ListOptions) ([]*Team, *Response, error)+
+ListUserTeams lists a user's teams +GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-user-teams +
+ + + + + + +func (s *OrganizationsService) PingHook(org string, id int) (*Response, error)+
+PingHook triggers a 'ping' event to be sent to the Hook. +
++GitHub API docs: https://developer.github.com/v3/orgs/hooks/#ping-a-hook +
+ + + + + + +func (s *OrganizationsService) PublicizeMembership(org, user string) (*Response, error)+
+PublicizeMembership publicizes a user's membership in an organization. (A +user cannot publicize the membership for another user.) +
++GitHub API docs: http://developer.github.com/v3/orgs/members/#publicize-a-users-membership +
+ + + + + + +func (s *OrganizationsService) RemoveMember(org, user string) (*Response, error)+
+RemoveMember removes a user from all teams of an organization. +
++GitHub API docs: http://developer.github.com/v3/orgs/members/#remove-a-member +
+ + + + + + +func (s *OrganizationsService) RemoveOrgMembership(user, org string) (*Response, error)+
+RemoveOrgMembership removes user from the specified organization. If the +user has been invited to the organization, this will cancel their invitation. +
++GitHub API docs: https://developer.github.com/v3/orgs/members/#remove-organization-membership +
+ + + + + + +func (s *OrganizationsService) RemoveTeamMembership(team int, user string) (*Response, error)+
+RemoveTeamMembership removes a user from a team. +
++GitHub API docs: https://developer.github.com/v3/orgs/teams/#remove-team-membership +
+ + + + + + +func (s *OrganizationsService) RemoveTeamRepo(team int, owner string, repo string) (*Response, error)+
+RemoveTeamRepo removes a repository from being managed by the specified +team. Note that this does not delete the repository, it just removes it +from the team. +
++GitHub API docs: http://developer.github.com/v3/orgs/teams/#remove-team-repo +
+ + + + + + + + +type Page struct { + PageName *string `json:"page_name,omitempty"` + Title *string `json:"title,omitempty"` + Summary *string `json:"summary,omitempty"` + Action *string `json:"action,omitempty"` + SHA *string `json:"sha,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` +}+
+Page represents a single Wiki page. +
+ + + + + + + + + + + + + + + + +type PageBuildEvent struct { + Build *PagesBuild `json:"build,omitempty"` + + // The following fields are only populated by Webhook events. + ID *int `json:"id,omitempty"` + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+PageBuildEvent represents an attempted build of a GitHub Pages site, whether +successful or not. +The Webhook event name is "page_build". +
++This event is triggered on push to a GitHub Pages enabled branch (gh-pages +for project pages, master for user and organization pages). +
++Events of this type are not visible in timelines, they are only used to trigger hooks. +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#pagebuildevent +
+ + + + + + + + + + + + + + + + +type Pages struct { + URL *string `json:"url,omitempty"` + Status *string `json:"status,omitempty"` + CNAME *string `json:"cname,omitempty"` + Custom404 *bool `json:"custom_404,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` +}+
+Pages represents a GitHub Pages site configuration. +
+ + + + + + + + + + + + + + + + +type PagesBuild struct { + URL *string `json:"url,omitempty"` + Status *string `json:"status,omitempty"` + Error *PagesError `json:"error,omitempty"` + Pusher *User `json:"pusher,omitempty"` + Commit *string `json:"commit,omitempty"` + Duration *int `json:"duration,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + UpdatedAt *Timestamp `json:"created_at,omitempty"` +}+
+PagesBuild represents the build information for a GitHub Pages site. +
+ + + + + + + + + + + + + + + + +type PagesError struct { + Message *string `json:"message,omitempty"` +}+
+PagesError represents a build error for a GitHub Pages site. +
+ + + + + + + + + + + + + + + + +type Plan struct { + Name *string `json:"name,omitempty"` + Space *int `json:"space,omitempty"` + Collaborators *int `json:"collaborators,omitempty"` + PrivateRepos *int `json:"private_repos,omitempty"` +}+
+Plan represents the payment plan for an account. See plans at https://github.com/plans. +
+ + + + + + + + + + + + + + +func (p Plan) String() string+ + + + + + + + +
type Protection struct { + Enabled *bool `json:"enabled,omitempty"` + RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks,omitempty"` +}+
+Protection represents a repository branch's protection +
+ + + + + + + + + + + + + + + + +type PublicEvent struct { + // The following fields are only populated by Webhook events. + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+PublicEvent is triggered when a private repository is open sourced. +According to GitHub: "Without a doubt: the best GitHub event." +The Webhook event name is "public". +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#publicevent +
+ + + + + + + + + + + + + + + + +type PullRequest struct { + ID *int `json:"id,omitempty"` + Number *int `json:"number,omitempty"` + State *string `json:"state,omitempty"` + Title *string `json:"title,omitempty"` + Body *string `json:"body,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + ClosedAt *time.Time `json:"closed_at,omitempty"` + MergedAt *time.Time `json:"merged_at,omitempty"` + User *User `json:"user,omitempty"` + Merged *bool `json:"merged,omitempty"` + Mergeable *bool `json:"mergeable,omitempty"` + MergedBy *User `json:"merged_by,omitempty"` + Comments *int `json:"comments,omitempty"` + Commits *int `json:"commits,omitempty"` + Additions *int `json:"additions,omitempty"` + Deletions *int `json:"deletions,omitempty"` + ChangedFiles *int `json:"changed_files,omitempty"` + URL *string `json:"url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + IssueURL *string `json:"issue_url,omitempty"` + StatusesURL *string `json:"statuses_url,omitempty"` + DiffURL *string `json:"diff_url,omitempty"` + PatchURL *string `json:"patch_url,omitempty"` + Assignee *User `json:"assignee,omitempty"` // probably only in webhooks + + Head *PullRequestBranch `json:"head,omitempty"` + Base *PullRequestBranch `json:"base,omitempty"` +}+
+PullRequest represents a GitHub pull request on a repository. +
+ + + + + + + + + + + + + + +func (p PullRequest) String() string+ + + + + + + + +
type PullRequestBranch struct { + Label *string `json:"label,omitempty"` + Ref *string `json:"ref,omitempty"` + SHA *string `json:"sha,omitempty"` + Repo *Repository `json:"repo,omitempty"` + User *User `json:"user,omitempty"` +}+
+PullRequestBranch represents a base or head branch in a GitHub pull request. +
+ + + + + + + + + + + + + + + + +type PullRequestComment struct { + ID *int `json:"id,omitempty"` + InReplyTo *int `json:"in_reply_to,omitempty"` + Body *string `json:"body,omitempty"` + Path *string `json:"path,omitempty"` + DiffHunk *string `json:"diff_hunk,omitempty"` + Position *int `json:"position,omitempty"` + OriginalPosition *int `json:"original_position,omitempty"` + CommitID *string `json:"commit_id,omitempty"` + OriginalCommitID *string `json:"original_commit_id,omitempty"` + User *User `json:"user,omitempty"` + Reactions *Reactions `json:"reactions,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + URL *string `json:"url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + PullRequestURL *string `json:"pull_request_url,omitempty"` +}+
+PullRequestComment represents a comment left on a pull request. +
+ + + + + + + + + + + + + + +func (p PullRequestComment) String() string+ + + + + + + + +
type PullRequestEvent struct { + // Action is the action that was performed. Possible values are: "assigned", + // "unassigned", "labeled", "unlabeled", "opened", "closed", or "reopened", + // "synchronize", "edited". If the action is "closed" and the merged key is false, + // the pull request was closed with unmerged commits. If the action is "closed" + // and the merged key is true, the pull request was merged. + Action *string `json:"action,omitempty"` + Number *int `json:"number,omitempty"` + PullRequest *PullRequest `json:"pull_request,omitempty"` + + // The following fields are only populated by Webhook events. + Changes *EditChange `json:"changes,omitempty"` + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+PullRequestEvent is triggered when a pull request is assigned, unassigned, +labeled, unlabeled, opened, closed, reopened, or synchronized. +The Webhook event name is "pull_request". +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#pullrequestevent +
+ + + + + + + + + + + + + + + + +type PullRequestLinks struct { + URL *string `json:"url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + DiffURL *string `json:"diff_url,omitempty"` + PatchURL *string `json:"patch_url,omitempty"` +}+
+PullRequestLinks object is added to the Issue object when it's an issue included +in the IssueCommentEvent webhook payload, if the webhooks is fired by a comment on a PR +
+ + + + + + + + + + + + + + + + +type PullRequestListCommentsOptions struct { + // Sort specifies how to sort comments. Possible values are: created, updated. + Sort string `url:"sort,omitempty"` + + // Direction in which to sort comments. Possible values are: asc, desc. + Direction string `url:"direction,omitempty"` + + // Since filters comments by time. + Since time.Time `url:"since,omitempty"` + + ListOptions +}+
+PullRequestListCommentsOptions specifies the optional parameters to the +PullRequestsService.ListComments method. +
+ + + + + + + + + + + + + + + + +type PullRequestListOptions struct { + // State filters pull requests based on their state. Possible values are: + // open, closed. Default is "open". + State string `url:"state,omitempty"` + + // Head filters pull requests by head user and branch name in the format of: + // "user:ref-name". + Head string `url:"head,omitempty"` + + // Base filters pull requests by base branch name. + Base string `url:"base,omitempty"` + + // Sort specifies how to sort pull requests. Possible values are: created, + // updated, popularity, long-running. Default is "created". + Sort string `url:"sort,omitempty"` + + // Direction in which to sort pull requests. Possible values are: asc, desc. + // If Sort is "created" or not specified, Default is "desc", otherwise Default + // is "asc" + Direction string `url:"direction,omitempty"` + + ListOptions +}+
+PullRequestListOptions specifies the optional parameters to the +PullRequestsService.List method. +
+ + + + + + + + + + + + + + + + +type PullRequestMergeResult struct { + SHA *string `json:"sha,omitempty"` + Merged *bool `json:"merged,omitempty"` + Message *string `json:"message,omitempty"` +}+
+PullRequestMergeResult represents the result of merging a pull request. +
+ + + + + + + + + + + + + + + + +type PullRequestOptions struct { + Squash bool +}+
+PullRequestOptions lets you define how a pull request will be merged. +
+ + + + + + + + + + + + + + + + +type PullRequestReviewCommentEvent struct { + // Action is the action that was performed on the comment. + // Possible values are: "created", "edited", "deleted". + Action *string `json:"action,omitempty"` + PullRequest *PullRequest `json:"pull_request,omitempty"` + Comment *PullRequestComment `json:"comment,omitempty"` + + // The following fields are only populated by Webhook events. + Changes *EditChange `json:"changes,omitempty"` + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+PullRequestReviewCommentEvent is triggered when a comment is created on a +portion of the unified diff of a pull request. +The Webhook event name is "pull_request_review_comment". +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#pullrequestreviewcommentevent +
+ + + + + + + + + + + + + + + + +type PullRequestsService service+
+PullRequestsService handles communication with the pull request related +methods of the GitHub API. +
++GitHub API docs: http://developer.github.com/v3/pulls/ +
+ + + + + + + + + + + + + + +func (s *PullRequestsService) Create(owner string, repo string, pull *NewPullRequest) (*PullRequest, *Response, error)+
+Create a new pull request on the specified repository. +
++GitHub API docs: https://developer.github.com/v3/pulls/#create-a-pull-request +
+ + + + + + +func (s *PullRequestsService) CreateComment(owner string, repo string, number int, comment *PullRequestComment) (*PullRequestComment, *Response, error)+
+CreateComment creates a new comment on the specified pull request. +
++GitHub API docs: https://developer.github.com/v3/pulls/comments/#create-a-comment +
+ + + + + + +func (s *PullRequestsService) DeleteComment(owner string, repo string, number int) (*Response, error)+
+DeleteComment deletes a pull request comment. +
++GitHub API docs: https://developer.github.com/v3/pulls/comments/#delete-a-comment +
+ + + + + + +func (s *PullRequestsService) Edit(owner string, repo string, number int, pull *PullRequest) (*PullRequest, *Response, error)+
+Edit a pull request. +
++GitHub API docs: https://developer.github.com/v3/pulls/#update-a-pull-request +
+ + + + + + +func (s *PullRequestsService) EditComment(owner string, repo string, number int, comment *PullRequestComment) (*PullRequestComment, *Response, error)+
+EditComment updates a pull request comment. +
++GitHub API docs: https://developer.github.com/v3/pulls/comments/#edit-a-comment +
+ + + + + + +func (s *PullRequestsService) Get(owner string, repo string, number int) (*PullRequest, *Response, error)+
+Get a single pull request. +
++GitHub API docs: https://developer.github.com/v3/pulls/#get-a-single-pull-request +
+ + + + + + +func (s *PullRequestsService) GetComment(owner string, repo string, number int) (*PullRequestComment, *Response, error)+
+GetComment fetches the specified pull request comment. +
++GitHub API docs: https://developer.github.com/v3/pulls/comments/#get-a-single-comment +
+ + + + + + +func (s *PullRequestsService) IsMerged(owner string, repo string, number int) (bool, *Response, error)+
+IsMerged checks if a pull request has been merged. +
++GitHub API docs: https://developer.github.com/v3/pulls/#get-if-a-pull-request-has-been-merged +
+ + + + + + +func (s *PullRequestsService) List(owner string, repo string, opt *PullRequestListOptions) ([]*PullRequest, *Response, error)+
+List the pull requests for the specified repository. +
++GitHub API docs: http://developer.github.com/v3/pulls/#list-pull-requests +
+ + + + + + +func (s *PullRequestsService) ListComments(owner string, repo string, number int, opt *PullRequestListCommentsOptions) ([]*PullRequestComment, *Response, error)+
+ListComments lists all comments on the specified pull request. Specifying a +pull request number of 0 will return all comments on all pull requests for +the repository. +
++GitHub API docs: https://developer.github.com/v3/pulls/comments/#list-comments-on-a-pull-request +
+ + + + + + +func (s *PullRequestsService) ListCommits(owner string, repo string, number int, opt *ListOptions) ([]*RepositoryCommit, *Response, error)+
+ListCommits lists the commits in a pull request. +
++GitHub API docs: https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request +
+ + + + + + +func (s *PullRequestsService) ListFiles(owner string, repo string, number int, opt *ListOptions) ([]*CommitFile, *Response, error)+
+ListFiles lists the files in a pull request. +
++GitHub API docs: https://developer.github.com/v3/pulls/#list-pull-requests-files +
+ + + + + + +func (s *PullRequestsService) Merge(owner string, repo string, number int, commitMessage string, options *PullRequestOptions) (*PullRequestMergeResult, *Response, error)+
+Merge a pull request (Merge Button™). +
++GitHub API docs: https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-buttontrade +
+ + + + + + + + +type PunchCard struct { + Day *int // Day of the week (0-6: =Sunday - Saturday). + Hour *int // Hour of day (0-23). + Commits *int // Number of commits. +}+
+PunchCard represents the number of commits made during a given hour of a +day of thew eek. +
+ + + + + + + + + + + + + + + + +type PushEvent struct { + PushID *int `json:"push_id,omitempty"` + Head *string `json:"head,omitempty"` + Ref *string `json:"ref,omitempty"` + Size *int `json:"size,omitempty"` + Commits []PushEventCommit `json:"commits,omitempty"` + Repo *PushEventRepository `json:"repository,omitempty"` + Before *string `json:"before,omitempty"` + DistinctSize *int `json:"distinct_size,omitempty"` + + // The following fields are only populated by Webhook events. + After *string `json:"after,omitempty"` + Created *bool `json:"created,omitempty"` + Deleted *bool `json:"deleted,omitempty"` + Forced *bool `json:"forced,omitempty"` + BaseRef *string `json:"base_ref,omitempty"` + Compare *string `json:"compare,omitempty"` + HeadCommit *PushEventCommit `json:"head_commit,omitempty"` + Pusher *User `json:"pusher,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+PushEvent represents a git push to a GitHub repository. +
++GitHub API docs: http://developer.github.com/v3/activity/events/types/#pushevent +
+ + + + + + + + + + + + + + +func (p PushEvent) String() string+ + + + + + + + +
type PushEventCommit struct { + Message *string `json:"message,omitempty"` + Author *CommitAuthor `json:"author,omitempty"` + URL *string `json:"url,omitempty"` + Distinct *bool `json:"distinct,omitempty"` + + // The following fields are only populated by Events API. + SHA *string `json:"sha,omitempty"` + + // The following fields are only populated by Webhook events. + ID *string `json:"id,omitempty"` + TreeID *string `json:"tree_id,omitempty"` + Timestamp *Timestamp `json:"timestamp,omitempty"` + Committer *CommitAuthor `json:"committer,omitempty"` + Added []string `json:"added,omitempty"` + Removed []string `json:"removed,omitempty"` + Modified []string `json:"modified,omitempty"` +}+
+PushEventCommit represents a git commit in a GitHub PushEvent. +
+ + + + + + + + + + + + + + +func (p PushEventCommit) String() string+ + + + + + + + +
type PushEventRepoOwner struct { + Name *string `json:"name,omitempty"` + Email *string `json:"email,omitempty"` +}+
+PushEventRepoOwner is a basic reporesntation of user/org in a PushEvent payload +
+ + + + + + + + + + + + + + + + +type PushEventRepository struct { + ID *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + FullName *string `json:"full_name,omitempty"` + Owner *PushEventRepoOwner `json:"owner,omitempty"` + Private *bool `json:"private,omitempty"` + Description *string `json:"description,omitempty"` + Fork *bool `json:"fork,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + PushedAt *Timestamp `json:"pushed_at,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` + Homepage *string `json:"homepage,omitempty"` + Size *int `json:"size,omitempty"` + StargazersCount *int `json:"stargazers_count,omitempty"` + WatchersCount *int `json:"watchers_count,omitempty"` + Language *string `json:"language,omitempty"` + HasIssues *bool `json:"has_issues,omitempty"` + HasDownloads *bool `json:"has_downloads,omitempty"` + HasWiki *bool `json:"has_wiki,omitempty"` + HasPages *bool `json:"has_pages,omitempty"` + ForksCount *int `json:"forks_count,omitempty"` + OpenIssuesCount *int `json:"open_issues_count,omitempty"` + DefaultBranch *string `json:"default_branch,omitempty"` + MasterBranch *string `json:"master_branch,omitempty"` + Organization *string `json:"organization,omitempty"` + + // The following fields are only populated by Webhook events. + URL *string `json:"url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` +}+
+PushEventRepository represents the repo object in a PushEvent payload +
+ + + + + + + + + + + + + + + + +type Rate struct { + // The number of requests per hour the client is currently limited to. + Limit int `json:"limit"` + + // The number of remaining requests the client can make this hour. + Remaining int `json:"remaining"` + + // The time at which the current rate limit will reset. + Reset Timestamp `json:"reset"` +}+
+Rate represents the rate limit for the current client. +
+ + + + + + + + + + + + + + +func (r Rate) String() string+ + + + + + + + +
type RateLimitError struct { + Rate Rate // Rate specifies last known rate limit for the client + Response *http.Response // HTTP response that caused this error + Message string `json:"message"` // error message +}+
+RateLimitError occurs when GitHub returns 403 Forbidden response with a rate limit +remaining value of 0, and error message starts with "API rate limit exceeded for ". +
+ + + + + + + + + + + + + + +func (r *RateLimitError) Error() string+ + + + + + + + +
type RateLimits struct { + // The rate limit for non-search API requests. Unauthenticated + // requests are limited to 60 per hour. Authenticated requests are + // limited to 5,000 per hour. + // + // GitHub API docs: https://developer.github.com/v3/#rate-limiting + Core *Rate `json:"core"` + + // The rate limit for search API requests. Unauthenticated requests + // are limited to 5 requests per minutes. Authenticated requests are + // limited to 20 per minute. + // + // GitHub API docs: https://developer.github.com/v3/search/#rate-limit + Search *Rate `json:"search"` +}+
+RateLimits represents the rate limits for the current client. +
+ + + + + + + + + + + + + + +func (r RateLimits) String() string+ + + + + + + + +
type Reaction struct { + // ID is the Reaction ID. + ID *int `json:"id,omitempty"` + User *User `json:"user,omitempty"` + // Content is the type of reaction. + // Possible values are: + // "+1", "-1", "laugh", "confused", "heart", "hooray". + Content *string `json:"content,omitempty"` +}+
+Reaction represents a GitHub reaction. +
+ + + + + + + + + + + + + + +func (r Reaction) String() string+ + + + + + + + +
type Reactions struct { + TotalCount *int `json:"total_count,omitempty"` + PlusOne *int `json:"+1,omitempty"` + MinusOne *int `json:"-1,omitempty"` + Laugh *int `json:"laugh,omitempty"` + Confused *int `json:"confused,omitempty"` + Heart *int `json:"heart,omitempty"` + Hooray *int `json:"hooray,omitempty"` + URL *string `json:"url,omitempty"` +}+
+Reactions represents a summary of GitHub reactions. +
+ + + + + + + + + + + + + + + + +type ReactionsService service+
+ReactionsService provides access to the reactions-related functions in the +GitHub API. +
++GitHub API docs: https://developer.github.com/v3/reactions/ +
+ + + + + + + + + + + + + + +func (s ReactionsService) CreateCommentReaction(owner, repo string, id int, content string) (*Reaction, *Response, error)+
+CreateCommentReaction creates a reaction for a commit comment. +Note that if you have already created a reaction of type content, the +previously created reaction will be returned with Status: 200 OK. +
++GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-a-commit-comment +
+ + + + + + +func (s ReactionsService) CreateIssueCommentReaction(owner, repo string, id int, content string) (*Reaction, *Response, error)+
+CreateIssueCommentReaction creates a reaction for an issue comment. +Note that if you have already created a reaction of type content, the +previously created reaction will be returned with Status: 200 OK. +
++GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue-comment +
+ + + + + + +func (s ReactionsService) CreateIssueReaction(owner, repo string, number int, content string) (*Reaction, *Response, error)+
+CreateIssueReaction creates a reaction for an issue. +Note that if you have already created a reaction of type content, the +previously created reaction will be returned with Status: 200 OK. +
++GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue +
+ + + + + + +func (s ReactionsService) CreatePullRequestCommentReaction(owner, repo string, id int, content string) (*Reaction, *Response, error)+
+CreatePullRequestCommentReaction creates a reaction for a pull request review comment. +Note that if you have already created a reaction of type content, the +previously created reaction will be returned with Status: 200 OK. +
++GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue-comment +
+ + + + + + +func (s *ReactionsService) DeleteReaction(id int) (*Response, error)+
+DeleteReaction deletes a reaction. +
++GitHub API docs: https://developer.github.com/v3/reaction/reactions/#delete-a-reaction-archive +
+ + + + + + +func (s *ReactionsService) ListCommentReactions(owner, repo string, id int, opt *ListOptions) ([]*Reaction, *Response, error)+
+ListCommentReactions lists the reactions for a commit comment. +
++GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-a-commit-comment +
+ + + + + + +func (s *ReactionsService) ListIssueCommentReactions(owner, repo string, id int, opt *ListOptions) ([]*Reaction, *Response, error)+
+ListIssueCommentReactions lists the reactions for an issue comment. +
++GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment +
+ + + + + + +func (s *ReactionsService) ListIssueReactions(owner, repo string, number int, opt *ListOptions) ([]*Reaction, *Response, error)+
+ListIssueReactions lists the reactions for an issue. +
++GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue +
+ + + + + + +func (s *ReactionsService) ListPullRequestCommentReactions(owner, repo string, id int, opt *ListOptions) ([]*Reaction, *Response, error)+
+ListPullRequestCommentReactions lists the reactions for a pull request review comment. +
++GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment +
+ + + + + + + + +type Reference struct { + Ref *string `json:"ref"` + URL *string `json:"url"` + Object *GitObject `json:"object"` +}+
+Reference represents a GitHub reference. +
+ + + + + + + + + + + + + + +func (r Reference) String() string+ + + + + + + + +
type ReferenceListOptions struct { + Type string `url:"-"` + + ListOptions +}+
+ReferenceListOptions specifies optional parameters to the +GitService.ListRefs method. +
+ + + + + + + + + + + + + + + + +type ReleaseAsset struct { + ID *int `json:"id,omitempty"` + URL *string `json:"url,omitempty"` + Name *string `json:"name,omitempty"` + Label *string `json:"label,omitempty"` + State *string `json:"state,omitempty"` + ContentType *string `json:"content_type,omitempty"` + Size *int `json:"size,omitempty"` + DownloadCount *int `json:"download_count,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` + BrowserDownloadURL *string `json:"browser_download_url,omitempty"` + Uploader *User `json:"uploader,omitempty"` +}+
+ReleaseAsset represents a Github release asset in a repository. +
+ + + + + + + + + + + + + + +func (r ReleaseAsset) String() string+ + + + + + + + +
type ReleaseEvent struct { + // Action is the action that was performed. Possible value is: "published". + Action *string `json:"action,omitempty"` + Release *RepositoryRelease `json:"release,omitempty"` + + // The following fields are only populated by Webhook events. + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+ReleaseEvent is triggered when a release is published. +The Webhook event name is "release". +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#releaseevent +
+ + + + + + + + + + + + + + + + +type Rename struct { + From *string `json:"from,omitempty"` + To *string `json:"to,omitempty"` +}+
+Rename contains details for 'renamed' events. +
+ + + + + + + + + + + + + + +func (r Rename) String() string+ + + + + + + + +
type RepoStatus struct { + ID *int `json:"id,omitempty"` + URL *string `json:"url,omitempty"` + + // State is the current state of the repository. Possible values are: + // pending, success, error, or failure. + State *string `json:"state,omitempty"` + + // TargetURL is the URL of the page representing this status. It will be + // linked from the GitHub UI to allow users to see the source of the status. + TargetURL *string `json:"target_url,omitempty"` + + // Description is a short high level summary of the status. + Description *string `json:"description,omitempty"` + + // A string label to differentiate this status from the statuses of other systems. + Context *string `json:"context,omitempty"` + + Creator *User `json:"creator,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +}+
+RepoStatus represents the status of a repository at a particular reference. +
+ + + + + + + + + + + + + + +func (r RepoStatus) String() string+ + + + + + + + +
type RepositoriesSearchResult struct { + Total *int `json:"total_count,omitempty"` + Repositories []Repository `json:"items,omitempty"` +}+
+RepositoriesSearchResult represents the result of a repositories search. +
+ + + + + + + + + + + + + + + + +type RepositoriesService service+
+RepositoriesService handles communication with the repository related +methods of the GitHub API. +
++GitHub API docs: http://developer.github.com/v3/repos/ +
+ + + + + + + + + + + + + + +func (s *RepositoriesService) AddCollaborator(owner, repo, user string, opt *RepositoryAddCollaboratorOptions) (*Response, error)+
+AddCollaborator adds the specified Github user as collaborator to the given repo. +
++GitHub API docs: https://developer.github.com/v3/repos/collaborators/#add-user-as-a-collaborator +
+ + + + + + +func (s *RepositoriesService) CompareCommits(owner, repo string, base, head string) (*CommitsComparison, *Response, error)+
+CompareCommits compares a range of commits with each other. +todo: support media formats - https://github.com/google/go-github/issues/6 +
++GitHub API docs: http://developer.github.com/v3/repos/commits/index.html#compare-two-commits +
+ + + + + + +func (s *RepositoriesService) Create(org string, repo *Repository) (*Repository, *Response, error)+
+Create a new repository. If an organization is specified, the new +repository will be created under that org. If the empty string is +specified, it will be created for the authenticated user. +
++GitHub API docs: http://developer.github.com/v3/repos/#create +
+ + + + + + +func (s *RepositoriesService) CreateComment(owner, repo, sha string, comment *RepositoryComment) (*RepositoryComment, *Response, error)+
+CreateComment creates a comment for the given commit. +Note: GitHub allows for comments to be created for non-existing files and positions. +
++GitHub API docs: http://developer.github.com/v3/repos/comments/#create-a-commit-comment +
+ + + + + + +func (s *RepositoriesService) CreateDeployment(owner, repo string, request *DeploymentRequest) (*Deployment, *Response, error)+
+CreateDeployment creates a new deployment for a repository. +
++GitHub API docs: https://developer.github.com/v3/repos/deployments/#create-a-deployment +
+ + + + + + +func (s *RepositoriesService) CreateDeploymentStatus(owner, repo string, deployment int, request *DeploymentStatusRequest) (*DeploymentStatus, *Response, error)+
+CreateDeploymentStatus creates a new status for a deployment. +
++GitHub API docs: https://developer.github.com/v3/repos/deployments/#create-a-deployment-status +
+ + + + + + +func (s *RepositoriesService) CreateFile(owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error)+
+CreateFile creates a new file in a repository at the given path and returns +the commit and file metadata. +
++GitHub API docs: http://developer.github.com/v3/repos/contents/#create-a-file +
+ + + + + + +func (s *RepositoriesService) CreateFork(owner, repo string, opt *RepositoryCreateForkOptions) (*Repository, *Response, error)+
+CreateFork creates a fork of the specified repository. +
++GitHub API docs: http://developer.github.com/v3/repos/forks/#list-forks +
+ + + + + + +func (s *RepositoriesService) CreateHook(owner, repo string, hook *Hook) (*Hook, *Response, error)+
+CreateHook creates a Hook for the specified repository. +Name and Config are required fields. +
++GitHub API docs: http://developer.github.com/v3/repos/hooks/#create-a-hook +
+ + + + + + +func (s *RepositoriesService) CreateKey(owner string, repo string, key *Key) (*Key, *Response, error)+
+CreateKey adds a deploy key for a repository. +
++GitHub API docs: http://developer.github.com/v3/repos/keys/#create +
+ + + + + + +func (s *RepositoriesService) CreateRelease(owner, repo string, release *RepositoryRelease) (*RepositoryRelease, *Response, error)+
+CreateRelease adds a new release for a repository. +
++GitHub API docs : http://developer.github.com/v3/repos/releases/#create-a-release +
+ + + + + + +func (s *RepositoriesService) CreateStatus(owner, repo, ref string, status *RepoStatus) (*RepoStatus, *Response, error)+
+CreateStatus creates a new status for a repository at the specified +reference. Ref can be a SHA, a branch name, or a tag name. +
++GitHub API docs: http://developer.github.com/v3/repos/statuses/#create-a-status +
+ + + + + + +func (s *RepositoriesService) Delete(owner, repo string) (*Response, error)+
+Delete a repository. +
++GitHub API docs: https://developer.github.com/v3/repos/#delete-a-repository +
+ + + + + + +func (s *RepositoriesService) DeleteComment(owner, repo string, id int) (*Response, error)+
+DeleteComment deletes a single comment from a repository. +
++GitHub API docs: http://developer.github.com/v3/repos/comments/#delete-a-commit-comment +
+ + + + + + +func (s *RepositoriesService) DeleteFile(owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error)+
+DeleteFile deletes a file from a repository and returns the commit. +Requires the blob SHA of the file to be deleted. +
++GitHub API docs: http://developer.github.com/v3/repos/contents/#delete-a-file +
+ + + + + + +func (s *RepositoriesService) DeleteHook(owner, repo string, id int) (*Response, error)+
+DeleteHook deletes a specified Hook. +
++GitHub API docs: http://developer.github.com/v3/repos/hooks/#delete-a-hook +
+ + + + + + +func (s *RepositoriesService) DeleteInvitation(repoID, invitationID int) (*Response, error)+
+DeleteInvitation deletes a repository invitation. +
++GitHub API docs: https://developer.github.com/v3/repos/invitations/#delete-a-repository-invitation +
+ + + + + + +func (s *RepositoriesService) DeleteKey(owner string, repo string, id int) (*Response, error)+
+DeleteKey deletes a deploy key. +
++GitHub API docs: http://developer.github.com/v3/repos/keys/#delete +
+ + + + + + +func (s *RepositoriesService) DeleteRelease(owner, repo string, id int) (*Response, error)+
+DeleteRelease delete a single release from a repository. +
++GitHub API docs : http://developer.github.com/v3/repos/releases/#delete-a-release +
+ + + + + + +func (s *RepositoriesService) DeleteReleaseAsset(owner, repo string, id int) (*Response, error)+
+DeleteReleaseAsset delete a single release asset from a repository. +
++GitHub API docs : http://developer.github.com/v3/repos/releases/#delete-a-release-asset +
+ + + + + + +func (s *RepositoriesService) DownloadContents(owner, repo, filepath string, opt *RepositoryContentGetOptions) (io.ReadCloser, error)+
+DownloadContents returns an io.ReadCloser that reads the contents of the +specified file. This function will work with files of any size, as opposed +to GetContents which is limited to 1 Mb files. It is the caller's +responsibility to close the ReadCloser. +
+ + + + + + +func (s *RepositoriesService) DownloadReleaseAsset(owner, repo string, id int) (rc io.ReadCloser, redirectURL string, err error)+
+DownloadReleaseAsset downloads a release asset or returns a redirect URL. +
++DownloadReleaseAsset returns an io.ReadCloser that reads the contents of the +specified release asset. It is the caller's responsibility to close the ReadCloser. +If a redirect is returned, the redirect URL will be returned as a string instead +of the io.ReadCloser. Exactly one of rc and redirectURL will be zero. +
++GitHub API docs : http://developer.github.com/v3/repos/releases/#get-a-single-release-asset +
+ + + + + + +func (s *RepositoriesService) Edit(owner, repo string, repository *Repository) (*Repository, *Response, error)+
+Edit updates a repository. +
++GitHub API docs: http://developer.github.com/v3/repos/#edit +
+ + + + + + +func (s *RepositoriesService) EditBranch(owner, repo, branchName string, branch *Branch) (*Branch, *Response, error)+
+EditBranch edits the branch (currently only Branch Protection) +
++GitHub API docs: https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection +
+ + + + + + +func (s *RepositoriesService) EditHook(owner, repo string, id int, hook *Hook) (*Hook, *Response, error)+
+EditHook updates a specified Hook. +
++GitHub API docs: http://developer.github.com/v3/repos/hooks/#edit-a-hook +
+ + + + + + +func (s *RepositoriesService) EditKey(owner string, repo string, id int, key *Key) (*Key, *Response, error)+
+EditKey edits a deploy key. +
++GitHub API docs: http://developer.github.com/v3/repos/keys/#edit +
+ + + + + + +func (s *RepositoriesService) EditRelease(owner, repo string, id int, release *RepositoryRelease) (*RepositoryRelease, *Response, error)+
+EditRelease edits a repository release. +
++GitHub API docs : http://developer.github.com/v3/repos/releases/#edit-a-release +
+ + + + + + +func (s *RepositoriesService) EditReleaseAsset(owner, repo string, id int, release *ReleaseAsset) (*ReleaseAsset, *Response, error)+
+EditReleaseAsset edits a repository release asset. +
++GitHub API docs : http://developer.github.com/v3/repos/releases/#edit-a-release-asset +
+ + + + + + +func (s *RepositoriesService) Get(owner, repo string) (*Repository, *Response, error)+
+Get fetches a repository. +
++GitHub API docs: http://developer.github.com/v3/repos/#get +
+ + + + + + +func (s *RepositoriesService) GetArchiveLink(owner, repo string, archiveformat archiveFormat, opt *RepositoryContentGetOptions) (*url.URL, *Response, error)+
+GetArchiveLink returns an URL to download a tarball or zipball archive for a +repository. The archiveFormat can be specified by either the github.Tarball +or github.Zipball constant. +
++GitHub API docs: http://developer.github.com/v3/repos/contents/#get-archive-link +
+ + + + + + +func (s *RepositoriesService) GetBranch(owner, repo, branch string) (*Branch, *Response, error)+
+GetBranch gets the specified branch for a repository. +
++GitHub API docs: https://developer.github.com/v3/repos/#get-branch +
+ + + + + + +func (s *RepositoriesService) GetByID(id int) (*Repository, *Response, error)+
+GetByID fetches a repository. +
++Note: GetByID uses the undocumented GitHub API endpoint /repositories/:id. +
+ + + + + + +func (s *RepositoriesService) GetCombinedStatus(owner, repo, ref string, opt *ListOptions) (*CombinedStatus, *Response, error)+
+GetCombinedStatus returns the combined status of a repository at the specified +reference. ref can be a SHA, a branch name, or a tag name. +
++GitHub API docs: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref +
+ + + + + + +func (s *RepositoriesService) GetComment(owner, repo string, id int) (*RepositoryComment, *Response, error)+
+GetComment gets a single comment from a repository. +
++GitHub API docs: http://developer.github.com/v3/repos/comments/#get-a-single-commit-comment +
+ + + + + + +func (s *RepositoriesService) GetCommit(owner, repo, sha string) (*RepositoryCommit, *Response, error)+
+GetCommit fetches the specified commit, including all details about it. +todo: support media formats - https://github.com/google/go-github/issues/6 +
++GitHub API docs: http://developer.github.com/v3/repos/commits/#get-a-single-commit +See also: http://developer.github.com//v3/git/commits/#get-a-single-commit provides the same functionality +
+ + + + + + +func (s *RepositoriesService) GetCommitSHA1(owner, repo, ref, lastSHA string) (string, *Response, error)+
+GetCommitSHA1 gets the SHA-1 of a commit reference. If a last-known SHA1 is +supplied and no new commits have occurred, a 304 Unmodified response is returned. +
++GitHub API docs: https://developer.github.com/v3/repos/commits/#get-the-sha-1-of-a-commit-reference +
+ + + + + + +func (s *RepositoriesService) GetContents(owner, repo, path string, opt *RepositoryContentGetOptions) (fileContent *RepositoryContent, directoryContent []*RepositoryContent, resp *Response, err error)+
+GetContents can return either the metadata and content of a single file +(when path references a file) or the metadata of all the files and/or +subdirectories of a directory (when path references a directory). To make it +easy to distinguish between both result types and to mimic the API as much +as possible, both result types will be returned but only one will contain a +value and the other will be nil. +
++GitHub API docs: http://developer.github.com/v3/repos/contents/#get-contents +
+ + + + + + +func (s *RepositoriesService) GetHook(owner, repo string, id int) (*Hook, *Response, error)+
+GetHook returns a single specified Hook. +
++GitHub API docs: http://developer.github.com/v3/repos/hooks/#get-single-hook +
+ + + + + + +func (s *RepositoriesService) GetKey(owner string, repo string, id int) (*Key, *Response, error)+
+GetKey fetches a single deploy key. +
++GitHub API docs: http://developer.github.com/v3/repos/keys/#get +
+ + + + + + +func (s *RepositoriesService) GetLatestPagesBuild(owner string, repo string) (*PagesBuild, *Response, error)+
+GetLatestPagesBuild fetches the latest build information for a GitHub pages site. +
++GitHub API docs: https://developer.github.com/v3/repos/pages/#list-latest-pages-build +
+ + + + + + +func (s *RepositoriesService) GetLatestRelease(owner, repo string) (*RepositoryRelease, *Response, error)+
+GetLatestRelease fetches the latest published release for the repository. +
++GitHub API docs: https://developer.github.com/v3/repos/releases/#get-the-latest-release +
+ + + + + + +func (s *RepositoriesService) GetPagesInfo(owner string, repo string) (*Pages, *Response, error)+
+GetPagesInfo fetches information about a GitHub Pages site. +
++GitHub API docs: https://developer.github.com/v3/repos/pages/#get-information-about-a-pages-site +
+ + + + + + +func (s *RepositoriesService) GetReadme(owner, repo string, opt *RepositoryContentGetOptions) (*RepositoryContent, *Response, error)+
+GetReadme gets the Readme file for the repository. +
++GitHub API docs: http://developer.github.com/v3/repos/contents/#get-the-readme +
+ + +▹ Example
+func (s *RepositoriesService) GetRelease(owner, repo string, id int) (*RepositoryRelease, *Response, error)+
+GetRelease fetches a single release. +
++GitHub API docs: http://developer.github.com/v3/repos/releases/#get-a-single-release +
+ + + + + + +func (s *RepositoriesService) GetReleaseAsset(owner, repo string, id int) (*ReleaseAsset, *Response, error)+
+GetReleaseAsset fetches a single release asset. +
++GitHub API docs : http://developer.github.com/v3/repos/releases/#get-a-single-release-asset +
+ + + + + + +func (s *RepositoriesService) GetReleaseByTag(owner, repo, tag string) (*RepositoryRelease, *Response, error)+
+GetReleaseByTag fetches a release with the specified tag. +
++GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-release-by-tag-name +
+ + + + + + +func (s *RepositoriesService) IsCollaborator(owner, repo, user string) (bool, *Response, error)+
+IsCollaborator checks whether the specified Github user has collaborator +access to the given repo. +Note: This will return false if the user is not a collaborator OR the user +is not a GitHub user. +
++GitHub API docs: http://developer.github.com/v3/repos/collaborators/#get +
+ + + + + + +func (s *RepositoriesService) License(owner, repo string) (*License, *Response, error)+
+License gets the contents of a repository's license if one is detected. +
++GitHub API docs: https://developer.github.com/v3/licenses/#get-the-contents-of-a-repositorys-license +
+ + + + + + +func (s *RepositoriesService) List(user string, opt *RepositoryListOptions) ([]*Repository, *Response, error)+
+List the repositories for a user. Passing the empty string will list +repositories for the authenticated user. +
++GitHub API docs: http://developer.github.com/v3/repos/#list-user-repositories +
+ + +▹ Example
+func (s *RepositoriesService) ListAll(opt *RepositoryListAllOptions) ([]*Repository, *Response, error)+
+ListAll lists all GitHub repositories in the order that they were created. +
++GitHub API docs: http://developer.github.com/v3/repos/#list-all-public-repositories +
+ + + + + + +func (s *RepositoriesService) ListBranches(owner string, repo string, opt *ListOptions) ([]*Branch, *Response, error)+
+ListBranches lists branches for the specified repository. +
++GitHub API docs: http://developer.github.com/v3/repos/#list-branches +
+ + + + + + +func (s *RepositoriesService) ListByOrg(org string, opt *RepositoryListByOrgOptions) ([]*Repository, *Response, error)+
+ListByOrg lists the repositories for an organization. +
++GitHub API docs: http://developer.github.com/v3/repos/#list-organization-repositories +
+ + + + + + +func (s *RepositoriesService) ListCodeFrequency(owner, repo string) ([]*WeeklyStats, *Response, error)+
+ListCodeFrequency returns a weekly aggregate of the number of additions and +deletions pushed to a repository. Returned WeeklyStats will contain +additions and deletions, but not total commits. +
++GitHub API Docs: https://developer.github.com/v3/repos/statistics/#code-frequency +
+ + + + + + +func (s *RepositoriesService) ListCollaborators(owner, repo string, opt *ListOptions) ([]*User, *Response, error)+
+ListCollaborators lists the Github users that have access to the repository. +
++GitHub API docs: http://developer.github.com/v3/repos/collaborators/#list +
+ + + + + + +func (s *RepositoriesService) ListComments(owner, repo string, opt *ListOptions) ([]*RepositoryComment, *Response, error)+
+ListComments lists all the comments for the repository. +
++GitHub API docs: http://developer.github.com/v3/repos/comments/#list-commit-comments-for-a-repository +
+ + + + + + +func (s *RepositoriesService) ListCommitActivity(owner, repo string) ([]*WeeklyCommitActivity, *Response, error)+
+ListCommitActivity returns the last year of commit activity +grouped by week. The days array is a group of commits per day, +starting on Sunday. +
++If this is the first time these statistics are requested for the given +repository, this method will return a non-nil error and a status code of +202. This is because this is the status that github returns to signify that +it is now computing the requested statistics. A follow up request, after a +delay of a second or so, should result in a successful request. +
++GitHub API Docs: https://developer.github.com/v3/repos/statistics/#commit-activity +
+ + + + + + +func (s *RepositoriesService) ListCommitComments(owner, repo, sha string, opt *ListOptions) ([]*RepositoryComment, *Response, error)+
+ListCommitComments lists all the comments for a given commit SHA. +
++GitHub API docs: http://developer.github.com/v3/repos/comments/#list-comments-for-a-single-commit +
+ + + + + + +func (s *RepositoriesService) ListCommits(owner, repo string, opt *CommitsListOptions) ([]*RepositoryCommit, *Response, error)+
+ListCommits lists the commits of a repository. +
++GitHub API docs: http://developer.github.com/v3/repos/commits/#list +
+ + + + + + +func (s *RepositoriesService) ListContributors(owner string, repository string, opt *ListContributorsOptions) ([]*Contributor, *Response, error)+
+ListContributors lists contributors for a repository. +
++GitHub API docs: http://developer.github.com/v3/repos/#list-contributors +
+ + + + + + +func (s *RepositoriesService) ListContributorsStats(owner, repo string) ([]*ContributorStats, *Response, error)+
+ListContributorsStats gets a repo's contributor list with additions, +deletions and commit counts. +
++If this is the first time these statistics are requested for the given +repository, this method will return a non-nil error and a status code of +202. This is because this is the status that github returns to signify that +it is now computing the requested statistics. A follow up request, after a +delay of a second or so, should result in a successful request. +
++GitHub API Docs: https://developer.github.com/v3/repos/statistics/#contributors +
+ + + + + + +func (s *RepositoriesService) ListDeploymentStatuses(owner, repo string, deployment int, opt *ListOptions) ([]*DeploymentStatus, *Response, error)+
+ListDeploymentStatuses lists the statuses of a given deployment of a repository. +
++GitHub API docs: https://developer.github.com/v3/repos/deployments/#list-deployment-statuses +
+ + + + + + +func (s *RepositoriesService) ListDeployments(owner, repo string, opt *DeploymentsListOptions) ([]*Deployment, *Response, error)+
+ListDeployments lists the deployments of a repository. +
++GitHub API docs: https://developer.github.com/v3/repos/deployments/#list-deployments +
+ + + + + + +func (s *RepositoriesService) ListForks(owner, repo string, opt *RepositoryListForksOptions) ([]*Repository, *Response, error)+
+ListForks lists the forks of the specified repository. +
++GitHub API docs: http://developer.github.com/v3/repos/forks/#list-forks +
+ + + + + + +func (s *RepositoriesService) ListHooks(owner, repo string, opt *ListOptions) ([]*Hook, *Response, error)+
+ListHooks lists all Hooks for the specified repository. +
++GitHub API docs: http://developer.github.com/v3/repos/hooks/#list +
+ + + + + + +func (s *RepositoriesService) ListInvitations(repoID int, opt *ListOptions) ([]*RepositoryInvitation, *Response, error)+
+ListInvitations lists all currently-open repository invitations. +
++GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-invitations-for-a-repository +
+ + + + + + +func (s *RepositoriesService) ListKeys(owner string, repo string, opt *ListOptions) ([]*Key, *Response, error)+
+ListKeys lists the deploy keys for a repository. +
++GitHub API docs: http://developer.github.com/v3/repos/keys/#list +
+ + + + + + +func (s *RepositoriesService) ListLanguages(owner string, repo string) (map[string]int, *Response, error)+
+ListLanguages lists languages for the specified repository. The returned map +specifies the languages and the number of bytes of code written in that +language. For example: +
+{ + "C": 78769, + "Python": 7769 +} ++
+GitHub API Docs: http://developer.github.com/v3/repos/#list-languages +
+ + + + + + +func (s *RepositoriesService) ListPagesBuilds(owner string, repo string) ([]*PagesBuild, *Response, error)+
+ListPagesBuilds lists the builds for a GitHub Pages site. +
++GitHub API docs: https://developer.github.com/v3/repos/pages/#list-pages-builds +
+ + + + + + +func (s *RepositoriesService) ListParticipation(owner, repo string) (*RepositoryParticipation, *Response, error)+
+ListParticipation returns the total commit counts for the 'owner' +and total commit counts in 'all'. 'all' is everyone combined, +including the 'owner' in the last 52 weeks. If you’d like to get +the commit counts for non-owners, you can subtract 'all' from 'owner'. +
++The array order is oldest week (index 0) to most recent week. +
++If this is the first time these statistics are requested for the given +repository, this method will return a non-nil error and a status code +of 202. This is because this is the status that github returns to +signify that it is now computing the requested statistics. A follow +up request, after a delay of a second or so, should result in a +successful request. +
++GitHub API Docs: https://developer.github.com/v3/repos/statistics/#participation +
+ + + + + + +func (s *RepositoriesService) ListPunchCard(owner, repo string) ([]*PunchCard, *Response, error)+
+ListPunchCard returns the number of commits per hour in each day. +
++GitHub API Docs: https://developer.github.com/v3/repos/statistics/#punch-card +
+ + + + + + +func (s *RepositoriesService) ListReleaseAssets(owner, repo string, id int, opt *ListOptions) ([]*ReleaseAsset, *Response, error)+
+ListReleaseAssets lists the release's assets. +
++GitHub API docs : http://developer.github.com/v3/repos/releases/#list-assets-for-a-release +
+ + + + + + +func (s *RepositoriesService) ListReleases(owner, repo string, opt *ListOptions) ([]*RepositoryRelease, *Response, error)+
+ListReleases lists the releases for a repository. +
++GitHub API docs: http://developer.github.com/v3/repos/releases/#list-releases-for-a-repository +
+ + + + + + +func (s *RepositoriesService) ListServiceHooks() ([]*ServiceHook, *Response, error)+
+ListServiceHooks is deprecated. Use Client.ListServiceHooks instead. +
+ + + + + + +func (s *RepositoriesService) ListStatuses(owner, repo, ref string, opt *ListOptions) ([]*RepoStatus, *Response, error)+
+ListStatuses lists the statuses of a repository at the specified +reference. ref can be a SHA, a branch name, or a tag name. +
++GitHub API docs: http://developer.github.com/v3/repos/statuses/#list-statuses-for-a-specific-ref +
+ + + + + + +func (s *RepositoriesService) ListTags(owner string, repo string, opt *ListOptions) ([]*RepositoryTag, *Response, error)+
+ListTags lists tags for the specified repository. +
++GitHub API docs: https://developer.github.com/v3/repos/#list-tags +
+ + + + + + +func (s *RepositoriesService) ListTeams(owner string, repo string, opt *ListOptions) ([]*Team, *Response, error)+
+ListTeams lists the teams for the specified repository. +
++GitHub API docs: https://developer.github.com/v3/repos/#list-teams +
+ + + + + + +func (s *RepositoriesService) Merge(owner, repo string, request *RepositoryMergeRequest) (*RepositoryCommit, *Response, error)+
+Merge a branch in the specified repository. +
++GitHub API docs: https://developer.github.com/v3/repos/merging/#perform-a-merge +
+ + + + + + +func (s *RepositoriesService) PingHook(owner, repo string, id int) (*Response, error)+
+PingHook triggers a 'ping' event to be sent to the Hook. +
++GitHub API docs: https://developer.github.com/v3/repos/hooks/#ping-a-hook +
+ + + + + + +func (s *RepositoriesService) RemoveCollaborator(owner, repo, user string) (*Response, error)+
+RemoveCollaborator removes the specified Github user as collaborator from the given repo. +Note: Does not return error if a valid user that is not a collaborator is removed. +
++GitHub API docs: http://developer.github.com/v3/repos/collaborators/#remove-collaborator +
+ + + + + + +func (s *RepositoriesService) RequestPageBuild(owner string, repo string) (*PagesBuild, *Response, error)+
+RequestPageBuild requests a build of a GitHub Pages site without needing to push new commit. +
++GitHub API docs: https://developer.github.com/v3/repos/pages/#request-a-page-build +
+ + + + + + +func (s *RepositoriesService) TestHook(owner, repo string, id int) (*Response, error)+
+TestHook triggers a test Hook by github. +
++GitHub API docs: http://developer.github.com/v3/repos/hooks/#test-a-push-hook +
+ + + + + + +func (s *RepositoriesService) UpdateComment(owner, repo string, id int, comment *RepositoryComment) (*RepositoryComment, *Response, error)+
+UpdateComment updates the body of a single comment. +
++GitHub API docs: http://developer.github.com/v3/repos/comments/#update-a-commit-comment +
+ + + + + + +func (s *RepositoriesService) UpdateFile(owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error)+
+UpdateFile updates a file in a repository at the given path and returns the +commit and file metadata. Requires the blob SHA of the file being updated. +
++GitHub API docs: http://developer.github.com/v3/repos/contents/#update-a-file +
+ + + + + + +func (s *RepositoriesService) UpdateInvitation(repoID, invitationID int, permissions string) (*RepositoryInvitation, *Response, error)+
+UpdateInvitation updates the permissions associated with a repository +invitation. +
++permissions represents the permissions that the associated user will have +on the repository. Possible values are: "read", "write", "admin". +
++GitHub API docs: https://developer.github.com/v3/repos/invitations/#update-a-repository-invitation +
+ + + + + + +func (s *RepositoriesService) UploadReleaseAsset(owner, repo string, id int, opt *UploadOptions, file *os.File) (*ReleaseAsset, *Response, error)+
+UploadReleaseAsset creates an asset by uploading a file into a release repository. +To upload assets that cannot be represented by an os.File, call NewUploadRequest directly. +
++GitHub API docs : http://developer.github.com/v3/repos/releases/#upload-a-release-asset +
+ + + + + + + + +type Repository struct { + ID *int `json:"id,omitempty"` + Owner *User `json:"owner,omitempty"` + Name *string `json:"name,omitempty"` + FullName *string `json:"full_name,omitempty"` + Description *string `json:"description,omitempty"` + Homepage *string `json:"homepage,omitempty"` + DefaultBranch *string `json:"default_branch,omitempty"` + MasterBranch *string `json:"master_branch,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + PushedAt *Timestamp `json:"pushed_at,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + CloneURL *string `json:"clone_url,omitempty"` + GitURL *string `json:"git_url,omitempty"` + MirrorURL *string `json:"mirror_url,omitempty"` + SSHURL *string `json:"ssh_url,omitempty"` + SVNURL *string `json:"svn_url,omitempty"` + Language *string `json:"language,omitempty"` + Fork *bool `json:"fork"` + ForksCount *int `json:"forks_count,omitempty"` + NetworkCount *int `json:"network_count,omitempty"` + OpenIssuesCount *int `json:"open_issues_count,omitempty"` + StargazersCount *int `json:"stargazers_count,omitempty"` + SubscribersCount *int `json:"subscribers_count,omitempty"` + WatchersCount *int `json:"watchers_count,omitempty"` + Size *int `json:"size,omitempty"` + AutoInit *bool `json:"auto_init,omitempty"` + Parent *Repository `json:"parent,omitempty"` + Source *Repository `json:"source,omitempty"` + Organization *Organization `json:"organization,omitempty"` + Permissions *map[string]bool `json:"permissions,omitempty"` + + // Only provided when using RepositoriesService.Get while in preview + License *License `json:"license,omitempty"` + + // Additional mutable fields when creating and editing a repository + Private *bool `json:"private"` + HasIssues *bool `json:"has_issues"` + HasWiki *bool `json:"has_wiki"` + HasDownloads *bool `json:"has_downloads"` + // Creating an organization repository. Required for non-owners. + TeamID *int `json:"team_id"` + + // API URLs + URL *string `json:"url,omitempty"` + ArchiveURL *string `json:"archive_url,omitempty"` + AssigneesURL *string `json:"assignees_url,omitempty"` + BlobsURL *string `json:"blobs_url,omitempty"` + BranchesURL *string `json:"branches_url,omitempty"` + CollaboratorsURL *string `json:"collaborators_url,omitempty"` + CommentsURL *string `json:"comments_url,omitempty"` + CommitsURL *string `json:"commits_url,omitempty"` + CompareURL *string `json:"compare_url,omitempty"` + ContentsURL *string `json:"contents_url,omitempty"` + ContributorsURL *string `json:"contributors_url,omitempty"` + DownloadsURL *string `json:"downloads_url,omitempty"` + EventsURL *string `json:"events_url,omitempty"` + ForksURL *string `json:"forks_url,omitempty"` + GitCommitsURL *string `json:"git_commits_url,omitempty"` + GitRefsURL *string `json:"git_refs_url,omitempty"` + GitTagsURL *string `json:"git_tags_url,omitempty"` + HooksURL *string `json:"hooks_url,omitempty"` + IssueCommentURL *string `json:"issue_comment_url,omitempty"` + IssueEventsURL *string `json:"issue_events_url,omitempty"` + IssuesURL *string `json:"issues_url,omitempty"` + KeysURL *string `json:"keys_url,omitempty"` + LabelsURL *string `json:"labels_url,omitempty"` + LanguagesURL *string `json:"languages_url,omitempty"` + MergesURL *string `json:"merges_url,omitempty"` + MilestonesURL *string `json:"milestones_url,omitempty"` + NotificationsURL *string `json:"notifications_url,omitempty"` + PullsURL *string `json:"pulls_url,omitempty"` + ReleasesURL *string `json:"releases_url,omitempty"` + StargazersURL *string `json:"stargazers_url,omitempty"` + StatusesURL *string `json:"statuses_url,omitempty"` + SubscribersURL *string `json:"subscribers_url,omitempty"` + SubscriptionURL *string `json:"subscription_url,omitempty"` + TagsURL *string `json:"tags_url,omitempty"` + TreesURL *string `json:"trees_url,omitempty"` + TeamsURL *string `json:"teams_url,omitempty"` + + // TextMatches is only populated from search results that request text matches + // See: search.go and https://developer.github.com/v3/search/#text-match-metadata + TextMatches []TextMatch `json:"text_matches,omitempty"` +}+
+Repository represents a GitHub repository. +
+ + + + + + + + + + + + + + +func (r Repository) String() string+ + + + + + + + +
type RepositoryAddCollaboratorOptions struct { + // Permission specifies the permission to grant the user on this repository. + // Possible values are: + // pull - team members can pull, but not push to or administer this repository + // push - team members can pull and push, but not administer this repository + // admin - team members can pull, push and administer this repository + // + // Default value is "push". This option is only valid for organization-owned repositories. + Permission string `json:"permission,omitempty"` +}+
+RepositoryAddCollaboratorOptions specifies the optional parameters to the +RepositoriesService.AddCollaborator method. +
+ + + + + + + + + + + + + + + + +type RepositoryComment struct { + HTMLURL *string `json:"html_url,omitempty"` + URL *string `json:"url,omitempty"` + ID *int `json:"id,omitempty"` + CommitID *string `json:"commit_id,omitempty"` + User *User `json:"user,omitempty"` + Reactions *Reactions `json:"reactions,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + + // User-mutable fields + Body *string `json:"body"` + // User-initialized fields + Path *string `json:"path,omitempty"` + Position *int `json:"position,omitempty"` +}+
+RepositoryComment represents a comment for a commit, file, or line in a repository. +
+ + + + + + + + + + + + + + +func (r RepositoryComment) String() string+ + + + + + + + +
type RepositoryCommit struct { + SHA *string `json:"sha,omitempty"` + Commit *Commit `json:"commit,omitempty"` + Author *User `json:"author,omitempty"` + Committer *User `json:"committer,omitempty"` + Parents []Commit `json:"parents,omitempty"` + Message *string `json:"message,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + + // Details about how many changes were made in this commit. Only filled in during GetCommit! + Stats *CommitStats `json:"stats,omitempty"` + // Details about which files, and how this commit touched. Only filled in during GetCommit! + Files []CommitFile `json:"files,omitempty"` +}+
+RepositoryCommit represents a commit in a repo. +Note that it's wrapping a Commit, so author/committer information is in two places, +but contain different details about them: in RepositoryCommit "github details", in Commit - "git details". +
+ + + + + + + + + + + + + + +func (r RepositoryCommit) String() string+ + + + + + + + +
type RepositoryContent struct { + Type *string `json:"type,omitempty"` + Encoding *string `json:"encoding,omitempty"` + Size *int `json:"size,omitempty"` + Name *string `json:"name,omitempty"` + Path *string `json:"path,omitempty"` + // Content contains the actual file content, which may be encoded. + // Callers should call GetContent which will decode the content if + // necessary. + Content *string `json:"content,omitempty"` + SHA *string `json:"sha,omitempty"` + URL *string `json:"url,omitempty"` + GitURL *string `json:"git_url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + DownloadURL *string `json:"download_url,omitempty"` +}+
+RepositoryContent represents a file or directory in a github repository. +
+ + + + + + + + + + + + + + +func (r *RepositoryContent) Decode() ([]byte, error)+
+Decode decodes the file content if it is base64 encoded. +
++Deprecated: Use GetContent instead. +
+ + + + + + +func (r *RepositoryContent) GetContent() (string, error)+
+GetContent returns the content of r, decoding it if necessary. +
+ + + + + + +func (r RepositoryContent) String() string+
+String converts RepositoryContent to a string. It's primarily for testing. +
+ + + + + + + + +type RepositoryContentFileOptions struct { + Message *string `json:"message,omitempty"` + Content []byte `json:"content,omitempty"` // unencoded + SHA *string `json:"sha,omitempty"` + Branch *string `json:"branch,omitempty"` + Author *CommitAuthor `json:"author,omitempty"` + Committer *CommitAuthor `json:"committer,omitempty"` +}+
+RepositoryContentFileOptions specifies optional parameters for CreateFile, UpdateFile, and DeleteFile. +
+ + + + + + + + + + + + + + + + +type RepositoryContentGetOptions struct { + Ref string `url:"ref,omitempty"` +}+
+RepositoryContentGetOptions represents an optional ref parameter, which can be a SHA, +branch, or tag +
+ + + + + + + + + + + + + + + + +type RepositoryContentResponse struct { + Content *RepositoryContent `json:"content,omitempty"` + Commit `json:"commit,omitempty"` +}+
+RepositoryContentResponse holds the parsed response from CreateFile, UpdateFile, and DeleteFile. +
+ + + + + + + + + + + + + + + + +type RepositoryCreateForkOptions struct { + // The organization to fork the repository into. + Organization string `url:"organization,omitempty"` +}+
+RepositoryCreateForkOptions specifies the optional parameters to the +RepositoriesService.CreateFork method. +
+ + + + + + + + + + + + + + + + +type RepositoryEvent struct { + // Action is the action that was performed. Possible values are: "created", "deleted", + // "publicized", "privatized". + Action *string `json:"action,omitempty"` + Repo *Repository `json:"repository,omitempty"` + + // The following fields are only populated by Webhook events. + Org *Organization `json:"organization,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+RepositoryEvent is triggered when a repository is created. +The Webhook event name is "repository". +
++Events of this type are not visible in timelines, they are only used to +trigger organization webhooks. +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#repositoryevent +
+ + + + + + + + + + + + + + + + +type RepositoryInvitation struct { + ID *int `json:"id,omitempty"` + Repo *Repository `json:"repository,omitempty"` + Invitee *User `json:"invitee,omitempty"` + Inviter *User `json:"inviter,omitempty"` + + // Permissions represents the permissions that the associated user will have + // on the repository. Possible values are: "read", "write", "admin". + Permissions *string `json:"permissions,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + URL *string `json:"url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` +}+
+RepositoryInvitation represents an invitation to collaborate on a repo. +
+ + + + + + + + + + + + + + + + +type RepositoryListAllOptions struct { + // ID of the last repository seen + Since int `url:"since,omitempty"` + + ListOptions +}+
+RepositoryListAllOptions specifies the optional parameters to the +RepositoriesService.ListAll method. +
+ + + + + + + + + + + + + + + + +type RepositoryListByOrgOptions struct { + // Type of repositories to list. Possible values are: all, public, private, + // forks, sources, member. Default is "all". + Type string `url:"type,omitempty"` + + ListOptions +}+
+RepositoryListByOrgOptions specifies the optional parameters to the +RepositoriesService.ListByOrg method. +
+ + + + + + + + + + + + + + + + +type RepositoryListForksOptions struct { + // How to sort the forks list. Possible values are: newest, oldest, + // watchers. Default is "newest". + Sort string `url:"sort,omitempty"` + + ListOptions +}+
+RepositoryListForksOptions specifies the optional parameters to the +RepositoriesService.ListForks method. +
+ + + + + + + + + + + + + + + + +type RepositoryListOptions struct { + // Visibility of repositories to list. Can be one of all, public, or private. + // Default: all + Visibility string `url:"visibility,omitempty"` + + // List repos of given affiliation[s]. + // Comma-separated list of values. Can include: + // * owner: Repositories that are owned by the authenticated user. + // * collaborator: Repositories that the user has been added to as a + // collaborator. + // * organization_member: Repositories that the user has access to through + // being a member of an organization. This includes every repository on + // every team that the user is on. + // Default: owner,collaborator,organization_member + Affiliation string `url:"affiliation,omitempty"` + + // Type of repositories to list. + // Can be one of all, owner, public, private, member. Default: all + // Will cause a 422 error if used in the same request as visibility or + // affiliation. + Type string `url:"type,omitempty"` + + // How to sort the repository list. Can be one of created, updated, pushed, + // full_name. Default: full_name + Sort string `url:"sort,omitempty"` + + // Direction in which to sort repositories. Can be one of asc or desc. + // Default: when using full_name: asc; otherwise desc + Direction string `url:"direction,omitempty"` + + ListOptions +}+
+RepositoryListOptions specifies the optional parameters to the +RepositoriesService.List method. +
+ + + + + + + + + + + + + + + + +type RepositoryMergeRequest struct { + Base *string `json:"base,omitempty"` + Head *string `json:"head,omitempty"` + CommitMessage *string `json:"commit_message,omitempty"` +}+
+RepositoryMergeRequest represents a request to merge a branch in a +repository. +
+ + + + + + + + + + + + + + + + +type RepositoryParticipation struct { + All []int `json:"all,omitempty"` + Owner []int `json:"owner,omitempty"` +}+
+RepositoryParticipation is the number of commits by everyone +who has contributed to the repository (including the owner) +as well as the number of commits by the owner themself. +
+ + + + + + + + + + + + + + +func (r RepositoryParticipation) String() string+ + + + + + + + +
type RepositoryRelease struct { + ID *int `json:"id,omitempty"` + TagName *string `json:"tag_name,omitempty"` + TargetCommitish *string `json:"target_commitish,omitempty"` + Name *string `json:"name,omitempty"` + Body *string `json:"body,omitempty"` + Draft *bool `json:"draft,omitempty"` + Prerelease *bool `json:"prerelease,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + PublishedAt *Timestamp `json:"published_at,omitempty"` + URL *string `json:"url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + AssetsURL *string `json:"assets_url,omitempty"` + Assets []ReleaseAsset `json:"assets,omitempty"` + UploadURL *string `json:"upload_url,omitempty"` + ZipballURL *string `json:"zipball_url,omitempty"` + TarballURL *string `json:"tarball_url,omitempty"` + Author *CommitAuthor `json:"author,omitempty"` +}+
+RepositoryRelease represents a GitHub release in a repository. +
+ + + + + + + + + + + + + + +func (r RepositoryRelease) String() string+ + + + + + + + +
type RepositoryTag struct { + Name *string `json:"name,omitempty"` + Commit *Commit `json:"commit,omitempty"` + ZipballURL *string `json:"zipball_url,omitempty"` + TarballURL *string `json:"tarball_url,omitempty"` +}+
+RepositoryTag represents a repository tag. +
+ + + + + + + + + + + + + + + + +type RequiredStatusChecks struct { + // Who required status checks apply to. + // Possible values are: + // off + // non_admins + // everyone + EnforcementLevel *string `json:"enforcement_level,omitempty"` + // The list of status checks which are required + Contexts *[]string `json:"contexts,omitempty"` +}+
+RequiredStatusChecks represents the protection status of a individual branch +
+ + + + + + + + + + + + + + + + +type Response struct { + *http.Response + + NextPage int + PrevPage int + FirstPage int + LastPage int + + Rate +}+
+Response is a GitHub API response. This wraps the standard http.Response +returned from GitHub and provides convenient access to things like +pagination links. +
+ + + + + + + + + + + + + + + + +type Scope string+
+Scope models a GitHub authorization scope. +
++GitHub API docs:https://developer.github.com/v3/oauth/#scopes +
+ + + +const ( + ScopeNone Scope = "(no scope)" // REVISIT: is this actually returned, or just a documentation artifact? + ScopeUser Scope = "user" + ScopeUserEmail Scope = "user:email" + ScopeUserFollow Scope = "user:follow" + ScopePublicRepo Scope = "public_repo" + ScopeRepo Scope = "repo" + ScopeRepoDeployment Scope = "repo_deployment" + ScopeRepoStatus Scope = "repo:status" + ScopeDeleteRepo Scope = "delete_repo" + ScopeNotifications Scope = "notifications" + ScopeGist Scope = "gist" + ScopeReadRepoHook Scope = "read:repo_hook" + ScopeWriteRepoHook Scope = "write:repo_hook" + ScopeAdminRepoHook Scope = "admin:repo_hook" + ScopeAdminOrgHook Scope = "admin:org_hook" + ScopeReadOrg Scope = "read:org" + ScopeWriteOrg Scope = "write:org" + ScopeAdminOrg Scope = "admin:org" + ScopeReadPublicKey Scope = "read:public_key" + ScopeWritePublicKey Scope = "write:public_key" + ScopeAdminPublicKey Scope = "admin:public_key" + ScopeReadGPGKey Scope = "read:gpg_key" + ScopeWriteGPGKey Scope = "write:gpg_key" + ScopeAdminGPGKey Scope = "admin:gpg_key" +)+
+This is the set of scopes for GitHub API V3 +
+ + + + + + + + + + + + + + + +type SearchOptions struct { + // How to sort the search results. Possible values are: + // - for repositories: stars, fork, updated + // - for code: indexed + // - for issues: comments, created, updated + // - for users: followers, repositories, joined + // + // Default is to sort by best match. + Sort string `url:"sort,omitempty"` + + // Sort order if sort parameter is provided. Possible values are: asc, + // desc. Default is desc. + Order string `url:"order,omitempty"` + + // Whether to retrieve text match metadata with a query + TextMatch bool `url:"-"` + + ListOptions +}+
+SearchOptions specifies optional parameters to the SearchService methods. +
+ + + + + + + + + + + + + + + + +type SearchService service+
+SearchService provides access to the search related functions +in the GitHub API. +
++GitHub API docs: http://developer.github.com/v3/search/ +
+ + + + + + + + + + + + + + +func (s *SearchService) Code(query string, opt *SearchOptions) (*CodeSearchResult, *Response, error)+
+Code searches code via various criteria. +
++GitHub API docs: http://developer.github.com/v3/search/#search-code +
+ + + + + + +func (s *SearchService) Issues(query string, opt *SearchOptions) (*IssuesSearchResult, *Response, error)+
+Issues searches issues via various criteria. +
++GitHub API docs: http://developer.github.com/v3/search/#search-issues +
+ + + + + + +func (s *SearchService) Repositories(query string, opt *SearchOptions) (*RepositoriesSearchResult, *Response, error)+
+Repositories searches repositories via various criteria. +
++GitHub API docs: http://developer.github.com/v3/search/#search-repositories +
+ + + + + + +func (s *SearchService) Users(query string, opt *SearchOptions) (*UsersSearchResult, *Response, error)+
+Users searches users via various criteria. +
++GitHub API docs: http://developer.github.com/v3/search/#search-users +
+ + + + + + + + +type ServiceHook struct { + Name *string `json:"name,omitempty"` + Events []string `json:"events,omitempty"` + SupportedEvents []string `json:"supported_events,omitempty"` + Schema [][]string `json:"schema,omitempty"` +}+
+ServiceHook represents a hook that has configuration settings, a list of +available events, and default events. +
+ + + + + + + + + + + + + + +func (s *ServiceHook) String() string+ + + + + + + + +
type SignatureVerification struct { + Verified *bool `json:"verified,omitempty"` + Reason *string `json:"reason,omitempty"` + Signature *string `json:"signature,omitempty"` + Payload *string `json:"payload,omitempty"` +}+
+SignatureVerification represents GPG signature verification. +
+ + + + + + + + + + + + + + + + +type Source struct { + ID *int `json:"id,omitempty"` + URL *string `json:"url,omitempty"` + Actor *User `json:"actor,omitempty"` +}+
+Source represents a reference's source. +
+ + + + + + + + + + + + + + + + +type SourceImportAuthor struct { + ID *int `json:"id,omitempty"` + RemoteID *string `json:"remote_id,omitempty"` + RemoteName *string `json:"remote_name,omitempty"` + Email *string `json:"email,omitempty"` + Name *string `json:"name,omitempty"` + URL *string `json:"url,omitempty"` + ImportURL *string `json:"import_url,omitempty"` +}+
+SourceImportAuthor identifies an author imported from a source repository. +
++GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-commit-authors +
+ + + + + + + + + + + + + + +func (a SourceImportAuthor) String() string+ + + + + + + + +
type Stargazer struct { + StarredAt *Timestamp `json:"starred_at,omitempty"` + User *User `json:"user,omitempty"` +}+
+Stargazer represents a user that has starred a repository. +
+ + + + + + + + + + + + + + + + +type StarredRepository struct { + StarredAt *Timestamp `json:"starred_at,omitempty"` + Repository *Repository `json:"repo,omitempty"` +}+
+StarredRepository is returned by ListStarred. +
+ + + + + + + + + + + + + + + + +type StatusEvent struct { + SHA *string `json:"sha,omitempty"` + // State is the new state. Possible values are: "pending", "success", "failure", "error". + State *string `json:"state,omitempty"` + Description *string `json:"description,omitempty"` + TargetURL *string `json:"target_url,omitempty"` + Branches []*Branch `json:"branches,omitempty"` + + // The following fields are only populated by Webhook events. + ID *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Context *string `json:"context,omitempty"` + Commit *PushEventCommit `json:"commit,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+StatusEvent is triggered when the status of a Git commit changes. +The Webhook event name is "status". +
++Events of this type are not visible in timelines, they are only used to +trigger hooks. +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#statusevent +
+ + + + + + + + + + + + + + + + +type Subscription struct { + Subscribed *bool `json:"subscribed,omitempty"` + Ignored *bool `json:"ignored,omitempty"` + Reason *string `json:"reason,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + URL *string `json:"url,omitempty"` + + // only populated for repository subscriptions + RepositoryURL *string `json:"repository_url,omitempty"` + + // only populated for thread subscriptions + ThreadURL *string `json:"thread_url,omitempty"` +}+
+Subscription identifies a repository or thread subscription. +
+ + + + + + + + + + + + + + + + +type Tag struct { + Tag *string `json:"tag,omitempty"` + SHA *string `json:"sha,omitempty"` + URL *string `json:"url,omitempty"` + Message *string `json:"message,omitempty"` + Tagger *CommitAuthor `json:"tagger,omitempty"` + Object *GitObject `json:"object,omitempty"` + Verification *SignatureVerification `json:"verification,omitempty"` +}+
+Tag represents a tag object. +
+ + + + + + + + + + + + + + + + +type Team struct { + ID *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` + URL *string `json:"url,omitempty"` + Slug *string `json:"slug,omitempty"` + + // Permission is deprecated when creating or editing a team in an org + // using the new GitHub permission model. It no longer identifies the + // permission a team has on its repos, but only specifies the default + // permission a repo is initially added with. Avoid confusion by + // specifying a permission value when calling AddTeamRepo. + Permission *string `json:"permission,omitempty"` + + // Privacy identifies the level of privacy this team should have. + // Possible values are: + // secret - only visible to organization owners and members of this team + // closed - visible to all members of this organization + // Default is "secret". + Privacy *string `json:"privacy,omitempty"` + + MembersCount *int `json:"members_count,omitempty"` + ReposCount *int `json:"repos_count,omitempty"` + Organization *Organization `json:"organization,omitempty"` + MembersURL *string `json:"members_url,omitempty"` + RepositoriesURL *string `json:"repositories_url,omitempty"` +}+
+Team represents a team within a GitHub organization. Teams are used to +manage access to an organization's repositories. +
+ + + + + + + + + + + + + + +func (t Team) String() string+ + + + + + + + +
type TeamAddEvent struct { + Team *Team `json:"team,omitempty"` + Repo *Repository `json:"repository,omitempty"` + + // The following fields are only populated by Webhook events. + Org *Organization `json:"organization,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+TeamAddEvent is triggered when a repository is added to a team. +The Webhook event name is "team_add". +
++Events of this type are not visible in timelines. These events are only used +to trigger hooks. +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#teamaddevent +
+ + + + + + + + + + + + + + + + +type TextMatch struct { + ObjectURL *string `json:"object_url,omitempty"` + ObjectType *string `json:"object_type,omitempty"` + Property *string `json:"property,omitempty"` + Fragment *string `json:"fragment,omitempty"` + Matches []Match `json:"matches,omitempty"` +}+
+TextMatch represents a text match for a SearchResult +
+ + + + + + + + + + + + + + +func (tm TextMatch) String() string+ + + + + + + + +
type Timeline struct { + ID *int `json:"id,omitempty"` + URL *string `json:"url,omitempty"` + CommitURL *string `json:"commit_url,omitempty"` + + // The User object that generated the event. + Actor *User `json:"actor,omitempty"` + + // Event identifies the actual type of Event that occurred. Possible values + // are: + // + // assigned + // The issue was assigned to the assignee. + // + // closed + // The issue was closed by the actor. When the commit_id is present, it + // identifies the commit that closed the issue using "closes / fixes #NN" + // syntax. + // + // commented + // A comment was added to the issue. + // + // committed + // A commit was added to the pull request's 'HEAD' branch. Only provided + // for pull requests. + // + // cross-referenced + // The issue was referenced from another issue. The 'source' attribute + // contains the 'id', 'actor', and 'url' of the reference's source. + // + // demilestoned + // The issue was removed from a milestone. + // + // head_ref_deleted + // The pull request's branch was deleted. + // + // head_ref_restored + // The pull request's branch was restored. + // + // labeled + // A label was added to the issue. + // + // locked + // The issue was locked by the actor. + // + // mentioned + // The actor was @mentioned in an issue body. + // + // merged + // The issue was merged by the actor. The 'commit_id' attribute is the + // SHA1 of the HEAD commit that was merged. + // + // milestoned + // The issue was added to a milestone. + // + // referenced + // The issue was referenced from a commit message. The 'commit_id' + // attribute is the commit SHA1 of where that happened. + // + // renamed + // The issue title was changed. + // + // reopened + // The issue was reopened by the actor. + // + // subscribed + // The actor subscribed to receive notifications for an issue. + // + // unassigned + // The assignee was unassigned from the issue. + // + // unlabeled + // A label was removed from the issue. + // + // unlocked + // The issue was unlocked by the actor. + // + // unsubscribed + // The actor unsubscribed to stop receiving notifications for an issue. + // + Event *string `json:"event,omitempty"` + + // The string SHA of a commit that referenced this Issue or Pull Request. + CommitID *string `json:"commit_id,omitempty"` + // The timestamp indicating when the event occurred. + CreatedAt *time.Time `json:"created_at,omitempty"` + // The Label object including `name` and `color` attributes. Only provided for + // 'labeled' and 'unlabeled' events. + Label *Label `json:"label,omitempty"` + // The User object which was assigned to (or unassigned from) this Issue or + // Pull Request. Only provided for 'assigned' and 'unassigned' events. + Assignee *User `json:"assignee,omitempty"` + // The Milestone object including a 'title' attribute. + // Only provided for 'milestoned' and 'demilestoned' events. + Milestone *Milestone `json:"milestone,omitempty"` + // The 'id', 'actor', and 'url' for the source of a reference from another issue. + // Only provided for 'cross-referenced' events. + Source *Source `json:"source,omitempty"` + // An object containing rename details including 'from' and 'to' attributes. + // Only provided for 'renamed' events. + Rename *Rename `json:"rename,omitempty"` +}+
+Timeline represents an event that occurred around an Issue or Pull Request. +
++It is similar to an IssueEvent but may contain more information. +GitHub API docs: https://developer.github.com/v3/issues/timeline/ +
+ + + + + + + + + + + + + + + + +type Timestamp struct { + time.Time +}+
+Timestamp represents a time that can be unmarshalled from a JSON string +formatted as either an RFC3339 or Unix timestamp. This is necessary for some +fields since the GitHub API is inconsistent in how it represents times. All +exported methods of time.Time can be called on Timestamp. +
+ + + + + + + + + + + + + + +func (t Timestamp) Equal(u Timestamp) bool+
+Equal reports whether t and u are equal based on time.Equal +
+ + + + + + +func (t Timestamp) String() string+ + + + + + +
func (t *Timestamp) UnmarshalJSON(data []byte) (err error)+
+UnmarshalJSON implements the json.Unmarshaler interface. +Time is expected in RFC3339 or Unix format. +
+ + + + + + + + +type Tree struct { + SHA *string `json:"sha,omitempty"` + Entries []TreeEntry `json:"tree,omitempty"` +}+
+Tree represents a GitHub tree. +
+ + + + + + + + + + + + + + +func (t Tree) String() string+ + + + + + + + +
type TreeEntry struct { + SHA *string `json:"sha,omitempty"` + Path *string `json:"path,omitempty"` + Mode *string `json:"mode,omitempty"` + Type *string `json:"type,omitempty"` + Size *int `json:"size,omitempty"` + Content *string `json:"content,omitempty"` +}+
+TreeEntry represents the contents of a tree structure. TreeEntry can +represent either a blob, a commit (in the case of a submodule), or another +tree. +
+ + + + + + + + + + + + + + +func (t TreeEntry) String() string+ + + + + + + + +
type TwoFactorAuthError ErrorResponse+
+TwoFactorAuthError occurs when using HTTP Basic Authentication for a user +that has two-factor authentication enabled. The request can be reattempted +by providing a one-time password in the request. +
+ + + + + + + + + + + + + + +func (r *TwoFactorAuthError) Error() string+ + + + + + + + +
type UnauthenticatedRateLimitedTransport struct { + // ClientID is the GitHub OAuth client ID of the current application, which + // can be found by selecting its entry in the list at + // https://github.com/settings/applications. + ClientID string + + // ClientSecret is the GitHub OAuth client secret of the current + // application. + ClientSecret string + + // Transport is the underlying HTTP transport to use when making requests. + // It will default to http.DefaultTransport if nil. + Transport http.RoundTripper +}+
+UnauthenticatedRateLimitedTransport allows you to make unauthenticated calls +that need to use a higher rate limit associated with your OAuth application. +
+t := &github.UnauthenticatedRateLimitedTransport{ + ClientID: "your app's client ID", + ClientSecret: "your app's client secret", +} +client := github.NewClient(t.Client()) ++
+This will append the querystring params client_id=xxx&client_secret=yyy to all +requests. +
++See http://developer.github.com/v3/#unauthenticated-rate-limited-requests for +more information. +
+ + + + + + + + + + + + + + +func (t *UnauthenticatedRateLimitedTransport) Client() *http.Client+
+Client returns an *http.Client that makes requests which are subject to the +rate limit of your OAuth application. +
+ + + + + + +func (t *UnauthenticatedRateLimitedTransport) RoundTrip(req *http.Request) (*http.Response, error)+
+RoundTrip implements the RoundTripper interface. +
+ + + + + + + + +type UploadOptions struct { + Name string `url:"name,omitempty"` +}+
+UploadOptions specifies the parameters to methods that support uploads. +
+ + + + + + + + + + + + + + + + +type User struct { + Login *string `json:"login,omitempty"` + ID *int `json:"id,omitempty"` + AvatarURL *string `json:"avatar_url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + GravatarID *string `json:"gravatar_id,omitempty"` + Name *string `json:"name,omitempty"` + Company *string `json:"company,omitempty"` + Blog *string `json:"blog,omitempty"` + Location *string `json:"location,omitempty"` + Email *string `json:"email,omitempty"` + Hireable *bool `json:"hireable,omitempty"` + Bio *string `json:"bio,omitempty"` + PublicRepos *int `json:"public_repos,omitempty"` + PublicGists *int `json:"public_gists,omitempty"` + Followers *int `json:"followers,omitempty"` + Following *int `json:"following,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` + SuspendedAt *Timestamp `json:"suspended_at,omitempty"` + Type *string `json:"type,omitempty"` + SiteAdmin *bool `json:"site_admin,omitempty"` + TotalPrivateRepos *int `json:"total_private_repos,omitempty"` + OwnedPrivateRepos *int `json:"owned_private_repos,omitempty"` + PrivateGists *int `json:"private_gists,omitempty"` + DiskUsage *int `json:"disk_usage,omitempty"` + Collaborators *int `json:"collaborators,omitempty"` + Plan *Plan `json:"plan,omitempty"` + + // API URLs + URL *string `json:"url,omitempty"` + EventsURL *string `json:"events_url,omitempty"` + FollowingURL *string `json:"following_url,omitempty"` + FollowersURL *string `json:"followers_url,omitempty"` + GistsURL *string `json:"gists_url,omitempty"` + OrganizationsURL *string `json:"organizations_url,omitempty"` + ReceivedEventsURL *string `json:"received_events_url,omitempty"` + ReposURL *string `json:"repos_url,omitempty"` + StarredURL *string `json:"starred_url,omitempty"` + SubscriptionsURL *string `json:"subscriptions_url,omitempty"` + + // TextMatches is only populated from search results that request text matches + // See: search.go and https://developer.github.com/v3/search/#text-match-metadata + TextMatches []TextMatch `json:"text_matches,omitempty"` + + // Permissions identifies the permissions that a user has on a given + // repository. This is only populated when calling Repositories.ListCollaborators. + Permissions *map[string]bool `json:"permissions,omitempty"` +}+
+User represents a GitHub user. +
+ + + + + + + + + + + + + + +func (u User) String() string+ + + + + + + + +
type UserEmail struct { + Email *string `json:"email,omitempty"` + Primary *bool `json:"primary,omitempty"` + Verified *bool `json:"verified,omitempty"` +}+
+UserEmail represents user's email address +
+ + + + + + + + + + + + + + + + +type UserListOptions struct { + // ID of the last user seen + Since int `url:"since,omitempty"` + + ListOptions +}+
+UserListOptions specifies optional parameters to the UsersService.ListAll +method. +
+ + + + + + + + + + + + + + + + +type UsersSearchResult struct { + Total *int `json:"total_count,omitempty"` + Users []User `json:"items,omitempty"` +}+
+UsersSearchResult represents the result of an issues search. +
+ + + + + + + + + + + + + + + + +type UsersService service+
+UsersService handles communication with the user related +methods of the GitHub API. +
++GitHub API docs: http://developer.github.com/v3/users/ +
+ + + + + + + + + + + + + + +func (s *UsersService) AcceptInvitation(invitationID int) (*Response, error)+
+AcceptInvitation accepts the currently-open repository invitation for the +authenticated user. +
++GitHub API docs: https://developer.github.com/v3/repos/invitations/#accept-a-repository-invitation +
+ + + + + + +func (s *UsersService) AddEmails(emails []string) ([]*UserEmail, *Response, error)+
+AddEmails adds email addresses of the authenticated user. +
++GitHub API docs: http://developer.github.com/v3/users/emails/#add-email-addresses +
+ + + + + + +func (s *UsersService) CreateGPGKey(armoredPublicKey string) (*GPGKey, *Response, error)+
+CreateGPGKey creates a GPG key. It requires authenticatation via Basic Auth +or OAuth with at least write:gpg_key scope. +
++GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#create-a-gpg-key +
+ + + + + + +func (s *UsersService) CreateKey(key *Key) (*Key, *Response, error)+
+CreateKey adds a public key for the authenticated user. +
++GitHub API docs: http://developer.github.com/v3/users/keys/#create-a-public-key +
+ + + + + + +func (s *UsersService) DeclineInvitation(invitationID int) (*Response, error)+
+DeclineInvitation declines the currently-open repository invitation for the +authenticated user. +
++GitHub API docs: https://developer.github.com/v3/repos/invitations/#decline-a-repository-invitation +
+ + + + + + +func (s *UsersService) DeleteEmails(emails []string) (*Response, error)+
+DeleteEmails deletes email addresses from authenticated user. +
++GitHub API docs: http://developer.github.com/v3/users/emails/#delete-email-addresses +
+ + + + + + +func (s *UsersService) DeleteGPGKey(id int) (*Response, error)+
+DeleteGPGKey deletes a GPG key. It requires authentication via Basic Auth or +via OAuth with at least admin:gpg_key scope. +
++GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#delete-a-gpg-key +
+ + + + + + +func (s *UsersService) DeleteKey(id int) (*Response, error)+
+DeleteKey deletes a public key. +
++GitHub API docs: http://developer.github.com/v3/users/keys/#delete-a-public-key +
+ + + + + + +func (s *UsersService) DemoteSiteAdmin(user string) (*Response, error)+
+DemoteSiteAdmin demotes a user from site administrator of a GitHub Enterprise instance. +
++GitHub API docs: https://developer.github.com/v3/users/administration/#demote-a-site-administrator-to-an-ordinary-user +
+ + + + + + +func (s *UsersService) Edit(user *User) (*User, *Response, error)+
+Edit the authenticated user. +
++GitHub API docs: http://developer.github.com/v3/users/#update-the-authenticated-user +
+ + + + + + +func (s *UsersService) Follow(user string) (*Response, error)+
+Follow will cause the authenticated user to follow the specified user. +
++GitHub API docs: http://developer.github.com/v3/users/followers/#follow-a-user +
+ + + + + + +func (s *UsersService) Get(user string) (*User, *Response, error)+
+Get fetches a user. Passing the empty string will fetch the authenticated +user. +
++GitHub API docs: http://developer.github.com/v3/users/#get-a-single-user +
+ + + + + + +func (s *UsersService) GetByID(id int) (*User, *Response, error)+
+GetByID fetches a user. +
++Note: GetByID uses the undocumented GitHub API endpoint /user/:id. +
+ + + + + + +func (s *UsersService) GetGPGKey(id int) (*GPGKey, *Response, error)+
+GetGPGKey gets extended details for a single GPG key. It requires authentication +via Basic Auth or via OAuth with at least read:gpg_key scope. +
++GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#get-a-single-gpg-key +
+ + + + + + +func (s *UsersService) GetKey(id int) (*Key, *Response, error)+
+GetKey fetches a single public key. +
++GitHub API docs: http://developer.github.com/v3/users/keys/#get-a-single-public-key +
+ + + + + + +func (s *UsersService) IsFollowing(user, target string) (bool, *Response, error)+
+IsFollowing checks if "user" is following "target". Passing the empty +string for "user" will check if the authenticated user is following "target". +
++GitHub API docs: http://developer.github.com/v3/users/followers/#check-if-you-are-following-a-user +
+ + + + + + +func (s *UsersService) ListAll(opt *UserListOptions) ([]*User, *Response, error)+
+ListAll lists all GitHub users. +
++To paginate through all users, populate 'Since' with the ID of the last user. +
++GitHub API docs: http://developer.github.com/v3/users/#get-all-users +
+ + +▹ Example
+func (s *UsersService) ListEmails(opt *ListOptions) ([]*UserEmail, *Response, error)+
+ListEmails lists all email addresses for the authenticated user. +
++GitHub API docs: http://developer.github.com/v3/users/emails/#list-email-addresses-for-a-user +
+ + + + + + +func (s *UsersService) ListFollowers(user string, opt *ListOptions) ([]*User, *Response, error)+
+ListFollowers lists the followers for a user. Passing the empty string will +fetch followers for the authenticated user. +
++GitHub API docs: http://developer.github.com/v3/users/followers/#list-followers-of-a-user +
+ + + + + + +func (s *UsersService) ListFollowing(user string, opt *ListOptions) ([]*User, *Response, error)+
+ListFollowing lists the people that a user is following. Passing the empty +string will list people the authenticated user is following. +
++GitHub API docs: http://developer.github.com/v3/users/followers/#list-users-followed-by-another-user +
+ + + + + + +func (s *UsersService) ListGPGKeys() ([]*GPGKey, *Response, error)+
+ListGPGKeys lists the current user's GPG keys. It requires authentication +via Basic Auth or via OAuth with at least read:gpg_key scope. +
++GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#list-your-gpg-keys +
+ + + + + + +func (s *UsersService) ListInvitations() ([]*RepositoryInvitation, *Response, error)+
+ListInvitations lists all currently-open repository invitations for the +authenticated user. +
++GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-a-users-repository-invitations +
+ + + + + + +func (s *UsersService) ListKeys(user string, opt *ListOptions) ([]*Key, *Response, error)+
+ListKeys lists the verified public keys for a user. Passing the empty +string will fetch keys for the authenticated user. +
++GitHub API docs: http://developer.github.com/v3/users/keys/#list-public-keys-for-a-user +
+ + + + + + +func (s *UsersService) PromoteSiteAdmin(user string) (*Response, error)+
+PromoteSiteAdmin promotes a user to a site administrator of a GitHub Enterprise instance. +
++GitHub API docs: https://developer.github.com/v3/users/administration/#promote-an-ordinary-user-to-a-site-administrator +
+ + + + + + +func (s *UsersService) Suspend(user string) (*Response, error)+
+Suspend a user on a GitHub Enterprise instance. +
++GitHub API docs: https://developer.github.com/v3/users/administration/#suspend-a-user +
+ + + + + + +func (s *UsersService) Unfollow(user string) (*Response, error)+
+Unfollow will cause the authenticated user to unfollow the specified user. +
++GitHub API docs: http://developer.github.com/v3/users/followers/#unfollow-a-user +
+ + + + + + +func (s *UsersService) Unsuspend(user string) (*Response, error)+
+Unsuspend a user on a GitHub Enterprise instance. +
++GitHub API docs: https://developer.github.com/v3/users/administration/#unsuspend-a-user +
+ + + + + + + + +type WatchEvent struct { + // Action is the action that was performed. Possible value is: "started". + Action *string `json:"action,omitempty"` + + // The following fields are only populated by Webhook events. + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+WatchEvent is related to starring a repository, not watching. See this API +blog post for an explanation: https://developer.github.com/changes/2012-09-05-watcher-api/ +
++The event’s actor is the user who starred a repository, and the event’s +repository is the repository that was starred. +
++GitHub docs: https://developer.github.com/v3/activity/events/types/#watchevent +
+ + + + + + + + + + + + + + + + +type WebHookAuthor struct { + Email *string `json:"email,omitempty"` + Name *string `json:"name,omitempty"` + Username *string `json:"username,omitempty"` +}+
+WebHookAuthor represents the author or committer of a commit, as specified +in a WebHookCommit. The commit author may not correspond to a GitHub User. +
+ + + + + + + + + + + + + + +func (w WebHookAuthor) String() string+ + + + + + + + +
type WebHookCommit struct { + Added []string `json:"added,omitempty"` + Author *WebHookAuthor `json:"author,omitempty"` + Committer *WebHookAuthor `json:"committer,omitempty"` + Distinct *bool `json:"distinct,omitempty"` + ID *string `json:"id,omitempty"` + Message *string `json:"message,omitempty"` + Modified []string `json:"modified,omitempty"` + Removed []string `json:"removed,omitempty"` + Timestamp *time.Time `json:"timestamp,omitempty"` +}+
+WebHookCommit represents the commit variant we receive from GitHub in a +WebHookPayload. +
+ + + + + + + + + + + + + + +func (w WebHookCommit) String() string+ + + + + + + + +
type WebHookPayload struct { + After *string `json:"after,omitempty"` + Before *string `json:"before,omitempty"` + Commits []WebHookCommit `json:"commits,omitempty"` + Compare *string `json:"compare,omitempty"` + Created *bool `json:"created,omitempty"` + Deleted *bool `json:"deleted,omitempty"` + Forced *bool `json:"forced,omitempty"` + HeadCommit *WebHookCommit `json:"head_commit,omitempty"` + Pusher *User `json:"pusher,omitempty"` + Ref *string `json:"ref,omitempty"` + Repo *Repository `json:"repository,omitempty"` + Sender *User `json:"sender,omitempty"` +}+
+WebHookPayload represents the data that is received from GitHub when a push +event hook is triggered. The format of these payloads pre-date most of the +GitHub v3 API, so there are lots of minor incompatibilities with the types +defined in the rest of the API. Therefore, several types are duplicated +here to account for these differences. +
++GitHub API docs: https://help.github.com/articles/post-receive-hooks +
+ + + + + + + + + + + + + + +func (w WebHookPayload) String() string+ + + + + + + + +
type WeeklyCommitActivity struct { + Days []int `json:"days,omitempty"` + Total *int `json:"total,omitempty"` + Week *Timestamp `json:"week,omitempty"` +}+
+WeeklyCommitActivity represents the weekly commit activity for a repository. +The days array is a group of commits per day, starting on Sunday. +
+ + + + + + + + + + + + + + +func (w WeeklyCommitActivity) String() string+ + + + + + + + +
type WeeklyStats struct { + Week *Timestamp `json:"w,omitempty"` + Additions *int `json:"a,omitempty"` + Deletions *int `json:"d,omitempty"` + Commits *int `json:"c,omitempty"` +}+
+WeeklyStats represents the number of additions, deletions and commits +a Contributor made in a given week. +
+ + + + + + + + + + + + + + +func (w WeeklyStats) String() string+ + + + + + + + + + + + + + + + + + +
func Values(v interface{}) (url.Values, error)+
+Values returns the url.Values encoding of v. +
++Values expects to be passed a struct, and traverses it recursively using the +following encoding rules. +
++Each exported struct field is encoded as a URL parameter unless +
+- the field's tag is "-", or +- the field is empty and its tag specifies the "omitempty" option ++
+The empty values are false, 0, any nil pointer or interface value, any array +slice, map, or string of length zero, and any time.Time that returns true +for IsZero(). +
++The URL parameter name defaults to the struct field name but can be +specified in the struct field's tag value. The "url" key in the struct +field's tag value is the key name, followed by an optional comma and +options. For example: +
+// Field is ignored by this package. +Field int `url:"-"` + +// Field appears as URL parameter "myName". +Field int `url:"myName"` + +// Field appears as URL parameter "myName" and the field is omitted if +// its value is empty +Field int `url:"myName,omitempty"` + +// Field appears as URL parameter "Field" (the default), but the field +// is skipped if empty. Note the leading comma. +Field int `url:",omitempty"` ++
+For encoding individual field values, the following type-dependent rules +apply: +
++Boolean values default to encoding as the strings "true" or "false". +Including the "int" option signals that the field should be encoded as the +strings "1" or "0". +
++time.Time values default to encoding as RFC3339 timestamps. Including the +"unix" option signals that the field should be encoded as a Unix time (see +time.Unix()) +
++Slice and Array values default to encoding as multiple URL values of the +same name. Including the "comma" option signals that the field should be +encoded as a single comma-delimited value. Including the "space" option +similarly encodes the value as a single space-delimited string. Including +the "semicolon" option will encode the value as a semicolon-delimited string. +Including the "brackets" option signals that the multiple URL values should +have "[]" appended to the value name. "numbered" will append a number to +the end of each incidence of the value name, example: +name0=value0&name1=value1, etc. +
++Anonymous struct fields are usually encoded as if their inner exported +fields were fields in the outer struct, subject to the standard Go +visibility rules. An anonymous struct field with a name given in its URL +tag is treated as having that name, rather than being anonymous. +
++Non-nil pointer values are encoded as the value pointed to. +
++Nested structs are encoded including parent fields in value names for +scoping. e.g: +
+"user[name]=acme&user[addr][postcode]=1234&user[addr][city]=SFO" ++
+All other values are encoded using their default string representation. +
++Multiple fields that encode to the same URL parameter name will be included +as multiple URL values of the same name. +
+ + + + + + + + +type Encoder interface { + EncodeValues(key string, v *url.Values) error +}+
+Encoder is an interface implemented by any type that wishes to encode +itself into URL values in a non-standard way. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ btree + | ++ Package btree implements in-memory B-Trees of arbitrary degree. + | +
+ go-github + | ++ + | +
+ github + | ++ Package github provides a client for using the GitHub API. + | +
+ go-querystring + | ++ + | +
+ query + | ++ Package query implements encoding of structs into URL query parameters. + | +
type Cache struct {
+ // contains filtered or unexported fields
+}
+ +Cache is an implementation of httpcache.Cache that supplements the in-memory map with persistent storage +
+ + + + + + + + + + + + +func New(basePath string) *Cache+
+New returns a new Cache that will store files in basePath +
+ + + + + +func NewWithDiskv(d *diskv.Diskv) *Cache+
+NewWithDiskv returns a new Cache using the provided Diskv as underlying +storage. +
+ + + + + + + +func (c *Cache) Delete(key string)+
+Delete removes the response with key from the cache +
+ + + + + + +func (c *Cache) Get(key string) (resp []byte, ok bool)+
+Get returns the response corresponding to key if present +
+ + + + + + +func (c *Cache) Set(key string, resp []byte)+
+Set saves a response to the cache as key +
+ + + + + + + + + + + + + + + + + + +const ( + + // XFromCache is the header added to responses that are returned from the cache + XFromCache = "X-From-Cache" +)+ + + + +
var ErrNoDateHeader = errors.New("no Date header")+
+ErrNoDateHeader indicates that the HTTP headers contained no Date header. +
+ + + + + + +func CachedResponse(c Cache, req *http.Request) (resp *http.Response, err error)+
+CachedResponse returns the cached http.Response for req if present, and nil +otherwise. +
+ + + + + + + +func Date(respHeaders http.Header) (date time.Time, err error)+
+Date parses and returns the value of the Date header. +
+ + + + + + + + +type Cache interface { + // Get returns the []byte representation of a cached response and a bool + // set to true if the value isn't empty + Get(key string) (responseBytes []byte, ok bool) + // Set stores the []byte representation of a response against a key + Set(key string, responseBytes []byte) + // Delete removes the value associated with the key + Delete(key string) +}+
+A Cache interface is used by the Transport to store and retrieve responses. +
+ + + + + + + + + + + + + + + + +type MemoryCache struct {
+ // contains filtered or unexported fields
+}
+ +MemoryCache is an implemtation of Cache that stores responses in an in-memory map. +
+ + + + + + + + + + + + +func NewMemoryCache() *MemoryCache+
+NewMemoryCache returns a new Cache that will store items in an in-memory map +
+ + + + + + + +func (c *MemoryCache) Delete(key string)+
+Delete removes key from the cache +
+ + + + + + +func (c *MemoryCache) Get(key string) (resp []byte, ok bool)+
+Get returns the []byte representation of the response and true if present, false if not +
+ + + + + + +func (c *MemoryCache) Set(key string, resp []byte)+
+Set saves response resp to the cache with key +
+ + + + + + + + +type Transport struct { + // The RoundTripper interface actually used to make requests + // If nil, http.DefaultTransport is used + Transport http.RoundTripper + Cache Cache + // If true, responses returned from the cache will be given an extra header, X-From-Cache + MarkCachedResponses bool + // contains filtered or unexported fields +}+
+Transport is an implementation of http.RoundTripper that will return values from a cache +where possible (avoiding a network request) and will additionally add validators (etag/if-modified-since) +to repeated requests allowing servers to return 304 / Not Modified +
+ + + + + + + + + + + + +func NewMemoryCacheTransport() *Transport+
+NewMemoryCacheTransport returns a new Transport using the in-memory cache implementation +
+ + + + + +func NewTransport(c Cache) *Transport+
+NewTransport returns a new Transport with the +provided Cache implementation and MarkCachedResponses set to true +
+ + + + + + + +func (t *Transport) CancelRequest(req *http.Request)+
+CancelRequest calls CancelRequest on the underlaying transport if implemented or +throw a warning otherwise. +
+ + + + + + +func (t *Transport) Client() *http.Client+
+Client returns an *http.Client that caches responses. +
+ + + + + + +func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error)+
+RoundTrip takes a Request and returns a Response +
++If there is a fresh Response already in cache, then it will be returned without connecting to +the server. +
++If there is a stale Response, then any validators it contains will be set on the new request +to give the server a chance to respond with NotModified. If this happens, then the cached Response +will be returned. +
+ + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ diskcache + | ++ Package diskcache provides an implementation of httpcache.Cache that uses the diskv package to supplement an in-memory map with persistent storage + | +
+ leveldbcache + | ++ Package leveldbcache provides an implementation of httpcache.Cache that uses github.com/syndtr/goleveldb/leveldb + | +
+ memcache + | ++ Package memcache provides an implementation of httpcache.Cache that uses App Engine's memcache package to store cached responses. + | +
+ redis + | ++ Package redis provides a redis interface for http caching. + | +
type Cache struct {
+ // contains filtered or unexported fields
+}
+ +Cache is an implementation of httpcache.Cache with leveldb storage +
+ + + + + + + + + + + + +func New(path string) (*Cache, error)+
+New returns a new Cache that will store leveldb in path +
+ + + + + +func NewWithDB(db *leveldb.DB) *Cache+
+NewWithDB returns a new Cache using the provided leveldb as underlying +storage. +
+ + + + + + + +func (c *Cache) Delete(key string)+
+Delete removes the response with key from the cache +
+ + + + + + +func (c *Cache) Get(key string) (resp []byte, ok bool)+
+Get returns the response corresponding to key if present +
+ + + + + + +func (c *Cache) Set(key string, resp []byte)+
+Set saves a response to the cache as key +
+ + + + + + + + + + + + + + + + + + +type Cache struct { + *memcache.Client +}+
+Cache is an implementation of httpcache.Cache that caches responses in a +memcache server. +
+ + + + + + + + + + + + +func New(server ...string) *Cache+
+New returns a new Cache using the provided memcache server(s) with equal +weight. If a server is listed multiple times, it gets a proportional amount +of weight. +
+ + + + + +func NewWithClient(client *memcache.Client) *Cache+
+NewWithClient returns a new Cache with the given memcache client. +
+ + + + + + + +func (c *Cache) Delete(key string)+
+Delete removes the response with key from the cache. +
+ + + + + + +func (c *Cache) Get(key string) (resp []byte, ok bool)+
+Get returns the response corresponding to key if present. +
+ + + + + + +func (c *Cache) Set(key string, resp []byte)+
+Set saves a response to the cache as key. +
+ + + + + + + + + + + + + + + + + + +func NewWithClient(client redis.Conn) httpcache.Cache+
+NewWithClient returns a new Cache with the given redis connection. +
+ + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ httpcache + | ++ Package httpcache provides a http.RoundTripper implementation that works as a mostly RFC-compliant cache for http responses. + | +
+ diskcache + | ++ Package diskcache provides an implementation of httpcache.Cache that uses the diskv package to supplement an in-memory map with persistent storage + | +
+ leveldbcache + | ++ Package leveldbcache provides an implementation of httpcache.Cache that uses github.com/syndtr/goleveldb/leveldb + | +
+ memcache + | ++ Package memcache provides an implementation of httpcache.Cache that uses App Engine's memcache package to store cached responses. + | +
+ redis + | ++ Package redis provides a redis interface for http caching. + | +
Name | +Synopsis | +
---|---|
.. | +|
+ PuerkitoBio + | ++ + | +
+ goquery + | ++ Package goquery implements features similar to jQuery, including the chainable syntax, to manipulate and query an HTML document. + | +
+ Sirupsen + | ++ + | +
+ logrus + | ++ Package logrus is a structured logger for Go, completely API compatible with the standard library logger. + | +
+ examples + | ++ + | +
+ basic + | ++ + | +
+ hook + | ++ + | +
+ hooks + | ++ + | +
+ syslog + | ++ + | +
+ test + | ++ + | +
+ andybalholm + | ++ + | +
+ cascadia + | ++ The cascadia package is an implementation of CSS selectors. + | +
+ fuzz + | ++ + | +
+ andygrunwald + | ++ + | +
+ go-jira + | ++ + | +
+ beorn7 + | ++ + | +
+ perks + | ++ + | +
+ quantile + | ++ Package quantile computes approximate quantiles over an unbounded data stream within low memory and CPU bounds. + | +
+ bradfitz + | ++ + | +
+ gomemcache + | ++ + | +
+ memcache + | ++ Package memcache provides a client for the memcached cache server. + | +
+ cenkalti + | ++ + | +
+ backoff + | ++ Package backoff implements backoff algorithms for retrying operations. + | +
+ codegangsta + | ++ + | +
+ cli + | ++ Package cli provides a minimal framework for creating and organizing command line Go applications. + | +
+ altsrc + | ++ + | +
+ dghubble + | ++ + | +
+ go-twitter + | ++ + | +
+ twitter + | ++ Package twitter provides a Client for the Twitter API. + | +
+ oauth1 + | ++ Package oauth1 is a Go implementation of the OAuth1 spec RFC 5849. + | +
+ dropbox + | ++ Package dropbox provides constants for using OAuth1 to access Dropbox. + | +
+ examples + | ++ + | +
+ tumblr + | ++ Package tumblr provides constants for using OAuth 1 to access Tumblr. + | +
+ twitter + | ++ Package twitter provides constants for using OAuth1 to access Twitter. + | +
+ sling + | ++ Package sling is a Go HTTP client library for creating and sending API requests. + | +
+ examples + | ++ + | +
+ die-net + | ++ + | +
+ lrucache + | ++ Package lrucache provides a byte-size-limited implementation of httpcache.Cache that stores data in memory. + | +
+ twotier + | ++ Package twotier provides a wrapper for two httpcache.Cache instances, allowing you to use both a small and fast cache for popular objects and fall back to a larger and slower cache for less popular ones. + | +
+ garyburd + | ++ + | +
+ redigo + | ++ + | +
+ redis + | ++ Package redis is a client for the Redis database. + | +
+ golang + | ++ + | +
+ protobuf + | ++ + | +
+ proto + | ++ Package proto converts data structures to and from the wire format of protocol buffers. + | +
+ proto3_proto + | ++ Package proto3_proto is a generated protocol buffer package. + | +
+ snappy + | ++ Package snappy implements the snappy block-based compression format. + | +
+ google + | ++ + | +
+ btree + | ++ Package btree implements in-memory B-Trees of arbitrary degree. + | +
+ go-github + | ++ + | +
+ github + | ++ Package github provides a client for using the GitHub API. + | +
+ go-querystring + | ++ + | +
+ query + | ++ Package query implements encoding of structs into URL query parameters. + | +
+ gregjones + | ++ + | +
+ httpcache + | ++ Package httpcache provides a http.RoundTripper implementation that works as a mostly RFC-compliant cache for http responses. + | +
+ diskcache + | ++ Package diskcache provides an implementation of httpcache.Cache that uses the diskv package to supplement an in-memory map with persistent storage + | +
+ leveldbcache + | ++ Package leveldbcache provides an implementation of httpcache.Cache that uses github.com/syndtr/goleveldb/leveldb + | +
+ memcache + | ++ Package memcache provides an implementation of httpcache.Cache that uses App Engine's memcache package to store cached responses. + | +
+ redis + | ++ Package redis provides a redis interface for http caching. + | +
+ matrix-org + | ++ + | +
+ dugong + | ++ + | +
+ go-neb + | ++ + | +
+ api + | ++ Package api contains the fundamental data types used by Go-NEB. + | +
+ handlers + | ++ Package handlers contains the HTTP handlers for Go-NEB. + | +
+ clients + | ++ + | +
+ database + | ++ + | +
+ errors + | ++ + | +
+ matrix + | ++ Package matrix provides an HTTP client that can interact with a Homeserver via r0 APIs (/sync). + | +
+ metrics + | ++ + | +
+ plugin + | ++ + | +
+ polling + | ++ + | +
+ realms + | ++ + | +
+ github + | ++ + | +
+ jira + | ++ + | +
+ urls + | ++ Package urls handles converting between various JIRA URL representations in a consistent way. + | +
+ server + | ++ Package server contains building blocks for REST APIs. + | +
+ services + | ++ + | +
+ echo + | ++ + | +
+ giphy + | ++ + | +
+ github + | ++ + | +
+ client + | ++ + | +
+ webhook + | ++ + | +
+ guggy + | ++ + | +
+ jira + | ++ + | +
+ webhook + | ++ + | +
+ rssbot + | ++ + | +
+ types + | ++ + | +
+ util + | ++ + | +
+ mattn + | ++ + | +
+ go-shellwords + | ++ + | +
+ go-sqlite3 + | ++ Package sqlite3 provides interface to SQLite3 databases. + | +
+ sqlite3_test + | ++ + | +
+ tool + | ++ + | +
+ matttproud + | ++ + | +
+ golang_protobuf_extensions + | ++ + | +
+ pbutil + | ++ Package pbutil provides record length-delimited Protocol Buffer streaming. + | +
+ mmcdole + | ++ + | +
+ gofeed + | ++ + | +
+ atom + | ++ + | +
+ cmd + | ++ + | +
+ ftest + | ++ + | +
+ extensions + | ++ + | +
+ rss + | ++ + | +
+ goxpp + | ++ + | +
+ peterbourgon + | ++ + | +
+ diskv + | ++ + | +
+ examples + | ++ + | +
+ content-addressable-store + | ++ + | +
+ super-simple-store + | ++ + | +
+ prometheus + | ++ + | +
+ client_golang + | ++ + | +
+ api + | ++ + | +
+ prometheus + | ++ Package prometheus provides bindings to the Prometheus HTTP API: http://prometheus.io/docs/querying/api/ + | +
+ examples + | ++ + | +
+ random + | ++ A simple example exposing fictional RPC latencies with different types of random distributions (uniform, normal, and exponential) as Prometheus metrics. + | +
+ simple + | ++ A minimal example of how to include Prometheus instrumentation. + | +
+ prometheus + | ++ Package prometheus provides metrics primitives to instrument code for monitoring. + | +
+ promhttp + | ++ Package promhttp contains functions to create http.Handler instances to expose Prometheus metrics via HTTP. + | +
+ push + | ++ Package push provides functions to push metrics to a Pushgateway. + | +
+ client_model + | ++ + | +
+ go + | ++ Package io_prometheus_client is a generated protocol buffer package. + | +
+ common + | ++ + | +
+ expfmt + | ++ A package for reading and writing Prometheus metrics. + | +
+ model + | ++ Package model contains common data structures that are shared across Prometheus components and libraries. + | +
+ procfs + | ++ Package procfs provides functions to retrieve system, kernel and process metrics from the pseudo-filesystem proc. + | +
+ syndtr + | ++ + | +
+ goleveldb + | ++ + | +
+ leveldb + | ++ Package leveldb provides implementation of LevelDB key/value database. + | +
+ cache + | ++ Package cache provides interface and implementation of a cache algorithms. + | +
+ comparer + | ++ Package comparer provides interface and implementation for ordering sets of data. + | +
+ errors + | ++ Package errors provides common error types used throughout leveldb. + | +
+ filter + | ++ Package filter provides interface and implementation of probabilistic data structure. + | +
+ iterator + | ++ Package iterator provides interface and implementation to traverse over contents of a database. + | +
+ journal + | ++ Package journal reads and writes sequences of journals. + | +
+ memdb + | ++ Package memdb provides in-memory key/value database implementation. + | +
+ opt + | ++ Package opt provides sets of options used by LevelDB. + | +
+ storage + | ++ Package storage provides storage abstraction for LevelDB. + | +
+ table + | ++ Package table allows read and write sorted key/value. + | +
+ testutil + | ++ + | +
+ util + | ++ Package util provides utilities used throughout leveldb. + | +
func NewFSHook(infoPath, warnPath, errorPath string, formatter log.Formatter, rotSched RotationScheduler) log.Hook+
+NewFSHook makes a logging hook that writes formatted +log entries to info, warn and error log files. Each log file +contains the messages with that severity or higher. If a formatter is +not specified, they will be logged using a JSON formatter. If a +RotationScheduler is set, the files will be cycled according to its rules. +
+ + + + + + + + +type DailyRotationSchedule struct { + GZip bool + // contains filtered or unexported fields +}+
+DailyRotationSchedule rotates log files daily. Logs are only rotated +when midnight passes *whilst the process is running*. E.g: if you run +the process on Day 4 then stop it and start it on Day 7, no rotation will +occur when the process starts. +
+ + + + + + + + + + + + + + +func (rs *DailyRotationSchedule) ShouldGZip() bool+ + + + + + +
func (rs *DailyRotationSchedule) ShouldRotate() (bool, string)+ + + + + + + + +
type RotationScheduler interface { + // ShouldRotate returns true if the file should be rotated. The suffix to apply + // to the filename is returned as the 2nd arg. + ShouldRotate() (bool, string) + // ShouldGZip returns true if the file should be gzipped when it is rotated. + ShouldGZip() bool +}+
+RotationScheduler determines when files should be rotated. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +type ConfigureAuthRealm struct { + Db *database.ServiceDB +}+
+ConfigureAuthRealm represents an HTTP handler capable of processing /admin/configureAuthRealm requests. +
+ + + + + + + + + + + + + + +func (h *ConfigureAuthRealm) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)+
+OnIncomingRequest handles POST requests to /admin/configureAuthRealm. The JSON object +provided is of type "api.ConfigureAuthRealmRequest". +
++Request: +
+POST /admin/configureAuthRealm +{ + "ID": "my-realm-id", + "Type": "github", + "Config": { + // Realm-specific configuration information + } +} ++
+Response: +
+HTTP/1.1 200 OK +{ + "ID": "my-realm-id", + "Type": "github", + "OldConfig": { + // Old auth realm config information + }, + "NewConfig": { + // New auth realm config information + }, +} ++ + + + + + + + +
type ConfigureClient struct { + Clients *clients.Clients +}+
+ConfigureClient represents an HTTP handler capable of processing /admin/configureClient requests. +
+ + + + + + + + + + + + + + +func (s *ConfigureClient) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)+
+OnIncomingRequest handles POST requests to /admin/configureClient. The JSON object provided +is of type "api.ClientConfig". +
++If a DisplayName is supplied, this request will set this client's display name +if the old ClientConfig DisplayName differs from the new ClientConfig DisplayName. +
++Request: +
+POST /admin/configureClient +{ + "UserID": "@my_bot:localhost", + "HomeserverURL": "http://localhost:8008", + "Sync": true, + "DisplayName": "My Bot" +} ++
+Response: +
+HTTP/1.1 200 OK +{ + "OldClient": { + // The old api.ClientConfig + }, + "NewClient": { + // The new api.ClientConfig + } +} ++ + + + + + + + +
type ConfigureService struct {
+ // contains filtered or unexported fields
+}
+ +ConfigureService represents an HTTP handler which can process /admin/configureService requests. +
+ + + + + + + + + + + + +func NewConfigureService(db *database.ServiceDB, clients *clients.Clients) *ConfigureService+
+NewConfigureService creates a new ConfigureService handler +
+ + + + + + + +func (s *ConfigureService) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)+
+OnIncomingRequest handles POST requests to /admin/configureService. +
++The request body MUST be of type "api.ConfigureServiceRequest". +
++Request: +
+POST /admin/configureService +{ + "ID": "my_service_id", + "Type": "service-type", + "UserID": "@my_bot:localhost", + "Config": { + // service-specific config information + } +} ++
+Response: +
+HTTP/1.1 200 OK +{ + "ID": "my_service_id", + "Type": "service-type", + "OldConfig": { + // old service-specific config information + }, + "NewConfig": { + // new service-specific config information + }, +} ++ + + + + + + + +
type GetService struct { + Db *database.ServiceDB +}+
+GetService represents an HTTP handler which can process /admin/getService requests. +
+ + + + + + + + + + + + + + +func (h *GetService) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)+
+OnIncomingRequest handles POST requests to /admin/getService. +
++The request body MUST be a JSON body which has an "ID" key which represents +the service ID to get. +
++Request: +
+POST /admin/getService +{ + "ID": "my_service_id" +} ++
+Response: +
+HTTP/1.1 200 OK +{ + "ID": "my_service_id", + "Type": "github", + "Config": { + // service-specific config information + } +} ++ + + + + + + + +
type GetSession struct { + Db *database.ServiceDB +}+
+GetSession represents an HTTP handler capable of processing /admin/getSession requests. +
+ + + + + + + + + + + + + + +func (h *GetSession) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)+
+OnIncomingRequest handles POST requests to /admin/getSession. +
++The JSON object provided MUST have a "RealmID" and "UserID" in order to fetch the +correct AuthSession. If there is no session for this tuple of realm and user ID, +a 200 OK is still returned with "Authenticated" set to false. +
++Request: +
+POST /admin/getSession +{ + "RealmID": "my-realm", + "UserID": "@my_user:localhost" +} ++
+Response: +
+HTTP/1.1 200 OK +{ + "ID": "session_id", + "Authenticated": true, + "Info": { + // Session-specific config info + } +} ++
+Response if session not found: +
+HTTP/1.1 200 OK +{ + "Authenticated": false +} ++ + + + + + + + +
type Heartbeat struct{}+
+Heartbeat implements the heartbeat API +
+ + + + + + + + + + + + + + +func (*Heartbeat) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)+
+OnIncomingRequest returns an empty JSON object which can be used to detect liveness of Go-NEB. +
++Request: +
+GET /test ++
+Response: +
+HTTP/1.1 200 OK +{} ++ + + + + + + + +
type RealmRedirect struct { + Db *database.ServiceDB +}+
+RealmRedirect represents an HTTP handler which can process incoming redirects for auth realms. +
+ + + + + + + + + + + + + + +func (rh *RealmRedirect) Handle(w http.ResponseWriter, req *http.Request)+
+Handle requests for an auth realm. +
++The last path segment of the URL MUST be the base64 form of the Realm ID. What response +this returns depends on the specific AuthRealm implementation. +
+ + + + + + + + +type RemoveAuthSession struct { + Db *database.ServiceDB +}+
+RemoveAuthSession represents an HTTP handler capable of processing /admin/removeAuthSession requests. +
+ + + + + + + + + + + + + + +func (h *RemoveAuthSession) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)+
+OnIncomingRequest handles POST requests to /admin/removeAuthSession. +
++The JSON object MUST contain the keys "RealmID" and "UserID" to identify the session to remove. +
++Request +
+POST /admin/removeAuthSession +{ + "RealmID": "github-realm", + "UserID": "@my_user:localhost" +} ++
+Response: +
+HTTP/1.1 200 OK +{} ++ + + + + + + + +
type RequestAuthSession struct { + Db *database.ServiceDB +}+
+RequestAuthSession represents an HTTP handler capable of processing /admin/requestAuthSession requests. +
+ + + + + + + + + + + + + + +func (h *RequestAuthSession) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)+
+OnIncomingRequest handles POST requests to /admin/requestAuthSession. The HTTP body MUST be +a JSON object representing type "api.RequestAuthSessionRequest". +
++This will return HTTP 400 if there are missing fields or the Realm ID is unknown. +For the format of the response, see the specific AuthRealm that the Realm ID corresponds to. +
++Request: +
+POST /admin/requestAuthSession +{ + "RealmID": "github_realm_id", + "UserID": "@my_user:localhost", + "Config": { + // AuthRealm specific config info + } +} ++
+Response: +
+HTTP/1.1 200 OK +{ + // AuthRealm-specific information +} ++ + + + + + + + +
type Webhook struct {
+ // contains filtered or unexported fields
+}
+ +Webhook represents an HTTP handler capable of accepting webhook requests on behalf of services. +
+ + + + + + + + + + + + +func NewWebhook(db *database.ServiceDB, cli *clients.Clients) *Webhook+
+NewWebhook returns a new webhook HTTP handler +
+ + + + + + + +func (wh *Webhook) Handle(w http.ResponseWriter, req *http.Request)+
+Handle an incoming webhook HTTP request. +
++The webhook MUST have a known base64 encoded service ID as the last path segment +in order for this request to be passed to the correct service, or else this will return +HTTP 400. If the base64 encoded service ID is unknown, this will return HTTP 404. +Beyond this, the exact response is determined by the specific Service implementation. +
+ + + + + + + + + + + + + + + + + + +type ClientConfig struct { + // The matrix User ID to connect with. E.g. @alice:matrix.org + UserID string + // A URL with the host and port of the matrix server. E.g. https://matrix.org:8448 + HomeserverURL string + // The matrix access token to authenticate the requests with. + AccessToken string + // True to start a sync stream for this user. If false, no /sync goroutine will be + // created and this client won't listen for new events from Matrix. For services + // which only SEND events into Matrix, it may be desirable to set Sync to false to reduce the + // number of goroutines Go-NEB has to maintain. For services which respond to !commands, + // Sync MUST be set to true in order to receive those commands. + Sync bool + // True to automatically join every room this client is invited to. + // This is desirable for services which have !commands as that means anyone can pull the bot + // into the room. It is up to the service to decide which, if any, users to respond to however. + AutoJoinRooms bool + // The desired display name for this client. + // This does not automatically set the display name for this client. See /configureClient. + DisplayName string +}+
+A ClientConfig contains the configuration information for a matrix client so that +Go-NEB can drive it. It forms the HTTP body to /configureClient requests. +
+ + + + + + + + + + + + + + +func (c *ClientConfig) Check() error+
+Check that the client has supplied the correct fields. +
+ + + + + + + + +type ConfigFile struct { + Clients []ClientConfig + Realms []ConfigureAuthRealmRequest + Services []ConfigureServiceRequest + Sessions []Session +}+
+ConfigFile represents config.sample.yaml +
+ + + + + + + + + + + + + + + + +type ConfigureAuthRealmRequest struct { + // An arbitrary unique identifier for this auth realm. This can be anything. + // Using an existing ID will REPLACE the entire existing AuthRealm with the new information. + ID string + // The type of auth realm. This determines which code is loaded to execute the + // auth realm. It must be a known type. E.g. "github". + Type string + // AuthRealm specific config information. See the docs for the auth realm you're interested in. + Config json.RawMessage +}+
+ConfigureAuthRealmRequest is a request to /configureAuthRealm +
+ + + + + + + + + + + + + + +func (c *ConfigureAuthRealmRequest) Check() error+
+Check validates the /configureAuthRealm request +
+ + + + + + + + +type ConfigureServiceRequest struct { + // An arbitrary unique identifier for this service. This can be anything. + // Using an existing ID will REPLACE the entire Service with the new information. + ID string + // The type of service. This determines which code is loaded to execute the + // service. It must be a known type, e.g. "github". + Type string + // The user ID of the configured client that this service will use to communicate with Matrix. + // The user MUST already be configured. + UserID string + // Service-specific config information. See the docs for the service you're interested in. + Config json.RawMessage +}+
+ConfigureServiceRequest is a request to /configureService +
+ + + + + + + + + + + + + + +func (c *ConfigureServiceRequest) Check() error+
+Check validates the /configureService request +
+ + + + + + + + +type RequestAuthSessionRequest struct { + // The realm ID to request a new auth session on. The realm MUST already exist. + RealmID string + // The Matrix user ID requesting the auth session. If the auth is successful, + // this user ID will be associated with the third-party credentials obtained. + UserID string + // AuthRealm specific config information. See the docs for the auth realm you're interested in. + Config json.RawMessage +}+
+RequestAuthSessionRequest is a request to /requestAuthSession +
+ + + + + + + + + + + + + + +func (r *RequestAuthSessionRequest) Check() error+
+Check that the request is valid. +
+ + + + + + + + +type Session struct { + SessionID string + RealmID string + UserID string + Config json.RawMessage +}+
+Session contains the complete auth session information for a given user on a given realm. +They are created for use with ConfigFile. +
+ + + + + + + + + + + + + + +func (c *Session) Check() error+
+Check validates the session config request +
+ + + + + + + + + + + + + + + + +type Clients struct {
+ // contains filtered or unexported fields
+}
+ +A Clients is a collection of clients used for bot services. +
+ + + + + + + + + + + + +func New(db *database.ServiceDB, cli *http.Client) *Clients+
+New makes a new collection of matrix clients +
+ + + + + + + +func (c *Clients) Client(userID string) (*matrix.Client, error)+
+Client gets a client for the userID +
+ + + + + + +func (c *Clients) Start() error+
+Start listening on client /sync streams +
+ + + + + + +func (c *Clients) Update(config api.ClientConfig) (api.ClientConfig, error)+
+Update updates the config for a matrix client +
+ + + + + + + + + + + + + + + + + + +func SetServiceDB(db Storer)+
+SetServiceDB sets the global service DB instance. +
+ + + + + + + + +type NopStorage struct{}+
+NopStorage nops every store API call. This is intended to be embedded into derived structs +in tests +
+ + + + + + + + + + + + + + +func (s *NopStorage) DeleteService(serviceID string) (err error)+
+DeleteService NOP +
+ + + + + + +func (s *NopStorage) InsertFromConfig(cfg *api.ConfigFile) error+
+InsertFromConfig NOP +
+ + + + + + +func (s *NopStorage) LoadAuthRealm(realmID string) (realm types.AuthRealm, err error)+
+LoadAuthRealm NOP +
+ + + + + + +func (s *NopStorage) LoadAuthRealmsByType(realmType string) (realms []types.AuthRealm, err error)+
+LoadAuthRealmsByType NOP +
+ + + + + + +func (s *NopStorage) LoadAuthSessionByID(realmID, sessionID string) (session types.AuthSession, err error)+
+LoadAuthSessionByID NOP +
+ + + + + + +func (s *NopStorage) LoadAuthSessionByUser(realmID, userID string) (session types.AuthSession, err error)+
+LoadAuthSessionByUser NOP +
+ + + + + + +func (s *NopStorage) LoadBotOptions(userID, roomID string) (opts types.BotOptions, err error)+
+LoadBotOptions NOP +
+ + + + + + +func (s *NopStorage) LoadMatrixClientConfig(userID string) (config api.ClientConfig, err error)+
+LoadMatrixClientConfig NOP +
+ + + + + + +func (s *NopStorage) LoadMatrixClientConfigs() (configs []api.ClientConfig, err error)+
+LoadMatrixClientConfigs NOP +
+ + + + + + +func (s *NopStorage) LoadNextBatch(userID string) (nextBatch string, err error)+
+LoadNextBatch NOP +
+ + + + + + +func (s *NopStorage) LoadService(serviceID string) (service types.Service, err error)+
+LoadService NOP +
+ + + + + + +func (s *NopStorage) LoadServicesByType(serviceType string) (services []types.Service, err error)+
+LoadServicesByType NOP +
+ + + + + + +func (s *NopStorage) LoadServicesForUser(serviceUserID string) (services []types.Service, err error)+
+LoadServicesForUser NOP +
+ + + + + + +func (s *NopStorage) RemoveAuthSession(realmID, userID string) error+
+RemoveAuthSession NOP +
+ + + + + + +func (s *NopStorage) StoreAuthRealm(realm types.AuthRealm) (old types.AuthRealm, err error)+
+StoreAuthRealm NOP +
+ + + + + + +func (s *NopStorage) StoreAuthSession(session types.AuthSession) (old types.AuthSession, err error)+
+StoreAuthSession NOP +
+ + + + + + +func (s *NopStorage) StoreBotOptions(opts types.BotOptions) (oldOpts types.BotOptions, err error)+
+StoreBotOptions NOP +
+ + + + + + +func (s *NopStorage) StoreMatrixClientConfig(config api.ClientConfig) (oldConfig api.ClientConfig, err error)+
+StoreMatrixClientConfig NOP +
+ + + + + + +func (s *NopStorage) StoreService(service types.Service) (oldService types.Service, err error)+
+StoreService NOP +
+ + + + + + +func (s *NopStorage) UpdateNextBatch(userID, nextBatch string) (err error)+
+UpdateNextBatch NOP +
+ + + + + + + + +type ServiceDB struct {
+ // contains filtered or unexported fields
+}
+ +A ServiceDB stores the configuration for the services +
+ + + + + + + + + + + + +func Open(databaseType, databaseURL string) (serviceDB *ServiceDB, err error)+
+Open a SQL database to use as a ServiceDB. This will automatically create +the necessary database tables if they aren't already present. +
+ + + + + + + +func (d *ServiceDB) DeleteService(serviceID string) (err error)+
+DeleteService deletes the given service from the database. +
+ + + + + + +func (d *ServiceDB) InsertFromConfig(cfg *api.ConfigFile) error+
+InsertFromConfig inserts entries from the config file into the database. This only really +makes sense for in-memory databases. +
+ + + + + + +func (d *ServiceDB) LoadAuthRealm(realmID string) (realm types.AuthRealm, err error)+
+LoadAuthRealm loads an AuthRealm from the database. +Returns sql.ErrNoRows if the realm isn't in the database. +
+ + + + + + +func (d *ServiceDB) LoadAuthRealmsByType(realmType string) (realms []types.AuthRealm, err error)+
+LoadAuthRealmsByType loads all auth realms with the given type from the database. +The realms are ordered based on their realm ID. +Returns an empty list if there are no realms with that type. +
+ + + + + + +func (d *ServiceDB) LoadAuthSessionByID(realmID, sessionID string) (session types.AuthSession, err error)+
+LoadAuthSessionByID loads an AuthSession from the database based on the given +realm and session ID. +Returns sql.ErrNoRows if the session isn't in the database. +
+ + + + + + +func (d *ServiceDB) LoadAuthSessionByUser(realmID, userID string) (session types.AuthSession, err error)+
+LoadAuthSessionByUser loads an AuthSession from the database based on the given +realm and user ID. +Returns sql.ErrNoRows if the session isn't in the database. +
+ + + + + + +func (d *ServiceDB) LoadBotOptions(userID, roomID string) (opts types.BotOptions, err error)+
+LoadBotOptions loads bot options from the database. +Returns sql.ErrNoRows if the bot options isn't in the database. +
+ + + + + + +func (d *ServiceDB) LoadMatrixClientConfig(userID string) (config api.ClientConfig, err error)+
+LoadMatrixClientConfig loads a Matrix client config from the database. +Returns sql.ErrNoRows if the client isn't in the database. +
+ + + + + + +func (d *ServiceDB) LoadMatrixClientConfigs() (configs []api.ClientConfig, err error)+
+LoadMatrixClientConfigs loads all Matrix client configs from the database. +
+ + + + + + +func (d *ServiceDB) LoadNextBatch(userID string) (nextBatch string, err error)+
+LoadNextBatch loads the next_batch token for the given user. +
+ + + + + + +func (d *ServiceDB) LoadService(serviceID string) (service types.Service, err error)+
+LoadService loads a service from the database. +Returns sql.ErrNoRows if the service isn't in the database. +
+ + + + + + +func (d *ServiceDB) LoadServicesByType(serviceType string) (services []types.Service, err error)+
+LoadServicesByType loads all the bot services configured for a given type. +Returns an empty list if there aren't any services configured. +
+ + + + + + +func (d *ServiceDB) LoadServicesForUser(serviceUserID string) (services []types.Service, err error)+
+LoadServicesForUser loads all the bot services configured for a given user. +Returns an empty list if there aren't any services configured. +
+ + + + + + +func (d *ServiceDB) RemoveAuthSession(realmID, userID string) error+
+RemoveAuthSession removes the auth session for the given user on the given realm. +No error is returned if the session did not exist in the first place. +
+ + + + + + +func (d *ServiceDB) StoreAuthRealm(realm types.AuthRealm) (old types.AuthRealm, err error)+
+StoreAuthRealm stores the given AuthRealm, clobbering based on the realm ID. +This function updates the time added/updated values. The previous realm, if any, is +returned. +
+ + + + + + +func (d *ServiceDB) StoreAuthSession(session types.AuthSession) (old types.AuthSession, err error)+
+StoreAuthSession stores the given AuthSession, clobbering based on the tuple of +user ID and realm ID. This function updates the time added/updated values. +The previous session, if any, is returned. +
+ + + + + + +func (d *ServiceDB) StoreBotOptions(opts types.BotOptions) (oldOpts types.BotOptions, err error)+
+StoreBotOptions stores a BotOptions into the database either by inserting a new +bot options or updating an existing bot options. Returns the old bot options if there +was one. +
+ + + + + + +func (d *ServiceDB) StoreMatrixClientConfig(config api.ClientConfig) (oldConfig api.ClientConfig, err error)+
+StoreMatrixClientConfig stores the Matrix client config for a bot service. +If a config already exists then it will be updated, otherwise a new config +will be inserted. The previous config is returned. +
+ + + + + + +func (d *ServiceDB) StoreService(service types.Service) (oldService types.Service, err error)+
+StoreService stores a service into the database either by inserting a new +service or updating an existing service. Returns the old service if there +was one. +
+ + + + + + +func (d *ServiceDB) UpdateNextBatch(userID, nextBatch string) (err error)+
+UpdateNextBatch updates the next_batch token for the given user. +
+ + + + + + + + +type Storer interface { + StoreMatrixClientConfig(config api.ClientConfig) (oldConfig api.ClientConfig, err error) + LoadMatrixClientConfigs() (configs []api.ClientConfig, err error) + LoadMatrixClientConfig(userID string) (config api.ClientConfig, err error) + + UpdateNextBatch(userID, nextBatch string) (err error) + LoadNextBatch(userID string) (nextBatch string, err error) + + LoadService(serviceID string) (service types.Service, err error) + DeleteService(serviceID string) (err error) + LoadServicesForUser(serviceUserID string) (services []types.Service, err error) + LoadServicesByType(serviceType string) (services []types.Service, err error) + StoreService(service types.Service) (oldService types.Service, err error) + + LoadAuthRealm(realmID string) (realm types.AuthRealm, err error) + LoadAuthRealmsByType(realmType string) (realms []types.AuthRealm, err error) + StoreAuthRealm(realm types.AuthRealm) (old types.AuthRealm, err error) + + StoreAuthSession(session types.AuthSession) (old types.AuthSession, err error) + LoadAuthSessionByUser(realmID, userID string) (session types.AuthSession, err error) + LoadAuthSessionByID(realmID, sessionID string) (session types.AuthSession, err error) + RemoveAuthSession(realmID, userID string) error + + LoadBotOptions(userID, roomID string) (opts types.BotOptions, err error) + StoreBotOptions(opts types.BotOptions) (oldOpts types.BotOptions, err error) + + InsertFromConfig(cfg *api.ConfigFile) error +}+
+Storer is the interface which needs to be conformed to in order to persist Go-NEB data +
+ + + + + + + + + + + + +func GetServiceDB() Storer+
+GetServiceDB gets the global service DB instance. +
+ + + + + + + + + + + + + + + + + + + +type HTTPError struct { + WrappedError error + Message string + Code int +}+
+HTTPError An HTTP Error response, which may wrap an underlying native Go Error. +
+ + + + + + + + + + + + + + +func (e HTTPError) Error() string+ + + + + + + + + + + + + + + + + + +
Name | +Synopsis | +
---|---|
.. | +|
+ api + | ++ Package api contains the fundamental data types used by Go-NEB. + | +
+ handlers + | ++ Package handlers contains the HTTP handlers for Go-NEB. + | +
+ clients + | ++ + | +
+ database + | ++ + | +
+ errors + | ++ + | +
+ matrix + | ++ Package matrix provides an HTTP client that can interact with a Homeserver via r0 APIs (/sync). + | +
+ metrics + | ++ + | +
+ plugin + | ++ + | +
+ polling + | ++ + | +
+ realms + | ++ + | +
+ github + | ++ + | +
+ jira + | ++ + | +
+ urls + | ++ Package urls handles converting between various JIRA URL representations in a consistent way. + | +
+ server + | ++ Package server contains building blocks for REST APIs. + | +
+ services + | ++ + | +
+ echo + | ++ + | +
+ giphy + | ++ + | +
+ github + | ++ + | +
+ client + | ++ + | +
+ webhook + | ++ + | +
+ guggy + | ++ + | +
+ jira + | ++ + | +
+ webhook + | ++ + | +
+ rssbot + | ++ + | +
+ types + | ++ + | +
+ util + | ++ + | +
type Client struct { + HomeserverURL *url.URL + Prefix string + UserID string + AccessToken string + Rooms map[string]*Room + Worker *Worker + + NextBatchStorer NextBatchStorer + // contains filtered or unexported fields +}+
+Client represents a Matrix client. +
+ + + + + + + + + + + + +func NewClient(httpClient *http.Client, homeserverURL *url.URL, accessToken, userID string) *Client+
+NewClient creates a new Matrix Client ready for syncing +
+ + + + + + + +func (cli *Client) JoinRoom(roomIDorAlias, serverName, invitingUserID string) (string, error)+
+JoinRoom joins the client to a room ID or alias. If serverName is specified, this will be added as a query param +to instruct the homeserver to join via that server. If invitingUserID is specified, the inviting user ID will be +inserted into the content of the join request. Returns a room ID. +
+ + + + + + +func (cli *Client) SendMessageEvent(roomID string, eventType string, contentJSON interface{}) (string, error)+
+SendMessageEvent sends a message event into a room, returning the event_id on success. +contentJSON should be a pointer to something that can be encoded as JSON using json.Marshal. +
+ + + + + + +func (cli *Client) SendText(roomID, text string) (string, error)+
+SendText sends an m.room.message event into the given room with a msgtype of m.text +
+ + + + + + +func (cli *Client) SetDisplayName(displayName string) error+
+SetDisplayName sets the user's profile display name +
+ + + + + + +func (cli *Client) StopSync()+
+StopSync stops the ongoing sync started by Sync. +
+ + + + + + +func (cli *Client) Sync()+
+Sync starts syncing with the provided Homeserver. This function will be invoked continually. +If Sync is called twice then the first sync will be stopped. +
+ + + + + + +func (cli *Client) UploadLink(link string) (string, error)+
+UploadLink uploads an HTTP URL and then returns an MXC URI. +
+ + + + + + +func (cli *Client) UploadToContentRepo(content io.Reader, contentType string, contentLength int64) (string, error)+
+UploadToContentRepo uploads the given bytes to the content repository and returns an MXC URI. +
+ + + + + + + + +type Event struct { + StateKey string `json:"state_key"` // The state key for the event. Only present on State Events. + Sender string `json:"sender"` // The user ID of the sender of the event + Type string `json:"type"` // The event type + Timestamp int `json:"origin_server_ts"` // The unix timestamp when this message was sent by the origin server + ID string `json:"event_id"` // The unique ID of this event + RoomID string `json:"room_id"` // The room the event was sent to. May be nil (e.g. for presence) + Content map[string]interface{} `json:"content"` // The JSON content of the event. +}+
+Event represents a single Matrix event. +
+ + + + + + + + + + + + + + +func (event *Event) Body() (body string, ok bool)+
+Body returns the value of the "body" key in the event content if it is +present and is a string. +
+ + + + + + +func (event *Event) MessageType() (msgtype string, ok bool)+
+MessageType returns the value of the "msgtype" key in the event content if +it is present and is a string. +
+ + + + + + + + +type HTMLMessage struct { + Body string `json:"body"` + MsgType string `json:"msgtype"` + Format string `json:"format"` + FormattedBody string `json:"formatted_body"` +}+
+An HTMLMessage is the contents of a Matrix HTML formated message event. +
+ + + + + + + + + + + + +func GetHTMLMessage(msgtype, htmlText string) HTMLMessage+
+GetHTMLMessage returns an HTMLMessage with the body set to a stripped version of the provided HTML, in addition +to the provided HTML. +
+ + + + + + + + + +type ImageInfo struct { + Height uint `json:"h"` + Width uint `json:"w"` + Mimetype string `json:"mimetype"` + Size uint `json:"size"` +}+
+ImageInfo contains info about an image +
+ + + + + + + + + + + + + + + + +type ImageMessage struct { + MsgType string `json:"msgtype"` + Body string `json:"body"` + URL string `json:"url"` + Info ImageInfo `json:"info"` +}+
+ImageMessage is an m.image event +
+ + + + + + + + + + + + + + + + +type NextBatchStorer interface { + // Save a next_batch token for a given user. Best effort. + Save(userID, nextBatch string) + // Load a next_batch token for a given user. Return an empty string if no token exists. + Load(userID string) string +}+
+NextBatchStorer controls loading/saving of next_batch tokens for users +
+ + + + + + + + + + + + + + + + +type OnEventListener func(*Event)+
+OnEventListener can be used with Worker.OnEventType to be informed of incoming events. +
+ + + + + + + + + + + + + + + + +type Room struct { + ID string + State map[string]map[string]*Event + Timeline []Event +}+
+Room represents a single Matrix room. +
+ + + + + + + + + + + + +func NewRoom(roomID string) *Room+
+NewRoom creates a new Room with the given ID +
+ + + + + + + +func (room Room) GetMembershipState(userID string) string+
+GetMembershipState returns the membership state of the given user ID in this room. If there is +no entry for this member, 'leave' is returned for consistency with left users. +
+ + + + + + +func (room Room) GetStateEvent(eventType string, stateKey string) *Event+
+GetStateEvent returns the state event for the given type/state_key combo, or nil. +
+ + + + + + +func (room Room) UpdateState(event *Event)+
+UpdateState updates the room's current state with the given Event. This will clobber events based +on the type/state_key combination. +
+ + + + + + + + +type StarterLinkMessage struct { + Body string + Link string +}+
+StarterLinkMessage represents a message with a starter_link custom data. +
+ + + + + + + + + + + + + + +func (m StarterLinkMessage) MarshalJSON() ([]byte, error)+
+MarshalJSON converts this message into actual event content JSON. +
+ + + + + + + + +type TextMessage struct { + MsgType string `json:"msgtype"` + Body string `json:"body"` +}+
+TextMessage is the contents of a Matrix formated message event. +
+ + + + + + + + + + + + + + + + +type Worker struct {
+ // contains filtered or unexported fields
+}
+ +Worker processes incoming events and updates the Matrix client's data structures. It also informs +any attached listeners of the new events. +
+ + + + + + + + + + + + + + +func (worker *Worker) OnEventType(eventType string, callback OnEventListener)+
+OnEventType allows callers to be notified when there are new events for the given event type. +There are no duplicate checks. +
+ + + + + + + + + + + + + + + + + + +const ( + StatusSuccess = "success" + StatusFailure = "failure" +)+
+Common status values +
+ + + + + + + +func IncrementAuthSession(realmType string)+
+IncrementAuthSession increments the /requestAuthSession request counter +
+ + + + + + + +func IncrementCommand(cmdName string, st Status)+
+IncrementCommand increments the pling command counter +
+ + + + + + + +func IncrementConfigureService(serviceType string)+
+IncrementConfigureService increments the /configureService counter +
+ + + + + + + +func IncrementWebhook(serviceType string)+
+IncrementWebhook increments the incoming webhook request counter +
+ + + + + + + + +type Status string+
+Status is the status of a measurable metric (incoming commands, outgoing polls, etc) +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +func OnMessage(plugins []Plugin, client *matrix.Client, event *matrix.Event)+
+OnMessage checks the message event to see whether it contains any commands +or expansions from the listed plugins and processes those commands or +expansions. +
+ + + + + + + + +type Command struct { + Path []string + Arguments []string + Help string + Command func(roomID, userID string, arguments []string) (content interface{}, err error) +}+
+A Command is something that a user invokes by sending a message starting with '!' +followed by a list of strings that name the command, followed by a list of argument +strings. The argument strings may be quoted using '\"' and '\” in the same way +that they are quoted in the unix shell. +
+ + + + + + + + + + + + + + + + +type Expansion struct { + Regexp *regexp.Regexp + Expand func(roomID, userID string, matchingGroups []string) interface{} +}+
+An Expansion is something that actives when the user sends any message +containing a string matching a given pattern. For example an RFC expansion +might expand "RFC 6214" into "Adaptation of RFC 1149 for IPv6" and link to +the appropriate RFC. +
+ + + + + + + + + + + + + + + + +type Plugin struct { + Commands []Command + Expansions []Expansion +}+
+A Plugin is a list of commands and expansions to apply to incoming messages. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +func SetClients(clis *clients.Clients)+
+SetClients sets a pool of clients for passing into OnPoll +
+ + + + + + + +func Start() error+
+Start polling already existing services +
+ + + + + + + +func StartPolling(service types.Service) error+
+StartPolling begins a polling loop for this service. +If one already exists for this service, it will be instructed to die. The new poll will not wait for this to happen, +so there may be a brief period of overlap. It is safe to immediately call `StopPolling(service)` to immediately terminate +this poll. +
+ + + + + + + +func StopPolling(service types.Service)+
+StopPolling stops all pollers for this service. +
+ + + + + + + + + + + + + + + + + + +type GithubRealm struct { + ClientSecret string + ClientID string + StarterLink string + // contains filtered or unexported fields +}+
+GithubRealm can handle OAuth processes with github.com +
+ + + + + + + + + + + + + + +func (r *GithubRealm) AuthSession(id, userID, realmID string) types.AuthSession+
+AuthSession returns a GithubSession for this user +
+ + + + + + +func (r *GithubRealm) ID() string+
+ID returns the realm ID +
+ + + + + + +func (r *GithubRealm) Init() error+
+Init does nothing. +
+ + + + + + +func (r *GithubRealm) OnReceiveRedirect(w http.ResponseWriter, req *http.Request)+
+OnReceiveRedirect processes OAuth redirect requests from Github +
+ + + + + + +func (r *GithubRealm) Register() error+
+Register does nothing. +
+ + + + + + +func (r *GithubRealm) RequestAuthSession(userID string, req json.RawMessage) interface{}+
+RequestAuthSession generates an OAuth2 URL for this user to auth with github via. +
+ + + + + + +func (r *GithubRealm) Type() string+
+Type is github +
+ + + + + + + + +type GithubSession struct { + // The client-supplied URL to redirect them to after the auth process is complete. + ClientsRedirectURL string + // AccessToken is the github access token for the user + AccessToken string + // Scopes are the set of *ALLOWED* scopes (which may not be the same as the requested scopes) + Scopes string + // contains filtered or unexported fields +}+
+GithubSession represents an authenticated github session +
+ + + + + + + + + + + + + + +func (s *GithubSession) Authenticated() bool+
+Authenticated returns true if the user has completed the auth process +
+ + + + + + +func (s *GithubSession) ID() string+
+ID returns the session ID +
+ + + + + + +func (s *GithubSession) Info() interface{}+
+Info returns a list of possible repositories that this session can integrate with. +
+ + + + + + +func (s *GithubSession) RealmID() string+
+RealmID returns the realm ID of the realm which performed the authentication +
+ + + + + + +func (s *GithubSession) UserID() string+
+UserID returns the user_id who authorised with Github +
+ + + + + + + + + + + + + + + + + + +type JIRARealm struct { + JIRAEndpoint string + Server string // clobbered based on /serverInfo request + Version string // clobbered based on /serverInfo request + ConsumerName string + ConsumerKey string + ConsumerSecret string + PublicKeyPEM string // clobbered based on PrivateKeyPEM + PrivateKeyPEM string + HasWebhook bool // clobbered based on NEB + StarterLink string + // contains filtered or unexported fields +}+
+JIRARealm is an AuthRealm which can process JIRA installations +
+ + + + + + + + + + + + + + +func (r *JIRARealm) AuthSession(id, userID, realmID string) types.AuthSession+
+AuthSession returns a JIRASession with the given parameters +
+ + + + + + +func (r *JIRARealm) ID() string+
+ID returns the ID of this JIRA realm. +
+ + + + + + +func (r *JIRARealm) Init() error+
+Init initialises the private key for this JIRA realm. +
+ + + + + + +func (r *JIRARealm) JIRAClient(userID string, allowUnauth bool) (*jira.Client, error)+
+JIRAClient returns an authenticated jira.Client for the given userID. Returns an unauthenticated +client if allowUnauth is true and no authenticated session is found, else returns an error. +
+ + + + + + +func (r *JIRARealm) OnReceiveRedirect(w http.ResponseWriter, req *http.Request)+
+OnReceiveRedirect is called when JIRA installations redirect back to NEB +
+ + + + + + +func (r *JIRARealm) ProjectKeyExists(userID, projectKey string) (bool, error)+
+ProjectKeyExists returns true if the given project key exists on this JIRA realm. +An authenticated client for userID will be used if one exists, else an +unauthenticated client will be used, which may not be able to see the complete list +of projects. +
+ + + + + + +func (r *JIRARealm) Register() error+
+Register is called when this realm is being created from an external entity +
+ + + + + + +func (r *JIRARealm) RequestAuthSession(userID string, req json.RawMessage) interface{}+
+RequestAuthSession is called by a user wishing to auth with this JIRA realm +
+ + + + + + +func (r *JIRARealm) Type() string+
+Type returns the type of realm this is. +
+ + + + + + + + +type JIRASession struct { + RequestSecret string + AccessToken string + AccessSecret string + ClientsRedirectURL string // where to redirect the client to after auth + // contains filtered or unexported fields +}+
+JIRASession represents a single authentication session between a user and a JIRA endpoint. +The endpoint is dictated by the realm ID. +
+ + + + + + + + + + + + + + +func (s *JIRASession) Authenticated() bool+
+Authenticated returns true if the user has completed the auth process +
+ + + + + + +func (s *JIRASession) ID() string+
+ID returns the OAuth1 request_token which is used when looking up sessions in the redirect +handler. +
+ + + + + + +func (s *JIRASession) Info() interface{}+
+Info returns nothing +
+ + + + + + +func (s *JIRASession) RealmID() string+
+RealmID returns the JIRA realm ID which created this session. +
+ + + + + + +func (s *JIRASession) UserID() string+
+UserID returns the ID of the user performing the authentication. +
+ + + + + + + + + + + + + + + + +func SameJIRAURL(a, b string) bool+
+SameJIRAURL returns true if the two given JIRA URLs are pointing to the same JIRA installation. +Equivalence is determined solely by the provided URLs, by sanitising them then comparing. +
+ + + + + + + + +type JIRAURL struct { + Base string // The base URL of the JIRA installation. Always has a trailing / and a protocol. + Key string // The URL key of the JIRA installation. Never has a trailing / or a protocol. + Raw string // The raw input URL, if given. Freeform. +}+
+JIRAURL contains the parsed representation of a JIRA URL +
+ + + + + + + + + + + + +func ParseJIRAURL(u string) (j JIRAURL, err error)+
+ParseJIRAURL parses a raw input URL and returns a struct which has various JIRA URL representations. The input +URL can be a JIRA REST URL, a speculative base JIRA URL from a client, or a URL key. The input string will be +stored as under JIRAURL.Raw. If a URL key is given, this struct will default to https as the protocol. +
+ + + + + + + + + + + + + + + + + + + +func MakeJSONAPI(handler JSONRequestHandler) http.HandlerFunc+
+MakeJSONAPI creates an HTTP handler which always responds to incoming requests with JSON responses. +
+ + + + + + + +func Protect(handler http.HandlerFunc) http.HandlerFunc+
+Protect panicking HTTP requests from taking down the entire process, and log them using +the correct logger, returning a 500 with a JSON response rather than abruptly closing the +connection. +
+ + + + + + + +func SetCORSHeaders(w http.ResponseWriter)+
+SetCORSHeaders sets unrestricted origin Access-Control headers on the response writer +
+ + + + + + + +func WithCORSOptions(handler http.HandlerFunc) http.HandlerFunc+
+WithCORSOptions intercepts all OPTIONS requests and responds with CORS headers. The request handler +is not invoked when this happens. +
+ + + + + + + + +type JSONError struct { + Message string `json:"message"` +}+
+JSONError represents a JSON API error response +
+ + + + + + + + + + + + + + + + +type JSONRequestHandler interface { + OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError) +}+
+JSONRequestHandler represents an interface that must be satisfied in order to respond to incoming +HTTP requests with JSON. The interface returned will be marshalled into JSON to be sent to the client, +unless the interface is []byte in which case the bytes are sent to the client unchanged. +If an error is returned, a JSON error response will also be returned, unless the error code +is a 302 REDIRECT in which case a redirect is sent based on the Message field. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +func New(token string) *github.Client+
+New returns a github Client which can perform Github API operations. +If `token` is empty, a non-authenticated client will be created. This should be +used sparingly where possible as you only get 60 requests/hour like that (IP locked). +
+ + + + + + + + +type TrimmedRepository struct { + Name *string `json:"name"` + Description *string `json:"description"` + Private *bool `json:"private"` + HTMLURL *string `json:"html_url"` + CreatedAt *github.Timestamp `json:"created_at"` + UpdatedAt *github.Timestamp `json:"updated_at"` + PushedAt *github.Timestamp `json:"pushed_at"` + Fork *bool `json:"fork"` + FullName *string `json:"full_name"` + Permissions *map[string]bool `json:"permissions"` +}+
+TrimmedRepository represents a cut-down version of github.Repository with only the keys the end-user is +likely to want. +
+ + + + + + + + + + + + +func TrimRepository(repo *github.Repository) TrimmedRepository+
+TrimRepository trims a github repo into important fields only. +
+ + + + + + + + + + + + + + + + + + + +func OnReceiveRequest(r *http.Request, secretToken string) (string, *github.Repository, *matrix.HTMLMessage, *errors.HTTPError)+
+OnReceiveRequest processes incoming github webhook requests and returns a +matrix message to send, along with parsed repo information. +The secretToken, if supplied, will be used to verify the request is from +Github. If it isn't, an error is returned. +
+ + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ echo + | ++ + | +
+ giphy + | ++ + | +
+ github + | ++ + | +
+ client + | ++ + | +
+ webhook + | ++ + | +
+ guggy + | ++ + | +
+ jira + | ++ + | +
+ webhook + | ++ + | +
+ rssbot + | ++ + | +
func OnReceiveRequest(req *http.Request) (string, *Event, *errors.HTTPError)+
+OnReceiveRequest is called when JIRA hits NEB with an update. +Returns the project key and webhook event, or an error. +
+ + + + + + + +func RegisterHook(jrealm *realms.JIRARealm, projects []string, userID, webhookEndpointURL string) error+
+RegisterHook checks to see if this user is allowed to track the given projects and then tracks them. +
+ + + + + + + + +type Event struct { + WebhookEvent string `json:"webhookEvent"` + Timestamp int64 `json:"timestamp"` + User jira.User `json:"user"` + Issue jira.Issue `json:"issue"` +}+
+Event represents an incoming JIRA webhook event +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +func BaseURL(u string) error+
+BaseURL sets the base URL of NEB to the url given. This URL must be accessible from the +public internet. +
+ + + + + + + +func PollingServiceTypes() (types []string)+
+PollingServiceTypes returns a list of service types which meet the Poller interface +
+ + + + + + + +func RegisterAuthRealm(factory func(string, string) AuthRealm)+
+RegisterAuthRealm registers a factory for creating AuthRealm instances. +
+ + + + + + + +func RegisterService(factory func(string, string, string) Service)+
+RegisterService registers a factory for creating Service instances. +
+ + + + + + + + +type AuthRealm interface { + ID() string + Type() string + Init() error + Register() error + OnReceiveRedirect(w http.ResponseWriter, req *http.Request) + AuthSession(id, userID, realmID string) AuthSession + RequestAuthSession(userID string, config json.RawMessage) interface{} +}+
+AuthRealm represents a place where a user can authenticate themselves. +This may static (like github.com) or a specific domain (like matrix.org/jira) +
+ + + + + + + + + + + + +func CreateAuthRealm(realmID, realmType string, realmJSON []byte) (AuthRealm, error)+
+CreateAuthRealm creates an AuthRealm of the given type and realm ID. +Returns an error if the realm couldn't be created or the JSON cannot be unmarshalled. +
+ + + + + + + + + +type AuthSession interface { + ID() string + UserID() string + RealmID() string + Authenticated() bool + Info() interface{} +}+
+AuthSession represents a single authentication session between a user and +an auth realm. +
+ + + + + + + + + + + + + + + + +type BotOptions struct { + RoomID string + UserID string + SetByUserID string + Options map[string]interface{} +}+
+BotOptions for a given bot user in a given room +
+ + + + + + + + + + + + + + + + +type DefaultService struct{}+
+DefaultService NO-OPs the implementation of optional Service interface methods. Feel free to override them. +
+ + + + + + + + + + + + + + +func (s *DefaultService) OnReceiveWebhook(w http.ResponseWriter, req *http.Request, cli *matrix.Client)+
+OnReceiveWebhook does nothing but 200 OK the request. +
+ + + + + + +func (s *DefaultService) Plugin(cli *matrix.Client, roomID string) plugin.Plugin+
+Plugin returns no plugins. +
+ + + + + + +func (s *DefaultService) PostRegister(oldService Service)+
+PostRegister does nothing. +
+ + + + + + +func (s *DefaultService) Register(oldService Service, client *matrix.Client) error+
+Register does nothing and returns no error. +
+ + + + + + + + +type Poller interface { + // OnPoll is called when the poller should poll. Return the timestamp when you want to be polled again. + // Return 0 to never be polled again. + OnPoll(client *matrix.Client) time.Time +}+
+Poller represents a thing which can poll. Services should implement this method signature to support polling. +
+ + + + + + + + + + + + + + + + +type Service interface { + // Return the user ID of this service. + ServiceUserID() string + // Return an opaque ID used to identify this service. + ServiceID() string + // Return the type of service. This string MUST NOT change. + ServiceType() string + Plugin(cli *matrix.Client, roomID string) plugin.Plugin + OnReceiveWebhook(w http.ResponseWriter, req *http.Request, cli *matrix.Client) + // A lifecycle function which is invoked when the service is being registered. The old service, if one exists, is provided, + // along with a Client instance for ServiceUserID(). If this function returns an error, the service will not be registered + // or persisted to the database, and the user's request will fail. This can be useful if you depend on external factors + // such as registering webhooks. + Register(oldService Service, client *matrix.Client) error + // A lifecycle function which is invoked after the service has been successfully registered and persisted to the database. + // This function is invoked within the critical section for configuring services, guaranteeing that there will not be + // concurrent modifications to this service whilst this function executes. This lifecycle hook should be used to clean + // up resources which are no longer needed (e.g. removing old webhooks). + PostRegister(oldService Service) +}+
+A Service is the configuration for a bot service. +
+ + + + + + + + + + + + +func CreateService(serviceID, serviceType, serviceUserID string, serviceJSON []byte) (Service, error)+
+CreateService creates a Service of the given type and serviceID. +Returns an error if the Service couldn't be created. +
+ + + + + + + + + + + + + + + + + + + +func Difference(a, b []string) (onlyA, onlyB []string)+
+Difference returns the elements that are only in the first list and +the elements that are only in the second. As a side-effect this sorts +the input lists in-place. +
+ + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ dugong + | ++ + | +
+ go-neb + | ++ + | +
+ api + | ++ Package api contains the fundamental data types used by Go-NEB. + | +
+ handlers + | ++ Package handlers contains the HTTP handlers for Go-NEB. + | +
+ clients + | ++ + | +
+ database + | ++ + | +
+ errors + | ++ + | +
+ matrix + | ++ Package matrix provides an HTTP client that can interact with a Homeserver via r0 APIs (/sync). + | +
+ metrics + | ++ + | +
+ plugin + | ++ + | +
+ polling + | ++ + | +
+ realms + | ++ + | +
+ github + | ++ + | +
+ jira + | ++ + | +
+ urls + | ++ Package urls handles converting between various JIRA URL representations in a consistent way. + | +
+ server + | ++ Package server contains building blocks for REST APIs. + | +
+ services + | ++ + | +
+ echo + | ++ + | +
+ giphy + | ++ + | +
+ github + | ++ + | +
+ client + | ++ + | +
+ webhook + | ++ + | +
+ guggy + | ++ + | +
+ jira + | ++ + | +
+ webhook + | ++ + | +
+ rssbot + | ++ + | +
+ types + | ++ + | +
+ util + | ++ + | +
var ( + ParseEnv bool = false + ParseBacktick bool = false +)+ + + + + + +
func Parse(line string) ([]string, error)+ + + + + + + + +
type Parser struct { + ParseEnv bool + ParseBacktick bool +}+ + + + + + + + + + + + +
func NewParser() *Parser+ + + + + + + +
func (p *Parser) Parse(line string) ([]string, error)+ + + + + + + + + + + + + + + + + + +
const ErrNoMask C.int = 0xff+ + + + +
var ( + ErrError = ErrNo(1) /* SQL error or missing database */ + ErrInternal = ErrNo(2) /* Internal logic error in SQLite */ + ErrPerm = ErrNo(3) /* Access permission denied */ + ErrAbort = ErrNo(4) /* Callback routine requested an abort */ + ErrBusy = ErrNo(5) /* The database file is locked */ + ErrLocked = ErrNo(6) /* A table in the database is locked */ + ErrNomem = ErrNo(7) /* A malloc() failed */ + ErrReadonly = ErrNo(8) /* Attempt to write a readonly database */ + ErrInterrupt = ErrNo(9) /* Operation terminated by sqlite3_interrupt() */ + ErrIoErr = ErrNo(10) /* Some kind of disk I/O error occurred */ + ErrCorrupt = ErrNo(11) /* The database disk image is malformed */ + ErrNotFound = ErrNo(12) /* Unknown opcode in sqlite3_file_control() */ + ErrFull = ErrNo(13) /* Insertion failed because database is full */ + ErrCantOpen = ErrNo(14) /* Unable to open the database file */ + ErrProtocol = ErrNo(15) /* Database lock protocol error */ + ErrEmpty = ErrNo(16) /* Database is empty */ + ErrSchema = ErrNo(17) /* The database schema changed */ + ErrTooBig = ErrNo(18) /* String or BLOB exceeds size limit */ + ErrConstraint = ErrNo(19) /* Abort due to constraint violation */ + ErrMismatch = ErrNo(20) /* Data type mismatch */ + ErrMisuse = ErrNo(21) /* Library used incorrectly */ + ErrNoLFS = ErrNo(22) /* Uses OS features not supported on host */ + ErrAuth = ErrNo(23) /* Authorization denied */ + ErrFormat = ErrNo(24) /* Auxiliary database format error */ + ErrRange = ErrNo(25) /* 2nd parameter to sqlite3_bind out of range */ + ErrNotADB = ErrNo(26) /* File opened that is not a database file */ + ErrNotice = ErrNo(27) /* Notifications from sqlite3_log() */ + ErrWarning = ErrNo(28) /* Warnings from sqlite3_log() */ +)+
+result codes from http://www.sqlite.org/c3ref/c_abort.html +
+ + +var ( + ErrIoErrRead = ErrIoErr.Extend(1) + ErrIoErrShortRead = ErrIoErr.Extend(2) + ErrIoErrWrite = ErrIoErr.Extend(3) + ErrIoErrFsync = ErrIoErr.Extend(4) + ErrIoErrDirFsync = ErrIoErr.Extend(5) + ErrIoErrTruncate = ErrIoErr.Extend(6) + ErrIoErrFstat = ErrIoErr.Extend(7) + ErrIoErrUnlock = ErrIoErr.Extend(8) + ErrIoErrRDlock = ErrIoErr.Extend(9) + ErrIoErrDelete = ErrIoErr.Extend(10) + ErrIoErrBlocked = ErrIoErr.Extend(11) + ErrIoErrNoMem = ErrIoErr.Extend(12) + ErrIoErrAccess = ErrIoErr.Extend(13) + ErrIoErrCheckReservedLock = ErrIoErr.Extend(14) + ErrIoErrLock = ErrIoErr.Extend(15) + ErrIoErrClose = ErrIoErr.Extend(16) + ErrIoErrDirClose = ErrIoErr.Extend(17) + ErrIoErrSHMOpen = ErrIoErr.Extend(18) + ErrIoErrSHMSize = ErrIoErr.Extend(19) + ErrIoErrSHMLock = ErrIoErr.Extend(20) + ErrIoErrSHMMap = ErrIoErr.Extend(21) + ErrIoErrSeek = ErrIoErr.Extend(22) + ErrIoErrDeleteNoent = ErrIoErr.Extend(23) + ErrIoErrMMap = ErrIoErr.Extend(24) + ErrIoErrGetTempPath = ErrIoErr.Extend(25) + ErrIoErrConvPath = ErrIoErr.Extend(26) + = ErrLocked.Extend(1) + ErrBusyRecovery = ErrBusy.Extend(1) + ErrBusySnapshot = ErrBusy.Extend(2) + ErrCantOpenNoTempDir = ErrCantOpen.Extend(1) + ErrCantOpenIsDir = ErrCantOpen.Extend(2) + ErrCantOpenFullPath = ErrCantOpen.Extend(3) + ErrCantOpenConvPath = ErrCantOpen.Extend(4) + ErrCorruptVTab = ErrCorrupt.Extend(1) + ErrReadonlyRecovery = ErrReadonly.Extend(1) + ErrReadonlyCantLock = ErrReadonly.Extend(2) + ErrReadonlyRollback = ErrReadonly.Extend(3) + ErrReadonlyDbMoved = ErrReadonly.Extend(4) + ErrAbortRollback = ErrAbort.Extend(2) + ErrConstraintCheck = ErrConstraint.Extend(1) + ErrConstraintCommitHook = ErrConstraint.Extend(2) + ErrConstraintForeignKey = ErrConstraint.Extend(3) + ErrConstraintFunction = ErrConstraint.Extend(4) + ErrConstraintNotNull = ErrConstraint.Extend(5) + ErrConstraintPrimaryKey = ErrConstraint.Extend(6) + ErrConstraintTrigger = ErrConstraint.Extend(7) + ErrConstraintUnique = ErrConstraint.Extend(8) + ErrConstraintVTab = ErrConstraint.Extend(9) + ErrConstraintRowId = ErrConstraint.Extend(10) + ErrNoticeRecoverWAL = ErrNotice.Extend(1) + ErrNoticeRecoverRollback = ErrNotice.Extend(2) + ErrWarningAutoIndex = ErrWarning.Extend(1) +)+
+result codes from http://www.sqlite.org/c3ref/c_abort_rollback.html +
+ + +var SQLiteTimestampFormats = []string{ + + "2006-01-02 15:04:05.999999999-07:00", + "2006-01-02T15:04:05.999999999-07:00", + "2006-01-02 15:04:05.999999999", + "2006-01-02T15:04:05.999999999", + "2006-01-02 15:04:05", + "2006-01-02T15:04:05", + "2006-01-02 15:04", + "2006-01-02T15:04", + "2006-01-02", +}+
+Timestamp formats understood by both this module and SQLite. +The first format in the slice will be used when saving time values +into the database. When parsing a string from a timestamp or +datetime column, the formats are tried in order. +
+ + + + + + +func Version() (libVersion string, libVersionNumber int, sourceId string)+
+Version returns SQLite library version information. +
+ + + + + + + + +type ErrNo int+ + + + + + + + + + + + + + +
func (err ErrNo) Error() string+ + + + + + +
func (err ErrNo) Extend(by int) ErrNoExtended+ + + + + + + + +
type ErrNoExtended int+ + + + + + + + + + + + + + +
func (err ErrNoExtended) Error() string+ + + + + + + + +
type Error struct { + Code ErrNo /* The error code returned by SQLite */ + ExtendedCode ErrNoExtended /* The extended error code returned by SQLite */ + // contains filtered or unexported fields +}+ + + + + + + + + + + + + + +
func (err Error) Error() string+ + + + + + + + +
type SQLiteBackup struct {
+ // contains filtered or unexported fields
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ func (b *SQLiteBackup) Close() error+ + + + + + +
func (b *SQLiteBackup) Finish() error+ + + + + + +
func (b *SQLiteBackup) PageCount() int+ + + + + + +
func (b *SQLiteBackup) Remaining() int+ + + + + + +
func (b *SQLiteBackup) Step(p int) (bool, error)+
+Backs up for one step. Calls the underlying `sqlite3_backup_step` function. +This function returns a boolean indicating if the backup is done and +an error signalling any other error. Done is returned if the underlying C +function returns SQLITE_DONE (Code 101) +
+ + + + + + + + +type SQLiteConn struct {
+ // contains filtered or unexported fields
+}
+ +Conn struct. +
+ + + + + + + + + + + + + + +func (c *SQLiteConn) AutoCommit() bool+
+AutoCommit return which currently auto commit or not. +
+ + + + + + +func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteBackup, error)+ + + + + + +
func (c *SQLiteConn) Begin() (driver.Tx, error)+
+Begin transaction. +
+ + + + + + +func (c *SQLiteConn) Close() error+
+Close the connection. +
+ + + + + + +func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error)+
+Implements Execer +
+ + + + + + +func (c *SQLiteConn) LoadExtension(lib string, entry string) error+ + + + + + +
func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error)+
+Prepare the query string. Return a new statement. +
+ + + + + + +func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error)+
+Implements Queryer +
+ + + + + + +func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error+ + + + + + +
func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error+
+RegisterFunc makes a Go function available as a SQLite function. +
++The Go function can have arguments of the following types: any +numeric type except complex, bool, []byte, string and +interface{}. interface{} arguments are given the direct translation +of the SQLite data type: int64 for INTEGER, float64 for FLOAT, +[]byte for BLOB, string for TEXT. +
++The function can additionally be variadic, as long as the type of +the variadic argument is one of the above. +
++If pure is true. SQLite will assume that the function's return +value depends only on its inputs, and make more aggressive +optimizations in its queries. +
++See _example/go_custom_funcs for a detailed example. +
+ + + + + + + + +type SQLiteDriver struct { + Extensions []string + ConnectHook func(*SQLiteConn) error +}+
+Driver struct. +
+ + + + + + + + + + + + + + +func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error)+
+Open database and return a new connection. +You can specify a DSN string using a URI as the filename. +
+test.db +file:test.db?cache=shared&mode=memory +:memory: +file::memory: ++
+go-sqlite3 adds the following query parameters to those used by SQLite: +
+_loc=XXX + Specify location of time format. It's possible to specify "auto". +_busy_timeout=XXX + Specify value for sqlite3_busy_timeout. +_txlock=XXX + Specify locking behavior for transactions. XXX can be "immediate", + "deferred", "exclusive". ++ + + + + + + + +
type SQLiteResult struct {
+ // contains filtered or unexported fields
+}
+ +Result struct. +
+ + + + + + + + + + + + + + +func (r *SQLiteResult) LastInsertId() (int64, error)+
+Return last inserted ID. +
+ + + + + + +func (r *SQLiteResult) RowsAffected() (int64, error)+
+Return how many rows affected. +
+ + + + + + + + +type SQLiteRows struct {
+ // contains filtered or unexported fields
+}
+ +Rows struct. +
+ + + + + + + + + + + + + + +func (rc *SQLiteRows) Close() error+
+Close the rows. +
+ + + + + + +func (rc *SQLiteRows) Columns() []string+
+Return column names. +
+ + + + + + +func (rc *SQLiteRows) DeclTypes() []string+
+Return column types. +
+ + + + + + +func (rc *SQLiteRows) Next(dest []driver.Value) error+
+Move cursor to next. +
+ + + + + + + + +type SQLiteStmt struct {
+ // contains filtered or unexported fields
+}
+ +Stmt struct. +
+ + + + + + + + + + + + + + +func (s *SQLiteStmt) Close() error+
+Close the statement. +
+ + + + + + +func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error)+
+Execute the statement with arguments. Return result object. +
+ + + + + + +func (s *SQLiteStmt) NumInput() int+
+Return a number of parameters. +
+ + + + + + +func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error)+
+Query the statement with arguments. Return records. +
+ + + + + + + + +type SQLiteTx struct {
+ // contains filtered or unexported fields
+}
+ +Tx struct. +
+ + + + + + + + + + + + + + +func (tx *SQLiteTx) Commit() error+
+Commit transaction. +
+ + + + + + +func (tx *SQLiteTx) Rollback() error+
+Rollback transaction. +
+ + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ sqlite3_test + | ++ + | +
+ tool + | ++ + | +
func BenchmarkExec(b *testing.B)+ + + + + + + +
func BenchmarkParams(b *testing.B)+ + + + + + + +
func BenchmarkQuery(b *testing.B)+ + + + + + + +
func BenchmarkRows(b *testing.B)+ + + + + + + +
func BenchmarkStmt(b *testing.B)+ + + + + + + +
func BenchmarkStmtRows(b *testing.B)+ + + + + + + +
func RunTests(t *testing.T, d *sql.DB, dialect Dialect)+
+RunTests runs the SQL test suite +
+ + + + + + + +func TestBlobs(t *testing.T)+ + + + + + + +
func TestManyQueryRow(t *testing.T)+ + + + + + + +
func TestPreparedStmt(t *testing.T)+ + + + + + + +
func TestResult(t *testing.T)+ + + + + + + +
func TestTxQuery(t *testing.T)+ + + + + + + + +
type DB struct { + *testing.T + *sql.DB + // contains filtered or unexported fields +}+ + + + + + + + + + + + + + + + +
type Dialect int+ + + +
const ( + SQLITE Dialect = iota + POSTGRESQL + MYSQL +)+ + + + + + + + + + + + + + + + + + + + + + + + + +
Name | +Synopsis | +
---|---|
.. | +|
+ go-shellwords + | ++ + | +
+ go-sqlite3 + | ++ Package sqlite3 provides interface to SQLite3 databases. + | +
+ sqlite3_test + | ++ + | +
+ tool + | ++ + | +
func ReadDelimited(r io.Reader, m proto.Message) (n int, err error)+
+ReadDelimited decodes a message from the provided length-delimited stream, +where the length is encoded as 32-bit varint prefix to the message body. +It returns the total number of bytes read and any applicable error. This is +roughly equivalent to the companion Java API's +MessageLite#parseDelimitedFrom. As per the reader contract, this function +calls r.Read repeatedly as required until exactly one message including its +prefix is read and decoded (or an error has occurred). The function never +reads more bytes from the stream than required. The function never returns +an error if a message has been read and decoded correctly, even if the end +of the stream has been reached in doing so. In that case, any subsequent +calls return (0, io.EOF). +
+ + + + + + + +func WriteDelimited(w io.Writer, m proto.Message) (n int, err error)+
+WriteDelimited encodes and dumps a message to the provided writer prefixed +with a 32-bit varint indicating the length of the encoded message, producing +a length-delimited record stream, which can be used to chain together +encoded messages of the same type together in a file. It returns the total +number of bytes written and any applicable error. This is roughly +equivalent to the companion Java API's MessageLite#writeDelimitedTo. +
+ + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ golang_protobuf_extensions + | ++ + | +
+ pbutil + | ++ Package pbutil provides record length-delimited Protocol Buffer streaming. + | +
type Category struct { + Term string `json:"term,omitempty"` + Scheme string `json:"scheme,omitempty"` + Label string `json:"label,omitempty"` +}+
+Category is category metadata for Feeds and Entries +
+ + + + + + + + + + + + + + + + +type Content struct { + Src string `json:"src,omitempty"` + Type string `json:"type,omitempty"` + Value string `json:"value,omitempty"` +}+
+Content either contains or links to the content of +the entry +
+ + + + + + + + + + + + + + + + +type Entry struct { + Title string `json:"title,omitempty"` + ID string `json:"id,omitempty"` + Updated string `json:"updated,omitempty"` + UpdatedParsed *time.Time `json:"updatedParsed,omitempty"` + Summary string `json:"summary,omitempty"` + Authors []*Person `json:"authors,omitempty"` + Contributors []*Person `json:"contributors,omitempty"` + Categories []*Category `json:"categories,omitempty"` + Links []*Link `json:"links,omitempty"` + Rights string `json:"rights,omitempty"` + Published string `json:"published,omitempty"` + PublishedParsed *time.Time `json:"publishedParsed,omitempty"` + Source *Source `json:"source,omitempty"` + Content *Content `json:"content,omitempty"` + Extensions ext.Extensions `json:"extensions,omitempty"` +}+
+Entry is an Atom Entry +
+ + + + + + + + + + + + + + + + +type Feed struct { + Title string `json:"title,omitempty"` + ID string `json:"id,omitempty"` + Updated string `json:"updated,omitempty"` + UpdatedParsed *time.Time `json:"updatedParsed,omitempty"` + Subtitle string `json:"subtitle,omitempty"` + Links []*Link `json:"links,omitempty"` + Language string `json:"language,omitempty"` + Generator *Generator `json:"generator,omitempty"` + Icon string `json:"icon,omitempty"` + Logo string `json:"logo,omitempty"` + Rights string `json:"rights,omitempty"` + Contributors []*Person `json:"contributors,omitempty"` + Authors []*Person `json:"authors,omitempty"` + Categories []*Category `json:"categories,omitempty"` + Entries []*Entry `json:"entries"` + Extensions ext.Extensions `json:"extensions,omitempty"` + Version string `json:"version"` +}+
+Feed is an Atom Feed +
+ + + + + + + + + + + + + + +func (f Feed) String() string+ + + + + + + + +
type Generator struct { + Value string `json:"value,omitempty"` + URI string `json:"uri,omitempty"` + Version string `json:"version,omitempty"` +}+
+Generator identifies the agent used to generate a +feed, for debugging and other purposes. +
+ + + + + + + + + + + + + + + + +type Link struct { + Href string `json:"href,omitempty"` + Hreflang string `json:"hreflang,omitempty"` + Rel string `json:"rel,omitempty"` + Type string `json:"type,omitempty"` + Title string `json:"title,omitempty"` + Length string `json:"length,omitempty"` +}+
+Link is an Atom link that defines a reference +from an entry or feed to a Web resource +
+ + + + + + + + + + + + + + + + +type Parser struct{}+
+Parser is an Atom Parser +
+ + + + + + + + + + + + + + +func (ap *Parser) Parse(feed io.Reader) (*Feed, error)+
+Parse parses an xml feed into an atom.Feed +
+ + + + + + + + +type Person struct { + Name string `json:"name,omitempty"` + Email string `json:"email,omitempty"` + URI string `json:"uri,omitempty"` +}+
+Person represents a person in an Atom feed +for things like Authors, Contributors, etc +
+ + + + + + + + + + + + + + + + +type Source struct { + Title string `json:"title,omitempty"` + ID string `json:"id,omitempty"` + Updated string `json:"updated,omitempty"` + UpdatedParsed *time.Time `json:"updatedParsed,omitempty"` + Subtitle string `json:"subtitle,omitempty"` + Links []*Link `json:"links,omitempty"` + Generator *Generator `json:"generator,omitempty"` + Icon string `json:"icon,omitempty"` + Logo string `json:"logo,omitempty"` + Rights string `json:"rights,omitempty"` + Contributors []*Person `json:"contributors,omitempty"` + Authors []*Person `json:"authors,omitempty"` + Categories []*Category `json:"categories,omitempty"` + Extensions ext.Extensions `json:"extensions,omitempty"` +}+
+Source contains the feed information for another +feed if a given entry came from that feed. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +type DublinCoreExtension struct { + Title []string `json:"title,omitempty"` + Creator []string `json:"creator,omitempty"` + Author []string `json:"author,omitempty"` + Subject []string `json:"subject,omitempty"` + Description []string `json:"description,omitempty"` + Publisher []string `json:"publisher,omitempty"` + Contributor []string `json:"contributor,omitempty"` + Date []string `json:"date,omitempty"` + Type []string `json:"type,omitempty"` + Format []string `json:"format,omitempty"` + Identifier []string `json:"identifier,omitempty"` + Source []string `json:"source,omitempty"` + Language []string `json:"language,omitempty"` + Relation []string `json:"relation,omitempty"` + Coverage []string `json:"coverage,omitempty"` + Rights []string `json:"rights,omitempty"` +}+
+DublinCoreExtension represents a feed extension +for the Dublin Core specification. +
+ + + + + + + + + + + + +func NewDublinCoreExtension(extensions map[string][]Extension) *DublinCoreExtension+
+NewDublinCoreExtension creates a new DublinCoreExtension +given the generic extension map for the "dc" prefix. +
+ + + + + + + + + +type Extension struct { + Name string `json:"name"` + Value string `json:"value"` + Attrs map[string]string `json:"attrs"` + Children map[string][]Extension `json:"children"` +}+
+Extension represents a single XML element that was in a non +default namespace in a Feed or Item/Entry. +
+ + + + + + + + + + + + + + + + +type Extensions map[string]map[string][]Extension+
+Extensions is the generic extension map for Feeds and Items. +The first map is for the element namespace prefix (e.g., itunes). +The second map is for the element name (e.g., author). +
+ + + + + + + + + + + + + + + + +type ITunesCategory struct { + Text string `json:"text,omitempty"` + Subcategory *ITunesCategory `json:"subcategory,omitempty"` +}+
+ITunesCategory is a category element for itunes feeds. +
+ + + + + + + + + + + + + + + + +type ITunesFeedExtension struct { + Author string `json:"author,omitempty"` + Block string `json:"block,omitempty"` + Categories []*ITunesCategory `json:"categories,omitempty"` + Explicit string `json:"explicit,omitempty"` + Keywords string `json:"keywords,omitempty"` + Owner *ITunesOwner `json:"owner,omitempty"` + Subtitle string `json:"subtitle,omitempty"` + Summary string `json:"summary,omitempty"` + Image string `json:"image,omitempty"` + Complete string `json:"complete,omitempty"` + NewFeedURL string `json:"newFeedUrl,omitempty"` +}+
+ITunesFeedExtension is a set of extension +fields for RSS feeds. +
+ + + + + + + + + + + + +func NewITunesFeedExtension(extensions map[string][]Extension) *ITunesFeedExtension+
+NewITunesFeedExtension creates an ITunesFeedExtension given an +extension map for the "itunes" key. +
+ + + + + + + + + +type ITunesItemExtension struct { + Author string `json:"author,omitempty"` + Block string `json:"block,omitempty"` + Duration string `json:"duration,omitempty"` + Explicit string `json:"explicit,omitempty"` + Keywords string `json:"keywords,omitempty"` + Subtitle string `json:"subtitle,omitempty"` + Summary string `json:"summary,omitempty"` + Image string `json:"image,omitempty"` + IsClosedCaptioned string `json:"isClosedCaptioned,omitempty"` + Order string `json:"order,omitempty"` +}+
+ITunesItemExtension is a set of extension +fields for RSS items. +
+ + + + + + + + + + + + +func NewITunesItemExtension(extensions map[string][]Extension) *ITunesItemExtension+
+NewITunesItemExtension creates an ITunesItemExtension given an +extension map for the "itunes" key. +
+ + + + + + + + + +type ITunesOwner struct { + Email string `json:"email,omitempty"` + Name string `json:"name,omitempty"` +}+
+ITunesOwner is the owner of a particular itunes feed. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +type DefaultAtomTranslator struct{}+
+DefaultAtomTranslator converts an atom.Feed struct +into the generic Feed struct. +
++This default implementation defines a set of +mapping rules between atom.Feed -> Feed +for each of the fields in Feed. +
+ + + + + + + + + + + + + + +func (t *DefaultAtomTranslator) Translate(feed interface{}) (*Feed, error)+
+Translate converts an Atom feed into the universal +feed type. +
+ + + + + + + + +type DefaultRSSTranslator struct{}+
+DefaultRSSTranslator converts an rss.Feed struct +into the generic Feed struct. +
++This default implementation defines a set of +mapping rules between rss.Feed -> Feed +for each of the fields in Feed. +
+ + + + + + + + + + + + + + +func (t *DefaultRSSTranslator) Translate(feed interface{}) (*Feed, error)+
+Translate converts an RSS feed into the universal +feed type. +
+ + + + + + + + +type Enclosure struct { + URL string `json:"url,omitempty"` + Length string `json:"length,omitempty"` + Type string `json:"type,omitempty"` +}+
+Enclosure is a file associated with a given Item. +
+ + + + + + + + + + + + + + + + +type Feed struct { + Title string `json:"title,omitempty"` + Description string `json:"description,omitempty"` + Link string `json:"link,omitempty"` + FeedLink string `json:"feedLink,omitempty"` + Updated string `json:"updated,omitempty"` + UpdatedParsed *time.Time `json:"updatedParsed,omitempty"` + Published string `json:"published,omitempty"` + PublishedParsed *time.Time `json:"publishedParsed,omitempty"` + Author *Person `json:"author,omitempty"` + Language string `json:"language,omitempty"` + Image *Image `json:"image,omitempty"` + Copyright string `json:"copyright,omitempty"` + Generator string `json:"generator,omitempty"` + Categories []string `json:"categories,omitempty"` + Extensions ext.Extensions `json:"extensions,omitempty"` + Custom map[string]string `json:"custom,omitempty"` + Items []*Item `json:"items"` + FeedType string `json:"feedType"` + FeedVersion string `json:"feedVersion"` +}+
+Feed is the universal Feed type that atom.Feed +and rss.Feed gets translated to. It represents +a web feed. +
+ + + + + + + + + + + + + + +func (f Feed) String() string+ + + + + + + + +
type FeedType int+
+FeedType represents one of the possible feed +types that we can detect. +
+ + + +const ( + // FeedTypeUnknown represents a feed that could not have its + // type determiend. + FeedTypeUnknown FeedType = iota + // FeedTypeAtom repesents an Atom feed + FeedTypeAtom + // FeedTypeRSS represents an RSS feed + FeedTypeRSS +)+ + + + + + + + + + + +
func DetectFeedType(feed io.Reader) FeedType+
+DetectFeedType attempts to determine the type of feed +by looking for specific xml elements unique to the +various feed types. +
+ +▹ Example
+type HTTPError struct { + StatusCode int + Status string +}+
+HTTPError represents an HTTP error returned by a server. +
+ + + + + + + + + + + + + + +func (err HTTPError) Error() string+ + + + + + + + +
type Image struct { + URL string `json:"url,omitempty"` + Title string `json:"title,omitempty"` +}+
+Image is an image that is the artwork for a given +feed or item. +
+ + + + + + + + + + + + + + + + +type Item struct { + Title string `json:"title,omitempty"` + Description string `json:"description,omitempty"` + Content string `json:"content,omitempty"` + Link string `json:"link,omitempty"` + Updated string `json:"updated,omitempty"` + UpdatedParsed *time.Time `json:"updatedParsed,omitempty"` + Published string `json:"published,omitempty"` + PublishedParsed *time.Time `json:"publishedParsed,omitempty"` + Author *Person `json:"author,omitempty"` + GUID string `json:"guid,omitempty"` + Image *Image `json:"image,omitempty"` + Categories []string `json:"categories,omitempty"` + Enclosures []*Enclosure `json:"enclosures,omitempty"` + Extensions ext.Extensions `json:"extensions,omitempty"` + Custom map[string]string `json:"custom,omitempty"` +}+
+Item is the universal Item type that atom.Entry +and rss.Item gets translated to. It represents +a single entry in a given feed. +
+ + + + + + + + + + + + + + + + +type Parser struct { + AtomTranslator Translator + RSSTranslator Translator + Client *http.Client + // contains filtered or unexported fields +}+
+Parser is a universal feed parser that detects +a given feed type, parsers it, and translates it +to the universal feed type. +
+ + + + + + + + + + + + +func NewParser() *Parser+
+NewParser creates a universal feed parser. +
+ + + + + + + +func (f *Parser) Parse(feed io.Reader) (*Feed, error)+
+Parse parses a RSS or Atom feed into +the universal gofeed.Feed. It takes an +io.Reader which should return the xml content. +
+ + +▹ Example
+func (f *Parser) ParseString(feed string) (*Feed, error)+
+ParseString parses a feed XML string and into the +universal feed type. +
+ + +▹ Example
+func (f *Parser) ParseURL(feedURL string) (feed *Feed, err error)+
+ParseURL fetches the contents of a given url and +attempts to parse the response into the universal feed type. +
+ + +▹ Example
+type Person struct { + Name string `json:"name,omitempty"` + Email string `json:"email,omitempty"` +}+
+Person is an individual specified in a feed +(e.g. an author) +
+ + + + + + + + + + + + + + + + +type Translator interface { + Translate(feed interface{}) (*Feed, error) +}+
+Translator converts a particular feed (atom.Feed or rss.Feed) +into the generic Feed struct +
+ + + + + + + + + + + + + + + + + + + + + + + + +type Category struct { + Domain string `json:"domain,omitempty"` + Value string `json:"value,omitempty"` +}+
+Category is category metadata for Feeds and Entries +
+ + + + + + + + + + + + + + + + +type Cloud struct { + Domain string `json:"domain,omitempty"` + Port string `json:"port,omitempty"` + Path string `json:"path,omitempty"` + RegisterProcedure string `json:"registerProcedure,omitempty"` + Protocol string `json:"protocol,omitempty"` +}+
+Cloud allows processes to register with a +cloud to be notified of updates to the channel, +implementing a lightweight publish-subscribe protocol +for RSS feeds +
+ + + + + + + + + + + + + + + + +type Enclosure struct { + URL string `json:"url,omitempty"` + Length string `json:"length,omitempty"` + Type string `json:"type,omitempty"` +}+
+Enclosure is a media object that is attached to +the item +
+ + + + + + + + + + + + + + + + +type Feed struct { + Title string `json:"title,omitempty"` + Link string `json:"link,omitempty"` + Description string `json:"description,omitempty"` + Language string `json:"language,omitempty"` + Copyright string `json:"copyright,omitempty"` + ManagingEditor string `json:"managingEditor,omitempty"` + WebMaster string `json:"webMaster,omitempty"` + PubDate string `json:"pubDate,omitempty"` + PubDateParsed *time.Time `json:"pubDateParsed,omitempty"` + LastBuildDate string `json:"lastBuildDate,omitempty"` + LastBuildDateParsed *time.Time `json:"lastBuildDateParsed,omitempty"` + Categories []*Category `json:"categories,omitempty"` + Generator string `json:"generator,omitempty"` + Docs string `json:"docs,omitempty"` + TTL string `json:"ttl,omitempty"` + Image *Image `json:"image,omitempty"` + Rating string `json:"rating,omitempty"` + SkipHours []string `json:"skipHours,omitempty"` + SkipDays []string `json:"skipDays,omitempty"` + Cloud *Cloud `json:"cloud,omitempty"` + TextInput *TextInput `json:"textInput,omitempty"` + DublinCoreExt *ext.DublinCoreExtension `json:"dcExt,omitempty"` + ITunesExt *ext.ITunesFeedExtension `json:"itunesExt,omitempty"` + Extensions ext.Extensions `json:"extensions,omitempty"` + Items []*Item `json:"items"` + Version string `json:"version"` +}+
+Feed is an RSS Feed +
+ + + + + + + + + + + + + + +func (f Feed) String() string+ + + + + + + + +
type GUID struct { + Value string `json:"value,omitempty"` + IsPermalink string `json:"isPermalink,omitempty"` +}+
+GUID is a unique identifier for an item +
+ + + + + + + + + + + + + + + + +type Image struct { + URL string `json:"url,omitempty"` + Link string `json:"link,omitempty"` + Title string `json:"title,omitempty"` + Width string `json:"width,omitempty"` + Height string `json:"height,omitempty"` + Description string `json:"description,omitempty"` +}+
+Image is an image that represents the feed +
+ + + + + + + + + + + + + + + + +type Item struct { + Title string `json:"title,omitempty"` + Link string `json:"link,omitempty"` + Description string `json:"description,omitempty"` + Author string `json:"author,omitempty"` + Categories []*Category `json:"categories,omitempty"` + Comments string `json:"comments,omitempty"` + Enclosure *Enclosure `json:"enclosure,omitempty"` + GUID *GUID `json:"guid,omitempty"` + PubDate string `json:"pubDate,omitempty"` + PubDateParsed *time.Time `json:"pubDateParsed,omitempty"` + Source *Source `json:"source,omitempty"` + DublinCoreExt *ext.DublinCoreExtension `json:"dcExt,omitempty"` + ITunesExt *ext.ITunesItemExtension `json:"itunesExt,omitempty"` + Extensions ext.Extensions `json:"extensions,omitempty"` +}+
+Item is an RSS Item +
+ + + + + + + + + + + + + + + + +type Parser struct{}+
+Parser is a RSS Parser +
+ + + + + + + + + + + + + + +func (rp *Parser) Parse(feed io.Reader) (*Feed, error)+
+Parse parses an xml feed into an rss.Feed +
+ + + + + + + + +type Source struct { + Title string `json:"title,omitempty"` + URL string `json:"url,omitempty"` +}+
+Source contains feed information for another +feed if a given item came from that feed +
+ + + + + + + + + + + + + + + + +type TextInput struct { + Title string `json:"title,omitempty"` + Description string `json:"description,omitempty"` + Name string `json:"name,omitempty"` + Link string `json:"link,omitempty"` +}+
+TextInput specifies a text input box that +can be displayed with the channel +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +type CharsetReader func(charset string, input io.Reader) (io.Reader, error)+ + + + + + + + + + + + + + + + +
type XMLEventType int+ + + +
const ( + StartDocument XMLEventType = iota + EndDocument + StartTag + EndTag + Text + Comment + ProcessingInstruction + Directive + IgnorableWhitespace // TODO: ? + +)+ + + + + + + + + + + + + + + +
type XMLPullParser struct { + // Document State + Spaces map[string]string + + // Token State + Depth int + Event XMLEventType + Attrs []xml.Attr + Name string + Space string + Text string + // contains filtered or unexported fields +}+ + + + + + + + + + + + +
func NewXMLPullParser(r io.Reader, strict bool, cr CharsetReader) *XMLPullParser+ + + + + + + +
func (p *XMLPullParser) Attribute(name string) string+ + + + + + +
func (p *XMLPullParser) DecodeElement(v interface{}) error+ + + + + + +
func (p *XMLPullParser) EventName(e XMLEventType) (name string)+ + + + + + +
func (p *XMLPullParser) EventType(t xml.Token) (event XMLEventType)+ + + + + + +
func (p *XMLPullParser) Expect(event XMLEventType, name string) (err error)+ + + + + + +
func (p *XMLPullParser) ExpectAll(event XMLEventType, space string, name string) (err error)+ + + + + + +
func (p *XMLPullParser) IsWhitespace() bool+ + + + + + +
func (p *XMLPullParser) Next() (event XMLEventType, err error)+ + + + + + +
func (p *XMLPullParser) NextTag() (event XMLEventType, err error)+ + + + + + +
func (p *XMLPullParser) NextText() (string, error)+ + + + + + +
func (p *XMLPullParser) NextToken() (event XMLEventType, err error)+ + + + + + +
func (p *XMLPullParser) Skip() error+ + + + + + + + + + + + + + + + + + +
Name | +Synopsis | +
---|---|
.. | +|
+ content-addressable-store + | ++ + | +
+ super-simple-store + | ++ + | +
type BTreeIndex struct { + sync.RWMutex + LessFunction + *btree.BTree +}+
+BTreeIndex is an implementation of the Index interface using google/btree. +
+ + + + + + + + + + + + + + +func (i *BTreeIndex) Delete(key string)+
+Delete removes the given key (only) from the BTree tree. +
+ + + + + + +func (i *BTreeIndex) Initialize(less LessFunction, keys <-chan string)+
+Initialize populates the BTree tree with data from the keys channel, +according to the passed less function. It's destructive to the BTreeIndex. +
+ + + + + + +func (i *BTreeIndex) Insert(key string)+
+Insert inserts the given key (only) into the BTree tree. +
+ + + + + + +func (i *BTreeIndex) Keys(from string, n int) []string+
+Keys yields a maximum of n keys in order. If the passed 'from' key is empty, +Keys will return the first n keys. If the passed 'from' key is non-empty, the +first key in the returned slice will be the key that immediately follows the +passed key, in key order. +
+ + + + + + + + +type Compression interface { + Writer(dst io.Writer) (io.WriteCloser, error) + Reader(src io.Reader) (io.ReadCloser, error) +}+
+Compression is an interface that Diskv uses to implement compression of +data. Writer takes a destination io.Writer and returns a WriteCloser that +compresses all data written through it. Reader takes a source io.Reader and +returns a ReadCloser that decompresses all data read through it. You may +define these methods on your own type, or use one of the NewCompression +helpers. +
+ + + + + + + + + + + + +func NewGzipCompression() Compression+
+NewGzipCompression returns a Gzip-based Compression. +
+ + + + + +func NewGzipCompressionLevel(level int) Compression+
+NewGzipCompressionLevel returns a Gzip-based Compression with the given level. +
+ + + + + +func NewZlibCompression() Compression+
+NewZlibCompression returns a Zlib-based Compression. +
+ + + + + +func NewZlibCompressionLevel(level int) Compression+
+NewZlibCompressionLevel returns a Zlib-based Compression with the given level. +
+ + + + + +func NewZlibCompressionLevelDict(level int, dict []byte) Compression+
+NewZlibCompressionLevelDict returns a Zlib-based Compression with the given +level, based on the given dictionary. +
+ + + + + + + + + +type Diskv struct { + Options + // contains filtered or unexported fields +}+
+Diskv implements the Diskv interface. You shouldn't construct Diskv +structures directly; instead, use the New constructor. +
+ + + + + + + + + + + + +func New(o Options) *Diskv+
+New returns an initialized Diskv structure, ready to use. +If the path identified by baseDir already contains data, +it will be accessible, but not yet cached. +
+ + + + + + + +func (d *Diskv) Erase(key string) error+
+Erase synchronously erases the given key from the disk and the cache. +
+ + + + + + +func (d *Diskv) EraseAll() error+
+EraseAll will delete all of the data from the store, both in the cache and on +the disk. Note that EraseAll doesn't distinguish diskv-related data from non- +diskv-related data. Care should be taken to always specify a diskv base +directory that is exclusively for diskv data. +
+ + + + + + +func (d *Diskv) Has(key string) bool+
+Has returns true if the given key exists. +
+ + + + + + +func (d *Diskv) Import(srcFilename, dstKey string, move bool) (err error)+
+Import imports the source file into diskv under the destination key. If the +destination key already exists, it's overwritten. If move is true, the +source file is removed after a successful import. +
+ + + + + + +func (d *Diskv) Keys(cancel <-chan struct{}) <-chan string+
+Keys returns a channel that will yield every key accessible by the store, +in undefined order. If a cancel channel is provided, closing it will +terminate and close the keys channel. +
+ + + + + + +func (d *Diskv) KeysPrefix(prefix string, cancel <-chan struct{}) <-chan string+
+KeysPrefix returns a channel that will yield every key accessible by the +store with the given prefix, in undefined order. If a cancel channel is +provided, closing it will terminate and close the keys channel. If the +provided prefix is the empty string, all keys will be yielded. +
+ + + + + + +func (d *Diskv) Read(key string) ([]byte, error)+
+Read reads the key and returns the value. +If the key is available in the cache, Read won't touch the disk. +If the key is not in the cache, Read will have the side-effect of +lazily caching the value. +
+ + + + + + +func (d *Diskv) ReadStream(key string, direct bool) (io.ReadCloser, error)+
+ReadStream reads the key and returns the value (data) as an io.ReadCloser. +If the value is cached from a previous read, and direct is false, +ReadStream will use the cached value. Otherwise, it will return a handle to +the file on disk, and cache the data on read. +
++If direct is true, ReadStream will lazily delete any cached value for the +key, and return a direct handle to the file on disk. +
++If compression is enabled, ReadStream taps into the io.Reader stream prior +to decompression, and caches the compressed data. +
+ + + + + + +func (d *Diskv) Write(key string, val []byte) error+
+Write synchronously writes the key-value pair to disk, making it immediately +available for reads. Write relies on the filesystem to perform an eventual +sync to physical media. If you need stronger guarantees, see WriteStream. +
+ + + + + + +func (d *Diskv) WriteStream(key string, r io.Reader, sync bool) error+
+WriteStream writes the data represented by the io.Reader to the disk, under +the provided key. If sync is true, WriteStream performs an explicit sync on +the file as soon as it's written. +
++bytes.Buffer provides io.Reader semantics for basic data types. +
+ + + + + + + + +type Index interface { + Initialize(less LessFunction, keys <-chan string) + Insert(key string) + Delete(key string) + Keys(from string, n int) []string +}+
+Index is a generic interface for things that can +provide an ordered list of keys. +
+ + + + + + + + + + + + + + + + +type LessFunction func(string, string) bool+
+LessFunction is used to initialize an Index of keys in a specific order. +
+ + + + + + + + + + + + + + + + +type Options struct { + BasePath string + Transform TransformFunction + CacheSizeMax uint64 // bytes + PathPerm os.FileMode + FilePerm os.FileMode + + Index Index + IndexLess LessFunction + + Compression Compression +}+
+Options define a set of properties that dictate Diskv behavior. +All values are optional. +
+ + + + + + + + + + + + + + + + +type TransformFunction func(s string) []string+
+TransformFunction transforms a key into a slice of strings, with each +element in the slice representing a directory in the file path where the +key's entry will eventually be stored. +
++For example, if TransformFunc transforms "abcdef" to ["ab", "cde", "f"], +the final location of the data file will be <basedir>/ab/cde/f/abcdef +
+ + + + + + + + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ examples + | ++ + | +
+ content-addressable-store + | ++ + | +
+ super-simple-store + | ++ + | +
Name | +Synopsis | +
---|---|
.. | +|
+ diskv + | ++ + | +
+ examples + | ++ + | +
+ content-addressable-store + | ++ + | +
+ super-simple-store + | ++ + | +
Name | +Synopsis | +
---|---|
.. | +|
+ prometheus + | ++ Package prometheus provides bindings to the Prometheus HTTP API: http://prometheus.io/docs/querying/api/ + | +
type CancelableTransport interface { + http.RoundTripper + CancelRequest(req *http.Request) +}+
+CancelableTransport is like net.Transport but provides +per-request cancelation functionality. +
+ + + + + +var DefaultTransport CancelableTransport = &http.Transport{ + Proxy: http.ProxyFromEnvironment, + Dial: (&net.Dialer{ + Timeout: 30 * time.Second, + KeepAlive: 30 * time.Second, + }).Dial, + TLSHandshakeTimeout: 10 * time.Second, +}+
+DefaultTransport is used if no Transport is set in Config. +
+ + + + + + + + + + + + + +type Client interface {
+ // contains filtered or unexported methods
+}
+ +Client is the interface for an API client. +
+ + + + + + + + + + + + +func New(cfg Config) (Client, error)+
+New returns a new Client. +
++It is safe to use the returned Client from multiple goroutines. +
+ + + + + + + + + +type Config struct { + // The address of the Prometheus to connect to. + Address string + + // Transport is used by the Client to drive HTTP requests. If not + // provided, DefaultTransport will be used. + Transport CancelableTransport +}+
+Config defines configuration parameters for a new client. +
+ + + + + + + + + + + + + + + + +type Error struct { + Type ErrorType + Msg string +}+
+Error is an error returned by the API. +
+ + + + + + + + + + + + + + +func (e *Error) Error() string+ + + + + + + + +
type ErrorType string+
+ErrorType models the different API error types. +
+ + + +const ( + ErrBadData ErrorType = "bad_data" + ErrTimeout = "timeout" + ErrCanceled = "canceled" + ErrExec = "execution" + ErrBadResponse = "bad_response" +)+
+Possible values for ErrorType. +
+ + + + + + + + + + + + + + + +type QueryAPI interface { + // Query performs a query for the given time. + Query(ctx context.Context, query string, ts time.Time) (model.Value, error) + // Query performs a query for the given range. + QueryRange(ctx context.Context, query string, r Range) (model.Value, error) +}+
+QueryAPI provides bindings the Prometheus's query API. +
+ + + + + + + + + + + + +func NewQueryAPI(c Client) QueryAPI+
+NewQueryAPI returns a new QueryAPI for the client. +
++It is safe to use the returned QueryAPI from multiple goroutines. +
+ + + + + + + + + +type Range struct { + // The boundaries of the time range. + Start, End time.Time + // The maximum time between two slices within the boundaries. + Step time.Duration +}+
+Range represents a sliced time range. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ random + | ++ A simple example exposing fictional RPC latencies with different types of random distributions (uniform, normal, and exponential) as Prometheus metrics. + | +
+ simple + | ++ A minimal example of how to include Prometheus instrumentation. + | +
+A simple example exposing fictional RPC latencies with different types of +random distributions (uniform, normal, and exponential) as Prometheus +metrics. +
+ + + + + + + + + + + + + ++A minimal example of how to include Prometheus instrumentation. +
+ + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ api + | ++ + | +
+ prometheus + | ++ Package prometheus provides bindings to the Prometheus HTTP API: http://prometheus.io/docs/querying/api/ + | +
+ examples + | ++ + | +
+ random + | ++ A simple example exposing fictional RPC latencies with different types of random distributions (uniform, normal, and exponential) as Prometheus metrics. + | +
+ simple + | ++ A minimal example of how to include Prometheus instrumentation. + | +
+ prometheus + | ++ Package prometheus provides metrics primitives to instrument code for monitoring. + | +
+ promhttp + | ++ Package promhttp contains functions to create http.Handler instances to expose Prometheus metrics via HTTP. + | +
+ push + | ++ Package push provides functions to push metrics to a Pushgateway. + | +
const ( + // DefMaxAge is the default duration for which observations stay + // relevant. + DefMaxAge time.Duration = 10 * time.Minute + // DefAgeBuckets is the default number of buckets used to calculate the + // age of observations. + DefAgeBuckets = 5 + // DefBufCap is the standard buffer size for collecting Summary observations. + DefBufCap = 500 +)+
+Default values for SummaryOpts. +
+ + + + +var ( + DefaultRegisterer Registerer = defaultRegistry + DefaultGatherer Gatherer = defaultRegistry +)+
+DefaultRegisterer and DefaultGatherer are the implementations of the +Registerer and Gatherer interface a number of convenience functions in this +package act on. Initially, both variables point to the same Registry, which +has a process collector (see NewProcessCollector) and a Go collector (see +NewGoCollector) already registered. This approach to keep default instances +as global state mirrors the approach of other packages in the Go standard +library. Note that there are caveats. Change the variables with caution and +only if you understand the consequences. Users who want to avoid global state +altogether should not use the convenience function and act on custom +instances instead. +
+ + +var ( + DefBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10} +)+
+DefBuckets are the default Histogram buckets. The default buckets are +tailored to broadly measure the response time (in seconds) of a network +service. Most likely, however, you will be required to define buckets +customized to your use case. +
+ + +var ( + DefObjectives = map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001} +)+
+DefObjectives are the default Summary quantile values. +
+ + + + + + +func BuildFQName(namespace, subsystem, name string) string+
+BuildFQName joins the given three name components by "_". Empty name +components are ignored. If the name parameter itself is empty, an empty +string is returned, no matter what. Metric implementations included in this +library use this function internally to generate the fully-qualified metric +name from the name component in their Opts. Users of the library will only +need this function if they implement their own Metric or instantiate a Desc +(with NewDesc) directly. +
+ + + + + + + +func ExponentialBuckets(start, factor float64, count int) []float64+
+ExponentialBuckets creates 'count' buckets, where the lowest bucket has an +upper bound of 'start' and each following bucket's upper bound is 'factor' +times the previous bucket's upper bound. The final +Inf bucket is not counted +and not included in the returned slice. The returned slice is meant to be +used for the Buckets field of HistogramOpts. +
++The function panics if 'count' is 0 or negative, if 'start' is 0 or negative, +or if 'factor' is less than or equal 1. +
+ + + + + + + +func Handler() http.Handler+
+Handler returns an HTTP handler for the DefaultGatherer. It is +already instrumented with InstrumentHandler (using "prometheus" as handler +name). +
++Deprecated: Please note the issues described in the doc comment of +InstrumentHandler. You might want to consider using promhttp.Handler instead +(which is non instrumented). +
+ + + + + + + +func InstrumentHandler(handlerName string, handler http.Handler) http.HandlerFunc+
+InstrumentHandler wraps the given HTTP handler for instrumentation. It +registers four metric collectors (if not already done) and reports HTTP +metrics to the (newly or already) registered collectors: http_requests_total +(CounterVec), http_request_duration_microseconds (Summary), +http_request_size_bytes (Summary), http_response_size_bytes (Summary). Each +has a constant label named "handler" with the provided handlerName as +value. http_requests_total is a metric vector partitioned by HTTP method +(label name "method") and HTTP status code (label name "code"). +
++Deprecated: InstrumentHandler has several issues: +
++- It uses Summaries rather than Histograms. Summaries are not useful if +aggregation across multiple instances is required. +
++- It uses microseconds as unit, which is deprecated and should be replaced by +seconds. +
++- The size of the request is calculated in a separate goroutine. Since this +calculator requires access to the request header, it creates a race with +any writes to the header performed during request handling. +httputil.ReverseProxy is a prominent example for a handler +performing such writes. +
++Upcoming versions of this package will provide ways of instrumenting HTTP +handlers that are more flexible and have fewer issues. Please prefer direct +instrumentation in the meantime. +
+ +▹ Example
+func InstrumentHandlerFunc(handlerName string, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc+
+InstrumentHandlerFunc wraps the given function for instrumentation. It +otherwise works in the same way as InstrumentHandler (and shares the same +issues). +
++Deprecated: InstrumentHandlerFunc is deprecated for the same reasons as +InstrumentHandler is. +
+ + + + + + + +func InstrumentHandlerFuncWithOpts(opts SummaryOpts, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc+
+InstrumentHandlerFuncWithOpts works like InstrumentHandlerFunc (and shares +the same issues) but provides more flexibility (at the cost of a more complex +call syntax). See InstrumentHandlerWithOpts for details how the provided +SummaryOpts are used. +
++Deprecated: InstrumentHandlerFuncWithOpts is deprecated for the same reasons +as InstrumentHandler is. +
+ + + + + + + +func InstrumentHandlerWithOpts(opts SummaryOpts, handler http.Handler) http.HandlerFunc+
+InstrumentHandlerWithOpts works like InstrumentHandler (and shares the same +issues) but provides more flexibility (at the cost of a more complex call +syntax). As InstrumentHandler, this function registers four metric +collectors, but it uses the provided SummaryOpts to create them. However, the +fields "Name" and "Help" in the SummaryOpts are ignored. "Name" is replaced +by "requests_total", "request_duration_microseconds", "request_size_bytes", +and "response_size_bytes", respectively. "Help" is replaced by an appropriate +help string. The names of the variable labels of the http_requests_total +CounterVec are "method" (get, post, etc.), and "code" (HTTP status code). +
++If InstrumentHandlerWithOpts is called as follows, it mimics exactly the +behavior of InstrumentHandler: +
+prometheus.InstrumentHandlerWithOpts( + prometheus.SummaryOpts{ + Subsystem: "http", + ConstLabels: prometheus.Labels{"handler": handlerName}, + }, + handler, +) ++
+Technical detail: "requests_total" is a CounterVec, not a SummaryVec, so it +cannot use SummaryOpts. Instead, a CounterOpts struct is created internally, +and all its fields are set to the equally named fields in the provided +SummaryOpts. +
++Deprecated: InstrumentHandlerWithOpts is deprecated for the same reasons as +InstrumentHandler is. +
+ + + + + + + +func LinearBuckets(start, width float64, count int) []float64+
+LinearBuckets creates 'count' buckets, each 'width' wide, where the lowest +bucket has an upper bound of 'start'. The final +Inf bucket is not counted +and not included in the returned slice. The returned slice is meant to be +used for the Buckets field of HistogramOpts. +
++The function panics if 'count' is zero or negative. +
+ + + + + + + +func MustRegister(cs ...Collector)+
+MustRegister registers the provided Collectors with the DefaultRegisterer and +panics if any error occurs. +
++MustRegister is a shortcut for DefaultRegisterer.MustRegister(cs...). See +there for more details. +
+ + + + + + + +func Register(c Collector) error+
+Register registers the provided Collector with the DefaultRegisterer. +
++Register is a shortcut for DefaultRegisterer.Register(c). See there for more +details. +
+ +▹ Example
+func SetMetricFamilyInjectionHook(hook func() []*dto.MetricFamily)+
+SetMetricFamilyInjectionHook replaces the DefaultGatherer with one that +gathers from the previous DefaultGatherers but then merges the MetricFamily +protobufs returned from the provided hook function with the MetricFamily +protobufs returned from the original DefaultGatherer. +
++Deprecated: This function manipulates the DefaultGatherer variable. Consider +the implications, i.e. don't do this concurrently with any uses of the +DefaultGatherer. In the rare cases where you need to inject MetricFamily +protobufs directly, it is recommended to use a custom Registry and combine it +with a custom Gatherer using the Gatherers type (see +there). SetMetricFamilyInjectionHook only exists for compatibility reasons +with previous versions of this package. +
+ + + + + + + +func UninstrumentedHandler() http.Handler+
+UninstrumentedHandler returns an HTTP handler for the DefaultGatherer. +
++Deprecated: Use promhttp.Handler instead. See there for further documentation. +
+ + + + + + + +func Unregister(c Collector) bool+
+Unregister removes the registration of the provided Collector from the +DefaultRegisterer. +
++Unregister is a shortcut for DefaultRegisterer.Unregister(c). See there for +more details. +
+ + + + + + + + +type AlreadyRegisteredError struct { + ExistingCollector, NewCollector Collector +}+
+AlreadyRegisteredError is returned by the Register method if the Collector to +be registered has already been registered before, or a different Collector +that collects the same metrics has been registered before. Registration fails +in that case, but you can detect from the kind of error what has +happened. The error contains fields for the existing Collector and the +(rejected) new Collector that equals the existing one. This can be used to +find out if an equal Collector has been registered before and switch over to +using the old one, as demonstrated in the example. +
+ + + + + + +▹ Example
+func (err AlreadyRegisteredError) Error() string+ + + + + + + + +
type Collector interface { + // Describe sends the super-set of all possible descriptors of metrics + // collected by this Collector to the provided channel and returns once + // the last descriptor has been sent. The sent descriptors fulfill the + // consistency and uniqueness requirements described in the Desc + // documentation. (It is valid if one and the same Collector sends + // duplicate descriptors. Those duplicates are simply ignored. However, + // two different Collectors must not send duplicate descriptors.) This + // method idempotently sends the same descriptors throughout the + // lifetime of the Collector. If a Collector encounters an error while + // executing this method, it must send an invalid descriptor (created + // with NewInvalidDesc) to signal the error to the registry. + Describe(chan<- *Desc) + // Collect is called by the Prometheus registry when collecting + // metrics. The implementation sends each collected metric via the + // provided channel and returns once the last metric has been sent. The + // descriptor of each sent metric is one of those returned by + // Describe. Returned metrics that share the same descriptor must differ + // in their variable label values. This method may be called + // concurrently and must therefore be implemented in a concurrency safe + // way. Blocking occurs at the expense of total performance of rendering + // all registered metrics. Ideally, Collector implementations support + // concurrent readers. + Collect(chan<- Metric) +}+
+Collector is the interface implemented by anything that can be used by +Prometheus to collect metrics. A Collector has to be registered for +collection. See Registerer.Register. +
++The stock metrics provided by this package (Gauge, Counter, Summary, +Histogram, Untyped) are also Collectors (which only ever collect one metric, +namely itself). An implementer of Collector may, however, collect multiple +metrics in a coordinated fashion and/or create metrics on the fly. Examples +for collectors already implemented in this library are the metric vectors +(i.e. collection of multiple instances of the same Metric but with different +label values) like GaugeVec or SummaryVec, and the ExpvarCollector. +
+ + + + + + +▹ Example
+func MustRegisterOrGet(c Collector) Collector+
+MustRegisterOrGet behaves like RegisterOrGet but panics instead of returning +an error. +
++Deprecated: This is deprecated for the same reason RegisterOrGet is. See +there for details. +
+ + + + + +func NewExpvarCollector(exports map[string]*Desc) Collector+
+NewExpvarCollector returns a newly allocated expvar Collector that still has +to be registered with a Prometheus registry. +
++An expvar Collector collects metrics from the expvar interface. It provides a +quick way to expose numeric values that are already exported via expvar as +Prometheus metrics. Note that the data models of expvar and Prometheus are +fundamentally different, and that the expvar Collector is inherently slower +than native Prometheus metrics. Thus, the expvar Collector is probably great +for experiments and prototying, but you should seriously consider a more +direct implementation of Prometheus metrics for monitoring production +systems. +
++The exports map has the following meaning: +
++The keys in the map correspond to expvar keys, i.e. for every expvar key you +want to export as Prometheus metric, you need an entry in the exports +map. The descriptor mapped to each key describes how to export the expvar +value. It defines the name and the help string of the Prometheus metric +proxying the expvar value. The type will always be Untyped. +
++For descriptors without variable labels, the expvar value must be a number or +a bool. The number is then directly exported as the Prometheus sample +value. (For a bool, 'false' translates to 0 and 'true' to 1). Expvar values +that are not numbers or bools are silently ignored. +
++If the descriptor has one variable label, the expvar value must be an expvar +map. The keys in the expvar map become the various values of the one +Prometheus label. The values in the expvar map must be numbers or bools again +as above. +
++For descriptors with more than one variable label, the expvar must be a +nested expvar map, i.e. where the values of the topmost map are maps again +etc. until a depth is reached that corresponds to the number of labels. The +leaves of that structure must be numbers or bools as above to serve as the +sample values. +
++Anything that does not fit into the scheme above is silently ignored. +
+ +▹ Example
+func NewGoCollector() Collector+
+NewGoCollector returns a collector which exports metrics about the current +go process. +
+ + + + + +func NewProcessCollector(pid int, namespace string) Collector+
+NewProcessCollector returns a collector which exports the current state of +process metrics including cpu, memory and file descriptor usage as well as +the process start time for the given process id under the given namespace. +
+ + + + + +func NewProcessCollectorPIDFn( + pidFn func() (int, error), + namespace string, +) Collector+
+NewProcessCollectorPIDFn returns a collector which exports the current state +of process metrics including cpu, memory and file descriptor usage as well +as the process start time under the given namespace. The given pidFn is +called on each collect and is used to determine the process to export +metrics for. +
+ + + + + +func RegisterOrGet(c Collector) (Collector, error)+
+RegisterOrGet registers the provided Collector with the DefaultRegisterer and +returns the Collector, unless an equal Collector was registered before, in +which case that Collector is returned. +
++Deprecated: RegisterOrGet is merely a convenience function for the +implementation as described in the documentation for +AlreadyRegisteredError. As the use case is relatively rare, this function +will be removed in a future version of this package to clean up the +namespace. +
+ + + + + + + + + +type Counter interface { + Metric + Collector + + // Set is used to set the Counter to an arbitrary value. It is only used + // if you have to transfer a value from an external counter into this + // Prometheus metric. Do not use it for regular handling of a + // Prometheus counter (as it can be used to break the contract of + // monotonically increasing values). + // + // Deprecated: Use NewConstMetric to create a counter for an external + // value. A Counter should never be set. + Set(float64) + // Inc increments the counter by 1. + Inc() + // Add adds the given value to the counter. It panics if the value is < + // 0. + Add(float64) +}+
+Counter is a Metric that represents a single numerical value that only ever +goes up. That implies that it cannot be used to count items whose number can +also go down, e.g. the number of currently running goroutines. Those +"counters" are represented by Gauges. +
++A Counter is typically used to count requests served, tasks completed, errors +occurred, etc. +
++To create Counter instances, use NewCounter. +
+ + + + + + +▹ Example
+func NewCounter(opts CounterOpts) Counter+
+NewCounter creates a new Counter based on the provided CounterOpts. +
+ + + + + + + + + +type CounterFunc interface { + Metric + Collector +}+
+CounterFunc is a Counter whose value is determined at collect time by calling a +provided function. +
++To create CounterFunc instances, use NewCounterFunc. +
+ + + + + + + + + + + + +func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc+
+NewCounterFunc creates a new CounterFunc based on the provided +CounterOpts. The value reported is determined by calling the given function +from within the Write method. Take into account that metric collection may +happen concurrently. If that results in concurrent calls to Write, like in +the case where a CounterFunc is directly registered with Prometheus, the +provided function must be concurrency-safe. The function should also honor +the contract for a Counter (values only go up, not down), but compliance will +not be checked. +
+ + + + + + + + + +type CounterOpts Opts+
+CounterOpts is an alias for Opts. See there for doc comments. +
+ + + + + + + + + + + + + + + + +type CounterVec struct { + *MetricVec +}+
+CounterVec is a Collector that bundles a set of Counters that all share the +same Desc, but have different values for their variable labels. This is used +if you want to count the same thing partitioned by various dimensions +(e.g. number of HTTP requests, partitioned by response code and +method). Create instances with NewCounterVec. +
++CounterVec embeds MetricVec. See there for a full list of methods with +detailed documentation. +
+ + + + + + +▹ Example
+func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec+
+NewCounterVec creates a new CounterVec based on the provided CounterOpts and +partitioned by the given label names. At least one label name must be +provided. +
+ + + + + + + +func (m *CounterVec) GetMetricWith(labels Labels) (Counter, error)+
+GetMetricWith replaces the method of the same name in MetricVec. The +difference is that this method returns a Counter and not a Metric so that no +type conversion is required. +
+ + + + + + +func (m *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error)+
+GetMetricWithLabelValues replaces the method of the same name in +MetricVec. The difference is that this method returns a Counter and not a +Metric so that no type conversion is required. +
+ + + + + + +func (m *CounterVec) With(labels Labels) Counter+
+With works as GetMetricWith, but panics where GetMetricWithLabels would have +returned an error. By not returning an error, With allows shortcuts like +
+myVec.With(Labels{"code": "404", "method": "GET"}).Add(42) ++ + + + + + +
func (m *CounterVec) WithLabelValues(lvs ...string) Counter+
+WithLabelValues works as GetMetricWithLabelValues, but panics where +GetMetricWithLabelValues would have returned an error. By not returning an +error, WithLabelValues allows shortcuts like +
+myVec.WithLabelValues("404", "GET").Add(42) ++ + + + + + + + +
type Desc struct {
+ // contains filtered or unexported fields
+}
+ +Desc is the descriptor used by every Prometheus Metric. It is essentially +the immutable meta-data of a Metric. The normal Metric implementations +included in this package manage their Desc under the hood. Users only have to +deal with Desc if they use advanced features like the ExpvarCollector or +custom Collectors and Metrics. +
++Descriptors registered with the same registry have to fulfill certain +consistency and uniqueness criteria if they share the same fully-qualified +name: They must have the same help string and the same label names (aka label +dimensions) in each, constLabels and variableLabels, but they must differ in +the values of the constLabels. +
++Descriptors that share the same fully-qualified names and the same label +values of their constLabels are considered equal. +
++Use NewDesc to create new Desc instances. +
+ + + + + + + + + + + + +func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *Desc+
+NewDesc allocates and initializes a new Desc. Errors are recorded in the Desc +and will be reported on registration time. variableLabels and constLabels can +be nil if no such labels should be set. fqName and help must not be empty. +
++variableLabels only contain the label names. Their label values are variable +and therefore not part of the Desc. (They are managed within the Metric.) +
++For constLabels, the label values are constant. Therefore, they are fully +specified in the Desc. See the Opts documentation for the implications of +constant labels. +
+ + + + + +func NewInvalidDesc(err error) *Desc+
+NewInvalidDesc returns an invalid descriptor, i.e. a descriptor with the +provided error set. If a collector returning such a descriptor is registered, +registration will fail with the provided error. NewInvalidDesc can be used by +a Collector to signal inability to describe itself. +
+ + + + + + + +func (d *Desc) String() string+ + + + + + + + +
type Gatherer interface { + // Gather calls the Collect method of the registered Collectors and then + // gathers the collected metrics into a lexicographically sorted slice + // of MetricFamily protobufs. Even if an error occurs, Gather attempts + // to gather as many metrics as possible. Hence, if a non-nil error is + // returned, the returned MetricFamily slice could be nil (in case of a + // fatal error that prevented any meaningful metric collection) or + // contain a number of MetricFamily protobufs, some of which might be + // incomplete, and some might be missing altogether. The returned error + // (which might be a MultiError) explains the details. In scenarios + // where complete collection is critical, the returned MetricFamily + // protobufs should be disregarded if the returned error is non-nil. + Gather() ([]*dto.MetricFamily, error) +}+
+Gatherer is the interface for the part of a registry in charge of gathering +the collected metrics into a number of MetricFamilies. The Gatherer interface +comes with the same general implication as described for the Registerer +interface. +
+ + + + + + + + + + + + + + + + +type GathererFunc func() ([]*dto.MetricFamily, error)+
+GathererFunc turns a function into a Gatherer. +
+ + + + + + + + + + + + + + +func (gf GathererFunc) Gather() ([]*dto.MetricFamily, error)+
+Gather implements Gatherer. +
+ + + + + + + + +type Gatherers []Gatherer+
+Gatherers is a slice of Gatherer instances that implements the Gatherer +interface itself. Its Gather method calls Gather on all Gatherers in the +slice in order and returns the merged results. Errors returned from the +Gather calles are all returned in a flattened MultiError. Duplicate and +inconsistent Metrics are skipped (first occurrence in slice order wins) and +reported in the returned error. +
++Gatherers can be used to merge the Gather results from multiple +Registries. It also provides a way to directly inject existing MetricFamily +protobufs into the gathering by creating a custom Gatherer with a Gather +method that simply returns the existing MetricFamily protobufs. Note that no +registration is involved (in contrast to Collector registration), so +obviously registration-time checks cannot happen. Any inconsistencies between +the gathered MetricFamilies are reported as errors by the Gather method, and +inconsistent Metrics are dropped. Invalid parts of the MetricFamilies +(e.g. syntactically invalid metric or label names) will go undetected. +
+ + + + + + +▹ Example
+func (gs Gatherers) Gather() ([]*dto.MetricFamily, error)+
+Gather implements Gatherer. +
+ + + + + + + + +type Gauge interface { + Metric + Collector + + // Set sets the Gauge to an arbitrary value. + Set(float64) + // Inc increments the Gauge by 1. + Inc() + // Dec decrements the Gauge by 1. + Dec() + // Add adds the given value to the Gauge. (The value can be + // negative, resulting in a decrease of the Gauge.) + Add(float64) + // Sub subtracts the given value from the Gauge. (The value can be + // negative, resulting in an increase of the Gauge.) + Sub(float64) +}+
+Gauge is a Metric that represents a single numerical value that can +arbitrarily go up and down. +
++A Gauge is typically used for measured values like temperatures or current +memory usage, but also "counts" that can go up and down, like the number of +running goroutines. +
++To create Gauge instances, use NewGauge. +
+ + + + + + +▹ Example
+func NewGauge(opts GaugeOpts) Gauge+
+NewGauge creates a new Gauge based on the provided GaugeOpts. +
+ + + + + + + + + +type GaugeFunc interface { + Metric + Collector +}+
+GaugeFunc is a Gauge whose value is determined at collect time by calling a +provided function. +
++To create GaugeFunc instances, use NewGaugeFunc. +
+ + + + + + +▹ Example
+func NewGaugeFunc(opts GaugeOpts, function func() float64) GaugeFunc+
+NewGaugeFunc creates a new GaugeFunc based on the provided GaugeOpts. The +value reported is determined by calling the given function from within the +Write method. Take into account that metric collection may happen +concurrently. If that results in concurrent calls to Write, like in the case +where a GaugeFunc is directly registered with Prometheus, the provided +function must be concurrency-safe. +
+ + + + + + + + + +type GaugeOpts Opts+
+GaugeOpts is an alias for Opts. See there for doc comments. +
+ + + + + + + + + + + + + + + + +type GaugeVec struct { + *MetricVec +}+
+GaugeVec is a Collector that bundles a set of Gauges that all share the same +Desc, but have different values for their variable labels. This is used if +you want to count the same thing partitioned by various dimensions +(e.g. number of operations queued, partitioned by user and operation +type). Create instances with NewGaugeVec. +
+ + + + + + +▹ Example
+func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec+
+NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and +partitioned by the given label names. At least one label name must be +provided. +
+ + + + + + + +func (m *GaugeVec) GetMetricWith(labels Labels) (Gauge, error)+
+GetMetricWith replaces the method of the same name in MetricVec. The +difference is that this method returns a Gauge and not a Metric so that no +type conversion is required. +
+ + + + + + +func (m *GaugeVec) GetMetricWithLabelValues(lvs ...string) (Gauge, error)+
+GetMetricWithLabelValues replaces the method of the same name in +MetricVec. The difference is that this method returns a Gauge and not a +Metric so that no type conversion is required. +
+ + + + + + +func (m *GaugeVec) With(labels Labels) Gauge+
+With works as GetMetricWith, but panics where GetMetricWithLabels would have +returned an error. By not returning an error, With allows shortcuts like +
+myVec.With(Labels{"code": "404", "method": "GET"}).Add(42) ++ + + + + + +
func (m *GaugeVec) WithLabelValues(lvs ...string) Gauge+
+WithLabelValues works as GetMetricWithLabelValues, but panics where +GetMetricWithLabelValues would have returned an error. By not returning an +error, WithLabelValues allows shortcuts like +
+myVec.WithLabelValues("404", "GET").Add(42) ++ + + + + + + + +
type Histogram interface { + Metric + Collector + + // Observe adds a single observation to the histogram. + Observe(float64) +}+
+A Histogram counts individual observations from an event or sample stream in +configurable buckets. Similar to a summary, it also provides a sum of +observations and an observation count. +
++On the Prometheus server, quantiles can be calculated from a Histogram using +the histogram_quantile function in the query language. +
++Note that Histograms, in contrast to Summaries, can be aggregated with the +Prometheus query language (see the documentation for detailed +procedures). However, Histograms require the user to pre-define suitable +buckets, and they are in general less accurate. The Observe method of a +Histogram has a very low performance overhead in comparison with the Observe +method of a Summary. +
++To create Histogram instances, use NewHistogram. +
+ + + + + + +▹ Example
+func NewHistogram(opts HistogramOpts) Histogram+
+NewHistogram creates a new Histogram based on the provided HistogramOpts. It +panics if the buckets in HistogramOpts are not in strictly increasing order. +
+ + + + + + + + + +type HistogramOpts struct { + // Namespace, Subsystem, and Name are components of the fully-qualified + // name of the Histogram (created by joining these components with + // "_"). Only Name is mandatory, the others merely help structuring the + // name. Note that the fully-qualified name of the Histogram must be a + // valid Prometheus metric name. + Namespace string + Subsystem string + Name string + + // Help provides information about this Histogram. Mandatory! + // + // Metrics with the same fully-qualified name must have the same Help + // string. + Help string + + // ConstLabels are used to attach fixed labels to this + // Histogram. Histograms with the same fully-qualified name must have the + // same label names in their ConstLabels. + // + // Note that in most cases, labels have a value that varies during the + // lifetime of a process. Those labels are usually managed with a + // HistogramVec. ConstLabels serve only special purposes. One is for the + // special case where the value of a label does not change during the + // lifetime of a process, e.g. if the revision of the running binary is + // put into a label. Another, more advanced purpose is if more than one + // Collector needs to collect Histograms with the same fully-qualified + // name. In that case, those Summaries must differ in the values of + // their ConstLabels. See the Collector examples. + // + // If the value of a label never changes (not even between binaries), + // that label most likely should not be a label at all (but part of the + // metric name). + ConstLabels Labels + + // Buckets defines the buckets into which observations are counted. Each + // element in the slice is the upper inclusive bound of a bucket. The + // values must be sorted in strictly increasing order. There is no need + // to add a highest bucket with +Inf bound, it will be added + // implicitly. The default value is DefBuckets. + Buckets []float64 +}+
+HistogramOpts bundles the options for creating a Histogram metric. It is +mandatory to set Name and Help to a non-empty string. All other fields are +optional and can safely be left at their zero value. +
+ + + + + + + + + + + + + + + + +type HistogramVec struct { + *MetricVec +}+
+HistogramVec is a Collector that bundles a set of Histograms that all share the +same Desc, but have different values for their variable labels. This is used +if you want to count the same thing partitioned by various dimensions +(e.g. HTTP request latencies, partitioned by status code and method). Create +instances with NewHistogramVec. +
+ + + + + + + + + + + + +func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec+
+NewHistogramVec creates a new HistogramVec based on the provided HistogramOpts and +partitioned by the given label names. At least one label name must be +provided. +
+ + + + + + + +func (m *HistogramVec) GetMetricWith(labels Labels) (Histogram, error)+
+GetMetricWith replaces the method of the same name in MetricVec. The +difference is that this method returns a Histogram and not a Metric so that no +type conversion is required. +
+ + + + + + +func (m *HistogramVec) GetMetricWithLabelValues(lvs ...string) (Histogram, error)+
+GetMetricWithLabelValues replaces the method of the same name in +MetricVec. The difference is that this method returns a Histogram and not a +Metric so that no type conversion is required. +
+ + + + + + +func (m *HistogramVec) With(labels Labels) Histogram+
+With works as GetMetricWith, but panics where GetMetricWithLabels would have +returned an error. By not returning an error, With allows shortcuts like +
+myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21) ++ + + + + + +
func (m *HistogramVec) WithLabelValues(lvs ...string) Histogram+
+WithLabelValues works as GetMetricWithLabelValues, but panics where +GetMetricWithLabelValues would have returned an error. By not returning an +error, WithLabelValues allows shortcuts like +
+myVec.WithLabelValues("404", "GET").Observe(42.21) ++ + + + + + + + +
type LabelPairSorter []*dto.LabelPair+
+LabelPairSorter implements sort.Interface. It is used to sort a slice of +dto.LabelPair pointers. This is useful for implementing the Write method of +custom metrics. +
+ + + + + + +▹ Example
+func (s LabelPairSorter) Len() int+ + + + + + +
func (s LabelPairSorter) Less(i, j int) bool+ + + + + + +
func (s LabelPairSorter) Swap(i, j int)+ + + + + + + + +
type Labels map[string]string+
+Labels represents a collection of label name -> value mappings. This type is +commonly used with the With(Labels) and GetMetricWith(Labels) methods of +metric vector Collectors, e.g.: +
+myVec.With(Labels{"code": "404", "method": "GET"}).Add(42) ++
+The other use-case is the specification of constant label pairs in Opts or to +create a Desc. +
+ + + + + + + + + + + + + + + + +type Metric interface { + // Desc returns the descriptor for the Metric. This method idempotently + // returns the same descriptor throughout the lifetime of the + // Metric. The returned descriptor is immutable by contract. A Metric + // unable to describe itself must return an invalid descriptor (created + // with NewInvalidDesc). + Desc() *Desc + // Write encodes the Metric into a "Metric" Protocol Buffer data + // transmission object. + // + // Metric implementations must observe concurrency safety as reads of + // this metric may occur at any time, and any blocking occurs at the + // expense of total performance of rendering all registered + // metrics. Ideally, Metric implementations should support concurrent + // readers. + // + // While populating dto.Metric, it is the responsibility of the + // implementation to ensure validity of the Metric protobuf (like valid + // UTF-8 strings or syntactically valid metric and label names). It is + // recommended to sort labels lexicographically. (Implementers may find + // LabelPairSorter useful for that.) Callers of Write should still make + // sure of sorting if they depend on it. + Write(*dto.Metric) error +}+
+A Metric models a single sample value with its meta data being exported to +Prometheus. Implementations of Metric in this package are Gauge, Counter, +Histogram, Summary, and Untyped. +
+ + + + + + + + + + + + +func MustNewConstHistogram( + desc *Desc, + count uint64, + sum float64, + buckets map[float64]uint64, + labelValues ...string, +) Metric+
+MustNewConstHistogram is a version of NewConstHistogram that panics where +NewConstMetric would have returned an error. +
+ + + + + +func MustNewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) Metric+
+MustNewConstMetric is a version of NewConstMetric that panics where +NewConstMetric would have returned an error. +
+ + + + + +func MustNewConstSummary( + desc *Desc, + count uint64, + sum float64, + quantiles map[float64]float64, + labelValues ...string, +) Metric+
+MustNewConstSummary is a version of NewConstSummary that panics where +NewConstMetric would have returned an error. +
+ + + + + +func NewConstHistogram( + desc *Desc, + count uint64, + sum float64, + buckets map[float64]uint64, + labelValues ...string, +) (Metric, error)+
+NewConstHistogram returns a metric representing a Prometheus histogram with +fixed values for the count, sum, and bucket counts. As those parameters +cannot be changed, the returned value does not implement the Histogram +interface (but only the Metric interface). Users of this package will not +have much use for it in regular operations. However, when implementing custom +Collectors, it is useful as a throw-away metric that is generated on the fly +to send it to Prometheus in the Collect method. +
++buckets is a map of upper bounds to cumulative counts, excluding the +Inf +bucket. +
++NewConstHistogram returns an error if the length of labelValues is not +consistent with the variable labels in Desc. +
+ +▹ Example
+func NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) (Metric, error)+
+NewConstMetric returns a metric with one fixed value that cannot be +changed. Users of this package will not have much use for it in regular +operations. However, when implementing custom Collectors, it is useful as a +throw-away metric that is generated on the fly to send it to Prometheus in +the Collect method. NewConstMetric returns an error if the length of +labelValues is not consistent with the variable labels in Desc. +
+ + + + + +func NewConstSummary( + desc *Desc, + count uint64, + sum float64, + quantiles map[float64]float64, + labelValues ...string, +) (Metric, error)+
+NewConstSummary returns a metric representing a Prometheus summary with fixed +values for the count, sum, and quantiles. As those parameters cannot be +changed, the returned value does not implement the Summary interface (but +only the Metric interface). Users of this package will not have much use for +it in regular operations. However, when implementing custom Collectors, it is +useful as a throw-away metric that is generated on the fly to send it to +Prometheus in the Collect method. +
++quantiles maps ranks to quantile values. For example, a median latency of +0.23s and a 99th percentile latency of 0.56s would be expressed as: +
+map[float64]float64{0.5: 0.23, 0.99: 0.56} ++
+NewConstSummary returns an error if the length of labelValues is not +consistent with the variable labels in Desc. +
+ +▹ Example
+func NewInvalidMetric(desc *Desc, err error) Metric+
+NewInvalidMetric returns a metric whose Write method always returns the +provided error. It is useful if a Collector finds itself unable to collect +a metric and wishes to report an error to the registry. +
+ + + + + + + + + +type MetricVec struct {
+ // contains filtered or unexported fields
+}
+ +MetricVec is a Collector to bundle metrics of the same name that +differ in their label values. MetricVec is usually not used directly but as a +building block for implementations of vectors of a given metric +type. GaugeVec, CounterVec, SummaryVec, and UntypedVec are examples already +provided in this package. +
+ + + + + + + + + + + + + + +func (m *MetricVec) Collect(ch chan<- Metric)+
+Collect implements Collector. +
+ + + + + + +func (m *MetricVec) Delete(labels Labels) bool+
+Delete deletes the metric where the variable labels are the same as those +passed in as labels. It returns true if a metric was deleted. +
++It is not an error if the number and names of the Labels are inconsistent +with those of the VariableLabels in the Desc of the MetricVec. However, such +inconsistent Labels can never match an actual Metric, so the method will +always return false in that case. +
++This method is used for the same purpose as DeleteLabelValues(...string). See +there for pros and cons of the two methods. +
+ + + + + + +func (m *MetricVec) DeleteLabelValues(lvs ...string) bool+
+DeleteLabelValues removes the metric where the variable labels are the same +as those passed in as labels (same order as the VariableLabels in Desc). It +returns true if a metric was deleted. +
++It is not an error if the number of label values is not the same as the +number of VariableLabels in Desc. However, such inconsistent label count can +never match an actual Metric, so the method will always return false in that +case. +
++Note that for more than one label value, this method is prone to mistakes +caused by an incorrect order of arguments. Consider Delete(Labels) as an +alternative to avoid that type of mistake. For higher label numbers, the +latter has a much more readable (albeit more verbose) syntax, but it comes +with a performance overhead (for creating and processing the Labels map). +See also the CounterVec example. +
+ + + + + + +func (m *MetricVec) Describe(ch chan<- *Desc)+
+Describe implements Collector. The length of the returned slice +is always one. +
+ + + + + + +func (m *MetricVec) GetMetricWith(labels Labels) (Metric, error)+
+GetMetricWith returns the Metric for the given Labels map (the label names +must match those of the VariableLabels in Desc). If that label map is +accessed for the first time, a new Metric is created. Implications of +creating a Metric without using it and keeping the Metric for later use are +the same as for GetMetricWithLabelValues. +
++An error is returned if the number and names of the Labels are inconsistent +with those of the VariableLabels in Desc. +
++This method is used for the same purpose as +GetMetricWithLabelValues(...string). See there for pros and cons of the two +methods. +
+ + + + + + +func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error)+
+GetMetricWithLabelValues returns the Metric for the given slice of label +values (same order as the VariableLabels in Desc). If that combination of +label values is accessed for the first time, a new Metric is created. +
++It is possible to call this method without using the returned Metric to only +create the new Metric but leave it at its start value (e.g. a Summary or +Histogram without any observations). See also the SummaryVec example. +
++Keeping the Metric for later use is possible (and should be considered if +performance is critical), but keep in mind that Reset, DeleteLabelValues and +Delete can be used to delete the Metric from the MetricVec. In that case, the +Metric will still exist, but it will not be exported anymore, even if a +Metric with the same label values is created later. See also the CounterVec +example. +
++An error is returned if the number of label values is not the same as the +number of VariableLabels in Desc. +
++Note that for more than one label value, this method is prone to mistakes +caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as +an alternative to avoid that type of mistake. For higher label numbers, the +latter has a much more readable (albeit more verbose) syntax, but it comes +with a performance overhead (for creating and processing the Labels map). +See also the GaugeVec example. +
+ + + + + + +func (m *MetricVec) Reset()+
+Reset deletes all metrics in this vector. +
+ + + + + + +func (m *MetricVec) With(labels Labels) Metric+
+With works as GetMetricWith, but panics if an error occurs. The method allows +neat syntax like: +
+httpReqs.With(Labels{"status":"404", "method":"POST"}).Inc() ++ + + + + + +
func (m *MetricVec) WithLabelValues(lvs ...string) Metric+
+WithLabelValues works as GetMetricWithLabelValues, but panics if an error +occurs. The method allows neat syntax like: +
+httpReqs.WithLabelValues("404", "POST").Inc() ++ + + + + + + + +
type MultiError []error+
+MultiError is a slice of errors implementing the error interface. It is used +by a Gatherer to report multiple errors during MetricFamily gathering. +
+ + + + + + + + + + + + + + +func (errs MultiError) Error() string+ + + + + + +
func (errs MultiError) MaybeUnwrap() error+
+MaybeUnwrap returns nil if len(errs) is 0. It returns the first and only +contained error as error if len(errs is 1). In all other cases, it returns +the MultiError directly. This is helpful for returning a MultiError in a way +that only uses the MultiError if needed. +
+ + + + + + + + +type Opts struct { + // Namespace, Subsystem, and Name are components of the fully-qualified + // name of the Metric (created by joining these components with + // "_"). Only Name is mandatory, the others merely help structuring the + // name. Note that the fully-qualified name of the metric must be a + // valid Prometheus metric name. + Namespace string + Subsystem string + Name string + + // Help provides information about this metric. Mandatory! + // + // Metrics with the same fully-qualified name must have the same Help + // string. + Help string + + // ConstLabels are used to attach fixed labels to this metric. Metrics + // with the same fully-qualified name must have the same label names in + // their ConstLabels. + // + // Note that in most cases, labels have a value that varies during the + // lifetime of a process. Those labels are usually managed with a metric + // vector collector (like CounterVec, GaugeVec, UntypedVec). ConstLabels + // serve only special purposes. One is for the special case where the + // value of a label does not change during the lifetime of a process, + // e.g. if the revision of the running binary is put into a + // label. Another, more advanced purpose is if more than one Collector + // needs to collect Metrics with the same fully-qualified name. In that + // case, those Metrics must differ in the values of their + // ConstLabels. See the Collector examples. + // + // If the value of a label never changes (not even between binaries), + // that label most likely should not be a label at all (but part of the + // metric name). + ConstLabels Labels +}+
+Opts bundles the options for creating most Metric types. Each metric +implementation XXX has its own XXXOpts type, but in most cases, it is just be +an alias of this type (which might change when the requirement arises.) +
++It is mandatory to set Name and Help to a non-empty string. All other fields +are optional and can safely be left at their zero value. +
+ + + + + + + + + + + + + + + + +type Registerer interface { + // Register registers a new Collector to be included in metrics + // collection. It returns an error if the descriptors provided by the + // Collector are invalid or if they — in combination with descriptors of + // already registered Collectors — do not fulfill the consistency and + // uniqueness criteria described in the documentation of metric.Desc. + // + // If the provided Collector is equal to a Collector already registered + // (which includes the case of re-registering the same Collector), the + // returned error is an instance of AlreadyRegisteredError, which + // contains the previously registered Collector. + // + // It is in general not safe to register the same Collector multiple + // times concurrently. + Register(Collector) error + // MustRegister works like Register but registers any number of + // Collectors and panics upon the first registration that causes an + // error. + MustRegister(...Collector) + // Unregister unregisters the Collector that equals the Collector passed + // in as an argument. (Two Collectors are considered equal if their + // Describe method yields the same set of descriptors.) The function + // returns whether a Collector was unregistered. + // + // Note that even after unregistering, it will not be possible to + // register a new Collector that is inconsistent with the unregistered + // Collector, e.g. a Collector collecting metrics with the same name but + // a different help string. The rationale here is that the same registry + // instance must only collect consistent metrics throughout its + // lifetime. + Unregister(Collector) bool +}+
+Registerer is the interface for the part of a registry in charge of +registering and unregistering. Users of custom registries should use +Registerer as type for registration purposes (rather then the Registry type +directly). In that way, they are free to use custom Registerer implementation +(e.g. for testing purposes). +
+ + + + + + + + + + + + + + + + +type Registry struct {
+ // contains filtered or unexported fields
+}
+ +Registry registers Prometheus collectors, collects their metrics, and gathers +them into MetricFamilies for exposition. It implements both Registerer and +Gatherer. The zero value is not usable. Create instances with NewRegistry or +NewPedanticRegistry. +
+ + + + + + + + + + + + +func NewPedanticRegistry() *Registry+
+NewPedanticRegistry returns a registry that checks during collection if each +collected Metric is consistent with its reported Desc, and if the Desc has +actually been registered with the registry. +
++Usually, a Registry will be happy as long as the union of all collected +Metrics is consistent and valid even if some metrics are not consistent with +their own Desc or a Desc provided by their registered Collector. Well-behaved +Collectors and Metrics will only provide consistent Descs. This Registry is +useful to test the implementation of Collectors and Metrics. +
+ + + + + +func NewRegistry() *Registry+
+NewRegistry creates a new vanilla Registry without any Collectors +pre-registered. +
+ + + + + + + +func (r *Registry) Gather() ([]*dto.MetricFamily, error)+
+Gather implements Gatherer. +
+ + + + + + +func (r *Registry) MustRegister(cs ...Collector)+
+MustRegister implements Registerer. +
+ + + + + + +func (r *Registry) Register(c Collector) error+
+Register implements Registerer. +
+ + + + + + +func (r *Registry) Unregister(c Collector) bool+
+Unregister implements Registerer. +
+ + + + + + + + +type Summary interface { + Metric + Collector + + // Observe adds a single observation to the summary. + Observe(float64) +}+
+A Summary captures individual observations from an event or sample stream and +summarizes them in a manner similar to traditional summary statistics: 1. sum +of observations, 2. observation count, 3. rank estimations. +
++A typical use-case is the observation of request latencies. By default, a +Summary provides the median, the 90th and the 99th percentile of the latency +as rank estimations. +
++Note that the rank estimations cannot be aggregated in a meaningful way with +the Prometheus query language (i.e. you cannot average or add them). If you +need aggregatable quantiles (e.g. you want the 99th percentile latency of all +queries served across all instances of a service), consider the Histogram +metric type. See the Prometheus documentation for more details. +
++To create Summary instances, use NewSummary. +
+ + + + + + +▹ Example
+func NewSummary(opts SummaryOpts) Summary+
+NewSummary creates a new Summary based on the provided SummaryOpts. +
+ + + + + + + + + +type SummaryOpts struct { + // Namespace, Subsystem, and Name are components of the fully-qualified + // name of the Summary (created by joining these components with + // "_"). Only Name is mandatory, the others merely help structuring the + // name. Note that the fully-qualified name of the Summary must be a + // valid Prometheus metric name. + Namespace string + Subsystem string + Name string + + // Help provides information about this Summary. Mandatory! + // + // Metrics with the same fully-qualified name must have the same Help + // string. + Help string + + // ConstLabels are used to attach fixed labels to this + // Summary. Summaries with the same fully-qualified name must have the + // same label names in their ConstLabels. + // + // Note that in most cases, labels have a value that varies during the + // lifetime of a process. Those labels are usually managed with a + // SummaryVec. ConstLabels serve only special purposes. One is for the + // special case where the value of a label does not change during the + // lifetime of a process, e.g. if the revision of the running binary is + // put into a label. Another, more advanced purpose is if more than one + // Collector needs to collect Summaries with the same fully-qualified + // name. In that case, those Summaries must differ in the values of + // their ConstLabels. See the Collector examples. + // + // If the value of a label never changes (not even between binaries), + // that label most likely should not be a label at all (but part of the + // metric name). + ConstLabels Labels + + // Objectives defines the quantile rank estimates with their respective + // absolute error. If Objectives[q] = e, then the value reported + // for q will be the φ-quantile value for some φ between q-e and q+e. + // The default value is DefObjectives. + Objectives map[float64]float64 + + // MaxAge defines the duration for which an observation stays relevant + // for the summary. Must be positive. The default value is DefMaxAge. + MaxAge time.Duration + + // AgeBuckets is the number of buckets used to exclude observations that + // are older than MaxAge from the summary. A higher number has a + // resource penalty, so only increase it if the higher resolution is + // really required. For very high observation rates, you might want to + // reduce the number of age buckets. With only one age bucket, you will + // effectively see a complete reset of the summary each time MaxAge has + // passed. The default value is DefAgeBuckets. + AgeBuckets uint32 + + // BufCap defines the default sample stream buffer size. The default + // value of DefBufCap should suffice for most uses. If there is a need + // to increase the value, a multiple of 500 is recommended (because that + // is the internal buffer size of the underlying package + // "github.com/bmizerany/perks/quantile"). + BufCap uint32 +}+
+SummaryOpts bundles the options for creating a Summary metric. It is +mandatory to set Name and Help to a non-empty string. All other fields are +optional and can safely be left at their zero value. +
+ + + + + + + + + + + + + + + + +type SummaryVec struct { + *MetricVec +}+
+SummaryVec is a Collector that bundles a set of Summaries that all share the +same Desc, but have different values for their variable labels. This is used +if you want to count the same thing partitioned by various dimensions +(e.g. HTTP request latencies, partitioned by status code and method). Create +instances with NewSummaryVec. +
+ + + + + + +▹ Example
+func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec+
+NewSummaryVec creates a new SummaryVec based on the provided SummaryOpts and +partitioned by the given label names. At least one label name must be +provided. +
+ + + + + + + +func (m *SummaryVec) GetMetricWith(labels Labels) (Summary, error)+
+GetMetricWith replaces the method of the same name in MetricVec. The +difference is that this method returns a Summary and not a Metric so that no +type conversion is required. +
+ + + + + + +func (m *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Summary, error)+
+GetMetricWithLabelValues replaces the method of the same name in +MetricVec. The difference is that this method returns a Summary and not a +Metric so that no type conversion is required. +
+ + + + + + +func (m *SummaryVec) With(labels Labels) Summary+
+With works as GetMetricWith, but panics where GetMetricWithLabels would have +returned an error. By not returning an error, With allows shortcuts like +
+myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21) ++ + + + + + +
func (m *SummaryVec) WithLabelValues(lvs ...string) Summary+
+WithLabelValues works as GetMetricWithLabelValues, but panics where +GetMetricWithLabelValues would have returned an error. By not returning an +error, WithLabelValues allows shortcuts like +
+myVec.WithLabelValues("404", "GET").Observe(42.21) ++ + + + + + + + +
type Untyped interface { + Metric + Collector + + // Set sets the Untyped metric to an arbitrary value. + Set(float64) + // Inc increments the Untyped metric by 1. + Inc() + // Dec decrements the Untyped metric by 1. + Dec() + // Add adds the given value to the Untyped metric. (The value can be + // negative, resulting in a decrease.) + Add(float64) + // Sub subtracts the given value from the Untyped metric. (The value can + // be negative, resulting in an increase.) + Sub(float64) +}+
+Untyped is a Metric that represents a single numerical value that can +arbitrarily go up and down. +
++An Untyped metric works the same as a Gauge. The only difference is that to +no type information is implied. +
++To create Untyped instances, use NewUntyped. +
+ + + + + + + + + + + + +func NewUntyped(opts UntypedOpts) Untyped+
+NewUntyped creates a new Untyped metric from the provided UntypedOpts. +
+ + + + + + + + + +type UntypedFunc interface { + Metric + Collector +}+
+UntypedFunc is an Untyped whose value is determined at collect time by +calling a provided function. +
++To create UntypedFunc instances, use NewUntypedFunc. +
+ + + + + + + + + + + + +func NewUntypedFunc(opts UntypedOpts, function func() float64) UntypedFunc+
+NewUntypedFunc creates a new UntypedFunc based on the provided +UntypedOpts. The value reported is determined by calling the given function +from within the Write method. Take into account that metric collection may +happen concurrently. If that results in concurrent calls to Write, like in +the case where an UntypedFunc is directly registered with Prometheus, the +provided function must be concurrency-safe. +
+ + + + + + + + + +type UntypedOpts Opts+
+UntypedOpts is an alias for Opts. See there for doc comments. +
+ + + + + + + + + + + + + + + + +type UntypedVec struct { + *MetricVec +}+
+UntypedVec is a Collector that bundles a set of Untyped metrics that all +share the same Desc, but have different values for their variable +labels. This is used if you want to count the same thing partitioned by +various dimensions. Create instances with NewUntypedVec. +
+ + + + + + + + + + + + +func NewUntypedVec(opts UntypedOpts, labelNames []string) *UntypedVec+
+NewUntypedVec creates a new UntypedVec based on the provided UntypedOpts and +partitioned by the given label names. At least one label name must be +provided. +
+ + + + + + + +func (m *UntypedVec) GetMetricWith(labels Labels) (Untyped, error)+
+GetMetricWith replaces the method of the same name in MetricVec. The +difference is that this method returns an Untyped and not a Metric so that no +type conversion is required. +
+ + + + + + +func (m *UntypedVec) GetMetricWithLabelValues(lvs ...string) (Untyped, error)+
+GetMetricWithLabelValues replaces the method of the same name in +MetricVec. The difference is that this method returns an Untyped and not a +Metric so that no type conversion is required. +
+ + + + + + +func (m *UntypedVec) With(labels Labels) Untyped+
+With works as GetMetricWith, but panics where GetMetricWithLabels would have +returned an error. By not returning an error, With allows shortcuts like +
+myVec.With(Labels{"code": "404", "method": "GET"}).Add(42) ++ + + + + + +
func (m *UntypedVec) WithLabelValues(lvs ...string) Untyped+
+WithLabelValues works as GetMetricWithLabelValues, but panics where +GetMetricWithLabelValues would have returned an error. By not returning an +error, WithLabelValues allows shortcuts like +
+myVec.WithLabelValues("404", "GET").Add(42) ++ + + + + + + + +
type ValueType int+
+ValueType is an enumeration of metric types that represent a simple value. +
+ + + +const ( + CounterValue ValueType + GaugeValue + UntypedValue +)+
+Possible values for the ValueType enum. +
+ + + + + + + + + + + + + + + + + + + + + + + +func Handler() http.Handler+
+Handler returns an HTTP handler for the prometheus.DefaultGatherer. The +Handler uses the default HandlerOpts, i.e. report the first error as an HTTP +error, no error logging, and compression if requested by the client. +
++If you want to create a Handler for the DefaultGatherer with different +HandlerOpts, create it with HandlerFor with prometheus.DefaultGatherer and +your desired HandlerOpts. +
+ + + + + + + +func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler+
+HandlerFor returns an http.Handler for the provided Gatherer. The behavior +of the Handler is defined by the provided HandlerOpts. +
+ + + + + + + + +type HandlerErrorHandling int+
+HandlerErrorHandling defines how a Handler serving metrics will handle +errors. +
+ + + +const ( + // Serve an HTTP status code 500 upon the first error + // encountered. Report the error message in the body. + HTTPErrorOnError HandlerErrorHandling = iota + // Ignore errors and try to serve as many metrics as possible. However, + // if no metrics can be served, serve an HTTP status code 500 and the + // last error message in the body. Only use this in deliberate "best + // effort" metrics collection scenarios. It is recommended to at least + // log errors (by providing an ErrorLog in HandlerOpts) to not mask + // errors completely. + ContinueOnError + // Panic upon the first error encountered (useful for "crash only" apps). + PanicOnError +)+
+These constants cause handlers serving metrics to behave as described if +errors are encountered. +
+ + + + + + + + + + + + + + + +type HandlerOpts struct { + // ErrorLog specifies an optional logger for errors collecting and + // serving metrics. If nil, errors are not logged at all. + ErrorLog Logger + // ErrorHandling defines how errors are handled. Note that errors are + // logged regardless of the configured ErrorHandling provided ErrorLog + // is not nil. + ErrorHandling HandlerErrorHandling + // If DisableCompression is true, the handler will never compress the + // response, even if requested by the client. + DisableCompression bool +}+
+HandlerOpts specifies options how to serve metrics via an http.Handler. The +zero value of HandlerOpts is a reasonable default. +
+ + + + + + + + + + + + + + + + +type Logger interface { + Println(v ...interface{}) +}+
+Logger is the minimal interface HandlerOpts needs for logging. Note that +log.Logger from the standard library implements this interface, and it is +easy to implement by custom loggers, if they don't do so already anyway. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +func AddCollectors(job string, grouping map[string]string, url string, collectors ...prometheus.Collector) error+
+AddCollectors works like AddFromGatherer, but it does not use a Gatherer. +Instead, it collects from the provided collectors directly. It is a +convenient way to push only a few metrics. +
+ + + + + + + +func AddFromGatherer(job string, grouping map[string]string, url string, g prometheus.Gatherer) error+
+AddFromGatherer works like FromGatherer, but only previously pushed metrics +with the same name (and the same job and other grouping labels) will be +replaced. (It uses HTTP method 'POST' to push to the Pushgateway.) +
+ + + + + + + +func Collectors(job string, grouping map[string]string, url string, collectors ...prometheus.Collector) error+
+Collectors works like FromGatherer, but it does not use a Gatherer. Instead, +it collects from the provided collectors directly. It is a convenient way to +push only a few metrics. +
+ +▹ Example
+func FromGatherer(job string, grouping map[string]string, url string, g prometheus.Gatherer) error+
+FromGatherer triggers a metric collection by the provided Gatherer (which is +usually implemented by a prometheus.Registry) and pushes all gathered metrics +to the Pushgateway specified by url, using the provided job name and the +(optional) further grouping labels (the grouping map may be nil). See the +Pushgateway documentation for detailed implications of the job and other +grouping labels. Neither the job name nor any grouping label value may +contain a "/". The metrics pushed must not contain a job label of their own +nor any of the grouping labels. +
++You can use just host:port or ip:port as url, in which case 'http://' is +added automatically. You can also include the schema in the URL. However, do +not include the '/metrics/jobs/...' part. +
++Note that all previously pushed metrics with the same job and other grouping +labels will be replaced with the metrics pushed by this call. (It uses HTTP +method 'PUT' to push to the Pushgateway.) +
+ +▹ Example
+func HostnameGroupingKey() map[string]string+
+HostnameGroupingKey returns a label map with the only entry +{instance="<hostname>"}. This can be conveniently used as the grouping +parameter if metrics should be pushed with the hostname as label. The +returned map is created upon each call so that the caller is free to add more +labels to the map. +
+ + + + + + + + + + + + + + + + + + +var MetricType_name = map[int32]string{ + 0: "COUNTER", + 1: "GAUGE", + 2: "SUMMARY", + 3: "UNTYPED", + 4: "HISTOGRAM", +}+ + +
var MetricType_value = map[string]int32{ + "COUNTER": 0, + "GAUGE": 1, + "SUMMARY": 2, + "UNTYPED": 3, + "HISTOGRAM": 4, +}+ + + + + + + +
type Bucket struct { + CumulativeCount *uint64 `protobuf:"varint,1,opt,name=cumulative_count" json:"cumulative_count,omitempty"` + UpperBound *float64 `protobuf:"fixed64,2,opt,name=upper_bound" json:"upper_bound,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (m *Bucket) GetCumulativeCount() uint64+ + + + + + +
func (m *Bucket) GetUpperBound() float64+ + + + + + +
func (*Bucket) ProtoMessage()+ + + + + + +
func (m *Bucket) Reset()+ + + + + + +
func (m *Bucket) String() string+ + + + + + + + +
type Counter struct { + Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (m *Counter) GetValue() float64+ + + + + + +
func (*Counter) ProtoMessage()+ + + + + + +
func (m *Counter) Reset()+ + + + + + +
func (m *Counter) String() string+ + + + + + + + +
type Gauge struct { + Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (m *Gauge) GetValue() float64+ + + + + + +
func (*Gauge) ProtoMessage()+ + + + + + +
func (m *Gauge) Reset()+ + + + + + +
func (m *Gauge) String() string+ + + + + + + + +
type Histogram struct { + SampleCount *uint64 `protobuf:"varint,1,opt,name=sample_count" json:"sample_count,omitempty"` + SampleSum *float64 `protobuf:"fixed64,2,opt,name=sample_sum" json:"sample_sum,omitempty"` + Bucket []*Bucket `protobuf:"bytes,3,rep,name=bucket" json:"bucket,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (m *Histogram) GetBucket() []*Bucket+ + + + + + +
func (m *Histogram) GetSampleCount() uint64+ + + + + + +
func (m *Histogram) GetSampleSum() float64+ + + + + + +
func (*Histogram) ProtoMessage()+ + + + + + +
func (m *Histogram) Reset()+ + + + + + +
func (m *Histogram) String() string+ + + + + + + + +
type LabelPair struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Value *string `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (m *LabelPair) GetName() string+ + + + + + +
func (m *LabelPair) GetValue() string+ + + + + + +
func (*LabelPair) ProtoMessage()+ + + + + + +
func (m *LabelPair) Reset()+ + + + + + +
func (m *LabelPair) String() string+ + + + + + + + +
type Metric struct { + Label []*LabelPair `protobuf:"bytes,1,rep,name=label" json:"label,omitempty"` + Gauge *Gauge `protobuf:"bytes,2,opt,name=gauge" json:"gauge,omitempty"` + Counter *Counter `protobuf:"bytes,3,opt,name=counter" json:"counter,omitempty"` + Summary *Summary `protobuf:"bytes,4,opt,name=summary" json:"summary,omitempty"` + Untyped *Untyped `protobuf:"bytes,5,opt,name=untyped" json:"untyped,omitempty"` + Histogram *Histogram `protobuf:"bytes,7,opt,name=histogram" json:"histogram,omitempty"` + TimestampMs *int64 `protobuf:"varint,6,opt,name=timestamp_ms" json:"timestamp_ms,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (m *Metric) GetCounter() *Counter+ + + + + + +
func (m *Metric) GetGauge() *Gauge+ + + + + + +
func (m *Metric) GetHistogram() *Histogram+ + + + + + +
func (m *Metric) GetLabel() []*LabelPair+ + + + + + +
func (m *Metric) GetSummary() *Summary+ + + + + + +
func (m *Metric) GetTimestampMs() int64+ + + + + + +
func (m *Metric) GetUntyped() *Untyped+ + + + + + +
func (*Metric) ProtoMessage()+ + + + + + +
func (m *Metric) Reset()+ + + + + + +
func (m *Metric) String() string+ + + + + + + + +
type MetricFamily struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Help *string `protobuf:"bytes,2,opt,name=help" json:"help,omitempty"` + Type *MetricType `protobuf:"varint,3,opt,name=type,enum=io.prometheus.client.MetricType" json:"type,omitempty"` + Metric []*Metric `protobuf:"bytes,4,rep,name=metric" json:"metric,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (m *MetricFamily) GetHelp() string+ + + + + + +
func (m *MetricFamily) GetMetric() []*Metric+ + + + + + +
func (m *MetricFamily) GetName() string+ + + + + + +
func (m *MetricFamily) GetType() MetricType+ + + + + + +
func (*MetricFamily) ProtoMessage()+ + + + + + +
func (m *MetricFamily) Reset()+ + + + + + +
func (m *MetricFamily) String() string+ + + + + + + + +
type MetricType int32+ + + +
const ( + MetricType_COUNTER MetricType = 0 + MetricType_GAUGE MetricType = 1 + MetricType_SUMMARY MetricType = 2 + MetricType_UNTYPED MetricType = 3 + MetricType_HISTOGRAM MetricType = 4 +)+ + + + + + + + + + + + + +
func (x MetricType) Enum() *MetricType+ + + + + + +
func (x MetricType) String() string+ + + + + + +
func (x *MetricType) UnmarshalJSON(data []byte) error+ + + + + + + + +
type Quantile struct { + Quantile *float64 `protobuf:"fixed64,1,opt,name=quantile" json:"quantile,omitempty"` + Value *float64 `protobuf:"fixed64,2,opt,name=value" json:"value,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (m *Quantile) GetQuantile() float64+ + + + + + +
func (m *Quantile) GetValue() float64+ + + + + + +
func (*Quantile) ProtoMessage()+ + + + + + +
func (m *Quantile) Reset()+ + + + + + +
func (m *Quantile) String() string+ + + + + + + + +
type Summary struct { + SampleCount *uint64 `protobuf:"varint,1,opt,name=sample_count" json:"sample_count,omitempty"` + SampleSum *float64 `protobuf:"fixed64,2,opt,name=sample_sum" json:"sample_sum,omitempty"` + Quantile []*Quantile `protobuf:"bytes,3,rep,name=quantile" json:"quantile,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (m *Summary) GetQuantile() []*Quantile+ + + + + + +
func (m *Summary) GetSampleCount() uint64+ + + + + + +
func (m *Summary) GetSampleSum() float64+ + + + + + +
func (*Summary) ProtoMessage()+ + + + + + +
func (m *Summary) Reset()+ + + + + + +
func (m *Summary) String() string+ + + + + + + + +
type Untyped struct { + Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` + XXX_unrecognized []byte `json:"-"` +}+ + + + + + + + + + + + + + +
func (m *Untyped) GetValue() float64+ + + + + + +
func (*Untyped) ProtoMessage()+ + + + + + +
func (m *Untyped) Reset()+ + + + + + +
func (m *Untyped) String() string+ + + + + + + + + + + + + + + + + + +
const ( + TextVersion = "0.0.4" + + ProtoType = `application/vnd.google.protobuf` + ProtoProtocol = `io.prometheus.client.MetricFamily` + ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";" + + // The Content-Type values for the different wire protocols. + FmtUnknown Format = `<unknown>` + FmtText Format = `text/plain; version=` + TextVersion + FmtProtoDelim Format = ProtoFmt + ` encoding=delimited` + FmtProtoText Format = ProtoFmt + ` encoding=text` + FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text` +)+ + + + + + + +
func ExtractSamples(o *DecodeOptions, fams ...*dto.MetricFamily) model.Vector+
+Extract samples builds a slice of samples from the provided metric families. +
+ + + + + + + +func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error)+
+MetricFamilyToText converts a MetricFamily proto message into text format and +writes the resulting lines to 'out'. It returns the number of bytes written +and any error encountered. The output will have the same order as the input, +no further sorting is performed. Furthermore, this function assumes the input +is already sanitized and does not perform any sanity checks. If the input +contains duplicate metrics or invalid metric or label names, the conversion +will result in invalid text format output. +
++This method fulfills the type 'prometheus.encoder'. +
+ + + + + + + + +type DecodeOptions struct { + // Timestamp is added to each value from the stream that has no explicit timestamp set. + Timestamp model.Time +}+ + + + + + + + + + + + + + + + +
type Decoder interface { + Decode(*dto.MetricFamily) error +}+
+Decoder types decode an input stream into metric families. +
+ + + + + + + + + + + + +func NewDecoder(r io.Reader, format Format) Decoder+
+NewDecoder returns a new decoder based on the given input format. +If the input format does not imply otherwise, a text format decoder is returned. +
+ + + + + + + + + +type Encoder interface { + Encode(*dto.MetricFamily) error +}+
+Encoder types encode metric families into an underlying wire protocol. +
+ + + + + + + + + + + + +func NewEncoder(w io.Writer, format Format) Encoder+
+NewEncoder returns a new encoder based on content type negotiation. +
+ + + + + + + + + +type Format string+ + + + + + + + + + + + +
func Negotiate(h http.Header) Format+
+Negotiate returns the Content-Type based on the given Accept header. +If no appropriate accepted type is found, FmtText is returned. +
+ + + + + +func ResponseFormat(h http.Header) Format+
+ResponseFormat extracts the correct format from a HTTP response header. +If no matching format can be found FormatUnknown is returned. +
+ + + + + + + + + +type ParseError struct { + Line int + Msg string +}+
+ParseError signals errors while parsing the simple and flat text-based +exchange format. +
+ + + + + + + + + + + + + + +func (e ParseError) Error() string+
+Error implements the error interface. +
+ + + + + + + + +type SampleDecoder struct { + Dec Decoder + Opts *DecodeOptions + // contains filtered or unexported fields +}+ + + + + + + + + + + + + + +
func (sd *SampleDecoder) Decode(s *model.Vector) error+ + + + + + + + +
type TextParser struct {
+ // contains filtered or unexported fields
+}
+ +TextParser is used to parse the simple and flat text-based exchange format. Its +zero value is ready to use. +
+ + + + + + + + + + + + + + +func (p *TextParser) TextToMetricFamilies(in io.Reader) (map[string]*dto.MetricFamily, error)+
+TextToMetricFamilies reads 'in' as the simple and flat text-based exchange +format and creates MetricFamily proto messages. It returns the MetricFamily +proto messages in a map where the metric names are the keys, along with any +error encountered. +
++If the input contains duplicate metrics (i.e. lines with the same metric name +and exactly the same label set), the resulting MetricFamily will contain +duplicate Metric proto messages. Similar is true for duplicate label +names. Checks for duplicates have to be performed separately, if required. +Also note that neither the metrics within each MetricFamily are sorted nor +the label pairs within each Metric. Sorting is not required for the most +frequent use of this method, which is sample ingestion in the Prometheus +server. However, for presentation purposes, you might want to sort the +metrics, and in some cases, you must sort the labels, e.g. for consumption by +the metric family injection hook of the Prometheus registry. +
++Summaries and histograms are rather special beasts. You would probably not +use them in the simple text format anyway. This method can deal with +summaries and histograms if they are presented in exactly the way the +text.Create function creates them. +
++This method must not be called concurrently. If you want to parse different +input concurrently, instantiate a separate Parser for each goroutine. +
+ + + + + + + + + + +const ( + // AlertNameLabel is the name of the label containing the an alert's name. + AlertNameLabel = "alertname" + + // ExportedLabelPrefix is the prefix to prepend to the label names present in + // exported metrics if a label of the same name is added by the server. + ExportedLabelPrefix = "exported_" + + // MetricNameLabel is the label name indicating the metric name of a + // timeseries. + MetricNameLabel = "__name__" + + // SchemeLabel is the name of the label that holds the scheme on which to + // scrape a target. + SchemeLabel = "__scheme__" + + // AddressLabel is the name of the label that holds the address of + // a scrape target. + AddressLabel = "__address__" + + // MetricsPathLabel is the name of the label that holds the path on which to + // scrape a target. + MetricsPathLabel = "__metrics_path__" + + // ReservedLabelPrefix is a prefix which is not legal in user-supplied + // label names. + ReservedLabelPrefix = "__" + + // MetaLabelPrefix is a prefix for labels that provide meta information. + // Labels with this prefix are used for intermediate label processing and + // will not be attached to time series. + MetaLabelPrefix = "__meta_" + + // TmpLabelPrefix is a prefix for temporary labels as part of relabelling. + // Labels with this prefix are used for intermediate label processing and + // will not be attached to time series. This is reserved for use in + // Prometheus configuration files by users. + TmpLabelPrefix = "__tmp_" + + // ParamLabelPrefix is a prefix for labels that provide URL parameters + // used to scrape a target. + ParamLabelPrefix = "__param_" + + // JobLabel is the label name indicating the job from which a timeseries + // was scraped. + JobLabel = "job" + + // InstanceLabel is the label name used for the instance label. + InstanceLabel = "instance" + + // BucketLabel is used for the label that defines the upper bound of a + // bucket of a histogram ("le" -> "less or equal"). + BucketLabel = "le" + + // QuantileLabel is used for the label that defines the quantile in a + // summary. + QuantileLabel = "quantile" +)+ + +
const ( + + // Earliest is the earliest Time representable. Handy for + // initializing a high watermark. + Earliest = Time(math.MinInt64) + // Latest is the latest Time representable. Handy for initializing + // a low watermark. + Latest = Time(math.MaxInt64) +)+ + +
const SeparatorByte byte = 255+
+SeparatorByte is a byte that cannot occur in valid UTF-8 sequences and is +used to separate label names, label values, and other strings from each other +when calculating their combined hash value (aka signature aka fingerprint). +
+ + + + +var ( + // ZeroSamplePair is the pseudo zero-value of SamplePair used to signal a + // non-existing sample pair. It is a SamplePair with timestamp Earliest and + // value 0.0. Note that the natural zero value of SamplePair has a timestamp + // of 0, which is possible to appear in a real SamplePair and thus not + // suitable to signal a non-existing SamplePair. + ZeroSamplePair = SamplePair{Timestamp: Earliest} + + // ZeroSample is the pseudo zero-value of Sample used to signal a + // non-existing sample. It is a Sample with timestamp Earliest, value 0.0, + // and metric nil. Note that the natural zero value of Sample has a timestamp + // of 0, which is possible to appear in a real Sample and thus not suitable + // to signal a non-existing Sample. + ZeroSample = Sample{Timestamp: Earliest} +)+ + +
var LabelNameRE = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")+
+LabelNameRE is a regular expression matching valid label names. +
+ + +var ( + MetricNameRE = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_:]*$`) +)+ + + + + + +
func IsValidMetricName(n LabelValue) bool+
+IsValidMetricName returns true iff name matches the pattern of MetricNameRE. +
+ + + + + + + +func LabelsToSignature(labels map[string]string) uint64+
+LabelsToSignature returns a quasi-unique signature (i.e., fingerprint) for a +given label set. (Collisions are possible but unlikely if the number of label +sets the function is applied to is small.) +
+ + + + + + + +func SignatureForLabels(m Metric, labels ...LabelName) uint64+
+SignatureForLabels works like LabelsToSignature but takes a Metric as +parameter (rather than a label map) and only includes the labels with the +specified LabelNames into the signature calculation. The labels passed in +will be sorted by this function. +
+ + + + + + + +func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64+
+SignatureWithoutLabels works like LabelsToSignature but takes a Metric as +parameter (rather than a label map) and excludes the labels with any of the +specified LabelNames from the signature calculation. +
+ + + + + + + + +type Alert struct { + // Label value pairs for purpose of aggregation, matching, and disposition + // dispatching. This must minimally include an "alertname" label. + Labels LabelSet `json:"labels"` + + // Extra key/value information which does not define alert identity. + Annotations LabelSet `json:"annotations"` + + // The known time range for this alert. Both ends are optional. + StartsAt time.Time `json:"startsAt,omitempty"` + EndsAt time.Time `json:"endsAt,omitempty"` + GeneratorURL string `json:"generatorURL"` +}+
+Alert is a generic representation of an alert in the Prometheus eco-system. +
+ + + + + + + + + + + + + + +func (a *Alert) Fingerprint() Fingerprint+
+Fingerprint returns a unique hash for the alert. It is equivalent to +the fingerprint of the alert's label set. +
+ + + + + + +func (a *Alert) Name() string+
+Name returns the name of the alert. It is equivalent to the "alertname" label. +
+ + + + + + +func (a *Alert) Resolved() bool+
+Resolved returns true iff the activity interval ended in the past. +
+ + + + + + +func (a *Alert) ResolvedAt(ts time.Time) bool+
+ResolvedAt returns true off the activity interval ended before +the given timestamp. +
+ + + + + + +func (a *Alert) Status() AlertStatus+
+Status returns the status of the alert. +
+ + + + + + +func (a *Alert) String() string+ + + + + + +
func (a *Alert) Validate() error+
+Validate checks whether the alert data is inconsistent. +
+ + + + + + + + +type AlertStatus string+ + + +
const ( + AlertFiring AlertStatus = "firing" + AlertResolved AlertStatus = "resolved" +)+ + + + + + + + + + + + + + + +
type Alerts []*Alert+
+Alert is a list of alerts that can be sorted in chronological order. +
+ + + + + + + + + + + + + + +func (as Alerts) HasFiring() bool+
+HasFiring returns true iff one of the alerts is not resolved. +
+ + + + + + +func (as Alerts) Len() int+ + + + + + +
func (as Alerts) Less(i, j int) bool+ + + + + + +
func (as Alerts) Status() AlertStatus+
+Status returns StatusFiring iff at least one of the alerts is firing. +
+ + + + + + +func (as Alerts) Swap(i, j int)+ + + + + + + + +
type Duration time.Duration+
+Duration wraps time.Duration. It is used to parse the custom duration format +from YAML. +This type should not propagate beyond the scope of input/output processing. +
+ + + + + + + + + + + + +func ParseDuration(durationStr string) (Duration, error)+
+StringToDuration parses a string into a time.Duration, assuming that a year +always has 365d, a week always has 7d, and a day always has 24h. +
+ + + + + + + +func (d Duration) MarshalYAML() (interface{}, error)+
+MarshalYAML implements the yaml.Marshaler interface. +
+ + + + + + +func (d Duration) String() string+ + + + + + +
func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error+
+UnmarshalYAML implements the yaml.Unmarshaler interface. +
+ + + + + + + + +type Fingerprint uint64+
+Fingerprint provides a hash-capable representation of a Metric. +For our purposes, FNV-1A 64-bit is used. +
+ + + + + + + + + + + + +func FingerprintFromString(s string) (Fingerprint, error)+
+FingerprintFromString transforms a string representation into a Fingerprint. +
+ + + + + +func ParseFingerprint(s string) (Fingerprint, error)+
+ParseFingerprint parses the input string into a fingerprint. +
+ + + + + + + +func (f Fingerprint) String() string+ + + + + + + + +
type FingerprintSet map[Fingerprint]struct{}+
+FingerprintSet is a set of Fingerprints. +
+ + + + + + + + + + + + + + +func (s FingerprintSet) Equal(o FingerprintSet) bool+
+Equal returns true if both sets contain the same elements (and not more). +
+ + + + + + +func (s FingerprintSet) Intersection(o FingerprintSet) FingerprintSet+
+Intersection returns the elements contained in both sets. +
+ + + + + + + + +type Fingerprints []Fingerprint+
+Fingerprints represents a collection of Fingerprint subject to a given +natural sorting scheme. It implements sort.Interface. +
+ + + + + + + + + + + + + + +func (f Fingerprints) Len() int+
+Len implements sort.Interface. +
+ + + + + + +func (f Fingerprints) Less(i, j int) bool+
+Less implements sort.Interface. +
+ + + + + + +func (f Fingerprints) Swap(i, j int)+
+Swap implements sort.Interface. +
+ + + + + + + + +type Interval struct { + Start, End Time +}+
+Interval describes and interval between two timestamps. +
+ + + + + + + + + + + + + + + + +type LabelName string+
+A LabelName is a key for a LabelSet or Metric. It has a value associated +therewith. +
+ + + + + + + + + + + + + + +func (ln LabelName) IsValid() bool+
+IsValid is true iff the label name matches the pattern of LabelNameRE. +
+ + + + + + +func (ln *LabelName) UnmarshalJSON(b []byte) error+
+UnmarshalJSON implements the json.Unmarshaler interface. +
+ + + + + + +func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error+
+UnmarshalYAML implements the yaml.Unmarshaler interface. +
+ + + + + + + + +type LabelNames []LabelName+
+LabelNames is a sortable LabelName slice. In implements sort.Interface. +
+ + + + + + + + + + + + + + +func (l LabelNames) Len() int+ + + + + + +
func (l LabelNames) Less(i, j int) bool+ + + + + + +
func (l LabelNames) String() string+ + + + + + +
func (l LabelNames) Swap(i, j int)+ + + + + + + + +
type LabelPair struct { + Name LabelName + Value LabelValue +}+
+LabelPair pairs a name with a value. +
+ + + + + + + + + + + + + + + + +type LabelPairs []*LabelPair+
+LabelPairs is a sortable slice of LabelPair pointers. It implements +sort.Interface. +
+ + + + + + + + + + + + + + +func (l LabelPairs) Len() int+ + + + + + +
func (l LabelPairs) Less(i, j int) bool+ + + + + + +
func (l LabelPairs) Swap(i, j int)+ + + + + + + + +
type LabelSet map[LabelName]LabelValue+
+A LabelSet is a collection of LabelName and LabelValue pairs. The LabelSet +may be fully-qualified down to the point where it may resolve to a single +Metric in the data store or not. All operations that occur within the realm +of a LabelSet can emit a vector of Metric entities to which the LabelSet may +match. +
+ + + + + + + + + + + + + + +func (ls LabelSet) Before(o LabelSet) bool+
+Before compares the metrics, using the following criteria: +
++If m has fewer labels than o, it is before o. If it has more, it is not. +
++If the number of labels is the same, the superset of all label names is +sorted alphanumerically. The first differing label pair found in that order +determines the outcome: If the label does not exist at all in m, then m is +before o, and vice versa. Otherwise the label value is compared +alphanumerically. +
++If m and o are equal, the method returns false. +
+ + + + + + +func (ls LabelSet) Clone() LabelSet+
+Clone returns a copy of the label set. +
+ + + + + + +func (ls LabelSet) Equal(o LabelSet) bool+
+Equal returns true iff both label sets have exactly the same key/value pairs. +
+ + + + + + +func (ls LabelSet) FastFingerprint() Fingerprint+
+FastFingerprint returns the LabelSet's Fingerprint calculated by a faster hashing +algorithm, which is, however, more susceptible to hash collisions. +
+ + + + + + +func (ls LabelSet) Fingerprint() Fingerprint+
+Fingerprint returns the LabelSet's fingerprint. +
+ + + + + + +func (l LabelSet) Merge(other LabelSet) LabelSet+
+Merge is a helper function to non-destructively merge two label sets. +
+ + + + + + +func (l LabelSet) String() string+ + + + + + +
func (l *LabelSet) UnmarshalJSON(b []byte) error+
+UnmarshalJSON implements the json.Unmarshaler interface. +
+ + + + + + +func (ls LabelSet) Validate() error+
+Validate checks whether all names and values in the label set +are valid. +
+ + + + + + + + +type LabelValue string+
+A LabelValue is an associated value for a LabelName. +
+ + + + + + + + + + + + + + +func (lv LabelValue) IsValid() bool+
+IsValid returns true iff the string is a valid UTF8. +
+ + + + + + + + +type LabelValues []LabelValue+
+LabelValues is a sortable LabelValue slice. It implements sort.Interface. +
+ + + + + + + + + + + + + + +func (l LabelValues) Len() int+ + + + + + +
func (l LabelValues) Less(i, j int) bool+ + + + + + +
func (l LabelValues) Swap(i, j int)+ + + + + + + + +
type Matcher struct { + Name LabelName `json:"name"` + Value string `json:"value"` + IsRegex bool `json:"isRegex"` +}+
+Matcher describes a matches the value of a given label. +
+ + + + + + + + + + + + + + +func (m *Matcher) UnmarshalJSON(b []byte) error+ + + + + + +
func (m *Matcher) Validate() error+
+Validate returns true iff all fields of the matcher have valid values. +
+ + + + + + + + +type Matrix []*SampleStream+
+Matrix is a list of time series. +
+ + + + + + + + + + + + + + +func (m Matrix) Len() int+ + + + + + +
func (m Matrix) Less(i, j int) bool+ + + + + + +
func (mat Matrix) String() string+ + + + + + +
func (m Matrix) Swap(i, j int)+ + + + + + +
func (Matrix) Type() ValueType+ + + + + + + + +
type Metric LabelSet+
+A Metric is similar to a LabelSet, but the key difference is that a Metric is +a singleton and refers to one and only one stream of samples. +
+ + + + + + + + + + + + + + +func (m Metric) Before(o Metric) bool+
+Before compares the metrics' underlying label sets. +
+ + + + + + +func (m Metric) Clone() Metric+
+Clone returns a copy of the Metric. +
+ + + + + + +func (m Metric) Equal(o Metric) bool+
+Equal compares the metrics. +
+ + + + + + +func (m Metric) FastFingerprint() Fingerprint+
+FastFingerprint returns a Metric's Fingerprint calculated by a faster hashing +algorithm, which is, however, more susceptible to hash collisions. +
+ + + + + + +func (m Metric) Fingerprint() Fingerprint+
+Fingerprint returns a Metric's Fingerprint. +
+ + + + + + +func (m Metric) String() string+ + + + + + + + +
type Sample struct { + Metric Metric `json:"metric"` + Value SampleValue `json:"value"` + Timestamp Time `json:"timestamp"` +}+
+Sample is a sample pair associated with a metric. +
+ + + + + + + + + + + + + + +func (s *Sample) Equal(o *Sample) bool+
+Equal compares first the metrics, then the timestamp, then the value. The +sematics of value equality is defined by SampleValue.Equal. +
+ + + + + + +func (s Sample) MarshalJSON() ([]byte, error)+
+MarshalJSON implements json.Marshaler. +
+ + + + + + +func (s Sample) String() string+ + + + + + +
func (s *Sample) UnmarshalJSON(b []byte) error+
+UnmarshalJSON implements json.Unmarshaler. +
+ + + + + + + + +type SamplePair struct { + Timestamp Time + Value SampleValue +}+
+SamplePair pairs a SampleValue with a Timestamp. +
+ + + + + + + + + + + + + + +func (s *SamplePair) Equal(o *SamplePair) bool+
+Equal returns true if this SamplePair and o have equal Values and equal +Timestamps. The sematics of Value equality is defined by SampleValue.Equal. +
+ + + + + + +func (s SamplePair) MarshalJSON() ([]byte, error)+
+MarshalJSON implements json.Marshaler. +
+ + + + + + +func (s SamplePair) String() string+ + + + + + +
func (s *SamplePair) UnmarshalJSON(b []byte) error+
+UnmarshalJSON implements json.Unmarshaler. +
+ + + + + + + + +type SampleStream struct { + Metric Metric `json:"metric"` + Values []SamplePair `json:"values"` +}+
+SampleStream is a stream of Values belonging to an attached COWMetric. +
+ + + + + + + + + + + + + + +func (ss SampleStream) String() string+ + + + + + + + +
type SampleValue float64+
+A SampleValue is a representation of a value for a given sample at a given +time. +
+ + + + + + + + + + + + + + +func (v SampleValue) Equal(o SampleValue) bool+
+Equal returns true if the value of v and o is equal or if both are NaN. Note +that v==o is false if both are NaN. If you want the conventional float +behavior, use == to compare two SampleValues. +
+ + + + + + +func (v SampleValue) MarshalJSON() ([]byte, error)+
+MarshalJSON implements json.Marshaler. +
+ + + + + + +func (v SampleValue) String() string+ + + + + + +
func (v *SampleValue) UnmarshalJSON(b []byte) error+
+UnmarshalJSON implements json.Unmarshaler. +
+ + + + + + + + +type Samples []*Sample+
+Samples is a sortable Sample slice. It implements sort.Interface. +
+ + + + + + + + + + + + + + +func (s Samples) Equal(o Samples) bool+
+Equal compares two sets of samples and returns true if they are equal. +
+ + + + + + +func (s Samples) Len() int+ + + + + + +
func (s Samples) Less(i, j int) bool+
+Less compares first the metrics, then the timestamp. +
+ + + + + + +func (s Samples) Swap(i, j int)+ + + + + + + + +
type Scalar struct { + Value SampleValue `json:"value"` + Timestamp Time `json:"timestamp"` +}+
+Scalar is a scalar value evaluated at the set timestamp. +
+ + + + + + + + + + + + + + +func (s Scalar) MarshalJSON() ([]byte, error)+
+MarshalJSON implements json.Marshaler. +
+ + + + + + +func (s Scalar) String() string+ + + + + + +
func (*Scalar) Type() ValueType+ + + + + + +
func (s *Scalar) UnmarshalJSON(b []byte) error+
+UnmarshalJSON implements json.Unmarshaler. +
+ + + + + + + + +type Silence struct { + ID uint64 `json:"id,omitempty"` + + Matchers []*Matcher `json:"matchers"` + + StartsAt time.Time `json:"startsAt"` + EndsAt time.Time `json:"endsAt"` + + CreatedAt time.Time `json:"createdAt,omitempty"` + CreatedBy string `json:"createdBy"` + Comment string `json:"comment,omitempty"` +}+
+Silence defines the representation of a silence definiton +in the Prometheus eco-system. +
+ + + + + + + + + + + + + + +func (s *Silence) Validate() error+
+Validate returns true iff all fields of the silence have valid values. +
+ + + + + + + + +type String struct { + Value string `json:"value"` + Timestamp Time `json:"timestamp"` +}+
+String is a string value evaluated at the set timestamp. +
+ + + + + + + + + + + + + + +func (s String) MarshalJSON() ([]byte, error)+
+MarshalJSON implements json.Marshaler. +
+ + + + + + +func (s *String) String() string+ + + + + + +
func (*String) Type() ValueType+ + + + + + +
func (s *String) UnmarshalJSON(b []byte) error+
+UnmarshalJSON implements json.Unmarshaler. +
+ + + + + + + + +type Time int64+
+Time is the number of milliseconds since the epoch +(1970-01-01 00:00 UTC) excluding leap seconds. +
+ + + + + + + + + + + + +func Now() Time+
+Now returns the current time as a Time. +
+ + + + + +func TimeFromUnix(t int64) Time+
+TimeFromUnix returns the Time equivalent to the Unix Time t +provided in seconds. +
+ + + + + +func TimeFromUnixNano(t int64) Time+
+TimeFromUnixNano returns the Time equivalent to the Unix Time +t provided in nanoseconds. +
+ + + + + + + +func (t Time) Add(d time.Duration) Time+
+Add returns the Time t + d. +
+ + + + + + +func (t Time) After(o Time) bool+
+After reports whether the Time t is after o. +
+ + + + + + +func (t Time) Before(o Time) bool+
+Before reports whether the Time t is before o. +
+ + + + + + +func (t Time) Equal(o Time) bool+
+Equal reports whether two Times represent the same instant. +
+ + + + + + +func (t Time) MarshalJSON() ([]byte, error)+
+MarshalJSON implements the json.Marshaler interface. +
+ + + + + + +func (t Time) String() string+
+String returns a string representation of the Time. +
+ + + + + + +func (t Time) Sub(o Time) time.Duration+
+Sub returns the Duration t - o. +
+ + + + + + +func (t Time) Time() time.Time+
+Time returns the time.Time representation of t. +
+ + + + + + +func (t Time) Unix() int64+
+Unix returns t as a Unix time, the number of seconds elapsed +since January 1, 1970 UTC. +
+ + + + + + +func (t Time) UnixNano() int64+
+UnixNano returns t as a Unix time, the number of nanoseconds elapsed +since January 1, 1970 UTC. +
+ + + + + + +func (t *Time) UnmarshalJSON(b []byte) error+
+UnmarshalJSON implements the json.Unmarshaler interface. +
+ + + + + + + + +type Value interface { + Type() ValueType + String() string +}+
+Value is a generic interface for values resulting from a query evaluation. +
+ + + + + + + + + + + + + + + + +type ValueType int+ + + +
const ( + ValNone ValueType = iota + ValScalar + ValVector + ValMatrix + ValString +)+ + + + + + + + + + + + + +
func (et ValueType) MarshalJSON() ([]byte, error)+
+MarshalJSON implements json.Marshaler. +
+ + + + + + +func (e ValueType) String() string+ + + + + + +
func (et *ValueType) UnmarshalJSON(b []byte) error+ + + + + + + + +
type Vector []*Sample+
+Vector is basically only an alias for Samples, but the +contract is that in a Vector, all Samples have the same timestamp. +
+ + + + + + + + + + + + + + +func (vec Vector) Equal(o Vector) bool+
+Equal compares two sets of samples and returns true if they are equal. +
+ + + + + + +func (vec Vector) Len() int+ + + + + + +
func (vec Vector) Less(i, j int) bool+
+Less compares first the metrics, then the timestamp. +
+ + + + + + +func (vec Vector) String() string+ + + + + + +
func (vec Vector) Swap(i, j int)+ + + + + + +
func (Vector) Type() ValueType+ + + + + + + + + + + + + + + + + + +
Name | +Synopsis | +
---|---|
.. | +|
+ client_golang + | ++ + | +
+ api + | ++ + | +
+ prometheus + | ++ Package prometheus provides bindings to the Prometheus HTTP API: http://prometheus.io/docs/querying/api/ + | +
+ examples + | ++ + | +
+ random + | ++ A simple example exposing fictional RPC latencies with different types of random distributions (uniform, normal, and exponential) as Prometheus metrics. + | +
+ simple + | ++ A minimal example of how to include Prometheus instrumentation. + | +
+ prometheus + | ++ Package prometheus provides metrics primitives to instrument code for monitoring. + | +
+ promhttp + | ++ Package promhttp contains functions to create http.Handler instances to expose Prometheus metrics via HTTP. + | +
+ push + | ++ Package push provides functions to push metrics to a Pushgateway. + | +
+ client_model + | ++ + | +
+ go + | ++ Package io_prometheus_client is a generated protocol buffer package. + | +
+ common + | ++ + | +
+ expfmt + | ++ A package for reading and writing Prometheus metrics. + | +
+ model + | ++ Package model contains common data structures that are shared across Prometheus components and libraries. + | +
+ procfs + | ++ Package procfs provides functions to retrieve system, kernel and process metrics from the pseudo-filesystem proc. + | +
const DefaultMountPoint = "/proc"
+ +DefaultMountPoint is the common mount point of the proc filesystem. +
+ + + + + + + +func NewIPVSBackendStatus() ([]IPVSBackendStatus, error)+
+NewIPVSBackendStatus reads and returns the status of all (virtual,real) server pairs. +
+ + + + + + + + +type FS string+
+FS represents the pseudo-filesystem proc, which provides an interface to +kernel data structures. +
+ + + + + + + + + + + + +func NewFS(mountPoint string) (FS, error)+
+NewFS returns a new FS mounted under the given mountPoint. It will error +if the mount point can't be read. +
+ + + + + + + +func (fs FS) AllProcs() (Procs, error)+
+AllProcs returns a list of all currently available processes. +
+ + + + + + +func (fs FS) NewIPVSBackendStatus() ([]IPVSBackendStatus, error)+
+NewIPVSBackendStatus reads and returns the status of all (virtual,real) server pairs from the specified `proc` filesystem. +
+ + + + + + +func (fs FS) NewIPVSStats() (IPVSStats, error)+
+NewIPVSStats reads the IPVS statistics from the specified `proc` filesystem. +
+ + + + + + +func (fs FS) NewProc(pid int) (Proc, error)+
+NewProc returns a process for the given pid. +
+ + + + + + +func (fs FS) NewStat() (Stat, error)+
+NewStat returns an information about current kernel/system statistics. +
+ + + + + + +func (fs FS) ParseMDStat() (mdstates []MDStat, err error)+
+ParseMDStat parses an mdstat-file and returns a struct with the relevant infos. +
+ + + + + + +func (fs FS) Path(p ...string) string+
+Path returns the path of the given subsystem relative to the procfs root. +
+ + + + + + +func (fs FS) Self() (Proc, error)+
+Self returns a process for the current process. +
+ + + + + + + + +type IPVSBackendStatus struct { + // The local (virtual) IP address. + LocalAddress net.IP + // The local (virtual) port. + LocalPort uint16 + // The transport protocol (TCP, UDP). + Proto string + // The remote (real) IP address. + RemoteAddress net.IP + // The remote (real) port. + RemotePort uint16 + // The current number of active connections for this virtual/real address pair. + ActiveConn uint64 + // The current number of inactive connections for this virtual/real address pair. + InactConn uint64 + // The current weight of this virtual/real address pair. + Weight uint64 +}+
+IPVSBackendStatus holds current metrics of one virtual / real address pair. +
+ + + + + + + + + + + + + + + + +type IPVSStats struct { + // Total count of connections. + Connections uint64 + // Total incoming packages processed. + IncomingPackets uint64 + // Total outgoing packages processed. + OutgoingPackets uint64 + // Total incoming traffic. + IncomingBytes uint64 + // Total outgoing traffic. + OutgoingBytes uint64 +}+
+IPVSStats holds IPVS statistics, as exposed by the kernel in `/proc/net/ip_vs_stats`. +
+ + + + + + + + + + + + +func NewIPVSStats() (IPVSStats, error)+
+NewIPVSStats reads the IPVS statistics. +
+ + + + + + + + + +type MDStat struct { + // Name of the device. + Name string + // activity-state of the device. + ActivityState string + // Number of active disks. + DisksActive int64 + // Total number of disks the device consists of. + DisksTotal int64 + // Number of blocks the device holds. + BlocksTotal int64 + // Number of blocks on the device that are in sync. + BlocksSynced int64 +}+
+MDStat holds info parsed from /proc/mdstat. +
+ + + + + + + + + + + + + + + + +type Proc struct { + // The process ID. + PID int + // contains filtered or unexported fields +}+
+Proc provides information about a running process. +
+ + + + + + + + + + + + +func NewProc(pid int) (Proc, error)+
+NewProc returns a process for the given pid under /proc. +
+ + + + + +func Self() (Proc, error)+
+Self returns a process for the current process read via /proc/self. +
+ + + + + + + +func (p Proc) CmdLine() ([]string, error)+
+CmdLine returns the command line of a process. +
+ + + + + + +func (p Proc) Comm() (string, error)+
+Comm returns the command name of a process. +
+ + + + + + +func (p Proc) Executable() (string, error)+
+Executable returns the absolute path of the executable command of a process. +
+ + + + + + +func (p Proc) FileDescriptorTargets() ([]string, error)+
+FileDescriptorTargets returns the targets of all file descriptors of a process. +If a file descriptor is not a symlink to a file (like a socket), that value will be the empty string. +
+ + + + + + +func (p Proc) FileDescriptors() ([]uintptr, error)+
+FileDescriptors returns the currently open file descriptors of a process. +
+ + + + + + +func (p Proc) FileDescriptorsLen() (int, error)+
+FileDescriptorsLen returns the number of currently open file descriptors of +a process. +
+ + + + + + +func (p Proc) NewIO() (ProcIO, error)+
+NewIO creates a new ProcIO instance from a given Proc instance. +
+ + + + + + +func (p Proc) NewLimits() (ProcLimits, error)+
+NewLimits returns the current soft limits of the process. +
+ + + + + + +func (p Proc) NewStat() (ProcStat, error)+
+NewStat returns the current status information of the process. +
+ + + + + + + + +type ProcIO struct { + // Chars read. + RChar uint64 + // Chars written. + WChar uint64 + // Read syscalls. + SyscR uint64 + // Write syscalls. + SyscW uint64 + // Bytes read. + ReadBytes uint64 + // Bytes written. + WriteBytes uint64 + // Bytes written, but taking into account truncation. See + // Documentation/filesystems/proc.txt in the kernel sources for + // detailed explanation. + CancelledWriteBytes int64 +}+
+ProcIO models the content of /proc/<pid>/io. +
+ + + + + + + + + + + + + + + + +type ProcLimits struct { + // CPU time limit in seconds. + CPUTime int + // Maximum size of files that the process may create. + FileSize int + // Maximum size of the process's data segment (initialized data, + // uninitialized data, and heap). + DataSize int + // Maximum size of the process stack in bytes. + StackSize int + // Maximum size of a core file. + CoreFileSize int + // Limit of the process's resident set in pages. + ResidentSet int + // Maximum number of processes that can be created for the real user ID of + // the calling process. + Processes int + // Value one greater than the maximum file descriptor number that can be + // opened by this process. + OpenFiles int + // Maximum number of bytes of memory that may be locked into RAM. + LockedMemory int + // Maximum size of the process's virtual memory address space in bytes. + AddressSpace int + // Limit on the combined number of flock(2) locks and fcntl(2) leases that + // this process may establish. + FileLocks int + // Limit of signals that may be queued for the real user ID of the calling + // process. + PendingSignals int + // Limit on the number of bytes that can be allocated for POSIX message + // queues for the real user ID of the calling process. + MsqqueueSize int + // Limit of the nice priority set using setpriority(2) or nice(2). + NicePriority int + // Limit of the real-time priority set using sched_setscheduler(2) or + // sched_setparam(2). + RealtimePriority int + // Limit (in microseconds) on the amount of CPU time that a process + // scheduled under a real-time scheduling policy may consume without making + // a blocking system call. + RealtimeTimeout int +}+
+ProcLimits represents the soft limits for each of the process's resource +limits. For more information see getrlimit(2): +http://man7.org/linux/man-pages/man2/getrlimit.2.html. +
+ + + + + + + + + + + + + + + + +type ProcStat struct { + // The process ID. + PID int + // The filename of the executable. + Comm string + // The process state. + State string + // The PID of the parent of this process. + PPID int + // The process group ID of the process. + PGRP int + // The session ID of the process. + Session int + // The controlling terminal of the process. + TTY int + // The ID of the foreground process group of the controlling terminal of + // the process. + TPGID int + // The kernel flags word of the process. + Flags uint + // The number of minor faults the process has made which have not required + // loading a memory page from disk. + MinFlt uint + // The number of minor faults that the process's waited-for children have + // made. + CMinFlt uint + // The number of major faults the process has made which have required + // loading a memory page from disk. + MajFlt uint + // The number of major faults that the process's waited-for children have + // made. + CMajFlt uint + // Amount of time that this process has been scheduled in user mode, + // measured in clock ticks. + UTime uint + // Amount of time that this process has been scheduled in kernel mode, + // measured in clock ticks. + STime uint + // Amount of time that this process's waited-for children have been + // scheduled in user mode, measured in clock ticks. + CUTime uint + // Amount of time that this process's waited-for children have been + // scheduled in kernel mode, measured in clock ticks. + CSTime uint + // For processes running a real-time scheduling policy, this is the negated + // scheduling priority, minus one. + Priority int + // The nice value, a value in the range 19 (low priority) to -20 (high + // priority). + Nice int + // Number of threads in this process. + NumThreads int + // The time the process started after system boot, the value is expressed + // in clock ticks. + Starttime uint64 + // Virtual memory size in bytes. + VSize int + // Resident set size in pages. + RSS int + // contains filtered or unexported fields +}+
+ProcStat provides status information about the process, +read from /proc/[pid]/stat. +
+ + + + + + + + + + + + + + +func (s ProcStat) CPUTime() float64+
+CPUTime returns the total CPU user and system time in seconds. +
+ + + + + + +func (s ProcStat) ResidentMemory() int+
+ResidentMemory returns the resident memory size in bytes. +
+ + + + + + +func (s ProcStat) StartTime() (float64, error)+
+StartTime returns the unix timestamp of the process in seconds. +
+ + + + + + +func (s ProcStat) VirtualMemory() int+
+VirtualMemory returns the virtual memory size in bytes. +
+ + + + + + + + +type Procs []Proc+
+Procs represents a list of Proc structs. +
+ + + + + + + + + + + + +func AllProcs() (Procs, error)+
+AllProcs returns a list of all currently available processes under /proc. +
+ + + + + + + +func (p Procs) Len() int+ + + + + + +
func (p Procs) Less(i, j int) bool+ + + + + + +
func (p Procs) Swap(i, j int)+ + + + + + + + +
type Stat struct { + // Boot time in seconds since the Epoch. + BootTime int64 +}+
+Stat represents kernel/system statistics. +
+ + + + + + + + + + + + +func NewStat() (Stat, error)+
+NewStat returns kernel/system statistics read from /proc/stat. +
+ + + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ leveldb + | ++ Package leveldb provides implementation of LevelDB key/value database. + | +
+ cache + | ++ Package cache provides interface and implementation of a cache algorithms. + | +
+ comparer + | ++ Package comparer provides interface and implementation for ordering sets of data. + | +
+ errors + | ++ Package errors provides common error types used throughout leveldb. + | +
+ filter + | ++ Package filter provides interface and implementation of probabilistic data structure. + | +
+ iterator + | ++ Package iterator provides interface and implementation to traverse over contents of a database. + | +
+ journal + | ++ Package journal reads and writes sequences of journals. + | +
+ memdb + | ++ Package memdb provides in-memory key/value database implementation. + | +
+ opt + | ++ Package opt provides sets of options used by LevelDB. + | +
+ storage + | ++ Package storage provides storage abstraction for LevelDB. + | +
+ table + | ++ Package table allows read and write sorted key/value. + | +
+ testutil + | ++ + | +
+ util + | ++ Package util provides utilities used throughout leveldb. + | +
type Cache struct {
+ // contains filtered or unexported fields
+}
+ +Cache is a 'cache map'. +
+ + + + + + + + + + + + +func NewCache(cacher Cacher) *Cache+
+NewCache creates a new 'cache map'. The cacher is optional and +may be nil. +
+ + + + + + + +func (r *Cache) Capacity() int+
+Capacity returns cache capacity. +
+ + + + + + +func (r *Cache) Close() error+
+Close closes the 'cache map' and forcefully releases all 'cache node'. +
+ + + + + + +func (r *Cache) CloseWeak() error+
+CloseWeak closes the 'cache map' and evict all 'cache node' from cacher, but +unlike Close it doesn't forcefully releases 'cache node'. +
+ + + + + + +func (r *Cache) Delete(ns, key uint64, onDel func()) bool+
+Delete removes and ban 'cache node' with the given namespace and key. +A banned 'cache node' will never inserted into the 'cache tree'. Ban +only attributed to the particular 'cache node', so when a 'cache node' +is recreated it will not be banned. +
++If onDel is not nil, then it will be executed if such 'cache node' +doesn't exist or once the 'cache node' is released. +
++Delete return true is such 'cache node' exist. +
+ + + + + + +func (r *Cache) Evict(ns, key uint64) bool+
+Evict evicts 'cache node' with the given namespace and key. This will +simply call Cacher.Evict. +
++Evict return true is such 'cache node' exist. +
+ + + + + + +func (r *Cache) EvictAll()+
+EvictAll evicts all 'cache node'. This will simply call Cacher.EvictAll. +
+ + + + + + +func (r *Cache) EvictNS(ns uint64)+
+EvictNS evicts 'cache node' with the given namespace. This will +simply call Cacher.EvictNS. +
+ + + + + + +func (r *Cache) Get(ns, key uint64, setFunc func() (size int, value Value)) *Handle+
+Get gets 'cache node' with the given namespace and key. +If cache node is not found and setFunc is not nil, Get will atomically creates +the 'cache node' by calling setFunc. Otherwise Get will returns nil. +
++The returned 'cache handle' should be released after use by calling Release +method. +
+ + + + + + +func (r *Cache) Nodes() int+
+Nodes returns number of 'cache node' in the map. +
+ + + + + + +func (r *Cache) SetCapacity(capacity int)+
+SetCapacity sets cache capacity. +
+ + + + + + +func (r *Cache) Size() int+
+Size returns sums of 'cache node' size in the map. +
+ + + + + + + + +type Cacher interface { + // Capacity returns cache capacity. + Capacity() int + + // SetCapacity sets cache capacity. + SetCapacity(capacity int) + + // Promote promotes the 'cache node'. + Promote(n *Node) + + // Ban evicts the 'cache node' and prevent subsequent 'promote'. + Ban(n *Node) + + // Evict evicts the 'cache node'. + Evict(n *Node) + + // EvictNS evicts 'cache node' with the given namespace. + EvictNS(ns uint64) + + // EvictAll evicts all 'cache node'. + EvictAll() + + // Close closes the 'cache tree' + Close() error +}+
+Cacher provides interface to implements a caching functionality. +An implementation must be safe for concurrent use. +
+ + + + + + + + + + + + +func NewLRU(capacity int) Cacher+
+NewLRU create a new LRU-cache. +
+ + + + + + + + + +type Handle struct {
+ // contains filtered or unexported fields
+}
+ +Handle is a 'cache handle' of a 'cache node'. +
+ + + + + + + + + + + + + + +func (h *Handle) Release()+
+Release releases this 'cache handle'. +It is safe to call release multiple times. +
+ + + + + + +func (h *Handle) Value() Value+
+Value returns the value of the 'cache node'. +
+ + + + + + + + +type NamespaceGetter struct { + Cache *Cache + NS uint64 +}+
+NamespaceGetter provides convenient wrapper for namespace. +
+ + + + + + + + + + + + + + +func (g *NamespaceGetter) Get(key uint64, setFunc func() (size int, value Value)) *Handle+
+Get simply calls Cache.Get() method. +
+ + + + + + + + +type Node struct { + CacheData unsafe.Pointer + // contains filtered or unexported fields +}+
+Node is a 'cache node'. +
+ + + + + + + + + + + + + + +func (n *Node) GetHandle() *Handle+
+GetHandle returns an handle for this 'cache node'. +
+ + + + + + +func (n *Node) Key() uint64+
+Key returns this 'cache node' key. +
+ + + + + + +func (n *Node) NS() uint64+
+NS returns this 'cache node' namespace. +
+ + + + + + +func (n *Node) Ref() int32+
+Ref returns this 'cache node' ref counter. +
+ + + + + + +func (n *Node) Size() int+
+Size returns this 'cache node' size. +
+ + + + + + +func (n *Node) Value() Value+
+Value returns this 'cache node' value. +
+ + + + + + + + +type Value interface{}+
+Value is a 'cacheable object'. It may implements util.Releaser, if +so the the Release method will be called once object is released. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +var DefaultComparer = bytesComparer{}
+ +DefaultComparer are default implementation of the Comparer interface. +It uses the natural ordering, consistent with bytes.Compare. +
+ + + + + + + +type BasicComparer interface { + // Compare returns -1, 0, or +1 depending on whether a is 'less than', + // 'equal to' or 'greater than' b. The two arguments can only be 'equal' + // if their contents are exactly equal. Furthermore, the empty slice + // must be 'less than' any non-empty slice. + Compare(a, b []byte) int +}+
+BasicComparer is the interface that wraps the basic Compare method. +
+ + + + + + + + + + + + + + + + +type Comparer interface { + BasicComparer + + // Name returns name of the comparer. + // + // The Level-DB on-disk format stores the comparer name, and opening a + // database with a different comparer from the one it was created with + // will result in an error. + // + // An implementation to a new name whenever the comparer implementation + // changes in a way that will cause the relative ordering of any two keys + // to change. + // + // Names starting with "leveldb." are reserved and should not be used + // by any users of this package. + Name() string + + // Separator appends a sequence of bytes x to dst such that a <= x && x < b, + // where 'less than' is consistent with Compare. An implementation should + // return nil if x equal to a. + // + // Either contents of a or b should not by any means modified. Doing so + // may cause corruption on the internal state. + Separator(dst, a, b []byte) []byte + + // Successor appends a sequence of bytes x to dst such that x >= b, where + // 'less than' is consistent with Compare. An implementation should return + // nil if x equal to b. + // + // Contents of b should not by any means modified. Doing so may cause + // corruption on the internal state. + Successor(dst, b []byte) []byte +}+
+Comparer defines a total ordering over the space of []byte keys: a 'less +than' relationship. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +var ( + ErrNotFound = New("leveldb: not found") + ErrReleased = util.ErrReleased + ErrHasReleaser = util.ErrHasReleaser +)+
+Common errors. +
+ + + + + + +func IsCorrupted(err error) bool+
+IsCorrupted returns a boolean indicating whether the error is indicating +a corruption. +
+ + + + + + + +func New(text string) error+
+New returns an error that formats as the given text. +
+ + + + + + + +func NewErrCorrupted(fd storage.FileDesc, err error) error+
+NewErrCorrupted creates new ErrCorrupted error. +
+ + + + + + + +func SetFd(err error, fd storage.FileDesc) error+
+SetFd sets 'file info' of the given error with the given file. +Currently only ErrCorrupted is supported, otherwise will do nothing. +
+ + + + + + + + +type ErrCorrupted struct { + Fd storage.FileDesc + Err error +}+
+ErrCorrupted is the type that wraps errors that indicate corruption in +the database. +
+ + + + + + + + + + + + + + +func (e *ErrCorrupted) Error() string+ + + + + + + + +
type ErrMissingFiles struct { + Fds []storage.FileDesc +}+
+ErrMissingFiles is the type that indicating a corruption due to missing +files. ErrMissingFiles always wrapped with ErrCorrupted. +
+ + + + + + + + + + + + + + +func (e *ErrMissingFiles) Error() string+ + + + + + + + + + + + + + + + + + +
type Buffer interface { + // Alloc allocs n bytes of slice from the buffer. This also advancing + // write offset. + Alloc(n int) []byte + + // Write appends the contents of p to the buffer. + Write(p []byte) (n int, err error) + + // WriteByte appends the byte c to the buffer. + WriteByte(c byte) error +}+
+Buffer is the interface that wraps basic Alloc, Write and WriteByte methods. +
+ + + + + + + + + + + + + + + + +type Filter interface { + // Name returns the name of this policy. + // + // Note that if the filter encoding changes in an incompatible way, + // the name returned by this method must be changed. Otherwise, old + // incompatible filters may be passed to methods of this type. + Name() string + + // NewGenerator creates a new filter generator. + NewGenerator() FilterGenerator + + // Contains returns true if the filter contains the given key. + // + // The filter are filters generated by the filter generator. + Contains(filter, key []byte) bool +}+
+Filter is the filter. +
+ + + + + + + + + + + + +func NewBloomFilter(bitsPerKey int) Filter+
+NewBloomFilter creates a new initialized bloom filter for given +bitsPerKey. +
++Since bitsPerKey is persisted individually for each bloom filter +serialization, bloom filters are backwards compatible with respect to +changing bitsPerKey. This means that no big performance penalty will +be experienced when changing the parameter. See documentation for +opt.Options.Filter for more information. +
+ + + + + + + + + +type FilterGenerator interface { + // Add adds a key to the filter generator. + // + // The key may become invalid after call to this method end, therefor + // key must be copied if implementation require keeping key for later + // use. The key should not modified directly, doing so may cause + // undefined results. + Add(key []byte) + + // Generate generates filters based on keys passed so far. After call + // to Generate the filter generator maybe resetted, depends on implementation. + Generate(b Buffer) +}+
+FilterGenerator is the filter generator. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +var ( + ErrNotFound = errors.ErrNotFound + ErrReadOnly = errors.New("leveldb: read-only mode") + ErrSnapshotReleased = errors.New("leveldb: snapshot released") + ErrIterReleased = errors.New("leveldb: iterator released") + ErrClosed = errors.New("leveldb: closed") +)+
+Common errors. +
+ + + + + + + +type Batch struct {
+ // contains filtered or unexported fields
+}
+ +Batch is a write batch. +
+ + + + + + + + + + + + + + +func (b *Batch) Delete(key []byte)+
+Delete appends 'delete operation' of the given key to the batch. +It is safe to modify the contents of the argument after Delete returns but +not before. +
+ + + + + + +func (b *Batch) Dump() []byte+
+Dump dumps batch contents. The returned slice can be loaded into the +batch using Load method. +The returned slice is not its own copy, so the contents should not be +modified. +
+ + + + + + +func (b *Batch) Len() int+
+Len returns number of records in the batch. +
+ + + + + + +func (b *Batch) Load(data []byte) error+
+Load loads given slice into the batch. Previous contents of the batch +will be discarded. +The given slice will not be copied and will be used as batch buffer, so +it is not safe to modify the contents of the slice. +
+ + + + + + +func (b *Batch) Put(key, value []byte)+
+Put appends 'put operation' of the given key/value pair to the batch. +It is safe to modify the contents of the argument after Put returns but not +before. +
+ + + + + + +func (b *Batch) Replay(r BatchReplay) error+
+Replay replays batch contents. +
+ + + + + + +func (b *Batch) Reset()+
+Reset resets the batch. +
+ + + + + + + + +type BatchReplay interface { + Put(key, value []byte) + Delete(key []byte) +}+
+BatchReplay wraps basic batch operations. +
+ + + + + + + + + + + + + + + + +type DB struct {
+ // contains filtered or unexported fields
+}
+ +DB is a LevelDB database. +
+ + + + + + + + + + + + +func Open(stor storage.Storage, o *opt.Options) (db *DB, err error)+
+Open opens or creates a DB for the given storage. +The DB will be created if not exist, unless ErrorIfMissing is true. +Also, if ErrorIfExist is true and the DB exist Open will returns +os.ErrExist error. +
++Open will return an error with type of ErrCorrupted if corruption +detected in the DB. Use errors.IsCorrupted to test whether an error is +due to corruption. Corrupted DB can be recovered with Recover function. +
++The returned DB instance is safe for concurrent use. +The DB must be closed after use, by calling Close method. +
+ + + + + +func OpenFile(path string, o *opt.Options) (db *DB, err error)+
+OpenFile opens or creates a DB for the given path. +The DB will be created if not exist, unless ErrorIfMissing is true. +Also, if ErrorIfExist is true and the DB exist OpenFile will returns +os.ErrExist error. +
++OpenFile uses standard file-system backed storage implementation as +described in the leveldb/storage package. +
++OpenFile will return an error with type of ErrCorrupted if corruption +detected in the DB. Use errors.IsCorrupted to test whether an error is +due to corruption. Corrupted DB can be recovered with Recover function. +
++The returned DB instance is safe for concurrent use. +The DB must be closed after use, by calling Close method. +
+ + + + + +func Recover(stor storage.Storage, o *opt.Options) (db *DB, err error)+
+Recover recovers and opens a DB with missing or corrupted manifest files +for the given storage. It will ignore any manifest files, valid or not. +The DB must already exist or it will returns an error. +Also, Recover will ignore ErrorIfMissing and ErrorIfExist options. +
++The returned DB instance is safe for concurrent use. +The DB must be closed after use, by calling Close method. +
+ + + + + +func RecoverFile(path string, o *opt.Options) (db *DB, err error)+
+RecoverFile recovers and opens a DB with missing or corrupted manifest files +for the given path. It will ignore any manifest files, valid or not. +The DB must already exist or it will returns an error. +Also, Recover will ignore ErrorIfMissing and ErrorIfExist options. +
++RecoverFile uses standard file-system backed storage implementation as described +in the leveldb/storage package. +
++The returned DB instance is safe for concurrent use. +The DB must be closed after use, by calling Close method. +
+ + + + + + + +func (db *DB) Close() error+
+Close closes the DB. This will also releases any outstanding snapshot, +abort any in-flight compaction and discard open transaction. +
++It is not safe to close a DB until all outstanding iterators are released. +It is valid to call Close multiple times. Other methods should not be +called after the DB has been closed. +
+ + + + + + +func (db *DB) CompactRange(r util.Range) error+
+CompactRange compacts the underlying DB for the given key range. +In particular, deleted and overwritten versions are discarded, +and the data is rearranged to reduce the cost of operations +needed to access the data. This operation should typically only +be invoked by users who understand the underlying implementation. +
++A nil Range.Start is treated as a key before all keys in the DB. +And a nil Range.Limit is treated as a key after all keys in the DB. +Therefore if both is nil then it will compact entire DB. +
+ + + + + + +func (db *DB) Delete(key []byte, wo *opt.WriteOptions) error+
+Delete deletes the value for the given key. Delete will not returns error if +key doesn't exist. Write merge also applies for Delete, see Write. +
++It is safe to modify the contents of the arguments after Delete returns but +not before. +
+ + + + + + +func (db *DB) Get(key []byte, ro *opt.ReadOptions) (value []byte, err error)+
+Get gets the value for the given key. It returns ErrNotFound if the +DB does not contains the key. +
++The returned slice is its own copy, it is safe to modify the contents +of the returned slice. +It is safe to modify the contents of the argument after Get returns. +
+ + + + + + +func (db *DB) GetProperty(name string) (value string, err error)+
+GetProperty returns value of the given property name. +
++Property names: +
+leveldb.num-files-at-level{n} + Returns the number of files at level 'n'. +leveldb.stats + Returns statistics of the underlying DB. +leveldb.sstables + Returns sstables list for each level. +leveldb.blockpool + Returns block pool stats. +leveldb.cachedblock + Returns size of cached block. +leveldb.openedtables + Returns number of opened tables. +leveldb.alivesnaps + Returns number of alive snapshots. +leveldb.aliveiters + Returns number of alive iterators. ++ + + + + + +
func (db *DB) GetSnapshot() (*Snapshot, error)+
+GetSnapshot returns a latest snapshot of the underlying DB. A snapshot +is a frozen snapshot of a DB state at a particular point in time. The +content of snapshot are guaranteed to be consistent. +
++The snapshot must be released after use, by calling Release method. +
+ + + + + + +func (db *DB) Has(key []byte, ro *opt.ReadOptions) (ret bool, err error)+
+Has returns true if the DB does contains the given key. +
++It is safe to modify the contents of the argument after Get returns. +
+ + + + + + +func (db *DB) NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator+
+NewIterator returns an iterator for the latest snapshot of the +underlying DB. +The returned iterator is not safe for concurrent use, but it is safe to use +multiple iterators concurrently, with each in a dedicated goroutine. +It is also safe to use an iterator concurrently with modifying its +underlying DB. The resultant key/value pairs are guaranteed to be +consistent. +
++Slice allows slicing the iterator to only contains keys in the given +range. A nil Range.Start is treated as a key before all keys in the +DB. And a nil Range.Limit is treated as a key after all keys in +the DB. +
++The iterator must be released after use, by calling Release method. +
++Also read Iterator documentation of the leveldb/iterator package. +
+ + + + + + +func (db *DB) OpenTransaction() (*Transaction, error)+
+OpenTransaction opens an atomic DB transaction. Only one transaction can be +opened at a time. Subsequent call to Write and OpenTransaction will be blocked +until in-flight transaction is committed or discarded. +The returned transaction handle is safe for concurrent use. +
++Transaction is expensive and can overwhelm compaction, especially if +transaction size is small. Use with caution. +
++The transaction must be closed once done, either by committing or discarding +the transaction. +Closing the DB will discard open transaction. +
+ + + + + + +func (db *DB) Put(key, value []byte, wo *opt.WriteOptions) error+
+Put sets the value for the given key. It overwrites any previous value +for that key; a DB is not a multi-map. Write merge also applies for Put, see +Write. +
++It is safe to modify the contents of the arguments after Put returns but not +before. +
+ + + + + + +func (db *DB) SetReadOnly() error+
+SetReadOnly makes DB read-only. It will stay read-only until reopened. +
+ + + + + + +func (db *DB) SizeOf(ranges []util.Range) (Sizes, error)+
+SizeOf calculates approximate sizes of the given key ranges. +The length of the returned sizes are equal with the length of the given +ranges. The returned sizes measure storage space usage, so if the user +data compresses by a factor of ten, the returned sizes will be one-tenth +the size of the corresponding user data size. +The results may not include the sizes of recently written data. +
+ + + + + + +func (db *DB) Write(batch *Batch, wo *opt.WriteOptions) error+
+Write apply the given batch to the DB. The batch records will be applied +sequentially. Write might be used concurrently, when used concurrently and +batch is small enough, write will try to merge the batches. Set NoWriteMerge +option to true to disable write merge. +
++It is safe to modify the contents of the arguments after Write returns but +not before. Write will not modify content of the batch. +
+ + + + + + + + +type ErrBatchCorrupted struct { + Reason string +}+
+ErrBatchCorrupted records reason of batch corruption. This error will be +wrapped with errors.ErrCorrupted. +
+ + + + + + + + + + + + + + +func (e *ErrBatchCorrupted) Error() string+ + + + + + + + +
type ErrInternalKeyCorrupted struct { + Ikey []byte + Reason string +}+
+ErrInternalKeyCorrupted records internal key corruption. +
+ + + + + + + + + + + + + + +func (e *ErrInternalKeyCorrupted) Error() string+ + + + + + + + +
type ErrManifestCorrupted struct { + Field string + Reason string +}+
+ErrManifestCorrupted records manifest corruption. This error will be +wrapped with errors.ErrCorrupted. +
+ + + + + + + + + + + + + + +func (e *ErrManifestCorrupted) Error() string+ + + + + + + + +
type Reader interface { + Get(key []byte, ro *opt.ReadOptions) (value []byte, err error) + NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator +}+
+Reader is the interface that wraps basic Get and NewIterator methods. +This interface implemented by both DB and Snapshot. +
+ + + + + + + + + + + + + + + + +type Sizes []int64+
+Sizes is list of size. +
+ + + + + + + + + + + + + + +func (sizes Sizes) Sum() int64+
+Sum returns sum of the sizes. +
+ + + + + + + + +type Snapshot struct {
+ // contains filtered or unexported fields
+}
+ +Snapshot is a DB snapshot. +
+ + + + + + + + + + + + + + +func (snap *Snapshot) Get(key []byte, ro *opt.ReadOptions) (value []byte, err error)+
+Get gets the value for the given key. It returns ErrNotFound if +the DB does not contains the key. +
++The caller should not modify the contents of the returned slice, but +it is safe to modify the contents of the argument after Get returns. +
+ + + + + + +func (snap *Snapshot) Has(key []byte, ro *opt.ReadOptions) (ret bool, err error)+
+Has returns true if the DB does contains the given key. +
++It is safe to modify the contents of the argument after Get returns. +
+ + + + + + +func (snap *Snapshot) NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator+
+NewIterator returns an iterator for the snapshot of the underlying DB. +The returned iterator is not safe for concurrent use, but it is safe to use +multiple iterators concurrently, with each in a dedicated goroutine. +It is also safe to use an iterator concurrently with modifying its +underlying DB. The resultant key/value pairs are guaranteed to be +consistent. +
++Slice allows slicing the iterator to only contains keys in the given +range. A nil Range.Start is treated as a key before all keys in the +DB. And a nil Range.Limit is treated as a key after all keys in +the DB. +
++The iterator must be released after use, by calling Release method. +Releasing the snapshot doesn't mean releasing the iterator too, the +iterator would be still valid until released. +
++Also read Iterator documentation of the leveldb/iterator package. +
+ + + + + + +func (snap *Snapshot) Release()+
+Release releases the snapshot. This will not release any returned +iterators, the iterators would still be valid until released or the +underlying DB is closed. +
++Other methods should not be called after the snapshot has been released. +
+ + + + + + +func (snap *Snapshot) String() string+ + + + + + + + +
type Transaction struct {
+ // contains filtered or unexported fields
+}
+ +Transaction is the transaction handle. +
+ + + + + + + + + + + + + + +func (tr *Transaction) Commit() error+
+Commit commits the transaction. If error is not nil, then the transaction is +not committed, it can then either be retried or discarded. +
++Other methods should not be called after transaction has been committed. +
+ + + + + + +func (tr *Transaction) Delete(key []byte, wo *opt.WriteOptions) error+
+Delete deletes the value for the given key. +Please note that the transaction is not compacted until committed, so if you +writes 10 same keys, then those 10 same keys are in the transaction. +
++It is safe to modify the contents of the arguments after Delete returns. +
+ + + + + + +func (tr *Transaction) Discard()+
+Discard discards the transaction. +
++Other methods should not be called after transaction has been discarded. +
+ + + + + + +func (tr *Transaction) Get(key []byte, ro *opt.ReadOptions) ([]byte, error)+
+Get gets the value for the given key. It returns ErrNotFound if the +DB does not contains the key. +
++The returned slice is its own copy, it is safe to modify the contents +of the returned slice. +It is safe to modify the contents of the argument after Get returns. +
+ + + + + + +func (tr *Transaction) Has(key []byte, ro *opt.ReadOptions) (bool, error)+
+Has returns true if the DB does contains the given key. +
++It is safe to modify the contents of the argument after Has returns. +
+ + + + + + +func (tr *Transaction) NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator+
+NewIterator returns an iterator for the latest snapshot of the transaction. +The returned iterator is not safe for concurrent use, but it is safe to use +multiple iterators concurrently, with each in a dedicated goroutine. +It is also safe to use an iterator concurrently while writes to the +transaction. The resultant key/value pairs are guaranteed to be consistent. +
++Slice allows slicing the iterator to only contains keys in the given +range. A nil Range.Start is treated as a key before all keys in the +DB. And a nil Range.Limit is treated as a key after all keys in +the DB. +
++The iterator must be released after use, by calling Release method. +
++Also read Iterator documentation of the leveldb/iterator package. +
+ + + + + + +func (tr *Transaction) Put(key, value []byte, wo *opt.WriteOptions) error+
+Put sets the value for the given key. It overwrites any previous value +for that key; a DB is not a multi-map. +Please note that the transaction is not compacted until committed, so if you +writes 10 same keys, then those 10 same keys are in the transaction. +
++It is safe to modify the contents of the arguments after Put returns. +
+ + + + + + +func (tr *Transaction) Write(b *Batch, wo *opt.WriteOptions) error+
+Write apply the given batch to the transaction. The batch will be applied +sequentially. +Please note that the transaction is not compacted until committed, so if you +writes 10 same keys, then those 10 same keys are in the transaction. +
++It is safe to modify the contents of the arguments after Write returns. +
+ + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ cache + | ++ Package cache provides interface and implementation of a cache algorithms. + | +
+ comparer + | ++ Package comparer provides interface and implementation for ordering sets of data. + | +
+ errors + | ++ Package errors provides common error types used throughout leveldb. + | +
+ filter + | ++ Package filter provides interface and implementation of probabilistic data structure. + | +
+ iterator + | ++ Package iterator provides interface and implementation to traverse over contents of a database. + | +
+ journal + | ++ Package journal reads and writes sequences of journals. + | +
+ memdb + | ++ Package memdb provides in-memory key/value database implementation. + | +
+ opt + | ++ Package opt provides sets of options used by LevelDB. + | +
+ storage + | ++ Package storage provides storage abstraction for LevelDB. + | +
+ table + | ++ Package table allows read and write sorted key/value. + | +
+ testutil + | ++ + | +
+ util + | ++ Package util provides utilities used throughout leveldb. + | +
var ( + ErrIterReleased = errors.New("leveldb/iterator: iterator released") +)+ + + + + + + +
type Array interface { + BasicArray + + // Index returns key/value pair with index of i. + Index(i int) (key, value []byte) +}+
+Array is the interface that wraps BasicArray and basic Index method. +
+ + + + + + + + + + + + + + + + +type ArrayIndexer interface { + BasicArray + + // Get returns a new data iterator with index of i. + Get(i int) Iterator +}+
+Array is the interface that wraps BasicArray and basic Get method. +
+ + + + + + + + + + + + + + + + +type BasicArray interface { + // Len returns length of the array. + Len() int + + // Search finds smallest index that point to a key that is greater + // than or equal to the given key. + Search(key []byte) int +}+
+BasicArray is the interface that wraps basic Len and Search method. +
+ + + + + + + + + + + + + + + + +type CommonIterator interface { + IteratorSeeker + + // util.Releaser is the interface that wraps basic Release method. + // When called Release will releases any resources associated with the + // iterator. + util.Releaser + + // util.ReleaseSetter is the interface that wraps the basic SetReleaser + // method. + util.ReleaseSetter + + // TODO: Remove this when ready. + Valid() bool + + // Error returns any accumulated error. Exhausting all the key/value pairs + // is not considered to be an error. + Error() error +}+
+CommonIterator is the interface that wraps common iterator methods. +
+ + + + + + + + + + + + + + + + +type ErrorCallbackSetter interface { + // SetErrorCallback allows set an error callback of the corresponding + // iterator. Use nil to clear the callback. + SetErrorCallback(f func(err error)) +}+
+ErrorCallbackSetter is the interface that wraps basic SetErrorCallback +method. +
++ErrorCallbackSetter implemented by indexed and merged iterator. +
+ + + + + + + + + + + + + + + + +type Iterator interface { + CommonIterator + + // Key returns the key of the current key/value pair, or nil if done. + // The caller should not modify the contents of the returned slice, and + // its contents may change on the next call to any 'seeks method'. + Key() []byte + + // Value returns the key of the current key/value pair, or nil if done. + // The caller should not modify the contents of the returned slice, and + // its contents may change on the next call to any 'seeks method'. + Value() []byte +}+
+Iterator iterates over a DB's key/value pairs in key order. +
++When encounter an error any 'seeks method' will return false and will +yield no key/value pairs. The error can be queried by calling the Error +method. Calling Release is still necessary. +
++An iterator must be released after use, but it is not necessary to read +an iterator until exhaustion. +Also, an iterator is not necessarily safe for concurrent use, but it is +safe to use multiple iterators concurrently, with each in a dedicated +goroutine. +
+ + + + + + + + + + + + +func NewArrayIterator(array Array) Iterator+
+NewArrayIterator returns an iterator from the given array. +
+ + + + + +func NewEmptyIterator(err error) Iterator+
+NewEmptyIterator creates an empty iterator. The err parameter can be +nil, but if not nil the given err will be returned by Error method. +
+ + + + + +func NewIndexedIterator(index IteratorIndexer, strict bool) Iterator+
+NewIndexedIterator returns an 'indexed iterator'. An index is iterator +that returns another iterator, a 'data iterator'. A 'data iterator' is the +iterator that contains actual key/value pairs. +
++If strict is true the any 'corruption errors' (i.e errors.IsCorrupted(err) == true) +won't be ignored and will halt 'indexed iterator', otherwise the iterator will +continue to the next 'data iterator'. Corruption on 'index iterator' will not be +ignored and will halt the iterator. +
+ + + + + +func NewMergedIterator(iters []Iterator, cmp comparer.Comparer, strict bool) Iterator+
+NewMergedIterator returns an iterator that merges its input. Walking the +resultant iterator will return all key/value pairs of all input iterators +in strictly increasing key order, as defined by cmp. +The input's key ranges may overlap, but there are assumed to be no duplicate +keys: if iters[i] contains a key k then iters[j] will not contain that key k. +None of the iters may be nil. +
++If strict is true the any 'corruption errors' (i.e errors.IsCorrupted(err) == true) +won't be ignored and will halt 'merged iterator', otherwise the iterator will +continue to the next 'input iterator'. +
+ + + + + + + + + +type IteratorIndexer interface { + CommonIterator + + // Get returns a new data iterator for the current position, or nil if + // done. + Get() Iterator +}+
+IteratorIndexer is the interface that wraps CommonIterator and basic Get +method. IteratorIndexer provides index for indexed iterator. +
+ + + + + + + + + + + + +func NewArrayIndexer(array ArrayIndexer) IteratorIndexer+
+NewArrayIndexer returns an index iterator from the given array. +
+ + + + + + + + + +type IteratorSeeker interface { + // First moves the iterator to the first key/value pair. If the iterator + // only contains one key/value pair then First and Last would moves + // to the same key/value pair. + // It returns whether such pair exist. + First() bool + + // Last moves the iterator to the last key/value pair. If the iterator + // only contains one key/value pair then First and Last would moves + // to the same key/value pair. + // It returns whether such pair exist. + Last() bool + + // Seek moves the iterator to the first key/value pair whose key is greater + // than or equal to the given key. + // It returns whether such pair exist. + // + // It is safe to modify the contents of the argument after Seek returns. + Seek(key []byte) bool + + // Next moves the iterator to the next key/value pair. + // It returns whether the iterator is exhausted. + Next() bool + + // Prev moves the iterator to the previous key/value pair. + // It returns whether the iterator is exhausted. + Prev() bool +}+
+IteratorSeeker is the interface that wraps the 'seeks method'. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +type Dropper interface { + Drop(err error) +}+
+Dropper is the interface that wrap simple Drop method. The Drop +method will be called when the journal reader dropping a block or chunk. +
+ + + + + + + + + + + + + + + + +type ErrCorrupted struct { + Size int + Reason string +}+
+ErrCorrupted is the error type that generated by corrupted block or chunk. +
+ + + + + + + + + + + + + + +func (e *ErrCorrupted) Error() string+ + + + + + + + +
type Reader struct {
+ // contains filtered or unexported fields
+}
+ +Reader reads journals from an underlying io.Reader. +
+ + + + + + + + + + + + +func NewReader(r io.Reader, dropper Dropper, strict, checksum bool) *Reader+
+NewReader returns a new reader. The dropper may be nil, and if +strict is true then corrupted or invalid chunk will halt the journal +reader entirely. +
+ + + + + + + +func (r *Reader) Next() (io.Reader, error)+
+Next returns a reader for the next journal. It returns io.EOF if there are no +more journals. The reader returned becomes stale after the next Next call, +and should no longer be used. If strict is false, the reader will returns +io.ErrUnexpectedEOF error when found corrupted journal. +
+ + + + + + +func (r *Reader) Reset(reader io.Reader, dropper Dropper, strict, checksum bool) error+
+Reset resets the journal reader, allows reuse of the journal reader. Reset returns +last accumulated error. +
+ + + + + + + + +type Writer struct {
+ // contains filtered or unexported fields
+}
+ +Writer writes journals to an underlying io.Writer. +
+ + + + + + + + + + + + +func NewWriter(w io.Writer) *Writer+
+NewWriter returns a new Writer. +
+ + + + + + + +func (w *Writer) Close() error+
+Close finishes the current journal and closes the writer. +
+ + + + + + +func (w *Writer) Flush() error+
+Flush finishes the current journal, writes to the underlying writer, and +flushes it if that writer implements interface{ Flush() error }. +
+ + + + + + +func (w *Writer) Next() (io.Writer, error)+
+Next returns a writer for the next journal. The writer returned becomes stale +after the next Close, Flush or Next call, and should no longer be used. +
+ + + + + + +func (w *Writer) Reset(writer io.Writer) (err error)+
+Reset resets the journal writer, allows reuse of the journal writer. Reset +will also closes the journal writer if not already. +
+ + + + + + + + + + + + + + + + + + +var ( + ErrNotFound = errors.ErrNotFound + ErrIterReleased = errors.New("leveldb/memdb: iterator released") +)+
+Common errors. +
+ + + + + + + +type DB struct {
+ // contains filtered or unexported fields
+}
+ +DB is an in-memory key/value database. +
+ + + + + + + + + + + + +func New(cmp comparer.BasicComparer, capacity int) *DB+
+New creates a new initialized in-memory key/value DB. The capacity +is the initial key/value buffer capacity. The capacity is advisory, +not enforced. +
++This DB is append-only, deleting an entry would remove entry node but not +reclaim KV buffer. +
++The returned DB instance is safe for concurrent use. +
+ + + + + + + +func (p *DB) Capacity() int+
+Capacity returns keys/values buffer capacity. +
+ + + + + + +func (p *DB) Contains(key []byte) bool+
+Contains returns true if the given key are in the DB. +
++It is safe to modify the contents of the arguments after Contains returns. +
+ + + + + + +func (p *DB) Delete(key []byte) error+
+Delete deletes the value for the given key. It returns ErrNotFound if +the DB does not contain the key. +
++It is safe to modify the contents of the arguments after Delete returns. +
+ + + + + + +func (p *DB) Find(key []byte) (rkey, value []byte, err error)+
+Find finds key/value pair whose key is greater than or equal to the +given key. It returns ErrNotFound if the table doesn't contain +such pair. +
++The caller should not modify the contents of the returned slice, but +it is safe to modify the contents of the argument after Find returns. +
+ + + + + + +func (p *DB) Free() int+
+Free returns keys/values free buffer before need to grow. +
+ + + + + + +func (p *DB) Get(key []byte) (value []byte, err error)+
+Get gets the value for the given key. It returns error.ErrNotFound if the +DB does not contain the key. +
++The caller should not modify the contents of the returned slice, but +it is safe to modify the contents of the argument after Get returns. +
+ + + + + + +func (p *DB) Len() int+
+Len returns the number of entries in the DB. +
+ + + + + + +func (p *DB) NewIterator(slice *util.Range) iterator.Iterator+
+NewIterator returns an iterator of the DB. +The returned iterator is not safe for concurrent use, but it is safe to use +multiple iterators concurrently, with each in a dedicated goroutine. +It is also safe to use an iterator concurrently with modifying its +underlying DB. However, the resultant key/value pairs are not guaranteed +to be a consistent snapshot of the DB at a particular point in time. +
++Slice allows slicing the iterator to only contains keys in the given +range. A nil Range.Start is treated as a key before all keys in the +DB. And a nil Range.Limit is treated as a key after all keys in +the DB. +
++The iterator must be released after use, by calling Release method. +
++Also read Iterator documentation of the leveldb/iterator package. +
+ + + + + + +func (p *DB) Put(key []byte, value []byte) error+
+Put sets the value for the given key. It overwrites any previous value +for that key; a DB is not a multi-map. +
++It is safe to modify the contents of the arguments after Put returns. +
+ + + + + + +func (p *DB) Reset()+
+Reset resets the DB to initial empty state. Allows reuse the buffer. +
+ + + + + + +func (p *DB) Size() int+
+Size returns sum of keys and values length. Note that deleted +key/value will not be accounted for, but it will still consume +the buffer, since the buffer is append only. +
+ + + + + + + + + + + + + + + + + + +const ( + KiB = 1024 + MiB = KiB * 1024 + GiB = MiB * 1024 +)+ + + + +
var ( + DefaultBlockCacher = LRUCacher + DefaultBlockCacheCapacity = 8 * MiB + DefaultBlockRestartInterval = 16 + DefaultBlockSize = 4 * KiB + DefaultCompactionExpandLimitFactor = 25 + DefaultCompactionGPOverlapsFactor = 10 + DefaultCompactionL0Trigger = 4 + DefaultCompactionSourceLimitFactor = 1 + DefaultCompactionTableSize = 2 * MiB + DefaultCompactionTableSizeMultiplier = 1.0 + DefaultCompactionTotalSize = 10 * MiB + DefaultCompactionTotalSizeMultiplier = 10.0 + DefaultCompressionType = SnappyCompression + DefaultIteratorSamplingRate = 1 * MiB + DefaultOpenFilesCacher = LRUCacher + DefaultOpenFilesCacheCapacity = 500 + DefaultWriteBuffer = 4 * MiB + DefaultWriteL0PauseTrigger = 12 + DefaultWriteL0SlowdownTrigger = 8 +)+ + +
var ( + // LRUCacher is the LRU-cache algorithm. + LRUCacher = &CacherFunc{cache.NewLRU} + + // NoCacher is the value to disable caching algorithm. + NoCacher = &CacherFunc{} +)+ + + + + + +
func GetStrict(o *Options, ro *ReadOptions, strict Strict) bool+ + + + + + + + +
type Cacher interface { + New(capacity int) cache.Cacher +}+
+Cacher is a caching algorithm. +
+ + + + + + + + + + + + + + + + +type CacherFunc struct { + NewFunc func(capacity int) cache.Cacher +}+ + + + + + + + + + + + + + +
func (f *CacherFunc) New(capacity int) cache.Cacher+ + + + + + + + +
type Compression uint+
+Compression is the 'sorted table' block compression algorithm to use. +
+ + + +const ( + DefaultCompression Compression = iota + NoCompression + SnappyCompression +)+ + + + + + + + + + + + + +
func (c Compression) String() string+ + + + + + + + +
type Options struct { + // AltFilters defines one or more 'alternative filters'. + // 'alternative filters' will be used during reads if a filter block + // does not match with the 'effective filter'. + // + // The default value is nil + AltFilters []filter.Filter + + // BlockCacher provides cache algorithm for LevelDB 'sorted table' block caching. + // Specify NoCacher to disable caching algorithm. + // + // The default value is LRUCacher. + BlockCacher Cacher + + // BlockCacheCapacity defines the capacity of the 'sorted table' block caching. + // Use -1 for zero, this has same effect as specifying NoCacher to BlockCacher. + // + // The default value is 8MiB. + BlockCacheCapacity int + + // BlockRestartInterval is the number of keys between restart points for + // delta encoding of keys. + // + // The default value is 16. + BlockRestartInterval int + + // BlockSize is the minimum uncompressed size in bytes of each 'sorted table' + // block. + // + // The default value is 4KiB. + BlockSize int + + // CompactionExpandLimitFactor limits compaction size after expanded. + // This will be multiplied by table size limit at compaction target level. + // + // The default value is 25. + CompactionExpandLimitFactor int + + // CompactionGPOverlapsFactor limits overlaps in grandparent (Level + 2) that a + // single 'sorted table' generates. + // This will be multiplied by table size limit at grandparent level. + // + // The default value is 10. + CompactionGPOverlapsFactor int + + // CompactionL0Trigger defines number of 'sorted table' at level-0 that will + // trigger compaction. + // + // The default value is 4. + CompactionL0Trigger int + + // CompactionSourceLimitFactor limits compaction source size. This doesn't apply to + // level-0. + // This will be multiplied by table size limit at compaction target level. + // + // The default value is 1. + CompactionSourceLimitFactor int + + // CompactionTableSize limits size of 'sorted table' that compaction generates. + // The limits for each level will be calculated as: + // CompactionTableSize * (CompactionTableSizeMultiplier ^ Level) + // The multiplier for each level can also fine-tuned using CompactionTableSizeMultiplierPerLevel. + // + // The default value is 2MiB. + CompactionTableSize int + + // CompactionTableSizeMultiplier defines multiplier for CompactionTableSize. + // + // The default value is 1. + CompactionTableSizeMultiplier float64 + + // CompactionTableSizeMultiplierPerLevel defines per-level multiplier for + // CompactionTableSize. + // Use zero to skip a level. + // + // The default value is nil. + CompactionTableSizeMultiplierPerLevel []float64 + + // CompactionTotalSize limits total size of 'sorted table' for each level. + // The limits for each level will be calculated as: + // CompactionTotalSize * (CompactionTotalSizeMultiplier ^ Level) + // The multiplier for each level can also fine-tuned using + // CompactionTotalSizeMultiplierPerLevel. + // + // The default value is 10MiB. + CompactionTotalSize int + + // CompactionTotalSizeMultiplier defines multiplier for CompactionTotalSize. + // + // The default value is 10. + CompactionTotalSizeMultiplier float64 + + // CompactionTotalSizeMultiplierPerLevel defines per-level multiplier for + // CompactionTotalSize. + // Use zero to skip a level. + // + // The default value is nil. + CompactionTotalSizeMultiplierPerLevel []float64 + + // Comparer defines a total ordering over the space of []byte keys: a 'less + // than' relationship. The same comparison algorithm must be used for reads + // and writes over the lifetime of the DB. + // + // The default value uses the same ordering as bytes.Compare. + Comparer comparer.Comparer + + // Compression defines the 'sorted table' block compression to use. + // + // The default value (DefaultCompression) uses snappy compression. + Compression Compression + + // DisableBufferPool allows disable use of util.BufferPool functionality. + // + // The default value is false. + DisableBufferPool bool + + // DisableBlockCache allows disable use of cache.Cache functionality on + // 'sorted table' block. + // + // The default value is false. + DisableBlockCache bool + + // DisableCompactionBackoff allows disable compaction retry backoff. + // + // The default value is false. + DisableCompactionBackoff bool + + // DisableLargeBatchTransaction allows disabling switch-to-transaction mode + // on large batch write. If enable batch writes large than WriteBuffer will + // use transaction. + // + // The default is false. + DisableLargeBatchTransaction bool + + // ErrorIfExist defines whether an error should returned if the DB already + // exist. + // + // The default value is false. + ErrorIfExist bool + + // ErrorIfMissing defines whether an error should returned if the DB is + // missing. If false then the database will be created if missing, otherwise + // an error will be returned. + // + // The default value is false. + ErrorIfMissing bool + + // Filter defines an 'effective filter' to use. An 'effective filter' + // if defined will be used to generate per-table filter block. + // The filter name will be stored on disk. + // During reads LevelDB will try to find matching filter from + // 'effective filter' and 'alternative filters'. + // + // Filter can be changed after a DB has been created. It is recommended + // to put old filter to the 'alternative filters' to mitigate lack of + // filter during transition period. + // + // A filter is used to reduce disk reads when looking for a specific key. + // + // The default value is nil. + Filter filter.Filter + + // IteratorSamplingRate defines approximate gap (in bytes) between read + // sampling of an iterator. The samples will be used to determine when + // compaction should be triggered. + // + // The default is 1MiB. + IteratorSamplingRate int + + // NoSync allows completely disable fsync. + // + // The default is false. + NoSync bool + + // NoWriteMerge allows disabling write merge. + // + // The default is false. + NoWriteMerge bool + + // OpenFilesCacher provides cache algorithm for open files caching. + // Specify NoCacher to disable caching algorithm. + // + // The default value is LRUCacher. + OpenFilesCacher Cacher + + // OpenFilesCacheCapacity defines the capacity of the open files caching. + // Use -1 for zero, this has same effect as specifying NoCacher to OpenFilesCacher. + // + // The default value is 500. + OpenFilesCacheCapacity int + + // If true then opens DB in read-only mode. + // + // The default value is false. + ReadOnly bool + + // Strict defines the DB strict level. + Strict Strict + + // WriteBuffer defines maximum size of a 'memdb' before flushed to + // 'sorted table'. 'memdb' is an in-memory DB backed by an on-disk + // unsorted journal. + // + // LevelDB may held up to two 'memdb' at the same time. + // + // The default value is 4MiB. + WriteBuffer int + + // WriteL0StopTrigger defines number of 'sorted table' at level-0 that will + // pause write. + // + // The default value is 12. + WriteL0PauseTrigger int + + // WriteL0SlowdownTrigger defines number of 'sorted table' at level-0 that + // will trigger write slowdown. + // + // The default value is 8. + WriteL0SlowdownTrigger int +}+
+Options holds the optional parameters for the DB at large. +
+ + + + + + + + + + + + + + +func (o *Options) GetAltFilters() []filter.Filter+ + + + + + +
func (o *Options) GetBlockCacheCapacity() int+ + + + + + +
func (o *Options) GetBlockCacher() Cacher+ + + + + + +
func (o *Options) GetBlockRestartInterval() int+ + + + + + +
func (o *Options) GetBlockSize() int+ + + + + + +
func (o *Options) GetCompactionExpandLimit(level int) int+ + + + + + +
func (o *Options) GetCompactionGPOverlaps(level int) int+ + + + + + +
func (o *Options) GetCompactionL0Trigger() int+ + + + + + +
func (o *Options) GetCompactionSourceLimit(level int) int+ + + + + + +
func (o *Options) GetCompactionTableSize(level int) int+ + + + + + +
func (o *Options) GetCompactionTotalSize(level int) int64+ + + + + + +
func (o *Options) GetComparer() comparer.Comparer+ + + + + + +
func (o *Options) GetCompression() Compression+ + + + + + +
func (o *Options) GetDisableBlockCache() bool+ + + + + + +
func (o *Options) GetDisableBufferPool() bool+ + + + + + +
func (o *Options) GetDisableCompactionBackoff() bool+ + + + + + +
func (o *Options) GetDisableLargeBatchTransaction() bool+ + + + + + +
func (o *Options) GetErrorIfExist() bool+ + + + + + +
func (o *Options) GetErrorIfMissing() bool+ + + + + + +
func (o *Options) GetFilter() filter.Filter+ + + + + + +
func (o *Options) GetIteratorSamplingRate() int+ + + + + + +
func (o *Options) GetNoSync() bool+ + + + + + +
func (o *Options) GetNoWriteMerge() bool+ + + + + + +
func (o *Options) GetOpenFilesCacheCapacity() int+ + + + + + +
func (o *Options) GetOpenFilesCacher() Cacher+ + + + + + +
func (o *Options) GetReadOnly() bool+ + + + + + +
func (o *Options) GetStrict(strict Strict) bool+ + + + + + +
func (o *Options) GetWriteBuffer() int+ + + + + + +
func (o *Options) GetWriteL0PauseTrigger() int+ + + + + + +
func (o *Options) GetWriteL0SlowdownTrigger() int+ + + + + + + + +
type ReadOptions struct { + // DontFillCache defines whether block reads for this 'read operation' + // should be cached. If false then the block will be cached. This does + // not affects already cached block. + // + // The default value is false. + DontFillCache bool + + // Strict will be OR'ed with global DB 'strict level' unless StrictOverride + // is present. Currently only StrictReader that has effect here. + Strict Strict +}+
+ReadOptions holds the optional parameters for 'read operation'. The +'read operation' includes Get, Find and NewIterator. +
+ + + + + + + + + + + + + + +func (ro *ReadOptions) GetDontFillCache() bool+ + + + + + +
func (ro *ReadOptions) GetStrict(strict Strict) bool+ + + + + + + + +
type Strict uint+
+Strict is the DB 'strict level'. +
+ + + +const ( + // If present then a corrupted or invalid chunk or block in manifest + // journal will cause an error instead of being dropped. + // This will prevent database with corrupted manifest to be opened. + StrictManifest Strict = 1 << iota + + // If present then journal chunk checksum will be verified. + StrictJournalChecksum + + // If present then a corrupted or invalid chunk or block in journal + // will cause an error instead of being dropped. + // This will prevent database with corrupted journal to be opened. + StrictJournal + + // If present then 'sorted table' block checksum will be verified. + // This has effect on both 'read operation' and compaction. + StrictBlockChecksum + + // If present then a corrupted 'sorted table' will fails compaction. + // The database will enter read-only mode. + StrictCompaction + + // If present then a corrupted 'sorted table' will halts 'read operation'. + StrictReader + + // If present then leveldb.Recover will drop corrupted 'sorted table'. + StrictRecovery + + // This only applicable for ReadOptions, if present then this ReadOptions + // 'strict level' will override global ones. + StrictOverride + + // StrictAll enables all strict flags. + StrictAll = StrictManifest | StrictJournalChecksum | StrictJournal | StrictBlockChecksum | StrictCompaction | StrictReader | StrictRecovery + + // DefaultStrict is the default strict flags. Specify any strict flags + // will override default strict flags as whole (i.e. not OR'ed). + DefaultStrict = StrictJournalChecksum | StrictBlockChecksum | StrictCompaction | StrictReader + + // NoStrict disables all strict flags. Override default strict flags. + NoStrict = ^StrictAll +)+ + + + + + + + + + + + + + + +
type WriteOptions struct { + // NoWriteMerge allows disabling write merge. + // + // The default is false. + NoWriteMerge bool + + // Sync is whether to sync underlying writes from the OS buffer cache + // through to actual disk, if applicable. Setting Sync can result in + // slower writes. + // + // If false, and the machine crashes, then some recent writes may be lost. + // Note that if it is just the process that crashes (and the machine does + // not) then no writes will be lost. + // + // In other words, Sync being false has the same semantics as a write + // system call. Sync being true means write followed by fsync. + // + // The default value is false. + Sync bool +}+
+WriteOptions holds the optional parameters for 'write operation'. The +'write operation' includes Write, Put and Delete. +
+ + + + + + + + + + + + + + +func (wo *WriteOptions) GetNoWriteMerge() bool+ + + + + + +
func (wo *WriteOptions) GetSync() bool+ + + + + + + + + + + + + + + + + + +
var ( + ErrInvalidFile = errors.New("leveldb/storage: invalid file for argument") + ErrLocked = errors.New("leveldb/storage: already locked") + ErrClosed = errors.New("leveldb/storage: closed") +)+
+Common error. +
+ + + + + + +func FileDescOk(fd FileDesc) bool+
+FileDescOk returns true if fd is a valid 'file descriptor'. +
+ + + + + + + + +type ErrCorrupted struct { + Fd FileDesc + Err error +}+
+ErrCorrupted is the type that wraps errors that indicate corruption of +a file. Package storage has its own type instead of using +errors.ErrCorrupted to prevent circular import. +
+ + + + + + + + + + + + + + +func (e *ErrCorrupted) Error() string+ + + + + + + + +
type FileDesc struct { + Type FileType + Num int64 +}+
+FileDesc is a 'file descriptor'. +
+ + + + + + + + + + + + + + +func (fd FileDesc) String() string+ + + + + + +
func (fd FileDesc) Zero() bool+
+Zero returns true if fd == (FileDesc{}). +
+ + + + + + + + +type FileType int+
+FileType represent a file type. +
+ + + +const ( + TypeManifest FileType = 1 << iota + TypeJournal + TypeTable + TypeTemp + + TypeAll = TypeManifest | TypeJournal | TypeTable | TypeTemp +)+
+File types. +
+ + + + + + + + + + + + + +func (t FileType) String() string+ + + + + + + + +
type Locker interface { + Unlock() +}+
+Locker is the interface that wraps Unlock method. +
+ + + + + + + + + + + + + + + + +type Reader interface { + io.ReadSeeker + io.ReaderAt + io.Closer +}+
+Reader is the interface that groups the basic Read, Seek, ReadAt and Close +methods. +
+ + + + + + + + + + + + + + + + +type Storage interface { + // Lock locks the storage. Any subsequent attempt to call Lock will fail + // until the last lock released. + // Caller should call Unlock method after use. + Lock() (Locker, error) + + // Log logs a string. This is used for logging. + // An implementation may write to a file, stdout or simply do nothing. + Log(str string) + + // SetMeta store 'file descriptor' that can later be acquired using GetMeta + // method. The 'file descriptor' should point to a valid file. + // SetMeta should be implemented in such way that changes should happen + // atomically. + SetMeta(fd FileDesc) error + + // GetMeta returns 'file descriptor' stored in meta. The 'file descriptor' + // can be updated using SetMeta method. + // Returns os.ErrNotExist if meta doesn't store any 'file descriptor', or + // 'file descriptor' point to nonexistent file. + GetMeta() (FileDesc, error) + + // List returns file descriptors that match the given file types. + // The file types may be OR'ed together. + List(ft FileType) ([]FileDesc, error) + + // Open opens file with the given 'file descriptor' read-only. + // Returns os.ErrNotExist error if the file does not exist. + // Returns ErrClosed if the underlying storage is closed. + Open(fd FileDesc) (Reader, error) + + // Create creates file with the given 'file descriptor', truncate if already + // exist and opens write-only. + // Returns ErrClosed if the underlying storage is closed. + Create(fd FileDesc) (Writer, error) + + // Remove removes file with the given 'file descriptor'. + // Returns ErrClosed if the underlying storage is closed. + Remove(fd FileDesc) error + + // Rename renames file from oldfd to newfd. + // Returns ErrClosed if the underlying storage is closed. + Rename(oldfd, newfd FileDesc) error + + // Close closes the storage. + // It is valid to call Close multiple times. Other methods should not be + // called after the storage has been closed. + Close() error +}+
+Storage is the storage. A storage instance must be safe for concurrent use. +
+ + + + + + + + + + + + +func NewMemStorage() Storage+
+NewMemStorage returns a new memory-backed storage implementation. +
+ + + + + +func OpenFile(path string, readOnly bool) (Storage, error)+
+OpenFile returns a new filesytem-backed storage implementation with the given +path. This also acquire a file lock, so any subsequent attempt to open the +same path will fail. +
++The storage must be closed after use, by calling Close method. +
+ + + + + + + + + +type Syncer interface { + // Sync commits the current contents of the file to stable storage. + Sync() error +}+
+Syncer is the interface that wraps basic Sync method. +
+ + + + + + + + + + + + + + + + +type Writer interface { + io.WriteCloser + Syncer +}+
+Writer is the interface that groups the basic Write, Sync and Close +methods. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +var ( + ErrNotFound = errors.ErrNotFound + ErrReaderReleased = errors.New("leveldb/table: reader released") + ErrIterReleased = errors.New("leveldb/table: iterator released") +)+
+Reader errors. +
+ + + + + + + +type ErrCorrupted struct { + Pos int64 + Size int64 + Kind string + Reason string +}+
+ErrCorrupted describes error due to corruption. This error will be wrapped +with errors.ErrCorrupted. +
+ + + + + + + + + + + + + + +func (e *ErrCorrupted) Error() string+ + + + + + + + +
type Reader struct {
+ // contains filtered or unexported fields
+}
+ +Reader is a table reader. +
+ + + + + + + + + + + + +func NewReader(f io.ReaderAt, size int64, fd storage.FileDesc, cache *cache.NamespaceGetter, bpool *util.BufferPool, o *opt.Options) (*Reader, error)+
+NewReader creates a new initialized table reader for the file. +The fi, cache and bpool is optional and can be nil. +
++The returned table reader instance is safe for concurrent use. +
+ + + + + + + +func (r *Reader) Find(key []byte, filtered bool, ro *opt.ReadOptions) (rkey, value []byte, err error)+
+Find finds key/value pair whose key is greater than or equal to the +given key. It returns ErrNotFound if the table doesn't contain +such pair. +If filtered is true then the nearest 'block' will be checked against +'filter data' (if present) and will immediately return ErrNotFound if +'filter data' indicates that such pair doesn't exist. +
++The caller may modify the contents of the returned slice as it is its +own copy. +It is safe to modify the contents of the argument after Find returns. +
+ + + + + + +func (r *Reader) FindKey(key []byte, filtered bool, ro *opt.ReadOptions) (rkey []byte, err error)+
+FindKey finds key that is greater than or equal to the given key. +It returns ErrNotFound if the table doesn't contain such key. +If filtered is true then the nearest 'block' will be checked against +'filter data' (if present) and will immediately return ErrNotFound if +'filter data' indicates that such key doesn't exist. +
++The caller may modify the contents of the returned slice as it is its +own copy. +It is safe to modify the contents of the argument after Find returns. +
+ + + + + + +func (r *Reader) Get(key []byte, ro *opt.ReadOptions) (value []byte, err error)+
+Get gets the value for the given key. It returns errors.ErrNotFound +if the table does not contain the key. +
++The caller may modify the contents of the returned slice as it is its +own copy. +It is safe to modify the contents of the argument after Find returns. +
+ + + + + + +func (r *Reader) NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator+
+NewIterator creates an iterator from the table. +
++Slice allows slicing the iterator to only contains keys in the given +range. A nil Range.Start is treated as a key before all keys in the +table. And a nil Range.Limit is treated as a key after all keys in +the table. +
++The returned iterator is not safe for concurrent use and should be released +after use. +
++Also read Iterator documentation of the leveldb/iterator package. +
+ + + + + + +func (r *Reader) OffsetOf(key []byte) (offset int64, err error)+
+OffsetOf returns approximate offset for the given key. +
++It is safe to modify the contents of the argument after Get returns. +
+ + + + + + +func (r *Reader) Release()+
+Release implements util.Releaser. +It also close the file if it is an io.Closer. +
+ + + + + + + + +type Writer struct {
+ // contains filtered or unexported fields
+}
+ +Writer is a table writer. +
+ + + + + + + + + + + + +func NewWriter(f io.Writer, o *opt.Options) *Writer+
+NewWriter creates a new initialized table writer for the file. +
++Table writer is not safe for concurrent use. +
+ + + + + + + +func (w *Writer) Append(key, value []byte) error+
+Append appends key/value pair to the table. The keys passed must +be in increasing order. +
++It is safe to modify the contents of the arguments after Append returns. +
+ + + + + + +func (w *Writer) BlocksLen() int+
+BlocksLen returns number of blocks written so far. +
+ + + + + + +func (w *Writer) BytesLen() int+
+BytesLen returns number of bytes written so far. +
+ + + + + + +func (w *Writer) Close() error+
+Close will finalize the table. Calling Append is not possible +after Close, but calling BlocksLen, EntriesLen and BytesLen +is still possible. +
+ + + + + + +func (w *Writer) EntriesLen() int+
+EntriesLen returns number of entries added so far. +
+ + + + + + + + + + + + + + + + + + +func AllKeyValueTesting(rnd *rand.Rand, body, setup func(KeyValue) DB, teardown func(DB))+ + + + + + + +
func BytesAfter(b []byte) []byte+ + + + + + + +
func BytesSeparator(a, b []byte) []byte+ + + + + + + +
func Defer(args ...interface{}) bool+ + + + + + + +
func DoDBTesting(t *DBTesting)+ + + + + + + +
func DoIteratorTesting(t *IteratorTesting)+ + + + + + + +
func KeyValueTesting(rnd *rand.Rand, kv KeyValue, p DB, setup func(KeyValue) DB, teardown func(DB))+ + + + + + + +
func Max(x, y int) int+ + + + + + + +
func Min(x, y int) int+ + + + + + + +
func NewRand() *rand.Rand+ + + + + + + +
func RandomIndex(rnd *rand.Rand, n, round int, fn func(i int))+ + + + + + + +
func RandomRange(rnd *rand.Rand, n, round int, fn func(start, limit int))+ + + + + + + +
func RandomSeed() int64+ + + + + + + +
func RunDefer(groups ...string) bool+ + + + + + + +
func RunSuite(t GinkgoTestingT, name string)+ + + + + + + +
func ShuffledIndex(rnd *rand.Rand, n, round int, fn func(i int))+ + + + + + + +
func TestFind(db Find, kv KeyValue)+ + + + + + + +
func TestFindAfterLast(db Find, kv KeyValue)+ + + + + + + +
func TestGet(db Get, kv KeyValue)+ + + + + + + +
func TestHas(db Has, kv KeyValue)+ + + + + + + +
func TestIter(db NewIterator, r *util.Range, kv KeyValue)+ + + + + + + + +
type DB interface{}+ + + + + + + + + + + + + + + + +
type DBAct int+ + + +
const ( + DBNone DBAct = iota + DBPut + DBOverwrite + DBDelete + DBDeleteNA +)+ + + + + + + + + + + + + +
func (a DBAct) String() string+ + + + + + + + +
type DBTesting struct { + Rand *rand.Rand + DB interface { + Get + Put + Delete + } + PostFn func(t *DBTesting) + Deleted, Present KeyValue + Act, LastAct DBAct + ActKey, LastActKey []byte +}+ + + + + + + + + + + + + + +
func (t *DBTesting) Delete(key []byte)+ + + + + + +
func (t *DBTesting) DeleteRandom() bool+ + + + + + +
func (t *DBTesting) Put(key, value []byte)+ + + + + + +
func (t *DBTesting) PutRandom() bool+ + + + + + +
func (t *DBTesting) RandomAct(round int)+ + + + + + +
func (t *DBTesting) TestAll()+ + + + + + +
func (t *DBTesting) TestAllDeleted()+ + + + + + +
func (t *DBTesting) TestAllPresent()+ + + + + + +
func (t *DBTesting) TestDeletedKey(key []byte)+ + + + + + +
func (t *DBTesting) TestPresentKV(key, value []byte)+ + + + + + +
func (t *DBTesting) Text() string+ + + + + + + + +
type Delete interface { + TestDelete(key []byte) error +}+ + + + + + + + + + + + + + + + +
type Find interface { + TestFind(key []byte) (rkey, rvalue []byte, err error) +}+ + + + + + + + + + + + + + + + +
type Get interface { + TestGet(key []byte) (value []byte, err error) +}+ + + + + + + + + + + + + + + + +
type Has interface { + TestHas(key []byte) (ret bool, err error) +}+ + + + + + + + + + + + + + + + +
type IterAct int+ + + +
const ( + IterNone IterAct = iota + IterFirst + IterLast + IterPrev + IterNext + IterSeek + IterSOI + IterEOI +)+ + + + + + + + + + + + + +
func (a IterAct) String() string+ + + + + + + + +
type IteratorTesting struct { + KeyValue + Iter iterator.Iterator + Rand *rand.Rand + PostFn func(t *IteratorTesting) + Pos int + Act, LastAct IterAct + // contains filtered or unexported fields +}+ + + + + + + + + + + + + + +
func (t *IteratorTesting) EOI()+ + + + + + +
func (t *IteratorTesting) First()+ + + + + + +
func (t *IteratorTesting) IsFirst() bool+ + + + + + +
func (t *IteratorTesting) IsLast() bool+ + + + + + +
func (t *IteratorTesting) Last()+ + + + + + +
func (t *IteratorTesting) Next()+ + + + + + +
func (t *IteratorTesting) NextAll()+ + + + + + +
func (t *IteratorTesting) Prev()+ + + + + + +
func (t *IteratorTesting) PrevAll()+ + + + + + +
func (t *IteratorTesting) SOI()+ + + + + + +
func (t *IteratorTesting) Seek(i int)+ + + + + + +
func (t *IteratorTesting) SeekInexact(i int)+ + + + + + +
func (t *IteratorTesting) SeekKey(key []byte)+ + + + + + +
func (t *IteratorTesting) TestKV()+ + + + + + +
func (t *IteratorTesting) Text() string+ + + + + + +
func (t *IteratorTesting) WalkNext(fn func(t *IteratorTesting))+ + + + + + +
func (t *IteratorTesting) WalkPrev(fn func(t *IteratorTesting))+ + + + + + + + +
type KeyValue struct {
+ // contains filtered or unexported fields
+}
+
+
+
+
+
+
+
+
+
+
+
+
+ func KeyValue_BigValue() *KeyValue+ + + + + +
func KeyValue_EmptyKey() *KeyValue+ + + + + +
func KeyValue_EmptyValue() *KeyValue+ + + + + +
func KeyValue_Generate(rnd *rand.Rand, n, incr, minlen, maxlen, vminlen, vmaxlen int) *KeyValue+ + + + + +
func KeyValue_MultipleKeyValue() *KeyValue+ + + + + +
func KeyValue_OneKeyValue() *KeyValue+ + + + + +
func KeyValue_SpecialKey() *KeyValue+ + + + + + + +
func (kv KeyValue) Clone() KeyValue+ + + + + + +
func (kv *KeyValue) Delete(key []byte) (exist bool, value []byte)+ + + + + + +
func (kv *KeyValue) DeleteIndex(i int) bool+ + + + + + +
func (kv KeyValue) Get(key []byte) (i int, exist bool)+ + + + + + +
func (kv KeyValue) GetString(key string) (i int, exist bool)+ + + + + + +
func (kv KeyValue) Index(i int) (key, value []byte)+ + + + + + +
func (kv KeyValue) IndexInexact(i int) (key_, key, value []byte)+ + + + + + +
func (kv KeyValue) IndexOrNil(i int) (key, value []byte)+ + + + + + +
func (kv KeyValue) IndexString(i int) (key, value string)+ + + + + + +
func (kv KeyValue) Iterate(fn func(i int, key, value []byte))+ + + + + + +
func (kv KeyValue) IterateInexact(fn func(i int, key_, key, value []byte))+ + + + + + +
func (kv KeyValue) IterateInexactString(fn func(i int, key_, key, value string))+ + + + + + +
func (kv KeyValue) IterateShuffled(rnd *rand.Rand, fn func(i int, key, value []byte))+ + + + + + +
func (kv KeyValue) IterateShuffledString(rnd *rand.Rand, fn func(i int, key, value string))+ + + + + + +
func (kv KeyValue) IterateString(fn func(i int, key, value string))+ + + + + + +
func (kv KeyValue) KeyAt(i int) []byte+ + + + + + +
func (kv KeyValue) Len() int+ + + + + + +
func (kv *KeyValue) Put(key, value []byte)+ + + + + + +
func (kv *KeyValue) PutString(key, value string)+ + + + + + +
func (kv *KeyValue) PutU(key, value []byte) bool+ + + + + + +
func (kv *KeyValue) PutUString(key, value string) bool+ + + + + + +
func (kv KeyValue) Range(start, limit int) (r util.Range)+ + + + + + +
func (kv KeyValue) Search(key []byte) int+ + + + + + +
func (kv KeyValue) SearchString(key string) int+ + + + + + +
func (kv *KeyValue) Size() int+ + + + + + +
func (kv KeyValue) Slice(start, limit int) KeyValue+ + + + + + +
func (kv KeyValue) SliceKey(start, limit []byte) KeyValue+ + + + + + +
func (kv KeyValue) SliceKeyString(start, limit string) KeyValue+ + + + + + +
func (kv KeyValue) SliceRange(r *util.Range) KeyValue+ + + + + + +
func (kv KeyValue) ValueAt(i int) []byte+ + + + + + + + +
type KeyValueEntry struct {
+ // contains filtered or unexported fields
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ type NewIterator interface { + TestNewIterator(slice *util.Range) iterator.Iterator +}+ + + + + + + + + + + + + + + + +
type Put interface { + TestPut(key []byte, value []byte) error +}+ + + + + + + + + + + + + + + + +
type Storage struct { + storage.Storage + // contains filtered or unexported fields +}+ + + + + + + + + + + + +
func NewStorage() *Storage+ + + + + + + +
func (s *Storage) Close() error+ + + + + + +
func (s *Storage) CloseCheck()+ + + + + + +
func (s *Storage) Counter(m StorageMode, t storage.FileType) (count int, bytes int64)+ + + + + + +
func (s *Storage) Create(fd storage.FileDesc) (w storage.Writer, err error)+ + + + + + +
func (s *Storage) EmulateError(m StorageMode, t storage.FileType, err error)+ + + + + + +
func (s *Storage) EmulateErrorOnce(m StorageMode, t storage.FileType, err error)+ + + + + + +
func (s *Storage) EmulateRandomError(m StorageMode, t storage.FileType, prob float64, err error)+ + + + + + +
func (s *Storage) ForceRemove(fd storage.FileDesc) (err error)+ + + + + + +
func (s *Storage) ForceRename(oldfd, newfd storage.FileDesc) (err error)+ + + + + + +
func (s *Storage) GetMeta() (fd storage.FileDesc, err error)+ + + + + + +
func (s *Storage) List(t storage.FileType) (fds []storage.FileDesc, err error)+ + + + + + +
func (s *Storage) Lock() (l storage.Locker, err error)+ + + + + + +
func (s *Storage) Log(str string)+ + + + + + +
func (s *Storage) OnClose(onClose func() (preserve bool, err error))+ + + + + + +
func (s *Storage) OnLog(onLog func(log string))+ + + + + + +
func (s *Storage) Open(fd storage.FileDesc) (r storage.Reader, err error)+ + + + + + +
func (s *Storage) Release(m StorageMode, t storage.FileType)+ + + + + + +
func (s *Storage) Remove(fd storage.FileDesc) (err error)+ + + + + + +
func (s *Storage) Rename(oldfd, newfd storage.FileDesc) (err error)+ + + + + + +
func (s *Storage) ResetCounter(m StorageMode, t storage.FileType)+ + + + + + +
func (s *Storage) SetMeta(fd storage.FileDesc) error+ + + + + + +
func (s *Storage) Stall(m StorageMode, t storage.FileType)+ + + + + + + + +
type StorageMode int+ + + +
const ( + ModeOpen StorageMode = 1 << iota + ModeCreate + ModeRemove + ModeRename + ModeRead + ModeWrite + ModeSync + ModeClose +)+ + + + + + + + + + + + + + + + + + + + + + + + + +
const MinRead = 512
+ +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. +
+ + + + +var ( + ErrReleased = errors.New("leveldb: resource already relesed") + ErrHasReleaser = errors.New("leveldb: releaser already defined") +)+ + + + + + +
func Hash(data []byte, seed uint32) uint32+
+Hash return hash of the given data. +
+ + + + + + + + +type BasicReleaser struct {
+ // contains filtered or unexported fields
+}
+ +BasicReleaser provides basic implementation of Releaser and ReleaseSetter. +
+ + + + + + + + + + + + + + +func (r *BasicReleaser) Release()+
+Release implements Releaser.Release. +
+ + + + + + +func (r *BasicReleaser) Released() bool+
+Released returns whether Release method already called. +
+ + + + + + +func (r *BasicReleaser) SetReleaser(releaser Releaser)+
+SetReleaser implements ReleaseSetter.SetReleaser. +
+ + + + + + + + +type Buffer struct {
+ // contains filtered or unexported fields
+}
+ +A Buffer is a variable-sized buffer of bytes with Read and Write methods. +The zero value for Buffer is an empty buffer ready to use. +
+ + + + + + + + + + + + +func NewBuffer(buf []byte) *Buffer+
+NewBuffer creates and initializes a new Buffer using buf as its initial +contents. It is intended to prepare a Buffer to read existing data. It +can also be used to size 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 (b *Buffer) Alloc(n int) []byte+
+Alloc allocs n bytes of slice from the buffer, growing the buffer as +needed. If n is negative, Alloc will panic. +If the buffer can't grow it will panic with bytes.ErrTooLarge. +
+ + + + + + +func (b *Buffer) Bytes() []byte+
+Bytes returns a slice of the contents of the unread portion of the buffer; +len(b.Bytes()) == b.Len(). If the caller changes the contents of the +returned slice, the contents of the buffer will change provided there +are no intervening method calls on the Buffer. +
+ + + + + + +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 bytes.ErrTooLarge. +
+ + + + + + +func (b *Buffer) Len() int+
+Len returns the number of bytes of the unread portion of the buffer; +b.Len() == len(b.Bytes()). +
+ + + + + + +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 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. +
+ + + + + + +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. +
+ + + + + + +func (b *Buffer) ReadByte() (c byte, err error)+
+ReadByte reads and returns the next byte from the buffer. +If no byte is available, it returns error io.EOF. +
+ + + + + + +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 (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 bytes.ErrTooLarge. +
+ + + + + + +func (b *Buffer) Reset()+
+Reset resets the buffer so it has no content. +b.Reset() is the same as b.Truncate(0). +
+ + + + + + +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>". +
+ + + + + + +func (b *Buffer) Truncate(n int)+
+Truncate discards all but the first n unread bytes from the buffer. +It panics if n is negative or greater than the length of the buffer. +
+ + + + + + +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 bytes.ErrTooLarge. +
+ + + + + + +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 +bytes.ErrTooLarge. +
+ + + + + + +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 BufferPool struct {
+ // contains filtered or unexported fields
+}
+ +BufferPool is a 'buffer pool'. +
+ + + + + + + + + + + + +func NewBufferPool(baseline int) *BufferPool+
+NewBufferPool creates a new initialized 'buffer pool'. +
+ + + + + + + +func (p *BufferPool) Close()+ + + + + + +
func (p *BufferPool) Get(n int) []byte+
+Get returns buffer with length of n. +
+ + + + + + +func (p *BufferPool) Put(b []byte)+
+Put adds given buffer to the pool. +
+ + + + + + +func (p *BufferPool) String() string+ + + + + + + + +
type CRC uint32+
+CRC is a CRC-32 checksum computed using Castagnoli's polynomial. +
+ + + + + + + + + + + + +func NewCRC(b []byte) CRC+
+NewCRC creates a new crc based on the given bytes. +
+ + + + + + + +func (c CRC) Update(b []byte) CRC+
+Update updates the crc with the given bytes. +
+ + + + + + +func (c CRC) Value() uint32+
+Value returns a masked crc. +
+ + + + + + + + +type NoopReleaser struct{}+ + + + + + + + + + + + + + +
func (NoopReleaser) Release()+ + + + + + + + +
type Range struct { + // Start of the key range, include in the range. + Start []byte + + // Limit of the key range, not include in the range. + Limit []byte +}+
+Range is a key range. +
+ + + + + + + + + + + + +func BytesPrefix(prefix []byte) *Range+
+BytesPrefix returns key range that satisfy the given prefix. +This only applicable for the standard 'bytes comparer'. +
+ + + + + + + + + +type ReleaseSetter interface { + // SetReleaser associates the given releaser to the resources. The + // releaser will be called once coresponding resources released. + // Calling SetReleaser with nil will clear the releaser. + // + // This will panic if a releaser already present or coresponding + // resource is already released. Releaser should be cleared first + // before assigned a new one. + SetReleaser(releaser Releaser) +}+
+ReleaseSetter is the interface that wraps the basic SetReleaser method. +
+ + + + + + + + + + + + + + + + +type Releaser interface { + // Release releases associated resources. Release should always success + // and can be called multipe times without causing error. + Release() +}+
+Releaser is the interface that wraps the basic Release method. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ goleveldb + | ++ + | +
+ leveldb + | ++ Package leveldb provides implementation of LevelDB key/value database. + | +
+ cache + | ++ Package cache provides interface and implementation of a cache algorithms. + | +
+ comparer + | ++ Package comparer provides interface and implementation for ordering sets of data. + | +
+ errors + | ++ Package errors provides common error types used throughout leveldb. + | +
+ filter + | ++ Package filter provides interface and implementation of probabilistic data structure. + | +
+ iterator + | ++ Package iterator provides interface and implementation to traverse over contents of a database. + | +
+ journal + | ++ Package journal reads and writes sequences of journals. + | +
+ memdb + | ++ Package memdb provides in-memory key/value database implementation. + | +
+ opt + | ++ Package opt provides sets of options used by LevelDB. + | +
+ storage + | ++ Package storage provides storage abstraction for LevelDB. + | +
+ table + | ++ Package table allows read and write sorted key/value. + | +
+ testutil + | ++ + | +
+ util + | ++ Package util provides utilities used throughout leveldb. + | +
Name | +Synopsis | +
---|---|
.. | +|
+ x + | ++ + | +
+ net + | ++ + | +
+ context + | ++ Package context defines the Context type, which carries deadlines, cancelation signals, and other request-scoped values across API boundaries and between processes. + | +
+ ctxhttp + | ++ Package ctxhttp provides helper functions for performing context-aware HTTP requests. + | +
+ html + | ++ Package html implements an HTML5-compliant tokenizer and parser. + | +
+ atom + | ++ Package atom provides integer codes (also known as atoms) for a fixed set of frequently occurring HTML strings: tag names and attribute keys such as "p" and "id". + | +
+ charset + | ++ Package charset provides common text encodings for HTML documents. + | +
+ oauth2 + | ++ Package oauth2 provides support for making OAuth2 authorized and authenticated HTTP requests. + | +
+ bitbucket + | ++ Package bitbucket provides constants for using OAuth2 to access Bitbucket. + | +
+ clientcredentials + | ++ Package clientcredentials implements the OAuth2.0 "client credentials" token flow, also known as the "two-legged OAuth 2.0". + | +
+ facebook + | ++ Package facebook provides constants for using OAuth2 to access Facebook. + | +
+ fitbit + | ++ Package fitbit provides constants for using OAuth2 to access the Fitbit API. + | +
+ github + | ++ Package github provides constants for using OAuth2 to access Github. + | +
+ google + | ++ Package google provides support for making OAuth2 authorized and authenticated HTTP requests to Google APIs. + | +
+ hipchat + | ++ Package hipchat provides constants for using OAuth2 to access HipChat. + | +
+ jws + | ++ Package jws provides encoding and decoding utilities for signed JWS messages. + | +
+ jwt + | ++ Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly known as "two-legged OAuth 2.0". + | +
+ linkedin + | ++ Package linkedin provides constants for using OAuth2 to access LinkedIn. + | +
+ microsoft + | ++ Package microsoft provides constants for using OAuth2 to access Windows Live ID. + | +
+ odnoklassniki + | ++ Package odnoklassniki provides constants for using OAuth2 to access Odnoklassniki. + | +
+ paypal + | ++ Package paypal provides constants for using OAuth2 to access PayPal. + | +
+ slack + | ++ Package slack provides constants for using OAuth2 to access Slack. + | +
+ vk + | ++ Package vk provides constants for using OAuth2 to access VK.com. + | +
+ text + | ++ + | +
+ encoding + | ++ Package encoding defines an interface for character encodings, such as Shift JIS and Windows 1252, that can convert to and from UTF-8. + | +
+ charmap + | ++ Package charmap provides simple character encodings such as IBM Code Page 437 and Windows 1252. + | +
+ htmlindex + | ++ Package htmlindex maps character set encoding names to Encodings as recommended by the W3C for use in HTML 5. + | +
+ ianaindex + | ++ Package ianaindex maps names to Encodings as specified by the IANA registry. + | +
+ japanese + | ++ Package japanese provides Japanese encodings such as EUC-JP and Shift JIS. + | +
+ korean + | ++ Package korean provides Korean encodings such as EUC-KR. + | +
+ simplifiedchinese + | ++ Package simplifiedchinese provides Simplified Chinese encodings such as GBK. + | +
+ traditionalchinese + | ++ Package traditionalchinese provides Traditional Chinese encodings such as Big5. + | +
+ unicode + | ++ Package unicode provides Unicode encodings such as UTF-16. + | +
+ utf32 + | ++ Package utf32 provides the UTF-32 Unicode encoding. + | +
+ language + | ++ Package language implements BCP 47 language tags and related functionality. + | +
+ display + | ++ Package display provides display names for languages, scripts and regions in a requested language. + | +
+ runes + | ++ Package runes provide transforms for UTF-8 encoded text. + | +
+ transform + | ++ Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations. + | +
Name | +Synopsis | +
---|---|
.. | +|
+ net + | ++ + | +
+ context + | ++ Package context defines the Context type, which carries deadlines, cancelation signals, and other request-scoped values across API boundaries and between processes. + | +
+ ctxhttp + | ++ Package ctxhttp provides helper functions for performing context-aware HTTP requests. + | +
+ html + | ++ Package html implements an HTML5-compliant tokenizer and parser. + | +
+ atom + | ++ Package atom provides integer codes (also known as atoms) for a fixed set of frequently occurring HTML strings: tag names and attribute keys such as "p" and "id". + | +
+ charset + | ++ Package charset provides common text encodings for HTML documents. + | +
+ oauth2 + | ++ Package oauth2 provides support for making OAuth2 authorized and authenticated HTTP requests. + | +
+ bitbucket + | ++ Package bitbucket provides constants for using OAuth2 to access Bitbucket. + | +
+ clientcredentials + | ++ Package clientcredentials implements the OAuth2.0 "client credentials" token flow, also known as the "two-legged OAuth 2.0". + | +
+ facebook + | ++ Package facebook provides constants for using OAuth2 to access Facebook. + | +
+ fitbit + | ++ Package fitbit provides constants for using OAuth2 to access the Fitbit API. + | +
+ github + | ++ Package github provides constants for using OAuth2 to access Github. + | +
+ google + | ++ Package google provides support for making OAuth2 authorized and authenticated HTTP requests to Google APIs. + | +
+ hipchat + | ++ Package hipchat provides constants for using OAuth2 to access HipChat. + | +
+ jws + | ++ Package jws provides encoding and decoding utilities for signed JWS messages. + | +
+ jwt + | ++ Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly known as "two-legged OAuth 2.0". + | +
+ linkedin + | ++ Package linkedin provides constants for using OAuth2 to access LinkedIn. + | +
+ microsoft + | ++ Package microsoft provides constants for using OAuth2 to access Windows Live ID. + | +
+ odnoklassniki + | ++ Package odnoklassniki provides constants for using OAuth2 to access Odnoklassniki. + | +
+ paypal + | ++ Package paypal provides constants for using OAuth2 to access PayPal. + | +
+ slack + | ++ Package slack provides constants for using OAuth2 to access Slack. + | +
+ vk + | ++ Package vk provides constants for using OAuth2 to access VK.com. + | +
+ text + | ++ + | +
+ encoding + | ++ Package encoding defines an interface for character encodings, such as Shift JIS and Windows 1252, that can convert to and from UTF-8. + | +
+ charmap + | ++ Package charmap provides simple character encodings such as IBM Code Page 437 and Windows 1252. + | +
+ htmlindex + | ++ Package htmlindex maps character set encoding names to Encodings as recommended by the W3C for use in HTML 5. + | +
+ ianaindex + | ++ Package ianaindex maps names to Encodings as specified by the IANA registry. + | +
+ japanese + | ++ Package japanese provides Japanese encodings such as EUC-JP and Shift JIS. + | +
+ korean + | ++ Package korean provides Korean encodings such as EUC-KR. + | +
+ simplifiedchinese + | ++ Package simplifiedchinese provides Simplified Chinese encodings such as GBK. + | +
+ traditionalchinese + | ++ Package traditionalchinese provides Traditional Chinese encodings such as Big5. + | +
+ unicode + | ++ Package unicode provides Unicode encodings such as UTF-16. + | +
+ utf32 + | ++ Package utf32 provides the UTF-32 Unicode encoding. + | +
+ language + | ++ Package language implements BCP 47 language tags and related functionality. + | +
+ display + | ++ Package display provides display names for languages, scripts and regions in a requested language. + | +
+ runes + | ++ Package runes provide transforms for UTF-8 encoded text. + | +
+ transform + | ++ Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations. + | +
func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error)+
+Do sends an HTTP request with the provided http.Client and returns an HTTP response. +If the client is nil, http.DefaultClient is used. +If the context is canceled or times out, ctx.Err() will be returned. +
+ + + + + + + +func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error)+
+Get issues a GET request via the Do function. +
+ + + + + + + +func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error)+
+Head issues a HEAD request via the Do function. +
+ + + + + + + +func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error)+
+Post issues a POST request via the Do function. +
+ + + + + + + +func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error)+
+PostForm issues a POST request via the Do function. +
+ + + + + + + + + + + + + + + + + + +var Canceled = errors.New("context canceled")+
+Canceled is the error returned by Context.Err when the context is canceled. +
+ + +var DeadlineExceeded = errors.New("context deadline exceeded")+
+DeadlineExceeded is the error returned by Context.Err when the context's +deadline passes. +
+ + + + + + + +type CancelFunc func()+
+A CancelFunc tells an operation to abandon its work. +A CancelFunc does not wait for the work to stop. +After the first call, subsequent calls to a CancelFunc do nothing. +
+ + + + + + + + + + + + + + + + +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. + // + // 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 http://blog.golang.org/pipelines for more examples of how to use + // a Done channel for cancelation. + Done() <-chan struct{} + + // Err returns a non-nil error value after Done is closed. Err returns + // Canceled if the context was canceled or DeadlineExceeded if the + // context's deadline passed. No other values for Err are defined. + // After Done is closed, successive calls to Err return the same value. + 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 stores using that key: + // + // // Package user defines a User type that's stored in Contexts. + // package user + // + // import "golang.org/x/net/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 = 0 + // + // // 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 interface{}) interface{} +}+
+A Context carries a deadline, a cancelation signal, and other values across +API boundaries. +
++Context's methods may be called by multiple goroutines simultaneously. +
+ + + + + + + + + + + + +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() 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). TODO is recognized by static analysis tools that determine +whether Contexts are propagated correctly in a program. +
+ + + + + +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. +
+ + + + + +func WithDeadline(parent Context, deadline 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's 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. +
+ + + + + +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
+func WithValue(parent Context, key interface{}, val interface{}) 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. +
+ + + + + + + + + + + + + + + + + +func String(s []byte) string+
+String returns a string whose contents are equal to s. In that sense, it is +equivalent to string(s) but may be more efficient. +
+ + + + + + + + +type Atom uint32+
+Atom is an integer code for a string. The zero value maps to "". +
+ + + +const ( + A Atom = 0x1 + Abbr Atom = 0x4 + Accept Atom = 0x2106 + AcceptCharset Atom = 0x210e + Accesskey Atom = 0x3309 + Action Atom = 0x1f606 + Address Atom = 0x4f307 + Align Atom = 0x1105 + Alt Atom = 0x4503 + Annotation Atom = 0x1670a + AnnotationXml Atom = 0x1670e + Applet Atom = 0x2b306 + Area Atom = 0x2fa04 + Article Atom = 0x38807 + Aside Atom = 0x8305 + Async Atom = 0x7b05 + Audio Atom = 0xa605 + Autocomplete Atom = 0x1fc0c + Autofocus Atom = 0xb309 + Autoplay Atom = 0xce08 + B Atom = 0x101 + Base Atom = 0xd604 + Basefont Atom = 0xd608 + Bdi Atom = 0x1a03 + Bdo Atom = 0xe703 + Bgsound Atom = 0x11807 + Big Atom = 0x12403 + Blink Atom = 0x12705 + Blockquote Atom = 0x12c0a + Body Atom = 0x2f04 + Br Atom = 0x202 + Button Atom = 0x13606 + Canvas Atom = 0x7f06 + Caption Atom = 0x1bb07 + Center Atom = 0x5b506 + Challenge Atom = 0x21f09 + Charset Atom = 0x2807 + Checked Atom = 0x32807 + Cite Atom = 0x3c804 + Class Atom = 0x4de05 + Code Atom = 0x14904 + Col Atom = 0x15003 + Colgroup Atom = 0x15008 + Color Atom = 0x15d05 + Cols Atom = 0x16204 + Colspan Atom = 0x16207 + Command Atom = 0x17507 + Content Atom = 0x42307 + Contenteditable Atom = 0x4230f + Atom = 0x3310b + Controls Atom = 0x18808 + Coords Atom = 0x19406 + Crossorigin Atom = 0x19f0b + Data Atom = 0x44a04 + Datalist Atom = 0x44a08 + Datetime Atom = 0x23c08 + Dd Atom = 0x26702 + Default Atom = 0x8607 + Defer Atom = 0x14b05 + Del Atom = 0x3ef03 + Desc Atom = 0x4db04 + Details Atom = 0x4807 + Dfn Atom = 0x6103 + Dialog Atom = 0x1b06 + Dir Atom = 0x6903 + Dirname Atom = 0x6907 + Disabled Atom = 0x10c08 + Div Atom = 0x11303 + Dl Atom = 0x11e02 + Download Atom = 0x40008 + Draggable Atom = 0x17b09 + Dropzone Atom = 0x39108 + Dt Atom = 0x50902 + Em Atom = 0x6502 + Embed Atom = 0x6505 + Enctype Atom = 0x21107 + Face Atom = 0x5b304 + Fieldset Atom = 0x1b008 + Atom = 0x1b80a + Figure Atom = 0x1cc06 + Font Atom = 0xda04 + Atom = 0x8d06 + For Atom = 0x1d803 + ForeignObject Atom = 0x1d80d + Foreignobject Atom = 0x1e50d + Form Atom = 0x1f204 + Formaction Atom = 0x1f20a + Formenctype Atom = 0x20d0b + Formmethod Atom = 0x2280a + Formnovalidate Atom = 0x2320e + Formtarget Atom = 0x2470a + Frame Atom = 0x9a05 + Frameset Atom = 0x9a08 + H1 Atom = 0x26e02 + H2 Atom = 0x29402 + H3 Atom = 0x2a702 + H4 Atom = 0x2e902 + H5 Atom = 0x2f302 + H6 Atom = 0x50b02 + Head Atom = 0x2d504 + Header Atom = 0x2d506 + Headers Atom = 0x2d507 + Height Atom = 0x25106 + Hgroup Atom = 0x25906 + Hidden Atom = 0x26506 + High Atom = 0x26b04 + Hr Atom = 0x27002 + Href Atom = 0x27004 + Hreflang Atom = 0x27008 + Html Atom = 0x25504 + HttpEquiv Atom = 0x2780a + I Atom = 0x601 + Icon Atom = 0x42204 + Id Atom = 0x8502 + Iframe Atom = 0x29606 + Image Atom = 0x29c05 + Img Atom = 0x2a103 + Input Atom = 0x3e805 + Inputmode Atom = 0x3e809 + Ins Atom = 0x1a803 + Isindex Atom = 0x2a907 + Ismap Atom = 0x2b005 + Itemid Atom = 0x33c06 + Itemprop Atom = 0x3c908 + Itemref Atom = 0x5ad07 + Itemscope Atom = 0x2b909 + Itemtype Atom = 0x2c308 + Kbd Atom = 0x1903 + Keygen Atom = 0x3906 + Keytype Atom = 0x53707 + Kind Atom = 0x10904 + Label Atom = 0xf005 + Lang Atom = 0x27404 + Legend Atom = 0x18206 + Li Atom = 0x1202 + Link Atom = 0x12804 + List Atom = 0x44e04 + Listing Atom = 0x44e07 + Loop Atom = 0xf404 + Low Atom = 0x11f03 + Malignmark Atom = 0x100a + Manifest Atom = 0x5f108 + Map Atom = 0x2b203 + Mark Atom = 0x1604 + Marquee Atom = 0x2cb07 + Math Atom = 0x2d204 + Max Atom = 0x2e103 + Maxlength Atom = 0x2e109 + Media Atom = 0x6e05 + Mediagroup Atom = 0x6e0a + Menu Atom = 0x33804 + Menuitem Atom = 0x33808 + Meta Atom = 0x45d04 + Meter Atom = 0x24205 + Method Atom = 0x22c06 + Mglyph Atom = 0x2a206 + Mi Atom = 0x2eb02 + Min Atom = 0x2eb03 + Minlength Atom = 0x2eb09 + Mn Atom = 0x23502 + Mo Atom = 0x3ed02 + Ms Atom = 0x2bc02 + Mtext Atom = 0x2f505 + Multiple Atom = 0x30308 + Muted Atom = 0x30b05 + Name Atom = 0x6c04 + Atom = 0x3e03 + Nobr Atom = 0x5704 + Noembed Atom = 0x6307 + Noframes Atom = 0x9808 + Noscript Atom = 0x3d208 + Novalidate Atom = 0x2360a + Object Atom = 0x1ec06 + Ol Atom = 0xc902 + Onabort Atom = 0x13a07 + Onafterprint Atom = 0x1c00c + Onautocomplete Atom = 0x1fa0e + Onautocompleteerror Atom = 0x1fa13 + Onbeforeprint Atom = 0x6040d + Onbeforeunload Atom = 0x4e70e + Onblur Atom = 0xaa06 + Oncancel Atom = 0xe908 + Oncanplay Atom = 0x28509 + Oncanplaythrough Atom = 0x28510 + Onchange Atom = 0x3a708 + Onclick Atom = 0x31007 + Onclose Atom = 0x31707 + Atom = 0x32f0d + Oncuechange Atom = 0x3420b + Ondblclick Atom = 0x34d0a + Ondrag Atom = 0x35706 + Ondragend Atom = 0x35709 + Ondragenter Atom = 0x3600b + Ondragleave Atom = 0x36b0b + Ondragover Atom = 0x3760a + Ondragstart Atom = 0x3800b + Ondrop Atom = 0x38f06 + Ondurationchange Atom = 0x39f10 + Onemptied Atom = 0x39609 + Onended Atom = 0x3af07 + Onerror Atom = 0x3b607 + Onfocus Atom = 0x3bd07 + Onhashchange Atom = 0x3da0c + Oninput Atom = 0x3e607 + Oninvalid Atom = 0x3f209 + Onkeydown Atom = 0x3fb09 + Onkeypress Atom = 0x4080a + Onkeyup Atom = 0x41807 + Onlanguagechange Atom = 0x43210 + Onload Atom = 0x44206 + Onloadeddata Atom = 0x4420c + Onloadedmetadata Atom = 0x45510 + Onloadstart Atom = 0x46b0b + Onmessage Atom = 0x47609 + Onmousedown Atom = 0x47f0b + Onmousemove Atom = 0x48a0b + Onmouseout Atom = 0x4950a + Onmouseover Atom = 0x4a20b + Onmouseup Atom = 0x4ad09 + Onmousewheel Atom = 0x4b60c + Onoffline Atom = 0x4c209 + Ononline Atom = 0x4cb08 + Onpagehide Atom = 0x4d30a + Onpageshow Atom = 0x4fe0a + Onpause Atom = 0x50d07 + Onplay Atom = 0x51706 + Onplaying Atom = 0x51709 + Onpopstate Atom = 0x5200a + Onprogress Atom = 0x52a0a + Onratechange Atom = 0x53e0c + Onreset Atom = 0x54a07 + Onresize Atom = 0x55108 + Onscroll Atom = 0x55f08 + Onseeked Atom = 0x56708 + Onseeking Atom = 0x56f09 + Onselect Atom = 0x57808 + Onshow Atom = 0x58206 + Onsort Atom = 0x58b06 + Onstalled Atom = 0x59509 + Onstorage Atom = 0x59e09 + Onsubmit Atom = 0x5a708 + Onsuspend Atom = 0x5bb09 + Ontimeupdate Atom = 0xdb0c + Ontoggle Atom = 0x5c408 + Onunload Atom = 0x5cc08 + Onvolumechange Atom = 0x5d40e + Onwaiting Atom = 0x5e209 + Open Atom = 0x3cf04 + Optgroup Atom = 0xf608 + Optimum Atom = 0x5eb07 + Option Atom = 0x60006 + Output Atom = 0x49c06 + P Atom = 0xc01 + Param Atom = 0xc05 + Pattern Atom = 0x5107 + Ping Atom = 0x7704 + Placeholder Atom = 0xc30b + Plaintext Atom = 0xfd09 + Poster Atom = 0x15706 + Pre Atom = 0x25e03 + Preload Atom = 0x25e07 + Progress Atom = 0x52c08 + Prompt Atom = 0x5fa06 + Public Atom = 0x41e06 + Q Atom = 0x13101 + Radiogroup Atom = 0x30a + Readonly Atom = 0x2fb08 + Rel Atom = 0x25f03 + Required Atom = 0x1d008 + Reversed Atom = 0x5a08 + Rows Atom = 0x9204 + Rowspan Atom = 0x9207 + Rp Atom = 0x1c602 + Rt Atom = 0x13f02 + Ruby Atom = 0xaf04 + S Atom = 0x2c01 + Samp Atom = 0x4e04 + Sandbox Atom = 0xbb07 + Scope Atom = 0x2bd05 + Scoped Atom = 0x2bd06 + Script Atom = 0x3d406 + Seamless Atom = 0x31c08 + Section Atom = 0x4e207 + Select Atom = 0x57a06 + Selected Atom = 0x57a08 + Shape Atom = 0x4f905 + Size Atom = 0x55504 + Sizes Atom = 0x55505 + Small Atom = 0x18f05 + Sortable Atom = 0x58d08 + Sorted Atom = 0x19906 + Source Atom = 0x1aa06 + Spacer Atom = 0x2db06 + Span Atom = 0x9504 + Spellcheck Atom = 0x3230a + Src Atom = 0x3c303 + Srcdoc Atom = 0x3c306 + Srclang Atom = 0x41107 + Start Atom = 0x38605 + Step Atom = 0x5f704 + Strike Atom = 0x53306 + Strong Atom = 0x55906 + Style Atom = 0x61105 + Sub Atom = 0x5a903 + Summary Atom = 0x61607 + Sup Atom = 0x61d03 + Svg Atom = 0x62003 + System Atom = 0x62306 + Tabindex Atom = 0x46308 + Table Atom = 0x42d05 + Target Atom = 0x24b06 + Tbody Atom = 0x2e05 + Td Atom = 0x4702 + Template Atom = 0x62608 + Textarea Atom = 0x2f608 + Tfoot Atom = 0x8c05 + Th Atom = 0x22e02 + Thead Atom = 0x2d405 + Time Atom = 0xdd04 + Title Atom = 0xa105 + Tr Atom = 0x10502 + Track Atom = 0x10505 + Translate Atom = 0x14009 + Tt Atom = 0x5302 + Type Atom = 0x21404 + Typemustmatch Atom = 0x2140d + U Atom = 0xb01 + Ul Atom = 0x8a02 + Usemap Atom = 0x51106 + Value Atom = 0x4005 + Var Atom = 0x11503 + Video Atom = 0x28105 + Wbr Atom = 0x12103 + Width Atom = 0x50705 + Wrap Atom = 0x58704 + Xmp Atom = 0xc103 +)+ + + + + + + + + + + +
func Lookup(s []byte) Atom+
+Lookup returns the atom whose name is s. It returns zero if there is no +such atom. The lookup is case sensitive. +
+ + + + + + + +func (a Atom) String() string+
+String returns the atom's name. +
+ + + + + + + + + + + + + + + + + + +func DetermineEncoding(content []byte, contentType string) (e encoding.Encoding, name string, certain bool)+
+DetermineEncoding determines the encoding of an HTML document by examining +up to the first 1024 bytes of content and the declared Content-Type. +
+ + + + + + + + +func Lookup(label string) (e encoding.Encoding, name string)+
+Lookup returns the encoding with the specified label, and its canonical +name. It returns nil and the empty string if label is not one of the +standard encodings for HTML. Matching is case-insensitive and ignores +leading and trailing whitespace. Encoders will use HTML escape sequences for +runes that are not supported by the character set. +
+ + + + + + + +func NewReader(r io.Reader, contentType string) (io.Reader, error)+
+NewReader returns an io.Reader that converts the content of r to UTF-8. +It calls DetermineEncoding to find out what r's encoding is. +
+ + + + + + + +func NewReaderLabel(label string, input io.Reader) (io.Reader, error)+
+NewReaderLabel returns a reader that converts from the specified charset to +UTF-8. It uses Lookup to find the encoding that corresponds to label, and +returns an error if Lookup returns nil. It is suitable for use as +encoding/xml.Decoder's CharsetReader function. +
+ + + + + + + + + + + + + + + + + + +var ErrBufferExceeded = errors.New("max buffer exceeded")+
+ErrBufferExceeded means that the buffering limit was exceeded. +
+ + + + + + +func EscapeString(s string) string+
+EscapeString escapes special characters like "<" to become "<". It +escapes only five such characters: <, >, &, ' and ". +UnescapeString(EscapeString(s)) == s always holds, but the converse isn't +always true. +
+ + + + + + + +func ParseFragment(r io.Reader, context *Node) ([]*Node, error)+
+ParseFragment parses a fragment of HTML and returns the nodes that were +found. If the fragment is the InnerHTML for an existing element, pass that +element in context. +
+ + + + + + + +func Render(w io.Writer, n *Node) error+
+Render renders the parse tree n to the given writer. +
++Rendering is done on a 'best effort' basis: calling Parse on the output of +Render will always result in something similar to the original tree, but it +is not necessarily an exact clone unless the original tree was 'well-formed'. +'Well-formed' is not easily specified; the HTML5 specification is +complicated. +
++Calling Parse on arbitrary input typically results in a 'well-formed' parse +tree. However, it is possible for Parse to yield a 'badly-formed' parse tree. +For example, in a 'well-formed' parse tree, no <a> element is a child of +another <a> element: parsing "<a><a>" results in two sibling elements. +Similarly, in a 'well-formed' parse tree, no <a> element is a child of a +<table> element: parsing "<p><table><a>" results in a <p> with two sibling +children; the <a> is reparented to the <table>'s parent. However, calling +Parse on "<a><table><a>" does not return an error, but the result has an <a> +element with an <a> child, and is therefore not 'well-formed'. +
++Programmatically constructed trees are typically also 'well-formed', but it +is possible to construct a tree that looks innocuous but, when rendered and +re-parsed, results in a different tree. A simple example is that a solitary +text node would become a tree containing <html>, <head> and <body> elements. +Another example is that the programmatic equivalent of "a<head>b</head>c" +becomes "<html><head><head/><body>abc</body></html>". +
+ + + + + + + +func UnescapeString(s string) string+
+UnescapeString unescapes entities like "<" to become "<". It unescapes a +larger range of entities than EscapeString escapes. For example, "á" +unescapes to "á", as does "á" and "&xE1;". +UnescapeString(EscapeString(s)) == s always holds, but the converse isn't +always true. +
+ + + + + + + + +type Attribute struct { + Namespace, Key, Val string +}+
+An Attribute is an attribute namespace-key-value triple. Namespace is +non-empty for foreign attributes like xlink, Key is alphabetic (and hence +does not contain escapable characters like '&', '<' or '>'), and Val is +unescaped (it looks like "a<b" rather than "a<b"). +
++Namespace is only used by the parser, not the tokenizer. +
+ + + + + + + + + + + + + + + + +type Node struct { + Parent, FirstChild, LastChild, PrevSibling, NextSibling *Node + + Type NodeType + DataAtom atom.Atom + Data string + Namespace string + Attr []Attribute +}+
+A Node consists of a NodeType and some Data (tag name for element nodes, +content for text) and are part of a tree of Nodes. Element nodes may also +have a Namespace and contain a slice of Attributes. Data is unescaped, so +that it looks like "a<b" rather than "a<b". For element nodes, DataAtom +is the atom for Data, or zero if Data is not a known tag name. +
++An empty Namespace implies a "http://www.w3.org/1999/xhtml" namespace. +Similarly, "math" is short for "http://www.w3.org/1998/Math/MathML", and +"svg" is short for "http://www.w3.org/2000/svg". +
+ + + + + + + + + + + + +func Parse(r io.Reader) (*Node, error)+
+Parse returns the parse tree for the HTML from the given Reader. +The input is assumed to be UTF-8 encoded. +
+ +▹ Example
+func (n *Node) AppendChild(c *Node)+
+AppendChild adds a node c as a child of n. +
++It will panic if c already has a parent or siblings. +
+ + + + + + +func (n *Node) InsertBefore(newChild, oldChild *Node)+
+InsertBefore inserts newChild as a child of n, immediately before oldChild +in the sequence of n's children. oldChild may be nil, in which case newChild +is appended to the end of n's children. +
++It will panic if newChild already has a parent or siblings. +
+ + + + + + +func (n *Node) RemoveChild(c *Node)+
+RemoveChild removes a node c that is a child of n. Afterwards, c will have +no parent and no siblings. +
++It will panic if c's parent is not n. +
+ + + + + + + + +type NodeType uint32+
+A NodeType is the type of a Node. +
+ + + +const ( + ErrorNode NodeType = iota + TextNode + DocumentNode + ElementNode + CommentNode + DoctypeNode +)+ + + + + + + + + + + + + + + +
type Token struct { + Type TokenType + DataAtom atom.Atom + Data string + Attr []Attribute +}+
+A Token consists of a TokenType and some Data (tag name for start and end +tags, content for text, comments and doctypes). A tag Token may also contain +a slice of Attributes. Data is unescaped for all Tokens (it looks like "a<b" +rather than "a<b"). For tag Tokens, DataAtom is the atom for Data, or +zero if Data is not a known tag name. +
+ + + + + + + + + + + + + + +func (t Token) String() string+
+String returns a string representation of the Token. +
+ + + + + + + + +type TokenType uint32+
+A TokenType is the type of a Token. +
+ + + +const ( + // ErrorToken means that an error occurred during tokenization. + ErrorToken TokenType = iota + // TextToken means a text node. + TextToken + // A StartTagToken looks like <a>. + StartTagToken + // An EndTagToken looks like </a>. + EndTagToken + // A SelfClosingTagToken tag looks like <br/>. + SelfClosingTagToken + // A CommentToken looks like <!--x-->. + CommentToken + // A DoctypeToken looks like <!DOCTYPE x> + DoctypeToken +)+ + + + + + + + + + + + + +
func (t TokenType) String() string+
+String returns a string representation of the TokenType. +
+ + + + + + + + +type Tokenizer struct {
+ // contains filtered or unexported fields
+}
+ +A Tokenizer returns a stream of HTML Tokens. +
+ + + + + + + + + + + + +func NewTokenizer(r io.Reader) *Tokenizer+
+NewTokenizer returns a new HTML Tokenizer for the given Reader. +The input is assumed to be UTF-8 encoded. +
+ + + + + +func NewTokenizerFragment(r io.Reader, contextTag string) *Tokenizer+
+NewTokenizerFragment returns a new HTML Tokenizer for the given Reader, for +tokenizing an existing element's InnerHTML fragment. contextTag is that +element's tag, such as "div" or "iframe". +
++For example, how the InnerHTML "a<b" is tokenized depends on whether it is +for a <p> tag or a <script> tag. +
++The input is assumed to be UTF-8 encoded. +
+ + + + + + + +func (z *Tokenizer) AllowCDATA(allowCDATA bool)+
+AllowCDATA sets whether or not the tokenizer recognizes <![CDATA[foo]]> as +the text "foo". The default value is false, which means to recognize it as +a bogus comment "<!-- [CDATA[foo]] -->" instead. +
++Strictly speaking, an HTML5 compliant tokenizer should allow CDATA if and +only if tokenizing foreign content, such as MathML and SVG. However, +tracking foreign-contentness is difficult to do purely in the tokenizer, +as opposed to the parser, due to HTML integration points: an <svg> element +can contain a <foreignObject> that is foreign-to-SVG but not foreign-to- +HTML. For strict compliance with the HTML5 tokenization algorithm, it is the +responsibility of the user of a tokenizer to call AllowCDATA as appropriate. +In practice, if using the tokenizer without caring whether MathML or SVG +CDATA is text or comments, such as tokenizing HTML to find all the anchor +text, it is acceptable to ignore this responsibility. +
+ + + + + + +func (z *Tokenizer) Buffered() []byte+
+Buffered returns a slice containing data buffered but not yet tokenized. +
+ + + + + + +func (z *Tokenizer) Err() error+
+Err returns the error associated with the most recent ErrorToken token. +This is typically io.EOF, meaning the end of tokenization. +
+ + + + + + +func (z *Tokenizer) Next() TokenType+
+Next scans the next token and returns its type. +
+ + + + + + +func (z *Tokenizer) NextIsNotRawText()+
+NextIsNotRawText instructs the tokenizer that the next token should not be +considered as 'raw text'. Some elements, such as script and title elements, +normally require the next token after the opening tag to be 'raw text' that +has no child elements. For example, tokenizing "<title>a<b>c</b>d</title>" +yields a start tag token for "<title>", a text token for "a<b>c</b>d", and +an end tag token for "</title>". There are no distinct start tag or end tag +tokens for the "<b>" and "</b>". +
++This tokenizer implementation will generally look for raw text at the right +times. Strictly speaking, an HTML5 compliant tokenizer should not look for +raw text if in foreign content: <title> generally needs raw text, but a +<title> inside an <svg> does not. Another example is that a <textarea> +generally needs raw text, but a <textarea> is not allowed as an immediate +child of a <select>; in normal parsing, a <textarea> implies </select>, but +one cannot close the implicit element when parsing a <select>'s InnerHTML. +Similarly to AllowCDATA, tracking the correct moment to override raw-text- +ness is difficult to do purely in the tokenizer, as opposed to the parser. +For strict compliance with the HTML5 tokenization algorithm, it is the +responsibility of the user of a tokenizer to call NextIsNotRawText as +appropriate. In practice, like AllowCDATA, it is acceptable to ignore this +responsibility for basic usage. +
++Note that this 'raw text' concept is different from the one offered by the +Tokenizer.Raw method. +
+ + + + + + +func (z *Tokenizer) Raw() []byte+
+Raw returns the unmodified text of the current token. Calling Next, Token, +Text, TagName or TagAttr may change the contents of the returned slice. +
+ + + + + + +func (z *Tokenizer) SetMaxBuf(n int)+
+SetMaxBuf sets a limit on the amount of data buffered during tokenization. +A value of 0 means unlimited. +
+ + + + + + +func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool)+
+TagAttr returns the lower-cased key and unescaped value of the next unparsed +attribute for the current tag token and whether there are more attributes. +The contents of the returned slices may change on the next call to Next. +
+ + + + + + +func (z *Tokenizer) TagName() (name []byte, hasAttr bool)+
+TagName returns the lower-cased name of a tag token (the `img` out of +`<IMG SRC="foo">`) and whether the tag has attributes. +The contents of the returned slice may change on the next call to Next. +
+ + + + + + +func (z *Tokenizer) Text() []byte+
+Text returns the unescaped text of a text, comment or doctype token. The +contents of the returned slice may change on the next call to Next. +
+ + + + + + +func (z *Tokenizer) Token() Token+
+Token returns the next Token. The result's Data and Attr values remain valid +after subsequent Next calls. +
+ + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ atom + | ++ Package atom provides integer codes (also known as atoms) for a fixed set of frequently occurring HTML strings: tag names and attribute keys such as "p" and "id". + | +
+ charset + | ++ Package charset provides common text encodings for HTML documents. + | +
Name | +Synopsis | +
---|---|
.. | +|
+ context + | ++ Package context defines the Context type, which carries deadlines, cancelation signals, and other request-scoped values across API boundaries and between processes. + | +
+ ctxhttp + | ++ Package ctxhttp provides helper functions for performing context-aware HTTP requests. + | +
+ html + | ++ Package html implements an HTML5-compliant tokenizer and parser. + | +
+ atom + | ++ Package atom provides integer codes (also known as atoms) for a fixed set of frequently occurring HTML strings: tag names and attribute keys such as "p" and "id". + | +
+ charset + | ++ Package charset provides common text encodings for HTML documents. + | +
var Endpoint = oauth2.Endpoint{ + AuthURL: "https://bitbucket.org/site/oauth2/authorize", + TokenURL: "https://bitbucket.org/site/oauth2/access_token", +}+
+Endpoint is Bitbucket's OAuth 2.0 endpoint. +
+ + + + + + + + + + + + + + + + + +type Config struct { + // ClientID is the application's ID. + ClientID string + + // ClientSecret is the application's secret. + ClientSecret string + + // TokenURL is the resource server's token endpoint + // URL. This is a constant specific to each server. + TokenURL string + + // Scope specifies optional requested permissions. + Scopes []string +}+
+Client Credentials Config describes a 2-legged OAuth2 flow, with both the +client application information and the server's endpoint URLs. +
+ + + + + + + + + + + + + + +func (c *Config) Client(ctx context.Context) *http.Client+
+Client returns an HTTP client using the provided token. +The token will auto-refresh as necessary. The underlying +HTTP transport will be obtained using the provided context. +The returned client and its Transport should not be modified. +
+ + + + + + +func (c *Config) Token(ctx context.Context) (*oauth2.Token, error)+
+Token uses client credentials to retrieve a token. +The HTTP client to use is derived from the context. +If nil, http.DefaultClient is used. +
+ + + + + + +func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource+
+TokenSource returns a TokenSource that returns t until t expires, +automatically refreshing it as necessary using the provided context and the +client ID and client secret. +
++Most users will use Config.Client instead. +
+ + + + + + + + + + + + + + + + + + +var Endpoint = oauth2.Endpoint{ + AuthURL: "https://www.facebook.com/dialog/oauth", + TokenURL: "https://graph.facebook.com/oauth/access_token", +}+
+Endpoint is Facebook's OAuth 2.0 endpoint. +
+ + + + + + + + + + + + + + + + + +var Endpoint = oauth2.Endpoint{ + AuthURL: "https://www.fitbit.com/oauth2/authorize", + TokenURL: "https://api.fitbit.com/oauth2/token", +}+
+Endpoint is the Fitbit API's OAuth 2.0 endpoint. +
+ + + + + + + + + + + + + + + + + +var Endpoint = oauth2.Endpoint{ + AuthURL: "https://github.com/login/oauth/authorize", + TokenURL: "https://github.com/login/oauth/access_token", +}+
+Endpoint is Github's OAuth 2.0 endpoint. +
+ + + + + + + + + + + + + + + + + +const JWTTokenURL = "https://accounts.google.com/o/oauth2/token"
+ +JWTTokenURL is Google's OAuth 2.0 token URL to use with the JWT flow. +
+ + + + +var Endpoint = oauth2.Endpoint{ + AuthURL: "https://accounts.google.com/o/oauth2/auth", + TokenURL: "https://accounts.google.com/o/oauth2/token", +}+
+Endpoint is Google's OAuth 2.0 endpoint. +
+ + + + + + +func AppEngineTokenSource(ctx context.Context, scope ...string) oauth2.TokenSource+
+AppEngineTokenSource returns a token source that fetches tokens +issued to the current App Engine application's service account. +If you are implementing a 3-legged OAuth 2.0 flow on App Engine +that involves user accounts, see oauth2.Config instead. +
++The provided context must have come from appengine.NewContext. +
+ + + + + + + +func ComputeTokenSource(account string) oauth2.TokenSource+
+ComputeTokenSource returns a token source that fetches access tokens +from Google Compute Engine (GCE)'s metadata server. It's only valid to use +this token source if your program is running on a GCE instance. +If no account is specified, "default" is used. +Further information about retrieving access tokens from the GCE metadata +server can be found at https://cloud.google.com/compute/docs/authentication. +
+ + + + + + + +func ConfigFromJSON(jsonKey []byte, scope ...string) (*oauth2.Config, error)+
+ConfigFromJSON uses a Google Developers Console client_credentials.json +file to construct a config. +client_credentials.json can be downloaded from +https://console.developers.google.com, under "Credentials". Download the Web +application credentials in the JSON format and provide the contents of the +file as jsonKey. +
+ + + + + + + +func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error)+
+DefaultClient returns an HTTP Client that uses the +DefaultTokenSource to obtain authentication credentials. +
++This client should be used when developing services +that run on Google App Engine or Google Compute Engine +and use "Application Default Credentials." +
++For more details, see: +https://developers.google.com/accounts/docs/application-default-credentials +
+ + + + + + + +func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error)+
+DefaultTokenSource is a token source that uses +"Application Default Credentials". +
++It looks for credentials in the following places, +preferring the first location found: +
+1. A JSON file whose path is specified by the + GOOGLE_APPLICATION_CREDENTIALS environment variable. +2. A JSON file in a location known to the gcloud command-line tool. + On Windows, this is %APPDATA%/gcloud/application_default_credentials.json. + On other systems, $HOME/.config/gcloud/application_default_credentials.json. +3. On Google App Engine it uses the appengine.AccessToken function. +4. On Google Compute Engine and Google App Engine Managed VMs, it fetches + credentials from the metadata server. + (In this final case any provided scopes are ignored.) ++
+For more details, see: +https://developers.google.com/accounts/docs/application-default-credentials +
+ + + + + + + +func JWTAccessTokenSourceFromJSON(jsonKey []byte, audience string) (oauth2.TokenSource, error)+
+JWTAccessTokenSourceFromJSON uses a Google Developers service account JSON +key file to read the credentials that authorize and authenticate the +requests, and returns a TokenSource that does not use any OAuth2 flow but +instead creates a JWT and sends that as the access token. +The audience is typically a URL that specifies the scope of the credentials. +
++Note that this is not a standard OAuth flow, but rather an +optimization supported by a few Google services. +Unless you know otherwise, you should use JWTConfigFromJSON instead. +
+ + + + + + + +func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error)+
+JWTConfigFromJSON uses a Google Developers service account JSON key file to read +the credentials that authorize and authenticate the requests. +Create a service account on "Credentials" for your project at +https://console.developers.google.com to download a JSON key file. +
+ + + + + + + + +type SDKConfig struct {
+ // contains filtered or unexported fields
+}
+ +An SDKConfig provides access to tokens from an account already +authorized via the Google Cloud SDK. +
+ + + + + + + + + + + + +func NewSDKConfig(account string) (*SDKConfig, error)+
+NewSDKConfig creates an SDKConfig for the given Google Cloud SDK +account. If account is empty, the account currently active in +Google Cloud SDK properties is used. +Google Cloud SDK credentials must be created by running `gcloud auth` +before using this function. +The Google Cloud SDK is available at https://cloud.google.com/sdk/. +
+ + + + + + + +func (c *SDKConfig) Client(ctx context.Context) *http.Client+
+Client returns an HTTP client using Google Cloud SDK credentials to +authorize requests. The token will auto-refresh as necessary. The +underlying http.RoundTripper will be obtained using the provided +context. The returned client and its Transport should not be +modified. +
+ + + + + + +func (c *SDKConfig) Scopes() []string+
+Scopes are the OAuth 2.0 scopes the current account is authorized for. +
+ + + + + + +func (c *SDKConfig) TokenSource(ctx context.Context) oauth2.TokenSource+
+TokenSource returns an oauth2.TokenSource that retrieve tokens from +Google Cloud SDK credentials using the provided context. +It will returns the current access token stored in the credentials, +and refresh it when it expires, but it won't update the credentials +with the new access token. +
+ + + + + + + + + + + + + + + + + + +var Endpoint = oauth2.Endpoint{ + AuthURL: "https://www.hipchat.com/users/authorize", + TokenURL: "https://api.hipchat.com/v2/oauth/token", +}+
+Endpoint is HipChat's OAuth 2.0 endpoint. +
+ + + + + + +func ClientCredentialsConfigFromCaps(capsJSON []byte, clientID, clientSecret string, scopes ...string) (*clientcredentials.Config, error)+
+ClientCredentialsConfigFromCaps generates a Config from a HipChat API +capabilities descriptor. It does not verify the scopes against the +capabilities document at this time. +
++For more information see: https://www.hipchat.com/docs/apiv2/method/get_capabilities +
+ + + + + + + +func ServerEndpoint(host string) oauth2.Endpoint+
+ServerEndpoint returns a new oauth2.Endpoint for a HipChat Server instance +running on the given domain or host. +
+ + + + + + + + + + + + + + + + + + +var HTTPClient internal.ContextKey+
+HTTPClient is the context key to use with golang.org/x/net/context's +WithValue function to associate an *http.Client value with a context. +
+ + +var NoContext = context.TODO()+
+NoContext is the default context you should supply if not using +your own context.Context (see https://golang.org/x/net/context). +
+ + + + + + +func NewClient(ctx context.Context, src TokenSource) *http.Client+
+NewClient creates an *http.Client from a Context and TokenSource. +The returned client is not valid beyond the lifetime of the context. +
++As a special case, if src is nil, a non-OAuth2 client is returned +using the provided context. This exists to support related OAuth2 +packages. +
+ + + + + + + +func RegisterBrokenAuthHeaderProvider(tokenURL string)+
+RegisterBrokenAuthHeaderProvider registers an OAuth2 server +identified by the tokenURL prefix as an OAuth2 implementation +which doesn't support the HTTP Basic authentication +scheme to authenticate with the authorization server. +Once a server is registered, credentials (client_id and client_secret) +will be passed as query parameters rather than being present +in the Authorization header. +See https://code.google.com/p/goauth2/issues/detail?id=31 for background. +
+ + + + + + + + +type AuthCodeOption interface {
+ // contains filtered or unexported methods
+}
+ +An AuthCodeOption is passed to Config.AuthCodeURL. +
+ + + + + +var ( + // AccessTypeOnline and AccessTypeOffline are options passed + // to the Options.AuthCodeURL method. They modify the + // "access_type" field that gets sent in the URL returned by + // AuthCodeURL. + // + // Online is the default if neither is specified. If your + // application needs to refresh access tokens when the user + // is not present at the browser, then use offline. This will + // result in your application obtaining a refresh token the + // first time your application exchanges an authorization + // code for a user. + AccessTypeOnline AuthCodeOption = SetAuthURLParam("access_type", "online") + AccessTypeOffline AuthCodeOption = SetAuthURLParam("access_type", "offline") + + // ApprovalForce forces the users to view the consent dialog + // and confirm the permissions request at the URL returned + // from AuthCodeURL, even if they've already done so. + ApprovalForce AuthCodeOption = SetAuthURLParam("approval_prompt", "force") +)+ + + + + + + + + +
func SetAuthURLParam(key, value string) AuthCodeOption+
+SetAuthURLParam builds an AuthCodeOption which passes key/value parameters +to a provider's authorization endpoint. +
+ + + + + + + + + +type Config struct { + // ClientID is the application's ID. + ClientID string + + // ClientSecret is the application's secret. + ClientSecret string + + // Endpoint contains the resource server's token endpoint + // URLs. These are constants specific to each server and are + // often available via site-specific packages, such as + // google.Endpoint or github.Endpoint. + Endpoint Endpoint + + // RedirectURL is the URL to redirect users going through + // the OAuth flow, after the resource owner's URLs. + RedirectURL string + + // Scope specifies optional requested permissions. + Scopes []string +}+
+Config describes a typical 3-legged OAuth2 flow, with both the +client application information and the server's endpoint URLs. +
+ + + + + + +▹ Example
+func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string+
+AuthCodeURL returns a URL to OAuth 2.0 provider's consent page +that asks for permissions for the required scopes explicitly. +
++State is a token to protect the user from CSRF attacks. You must +always provide a non-zero string and validate that it matches the +the state query parameter on your redirect callback. +See http://tools.ietf.org/html/rfc6749#section-10.12 for more info. +
++Opts may include AccessTypeOnline or AccessTypeOffline, as well +as ApprovalForce. +
+ + + + + + +func (c *Config) Client(ctx context.Context, t *Token) *http.Client+
+Client returns an HTTP client using the provided token. +The token will auto-refresh as necessary. The underlying +HTTP transport will be obtained using the provided context. +The returned client and its Transport should not be modified. +
+ + + + + + +func (c *Config) Exchange(ctx context.Context, code string) (*Token, error)+
+Exchange converts an authorization code into a token. +
++It is used after a resource provider redirects the user back +to the Redirect URI (the URL obtained from AuthCodeURL). +
++The HTTP client to use is derived from the context. +If a client is not provided via the context, http.DefaultClient is used. +
++The code will be in the *http.Request.FormValue("code"). Before +calling Exchange, be sure to validate FormValue("state"). +
+ + + + + + +func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error)+
+PasswordCredentialsToken converts a resource owner username and password +pair into a token. +
++Per the RFC, this grant type should only be used "when there is a high +degree of trust between the resource owner and the client (e.g., the client +is part of the device operating system or a highly privileged application), +and when other authorization grant types are not available." +See https://tools.ietf.org/html/rfc6749#section-4.3 for more info. +
++The HTTP client to use is derived from the context. +If nil, http.DefaultClient is used. +
+ + + + + + +func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource+
+TokenSource returns a TokenSource that returns t until t expires, +automatically refreshing it as necessary using the provided context. +
++Most users will use Config.Client instead. +
+ + + + + + + + +type Endpoint struct { + AuthURL string + TokenURL string +}+
+Endpoint contains the OAuth 2.0 provider's authorization and token +endpoint URLs. +
+ + + + + + + + + + + + + + + + +type Token struct { + // AccessToken is the token that authorizes and authenticates + // the requests. + AccessToken string `json:"access_token"` + + // TokenType is the type of token. + // The Type method returns either this or "Bearer", the default. + TokenType string `json:"token_type,omitempty"` + + // RefreshToken is a token that's used by the application + // (as opposed to the user) to refresh the access token + // if it expires. + RefreshToken string `json:"refresh_token,omitempty"` + + // Expiry is the optional expiration time of the access token. + // + // If zero, TokenSource implementations will reuse the same + // token forever and RefreshToken or equivalent + // mechanisms for that TokenSource will not be used. + Expiry time.Time `json:"expiry,omitempty"` + // contains filtered or unexported fields +}+
+Token represents the crendentials used to authorize +the requests to access protected resources on the OAuth 2.0 +provider's backend. +
++Most users of this package should not access fields of Token +directly. They're exported mostly for use by related packages +implementing derivative OAuth2 flows. +
+ + + + + + + + + + + + + + +func (t *Token) Extra(key string) interface{}+
+Extra returns an extra field. +Extra fields are key-value pairs returned by the server as a +part of the token retrieval response. +
+ + + + + + +func (t *Token) SetAuthHeader(r *http.Request)+
+SetAuthHeader sets the Authorization header to r using the access +token in t. +
++This method is unnecessary when using Transport or an HTTP Client +returned by this package. +
+ + + + + + +func (t *Token) Type() string+
+Type returns t.TokenType if non-empty, else "Bearer". +
+ + + + + + +func (t *Token) Valid() bool+
+Valid reports whether t is non-nil, has an AccessToken, and is not expired. +
+ + + + + + +func (t *Token) WithExtra(extra interface{}) *Token+
+WithExtra returns a new Token that's a clone of t, but using the +provided raw extra map. This is only intended for use by packages +implementing derivative OAuth2 flows. +
+ + + + + + + + +type TokenSource interface { + // Token returns a token or an error. + // Token must be safe for concurrent use by multiple goroutines. + // The returned Token must not be modified. + Token() (*Token, error) +}+
+A TokenSource is anything that can return a token. +
+ + + + + + + + + + + + +func ReuseTokenSource(t *Token, src TokenSource) TokenSource+
+ReuseTokenSource returns a TokenSource which repeatedly returns the +same token as long as it's valid, starting with t. +When its cached token is invalid, a new token is obtained from src. +
++ReuseTokenSource is typically used to reuse tokens from a cache +(such as a file on disk) between runs of a program, rather than +obtaining new tokens unnecessarily. +
++The initial token t may be nil, in which case the TokenSource is +wrapped in a caching version if it isn't one already. This also +means it's always safe to wrap ReuseTokenSource around any other +TokenSource without adverse effects. +
+ + + + + +func StaticTokenSource(t *Token) TokenSource+
+StaticTokenSource returns a TokenSource that always returns the same token. +Because the provided token t is never refreshed, StaticTokenSource is only +useful for tokens that never expire. +
+ + + + + + + + + +type Transport struct { + // Source supplies the token to add to outgoing requests' + // Authorization headers. + Source TokenSource + + // Base is the base RoundTripper used to make HTTP requests. + // If nil, http.DefaultTransport is used. + Base http.RoundTripper + // contains filtered or unexported fields +}+
+Transport is an http.RoundTripper that makes OAuth 2.0 HTTP requests, +wrapping a base RoundTripper and adding an Authorization header +with a token from the supplied Sources. +
++Transport is a low-level mechanism. Most code will use the +higher-level Config.Client method instead. +
+ + + + + + + + + + + + + + +func (t *Transport) CancelRequest(req *http.Request)+
+CancelRequest cancels an in-flight request by closing its connection. +
+ + + + + + +func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)+
+RoundTrip authorizes and authenticates the request with an +access token. If no token exists or token is expired, +tries to refresh/fetch a new token. +
+ + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ bitbucket + | ++ Package bitbucket provides constants for using OAuth2 to access Bitbucket. + | +
+ clientcredentials + | ++ Package clientcredentials implements the OAuth2.0 "client credentials" token flow, also known as the "two-legged OAuth 2.0". + | +
+ facebook + | ++ Package facebook provides constants for using OAuth2 to access Facebook. + | +
+ fitbit + | ++ Package fitbit provides constants for using OAuth2 to access the Fitbit API. + | +
+ github + | ++ Package github provides constants for using OAuth2 to access Github. + | +
+ google + | ++ Package google provides support for making OAuth2 authorized and authenticated HTTP requests to Google APIs. + | +
+ hipchat + | ++ Package hipchat provides constants for using OAuth2 to access HipChat. + | +
+ jws + | ++ Package jws provides encoding and decoding utilities for signed JWS messages. + | +
+ jwt + | ++ Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly known as "two-legged OAuth 2.0". + | +
+ linkedin + | ++ Package linkedin provides constants for using OAuth2 to access LinkedIn. + | +
+ microsoft + | ++ Package microsoft provides constants for using OAuth2 to access Windows Live ID. + | +
+ odnoklassniki + | ++ Package odnoklassniki provides constants for using OAuth2 to access Odnoklassniki. + | +
+ paypal + | ++ Package paypal provides constants for using OAuth2 to access PayPal. + | +
+ slack + | ++ Package slack provides constants for using OAuth2 to access Slack. + | +
+ vk + | ++ Package vk provides constants for using OAuth2 to access VK.com. + | +
func CondVal(v string) []string+ + + + + + + +
func ContextClient(ctx context.Context) (*http.Client, error)+ + + + + + + +
func ContextTransport(ctx context.Context) http.RoundTripper+ + + + + + + +
func ParseINI(ini io.Reader) (map[string]map[string]string, error)+ + + + + + + +
func ParseKey(key []byte) (*rsa.PrivateKey, error)+
+ParseKey converts the binary contents of a private key file +to an *rsa.PrivateKey. It detects whether the private key is in a +PEM container or not. If so, it extracts the the private key +from PEM container before conversion. It only supports PEM +containers with no passphrase. +
+ + + + + + + +func RegisterBrokenAuthHeaderProvider(tokenURL string)+ + + + + + + +
func RegisterContextClientFunc(fn ContextClientFunc)+ + + + + + + + +
type ContextClientFunc func(context.Context) (*http.Client, error)+
+ContextClientFunc is a func which tries to return an *http.Client +given a Context value. If it returns an error, the search stops +with that error. If it returns (nil, nil), the search continues +down the list of registered funcs. +
+ + + + + + + + + + + + + + + + +type ContextKey struct{}+
+ContextKey is just an empty struct. It exists so HTTPClient can be +an immutable public variable with a unique type. It's immutable +because nobody else can create a ContextKey, being unexported. +
+ + + + + +var HTTPClient ContextKey+
+HTTPClient is the context key to use with golang.org/x/net/context's +WithValue function to associate an *http.Client value with a context. +
+ + + + + + + + + + + + + +type ErrorTransport struct{ Err error }+
+ErrorTransport returns the specified error on RoundTrip. +This RoundTripper should be used in rare error cases where +error handling can be postponed to response handling time. +
+ + + + + + + + + + + + + + +func (t ErrorTransport) RoundTrip(*http.Request) (*http.Response, error)+ + + + + + + + +
type Token struct { + // AccessToken is the token that authorizes and authenticates + // the requests. + AccessToken string + + // TokenType is the type of token. + // The Type method returns either this or "Bearer", the default. + TokenType string + + // RefreshToken is a token that's used by the application + // (as opposed to the user) to refresh the access token + // if it expires. + RefreshToken string + + // Expiry is the optional expiration time of the access token. + // + // If zero, TokenSource implementations will reuse the same + // token forever and RefreshToken or equivalent + // mechanisms for that TokenSource will not be used. + Expiry time.Time + + // Raw optionally contains extra metadata from the server + // when updating a token. + Raw interface{} +}+
+Token represents the crendentials used to authorize +the requests to access protected resources on the OAuth 2.0 +provider's backend. +
++This type is a mirror of oauth2.Token and exists to break +an otherwise-circular dependency. Other internal packages +should convert this Token into an oauth2.Token before use. +
+ + + + + + + + + + + + +func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values) (*Token, error)+ + + + + + + + + + + + + + + + + + + +
func Encode(header *Header, c *ClaimSet, key *rsa.PrivateKey) (string, error)+
+Encode encodes a signed JWS with provided header and claim set. +This invokes EncodeWithSigner using crypto/rsa.SignPKCS1v15 with the given RSA private key. +
+ + + + + + + +func EncodeWithSigner(header *Header, c *ClaimSet, sg Signer) (string, error)+
+EncodeWithSigner encodes a header and claim set with the provided signer. +
+ + + + + + + +func Verify(token string, key *rsa.PublicKey) error+
+Verify tests whether the provided JWT token's signature was produced by the private key +associated with the supplied public key. +
+ + + + + + + + +type ClaimSet struct { + Iss string `json:"iss"` // email address of the client_id of the application making the access token request + Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests + Aud string `json:"aud"` // descriptor of the intended target of the assertion (Optional). + Exp int64 `json:"exp"` // the expiration time of the assertion (seconds since Unix epoch) + Iat int64 `json:"iat"` // the time the assertion was issued (seconds since Unix epoch) + Typ string `json:"typ,omitempty"` // token type (Optional). + + // Email for which the application is requesting delegated access (Optional). + Sub string `json:"sub,omitempty"` + + // The old name of Sub. Client keeps setting Prn to be + // complaint with legacy OAuth 2.0 providers. (Optional) + Prn string `json:"prn,omitempty"` + + // See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3 + // This array is marshalled using custom code (see (c *ClaimSet) encode()). + PrivateClaims map[string]interface{} `json:"-"` +}+
+ClaimSet contains information about the JWT signature including the +permissions being requested (scopes), the target of the token, the issuer, +the time the token was issued, and the lifetime of the token. +
+ + + + + + + + + + + + +func Decode(payload string) (*ClaimSet, error)+
+Decode decodes a claim set from a JWS payload. +
+ + + + + + + + + +type Header struct { + // The algorithm used for signature. + Algorithm string `json:"alg"` + + // Represents the token type. + Typ string `json:"typ"` + + // The optional hint of which key is being used. + KeyID string `json:"kid,omitempty"` +}+
+Header represents the header for the signed JWS payloads. +
+ + + + + + + + + + + + + + + + +type Signer func(data []byte) (sig []byte, err error)+
+Signer returns a signature for the given data. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +type Config struct { + // Email is the OAuth client identifier used when communicating with + // the configured OAuth provider. + Email string + + // PrivateKey contains the contents of an RSA private key or the + // contents of a PEM file that contains a private key. The provided + // private key is used to sign JWT payloads. + // PEM containers with a passphrase are not supported. + // Use the following command to convert a PKCS 12 file into a PEM. + // + // $ openssl pkcs12 -in key.p12 -out key.pem -nodes + // + PrivateKey []byte + + // PrivateKeyID contains an optional hint indicating which key is being + // used. + PrivateKeyID string + + // Subject is the optional user to impersonate. + Subject string + + // Scopes optionally specifies a list of requested permission scopes. + Scopes []string + + // TokenURL is the endpoint required to complete the 2-legged JWT flow. + TokenURL string + + // Expires optionally specifies how long the token is valid for. + Expires time.Duration +}+
+Config is the configuration for using JWT to fetch tokens, +commonly known as "two-legged OAuth 2.0". +
+ + + + + + + + + + + + + + +func (c *Config) Client(ctx context.Context) *http.Client+
+Client returns an HTTP client wrapping the context's +HTTP transport and adding Authorization headers with tokens +obtained from c. +
++The returned client and its Transport should not be modified. +
+ + + + + + +func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource+
+TokenSource returns a JWT TokenSource using the configuration +in c and the HTTP client from the provided context. +
+ + + + + + + + + + + + + + + + + + +var Endpoint = oauth2.Endpoint{ + AuthURL: "https://www.linkedin.com/uas/oauth2/authorization", + TokenURL: "https://www.linkedin.com/uas/oauth2/accessToken", +}+
+Endpoint is LinkedIn's OAuth 2.0 endpoint. +
+ + + + + + + + + + + + + + + + + +var LiveConnectEndpoint = oauth2.Endpoint{ + AuthURL: "https://login.live.com/oauth20_authorize.srf", + TokenURL: "https://login.live.com/oauth20_token.srf", +}+
+LiveConnectEndpoint is Windows's Live ID OAuth 2.0 endpoint. +
+ + + + + + + + + + + + + + + + + +var Endpoint = oauth2.Endpoint{ + AuthURL: "https://www.odnoklassniki.ru/oauth/authorize", + TokenURL: "https://api.odnoklassniki.ru/oauth/token.do", +}+
+Endpoint is Odnoklassniki's OAuth 2.0 endpoint. +
+ + + + + + + + + + + + + + + + + +var Endpoint = oauth2.Endpoint{ + AuthURL: "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize", + TokenURL: "https://api.paypal.com/v1/identity/openidconnect/tokenservice", +}+
+Endpoint is PayPal's OAuth 2.0 endpoint in live (production) environment. +
+ + +var SandboxEndpoint = oauth2.Endpoint{ + AuthURL: "https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize", + TokenURL: "https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice", +}+
+SandboxEndpoint is PayPal's OAuth 2.0 endpoint in sandbox (testing) environment. +
+ + + + + + + + + + + + + + + + + +var Endpoint = oauth2.Endpoint{ + AuthURL: "https://slack.com/oauth/authorize", + TokenURL: "https://slack.com/api/oauth.access", +}+
+Endpoint is Slack's OAuth 2.0 endpoint. +
+ + + + + + + + + + + + + + + + + +var Endpoint = oauth2.Endpoint{ + AuthURL: "https://oauth.vk.com/authorize", + TokenURL: "https://oauth.vk.com/access_token", +}+
+Endpoint is VK's OAuth 2.0 endpoint. +
+ + + + + + + + + + + + + + + + + +var ( + // ISO8859_6E is the ISO 8859-6E encoding. + ISO8859_6E encoding.Encoding = &iso8859_6E + + // ISO8859_6I is the ISO 8859-6I encoding. + ISO8859_6I encoding.Encoding = &iso8859_6I + + // ISO8859_8E is the ISO 8859-8E encoding. + ISO8859_8E encoding.Encoding = &iso8859_8E + + // ISO8859_8I is the ISO 8859-8I encoding. + ISO8859_8I encoding.Encoding = &iso8859_8I +)+
+These encodings vary only in the way clients should interpret them. Their +coded character set is identical and a single implementation can be shared. +
+ + +var All = listAll
+ +All is a list of all defined encodings in this package. +
+ + +var CodePage437 encoding.Encoding = &codePage437+
+CodePage437 is the IBM Code Page 437 encoding. +
+ + +var CodePage850 encoding.Encoding = &codePage850+
+CodePage850 is the IBM Code Page 850 encoding. +
+ + +var CodePage852 encoding.Encoding = &codePage852+
+CodePage852 is the IBM Code Page 852 encoding. +
+ + +var CodePage855 encoding.Encoding = &codePage855+
+CodePage855 is the IBM Code Page 855 encoding. +
+ + +var CodePage858 encoding.Encoding = &codePage858+
+CodePage858 is the Windows Code Page 858 encoding. +
+ + +var CodePage860 encoding.Encoding = &codePage860+
+CodePage860 is the IBM Code Page 860 encoding. +
+ + +var CodePage862 encoding.Encoding = &codePage862+
+CodePage862 is the IBM Code Page 862 encoding. +
+ + +var CodePage863 encoding.Encoding = &codePage863+
+CodePage863 is the IBM Code Page 863 encoding. +
+ + +var CodePage865 encoding.Encoding = &codePage865+
+CodePage865 is the IBM Code Page 865 encoding. +
+ + +var CodePage866 encoding.Encoding = &codePage866+
+CodePage866 is the IBM Code Page 866 encoding. +
+ + +var ISO8859_1 encoding.Encoding = &iso8859_1+
+ISO8859_1 is the ISO 8859-1 encoding. +
+ + +var ISO8859_10 encoding.Encoding = &iso8859_10+
+ISO8859_10 is the ISO 8859-10 encoding. +
+ + +var ISO8859_13 encoding.Encoding = &iso8859_13+
+ISO8859_13 is the ISO 8859-13 encoding. +
+ + +var ISO8859_14 encoding.Encoding = &iso8859_14+
+ISO8859_14 is the ISO 8859-14 encoding. +
+ + +var ISO8859_15 encoding.Encoding = &iso8859_15+
+ISO8859_15 is the ISO 8859-15 encoding. +
+ + +var ISO8859_16 encoding.Encoding = &iso8859_16+
+ISO8859_16 is the ISO 8859-16 encoding. +
+ + +var ISO8859_2 encoding.Encoding = &iso8859_2+
+ISO8859_2 is the ISO 8859-2 encoding. +
+ + +var ISO8859_3 encoding.Encoding = &iso8859_3+
+ISO8859_3 is the ISO 8859-3 encoding. +
+ + +var ISO8859_4 encoding.Encoding = &iso8859_4+
+ISO8859_4 is the ISO 8859-4 encoding. +
+ + +var ISO8859_5 encoding.Encoding = &iso8859_5+
+ISO8859_5 is the ISO 8859-5 encoding. +
+ + +var ISO8859_6 encoding.Encoding = &iso8859_6+
+ISO8859_6 is the ISO 8859-6 encoding. +
+ + +var ISO8859_7 encoding.Encoding = &iso8859_7+
+ISO8859_7 is the ISO 8859-7 encoding. +
+ + +var ISO8859_8 encoding.Encoding = &iso8859_8+
+ISO8859_8 is the ISO 8859-8 encoding. +
+ + +var KOI8R encoding.Encoding = &koi8R+
+KOI8R is the KOI8-R encoding. +
+ + +var KOI8U encoding.Encoding = &koi8U+
+KOI8U is the KOI8-U encoding. +
+ + +var Macintosh encoding.Encoding = &macintosh+
+Macintosh is the Macintosh encoding. +
+ + +var MacintoshCyrillic encoding.Encoding = &macintoshCyrillic+
+MacintoshCyrillic is the Macintosh Cyrillic encoding. +
+ + +var Windows1250 encoding.Encoding = &windows1250+
+Windows1250 is the Windows 1250 encoding. +
+ + +var Windows1251 encoding.Encoding = &windows1251+
+Windows1251 is the Windows 1251 encoding. +
+ + +var Windows1252 encoding.Encoding = &windows1252+
+Windows1252 is the Windows 1252 encoding. +
+ + +var Windows1253 encoding.Encoding = &windows1253+
+Windows1253 is the Windows 1253 encoding. +
+ + +var Windows1254 encoding.Encoding = &windows1254+
+Windows1254 is the Windows 1254 encoding. +
+ + +var Windows1255 encoding.Encoding = &windows1255+
+Windows1255 is the Windows 1255 encoding. +
+ + +var Windows1256 encoding.Encoding = &windows1256+
+Windows1256 is the Windows 1256 encoding. +
+ + +var Windows1257 encoding.Encoding = &windows1257+
+Windows1257 is the Windows 1257 encoding. +
+ + +var Windows1258 encoding.Encoding = &windows1258+
+Windows1258 is the Windows 1258 encoding. +
+ + +var Windows874 encoding.Encoding = &windows874+
+Windows874 is the Windows 874 encoding. +
+ + +var XUserDefined encoding.Encoding = &xUserDefined+
+XUserDefined is the X-User-Defined encoding. +
++It is defined at http://encoding.spec.whatwg.org/#x-user-defined +
+ + + + + + + + + + + + + + + + + +func Get(name string) (encoding.Encoding, error)+
+Get returns an Encoding for one of the names listed in +http://www.w3.org/TR/encoding using the Default Index. Matching is case- +insensitive. +
+ + + + + + + +func LanguageDefault(tag language.Tag) string+
+LanguageDefault returns the canonical name of the default encoding for a +given language. +
+ + + + + + + +func Name(e encoding.Encoding) (string, error)+
+Name reports the canonical name of the given Encoding. It will return +an error if e is not associated with a supported encoding scheme. +
+ + + + + + + + + + + + + + + + + + +type Index struct { +}+
+Index maps names registered by IANA to Encodings. +
+ + + + + +var ( + // MIME is an index to map MIME names. It does not support aliases. + MIME *Index + + // IANA is an index that supports all names and aliases using IANA names as + // the canonical identifier. + IANA *Index +)+ + + +
▹ Example
+func (x *Index) Get(name string) (encoding.Encoding, error)+
+Get returns an Encoding for IANA-registered names. Matching is +case-insensitive. +
+ + + + + + +func (x *Index) Name(e encoding.Encoding) (string, error)+
+Name reports the canonical name of the given Encoding. It will return an +error if the e is not associated with a known encoding scheme. +
+ + + + + + + + + + + + + + + + + + +const ASCIISub = '\x1a'
+ +ASCIISub is the ASCII substitute character, as recommended by +http://unicode.org/reports/tr36/#Text_Comparison +
+ + + + +var ErrInvalidUTF8 = errors.New("encoding: invalid UTF-8")+
+ErrInvalidUTF8 means that a transformer encountered invalid UTF-8. +
+ + +var UTF8Validator transform.Transformer = utf8Validator{}+
+UTF8Validator is a transformer that returns ErrInvalidUTF8 on the first +input byte that is not valid UTF-8. +
+ + + + + + + +type Decoder struct { + transform.Transformer + // contains filtered or unexported fields +}+
+A Decoder converts bytes to UTF-8. It implements transform.Transformer. +
++Transforming source bytes that are not of that encoding will not result in an +error per se. Each byte that cannot be transcoded will be represented in the +output by the UTF-8 encoding of '\uFFFD', the replacement rune. +
+ + + + + + + + + + + + + + +func (d *Decoder) Bytes(b []byte) ([]byte, error)+
+Bytes converts the given encoded bytes to UTF-8. It returns the converted +bytes or nil, err if any error occurred. +
+ + + + + + +func (d *Decoder) Reader(r io.Reader) io.Reader+
+Reader wraps another Reader to decode its bytes. +
++The Decoder may not be used for any other operation as long as the returned +Reader is in use. +
+ + + + + + +func (d *Decoder) String(s string) (string, error)+
+String converts the given encoded string to UTF-8. It returns the converted +string or "", err if any error occurred. +
+ + + + + + + + +type Encoder struct { + transform.Transformer + // contains filtered or unexported fields +}+
+An Encoder converts bytes from UTF-8. It implements transform.Transformer. +
++Each rune that cannot be transcoded will result in an error. In this case, +the transform will consume all source byte up to, not including the offending +rune. Transforming source bytes that are not valid UTF-8 will be replaced by +`\uFFFD`. To return early with an error instead, use transform.Chain to +preprocess the data with a UTF8Validator. +
+ + + + + + + + + + + + +func HTMLEscapeUnsupported(e *Encoder) *Encoder+
+HTMLEscapeUnsupported wraps encoders to replace source runes outside the +repertoire of the destination encoding with HTML escape sequences. +
++This wrapper exists to comply to URL and HTML forms requiring a +non-terminating legacy encoder. The produced sequences may lead to data +loss as they are indistinguishable from legitimate input. To avoid this +issue, use UTF-8 encodings whenever possible. +
+ + + + + +func ReplaceUnsupported(e *Encoder) *Encoder+
+ReplaceUnsupported wraps encoders to replace source runes outside the +repertoire of the destination encoding with an encoding-specific +replacement. +
++This wrapper is only provided for backwards compatibility and legacy +handling. Its use is strongly discouraged. Use UTF-8 whenever possible. +
+ + + + + + + +func (e *Encoder) Bytes(b []byte) ([]byte, error)+
+Bytes converts bytes from UTF-8. It returns the converted bytes or nil, err if +any error occurred. +
+ + + + + + +func (e *Encoder) String(s string) (string, error)+
+String converts a string from UTF-8. It returns the converted string or +"", err if any error occurred. +
+ + + + + + +func (e *Encoder) Writer(w io.Writer) io.Writer+
+Writer wraps another Writer to encode its UTF-8 output. +
++The Encoder may not be used for any other operation as long as the returned +Writer is in use. +
+ + + + + + + + +type Encoding interface { + // NewDecoder returns a Decoder. + NewDecoder() *Decoder + + // NewEncoder returns an Encoder. + NewEncoder() *Encoder +}+
+Encoding is a character set encoding that can be transformed to and from +UTF-8. +
+ + + + + +var Nop Encoding = nop{}+
+Nop is the nop encoding. Its transformed bytes are the same as the source +bytes; it does not replace invalid UTF-8 sequences. +
+ + +var Replacement Encoding = replacement{}+
+Replacement is the replacement encoding. Decoding from the replacement +encoding yields a single '\uFFFD' replacement rune. Encoding from UTF-8 to +the replacement encoding yields the same as the source bytes except that +invalid UTF-8 is converted to '\uFFFD'. +
++It is defined at http://encoding.spec.whatwg.org/#replacement +
+ + + + + + + + + + + + + + + + + + + + + +Name | +Synopsis | +
---|---|
.. | +|
+ charmap + | ++ Package charmap provides simple character encodings such as IBM Code Page 437 and Windows 1252. + | +
+ htmlindex + | ++ Package htmlindex maps character set encoding names to Encodings as recommended by the W3C for use in HTML 5. + | +
+ ianaindex + | ++ Package ianaindex maps names to Encodings as specified by the IANA registry. + | +
+ japanese + | ++ Package japanese provides Japanese encodings such as EUC-JP and Shift JIS. + | +
+ korean + | ++ Package korean provides Korean encodings such as EUC-KR. + | +
+ simplifiedchinese + | ++ Package simplifiedchinese provides Simplified Chinese encodings such as GBK. + | +
+ traditionalchinese + | ++ Package traditionalchinese provides Traditional Chinese encodings such as Big5. + | +
+ unicode + | ++ Package unicode provides Unicode encodings such as UTF-16. + | +
+ utf32 + | ++ Package utf32 provides the UTF-32 Unicode encoding. + | +
var All = []encoding.Encoding{EUCJP, ISO2022JP, ShiftJIS}+
+All is a list of all defined encodings in this package. +
+ + +var EUCJP encoding.Encoding = &eucJP+
+EUCJP is the EUC-JP encoding. +
+ + +var ISO2022JP encoding.Encoding = &iso2022JP+
+ISO2022JP is the ISO-2022-JP encoding. +
+ + +var ShiftJIS encoding.Encoding = &shiftJIS+
+ShiftJIS is the Shift JIS encoding, also known as Code Page 932 and +Windows-31J. +
+ + + + + + + + + + + + + + + + + +var All = []encoding.Encoding{EUCKR}+
+All is a list of all defined encodings in this package. +
+ + +var EUCKR encoding.Encoding = &eucKR+
+EUCKR is the EUC-KR encoding, also known as Code Page 949. +
+ + + + + + + + + + + + + + + + + +var ( + // GB18030 is the GB18030 encoding. + GB18030 encoding.Encoding = &gbk18030 + // GBK is the GBK encoding. It encodes an extension of the GB2312 character set + // and is also known as Code Page 936. + GBK encoding.Encoding = &gbk +)+ + +
var All = []encoding.Encoding{GB18030, GBK, HZGB2312}+
+All is a list of all defined encodings in this package. +
+ + +var HZGB2312 encoding.Encoding = &hzGB2312+
+HZGB2312 is the HZ-GB2312 encoding. +
+ + + + + + + + + + + + + + + + + +var All = []encoding.Encoding{Big5}+
+All is a list of all defined encodings in this package. +
+ + +var Big5 encoding.Encoding = &big5+
+Big5 is the Big5 encoding, also known as Code Page 950. +
+ + + + + + + + + + + + + + + + + +var All = []encoding.Encoding{ + UTF8, + UTF16(BigEndian, UseBOM), + UTF16(BigEndian, IgnoreBOM), + UTF16(LittleEndian, IgnoreBOM), +}+
+All lists a configuration for each IANA-defined UTF-16 variant. +
+ + +var ErrMissingBOM = errors.New("encoding: missing byte order mark")+
+ErrMissingBOM means that decoding UTF-16 input with ExpectBOM did not find a +starting byte order mark. +
+ + +var UTF8 encoding.Encoding = utf8enc+
+UTF8 is the UTF-8 encoding. +
+ + + + + + +func BOMOverride(fallback transform.Transformer) transform.Transformer+
+BOMOverride returns a new decoder transformer that is identical to fallback, +except that the presence of a Byte Order Mark at the start of the input +causes it to switch to the corresponding Unicode decoding. It will only +consider BOMs for UTF-8, UTF-16BE, and UTF-16LE. +
++This differs from using ExpectBOM by allowing a BOM to switch to UTF-8, not +just UTF-16 variants, and allowing falling back to any encoding scheme. +
++This technique is recommended by the W3C for use in HTML 5: "For +compatibility with deployed content, the byte order mark (also known as BOM) +is considered more authoritative than anything else." +http://www.w3.org/TR/encoding/#specification-hooks +
++Using BOMOverride is mostly intended for use cases where the first characters +of a fallback encoding are known to not be a BOM, for example, for valid HTML +and most encodings. +
+ + + + + + + +func UTF16(e Endianness, b BOMPolicy) encoding.Encoding+
+UTF16 returns a UTF-16 Encoding for the given default endianness and byte +order mark (BOM) policy. +
++When decoding from UTF-16 to UTF-8, if the BOMPolicy is IgnoreBOM then +neither BOMs U+FEFF nor noncharacters U+FFFE in the input stream will affect +the endianness used for decoding, and will instead be output as their +standard UTF-8 encodings: "\xef\xbb\xbf" and "\xef\xbf\xbe". If the BOMPolicy +is UseBOM or ExpectBOM a staring BOM is not written to the UTF-8 output. +Instead, it overrides the default endianness e for the remainder of the +transformation. Any subsequent BOMs U+FEFF or noncharacters U+FFFE will not +affect the endianness used, and will instead be output as their standard +UTF-8 encodings. For UseBOM, if there is no starting BOM, it will proceed +with the default Endianness. For ExpectBOM, in that case, the transformation +will return early with an ErrMissingBOM error. +
++When encoding from UTF-8 to UTF-16, a BOM will be inserted at the start of +the output if the BOMPolicy is UseBOM or ExpectBOM. Otherwise, a BOM will not +be inserted. The UTF-8 input does not need to contain a BOM. +
++There is no concept of a 'native' endianness. If the UTF-16 data is produced +and consumed in a greater context that implies a certain endianness, use +IgnoreBOM. Otherwise, use ExpectBOM and always produce and consume a BOM. +
++In the language of http://www.unicode.org/faq/utf_bom.html#bom10, IgnoreBOM +corresponds to "Where the precise type of the data stream is known... the +BOM should not be used" and ExpectBOM corresponds to "A particular +protocol... may require use of the BOM". +
+ + + + + + + + +type BOMPolicy uint8+
+BOMPolicy is a UTF-16 encoding's byte order mark policy. +
+ + + +const ( + + // IgnoreBOM means to ignore any byte order marks. + IgnoreBOM BOMPolicy = 0 + + // UseBOM means that the UTF-16 form may start with a byte order mark, which + // will be used to override the default encoding. + UseBOM BOMPolicy = writeBOM | acceptBOM + + // ExpectBOM means that the UTF-16 form must start with a byte order mark, + // which will be used to override the default encoding. + ExpectBOM BOMPolicy = writeBOM | acceptBOM | requireBOM +)+ + + + + + + + + + + + + + + +
type Endianness bool+
+Endianness is a UTF-16 encoding's default endianness. +
+ + + +const ( + // BigEndian is UTF-16BE. + BigEndian Endianness = false + // LittleEndian is UTF-16LE. + LittleEndian Endianness = true +)+ + + + + + + + + + + + + + + + + + + + + + + +
var All = []encoding.Encoding{ + UTF32(BigEndian, UseBOM), + UTF32(BigEndian, IgnoreBOM), + UTF32(LittleEndian, IgnoreBOM), +}+
+All lists a configuration for each IANA-defined UTF-32 variant. +
+ + +var ErrMissingBOM = errors.New("encoding: missing byte order mark")+
+ErrMissingBOM means that decoding UTF-32 input with ExpectBOM did not +find a starting byte order mark. +
+ + + + + + +func UTF32(e Endianness, b BOMPolicy) encoding.Encoding+
+UTF32 returns a UTF-32 Encoding for the given default endianness and +byte order mark (BOM) policy. +
++When decoding from UTF-32 to UTF-8, if the BOMPolicy is IgnoreBOM then +neither BOMs U+FEFF nor ill-formed code units 0xFFFE0000 in the input +stream will affect the endianness used for decoding. Instead BOMs will +be output as their standard UTF-8 encoding "\xef\xbb\xbf" while +0xFFFE0000 code units will be output as "\xef\xbf\xbd", the standard +UTF-8 encoding for the Unicode replacement character. If the BOMPolicy +is UseBOM or ExpectBOM a starting BOM is not written to the UTF-8 +output. Instead, it overrides the default endianness e for the remainder +of the transformation. Any subsequent BOMs U+FEFF or ill-formed code +units 0xFFFE0000 will not affect the endianness used, and will instead +be output as their standard UTF-8 (replacement) encodings. For UseBOM, +if there is no starting BOM, it will proceed with the default +Endianness. For ExpectBOM, in that case, the transformation will return +early with an ErrMissingBOM error. +
++When encoding from UTF-8 to UTF-32, a BOM will be inserted at the start +of the output if the BOMPolicy is UseBOM or ExpectBOM. Otherwise, a BOM +will not be inserted. The UTF-8 input does not need to contain a BOM. +
++There is no concept of a 'native' endianness. If the UTF-32 data is +produced and consumed in a greater context that implies a certain +endianness, use IgnoreBOM. Otherwise, use ExpectBOM and always produce +and consume a BOM. +
++In the language of http://www.unicode.org/faq/utf_bom.html#bom10, +IgnoreBOM corresponds to "Where the precise type of the data stream is +known... the BOM should not be used" and ExpectBOM corresponds to "A +particular protocol... may require use of the BOM". +
+ + + + + + + + +type BOMPolicy uint8+
+BOMPolicy is a UTF-32 encodings's byte order mark policy. +
+ + + +const ( + + // IgnoreBOM means to ignore any byte order marks. + IgnoreBOM BOMPolicy = 0 + + // UseBOM means that the UTF-32 form may start with a byte order mark, + // which will be used to override the default encoding. + UseBOM BOMPolicy = writeBOM | acceptBOM + + // ExpectBOM means that the UTF-32 form must start with a byte order mark, + // which will be used to override the default encoding. + ExpectBOM BOMPolicy = writeBOM | acceptBOM | requireBOM +)+ + + + + + + + + + + + + + + +
type Endianness bool+
+Endianness is a UTF-32 encoding's default endianness. +
+ + + +const ( + // BigEndian is UTF-32BE. + BigEndian Endianness = false + // LittleEndian is UTF-32LE. + LittleEndian Endianness = true +)+ + + + + + + + + + + + + + + + + + + + + + + + + +
Name | +Synopsis | +
---|---|
.. | +|
+ encoding + | ++ Package encoding defines an interface for character encodings, such as Shift JIS and Windows 1252, that can convert to and from UTF-8. + | +
+ charmap + | ++ Package charmap provides simple character encodings such as IBM Code Page 437 and Windows 1252. + | +
+ htmlindex + | ++ Package htmlindex maps character set encoding names to Encodings as recommended by the W3C for use in HTML 5. + | +
+ ianaindex + | ++ Package ianaindex maps names to Encodings as specified by the IANA registry. + | +
+ japanese + | ++ Package japanese provides Japanese encodings such as EUC-JP and Shift JIS. + | +
+ korean + | ++ Package korean provides Korean encodings such as EUC-KR. + | +
+ simplifiedchinese + | ++ Package simplifiedchinese provides Simplified Chinese encodings such as GBK. + | +
+ traditionalchinese + | ++ Package traditionalchinese provides Traditional Chinese encodings such as Big5. + | +
+ unicode + | ++ Package unicode provides Unicode encodings such as UTF-16. + | +
+ utf32 + | ++ Package utf32 provides the UTF-32 Unicode encoding. + | +
+ language + | ++ Package language implements BCP 47 language tags and related functionality. + | +
+ display + | ++ Package display provides display names for languages, scripts and regions in a requested language. + | +
+ runes + | ++ Package runes provide transforms for UTF-8 encoded text. + | +
+ transform + | ++ Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations. + | +
const CLDRVersion = "29"
+ +CLDRVersion is the CLDR version from which the tables in this package are derived. +
+ + +const Version = "29"
+ +Version is deprecated. Use CLDRVersion. +
+ + + + +var ( + // Supported lists the languages for which names are defined. + Supported language.Coverage + + // The set of all possible values for which names are defined. Note that not + // all Namer implementations will cover all the values of a given type. + // A Namer will return the empty string for unsupported values. + Values language.Coverage +)+ + + + + + + +
type Dictionary struct {
+ // contains filtered or unexported fields
+}
+ +A Dictionary holds a collection of Namers for a single language. One can +reduce the amount of data linked in to a binary by only referencing +Dictionaries for the languages one needs to support instead of using the +generic Namer factories. +
+ + + + + +var ( + Afrikaans *Dictionary = &af // af + Amharic *Dictionary = &am // am + Arabic *Dictionary = &ar // ar + ModernStandardArabic *Dictionary = Arabic // ar-001 + Azerbaijani *Dictionary = &az // az + Bulgarian *Dictionary = &bg // bg + Bengali *Dictionary = &bn // bn + Catalan *Dictionary = &ca // ca + Czech *Dictionary = &cs // cs + Danish *Dictionary = &da // da + German *Dictionary = &de // de + Greek *Dictionary = &el // el + English *Dictionary = &en // en + AmericanEnglish *Dictionary = English // en-US + BritishEnglish *Dictionary = English // en-GB + Spanish *Dictionary = &es // es + EuropeanSpanish *Dictionary = Spanish // es-ES + LatinAmericanSpanish *Dictionary = Spanish // es-419 + Estonian *Dictionary = &et // et + Persian *Dictionary = &fa // fa + Finnish *Dictionary = &fi // fi + Filipino *Dictionary = &fil // fil + French *Dictionary = &fr // fr + Gujarati *Dictionary = &gu // gu + Hebrew *Dictionary = &he // he + Hindi *Dictionary = &hi // hi + Croatian *Dictionary = &hr // hr + Hungarian *Dictionary = &hu // hu + Armenian *Dictionary = &hy // hy + Indonesian *Dictionary = &id // id + Icelandic *Dictionary = &is // is + Italian *Dictionary = &it // it + Japanese *Dictionary = &ja // ja + Georgian *Dictionary = &ka // ka + Kazakh *Dictionary = &kk // kk + Khmer *Dictionary = &km // km + Kannada *Dictionary = &kn // kn + Korean *Dictionary = &ko // ko + Kirghiz *Dictionary = &ky // ky + Lao *Dictionary = &lo // lo + Lithuanian *Dictionary = < // lt + Latvian *Dictionary = &lv // lv + Macedonian *Dictionary = &mk // mk + Malayalam *Dictionary = &ml // ml + Mongolian *Dictionary = &mn // mn + Marathi *Dictionary = &mr // mr + Malay *Dictionary = &ms // ms + Burmese *Dictionary = &my // my + Nepali *Dictionary = &ne // ne + Dutch *Dictionary = &nl // nl + Norwegian *Dictionary = &no // no + Punjabi *Dictionary = &pa // pa + Polish *Dictionary = &pl // pl + Portuguese *Dictionary = &pt // pt + BrazilianPortuguese *Dictionary = Portuguese // pt-BR + EuropeanPortuguese *Dictionary = &ptPT // pt-PT + Romanian *Dictionary = &ro // ro + Russian *Dictionary = &ru // ru + Sinhala *Dictionary = &si // si + Slovak *Dictionary = &sk // sk + Slovenian *Dictionary = &sl // sl + Albanian *Dictionary = &sq // sq + Serbian *Dictionary = &sr // sr + SerbianLatin *Dictionary = &srLatn // sr + Swedish *Dictionary = &sv // sv + Swahili *Dictionary = &sw // sw + Tamil *Dictionary = &ta // ta + Telugu *Dictionary = &te // te + Thai *Dictionary = &th // th + Turkish *Dictionary = &tr // tr + Ukrainian *Dictionary = &uk // uk + Urdu *Dictionary = &ur // ur + Uzbek *Dictionary = &uz // uz + Vietnamese *Dictionary = &vi // vi + Chinese *Dictionary = &zh // zh + SimplifiedChinese *Dictionary = Chinese // zh-Hans + TraditionalChinese *Dictionary = &zhHant // zh-Hant + Zulu *Dictionary = &zu // zu +)+ + + +
▹ Example
+func (d *Dictionary) Languages() Namer+
+Languages returns a Namer for naming languages. It returns nil if there is no +data for the given tag. The type passed to Name must be either language.Base +or language.Tag. Note that the result may differ between passing a tag or its +base language. For example, for English, passing "nl-BE" would return Flemish +whereas passing "nl" returns "Dutch". +
+ + + + + + +func (d *Dictionary) Regions() Namer+
+Regions returns a Namer for naming regions. It returns nil if there is no +data for the given tag. The type passed to Name must be either a +language.Region or a language.Tag. It will not attempt to infer a region for +tags with an unspecified region. +
+ + + + + + +func (d *Dictionary) Scripts() Namer+
+Scripts returns a Namer for naming scripts. It returns nil if there is no +data for the given tag. The type passed to Name must be either a +language.Script or a language.Tag. It will not attempt to infer a script for +tags with an unspecified script. +
+ + + + + + +func (d *Dictionary) Tags() Namer+
+Tags returns a Namer for giving a full description of a tag. The names of +scripts and regions that are not already implied by the language name will +in appended within parentheses. It returns nil if there is not data for the +given tag. The type passed to Name must be a tag. +
+ + + + + + + + +type Namer interface { + // Name returns a display string for the given value. A Namer returns an + // empty string for values it does not support. A Namer may support naming + // an unspecified value. For example, when getting the name for a region for + // a tag that does not have a defined Region, it may return the name for an + // unknown region. It is up to the user to filter calls to Name for values + // for which one does not want to have a name string. + Name(x interface{}) string +}+
+A Namer is used to get the name for a given value, such as a Tag, Language, +Script or Region. +
+ + + + + + +▹ Example
+func Languages(t language.Tag) Namer+
+Languages returns a Namer for naming languages. It returns nil if there is no +data for the given tag. The type passed to Name must be either language.Base +or language.Tag. Note that the result may differ between passing a tag or its +base language. For example, for English, passing "nl-BE" would return Flemish +whereas passing "nl" returns "Dutch". +
+ + + + + +func Regions(t language.Tag) Namer+
+Regions returns a Namer for naming regions. It returns nil if there is no +data for the given tag. The type passed to Name must be either a +language.Region or a language.Tag. It will not attempt to infer a region for +tags with an unspecified region. +
+ + + + + +func Scripts(t language.Tag) Namer+
+Scripts returns a Namer for naming scripts. It returns nil if there is no +data for the given tag. The type passed to Name must be either a +language.Script or a language.Tag. It will not attempt to infer a script for +tags with an unspecified script. +
+ + + + + +func Tags(t language.Tag) Namer+
+Tags returns a Namer for giving a full description of a tag. The names of +scripts and regions that are not already implied by the language name will +in appended within parentheses. It returns nil if there is not data for the +given tag. The type passed to Name must be a tag. +
+ +▹ Example
+type SelfNamer struct { + // Supported defines the values supported by this Namer. + Supported language.Coverage +}+
+A SelfNamer implements a Namer that returns the name of language in this same +language. It provides a very compact mechanism to provide a comprehensive +list of languages to users in their native language. +
+ + + + + +var ( + // Self is a shared instance of a SelfNamer. + Self *SelfNamer = &self +)+ + + + + + + + + + + +
func (n SelfNamer) Name(x interface{}) string+
+Name returns the name of a given language tag in the language identified by +this tag. It supports both the language.Base and language.Tag types. +
+ + + + + + + + + + + + + + + + + + +const CLDRVersion = "29"
+ +CLDRVersion is the CLDR version from which the tables in this package are derived. +
+ + +const NumCompactTags = 747
+ +NumCompactTags is the number of common tags. The maximum tag is +NumCompactTags-1. +
+ + + + +var ErrMissingLikelyTagsData = errors.New("missing likely tags data")+
+ErrMissingLikelyTagsData indicates no information was available +to compute likely values of missing tags. +
+ + + + + + +func CompactIndex(t Tag) (index int, ok bool)+
+CompactIndex returns an index, where 0 <= index < NumCompactTags, for tags +for which data exists in the text repository. The index will change over time +and should not be stored in persistent storage. Extensions, except for the +'va' type of the 'u' extension, are ignored. It will return 0, false if no +compact tag exists, where 0 is the index for the root language (Und). +
+ + + + + + + +func ParseAcceptLanguage(s string) (tag []Tag, q []float32, err error)+
+ParseAcceptLanguage parses the contents of a Accept-Language header as +defined in http://www.ietf.org/rfc/rfc2616.txt and returns a list of Tags and +a list of corresponding quality weights. It is more permissive than RFC 2616 +and may return non-nil slices even if the input is not valid. +The Tags will be sorted by highest weight first and then by first occurrence. +Tags with a weight of zero will be dropped. An error will be returned if the +input could not be parsed. +
+ +▹ Example
+type Base struct {
+ // contains filtered or unexported fields
+}
+ +Base is an ISO 639 language code, used for encoding the base language +of a language tag. +
+ + + + + + + + + + + + +func MustParseBase(s string) Base+
+MustParseBase is like ParseBase, but panics if the given base cannot be parsed. +It simplifies safe initialization of Base values. +
+ + + + + +func ParseBase(s string) (Base, error)+
+ParseBase parses a 2- or 3-letter ISO 639 code. +It returns a ValueError if s is a well-formed but unknown language identifier +or another error if another error occurred. +
+ + + + + + + +func (b Base) ISO3() string+
+ISO3 returns the ISO 639-3 language code. +
+ + + + + + +func (b Base) IsPrivateUse() bool+
+IsPrivateUse reports whether this language code is reserved for private use. +
+ + + + + + +func (b Base) String() string+
+String returns the BCP 47 representation of the langID. +Use b as variable name, instead of id, to ensure the variable +used is consistent with that of Base in which this type is embedded. +
+ + + + + + + + +type CanonType int+
+CanonType can be used to enable or disable various types of canonicalization. +
+ + + +const ( + // Replace deprecated base languages with their preferred replacements. + DeprecatedBase CanonType = 1 << iota + // Replace deprecated scripts with their preferred replacements. + DeprecatedScript + // Replace deprecated regions with their preferred replacements. + DeprecatedRegion + // Remove redundant scripts. + SuppressScript + // Normalize legacy encodings. This includes legacy languages defined in + // CLDR as well as bibliographic codes defined in ISO-639. + Legacy + // Map the dominant language of a macro language group to the macro language + // subtag. For example cmn -> zh. + Macro + // The CLDR flag should be used if full compatibility with CLDR is required. + // There are a few cases where language.Tag may differ from CLDR. To follow all + // of CLDR's suggestions, use All|CLDR. + CLDR + + // Raw can be used to Compose or Parse without Canonicalization. + Raw CanonType = 0 + + // Replace all deprecated tags with their preferred replacements. + Deprecated = DeprecatedBase | DeprecatedScript | DeprecatedRegion + + // All canonicalizations recommended by BCP 47. + BCP47 = Deprecated | SuppressScript + + // All canonicalizations. + All = BCP47 | Legacy | Macro + + // Default is the canonicalization used by Parse, Make and Compose. To + // preserve as much information as possible, canonicalizations that remove + // potentially valuable information are not included. The Matcher is + // designed to recognize similar tags that would be the same if + // they were canonicalized using All. + Default = Deprecated | Legacy +)+ + + + + +
▹ Example
+func (c CanonType) Canonicalize(t Tag) (Tag, error)+
+Canonicalize returns the canonicalized equivalent of the tag. +
+ + + + + + +func (c CanonType) Compose(part ...interface{}) (t Tag, err error)+
+Compose creates a Tag from individual parts, which may be of type Tag, Base, +Script, Region, Variant, []Variant, Extension, []Extension or error. If a +Base, Script or Region or slice of type Variant or Extension is passed more +than once, the latter will overwrite the former. Variants and Extensions are +accumulated, but if two extensions of the same type are passed, the latter +will replace the former. A Tag overwrites all former values and typically +only makes sense as the first argument. The resulting tag is returned after +canonicalizing using CanonType c. If one or more errors are encountered, +one of the errors is returned. +
+ + + + + + +func (c CanonType) Make(s string) Tag+
+Make is a convenience wrapper for c.Parse that omits the error. +In case of an error, a sensible default is returned. +
+ + + + + + +func (c CanonType) MustParse(s string) Tag+
+MustParse is like Parse, but panics if the given BCP 47 tag cannot be parsed. +It simplifies safe initialization of Tag values. +
+ + + + + + +func (c CanonType) Parse(s string) (t Tag, err error)+
+Parse parses the given BCP 47 string and returns a valid Tag. If parsing +failed it returns an error and any part of the tag that could be parsed. +If parsing succeeded but an unknown value was found, it returns +ValueError. The Tag returned in this case is just stripped of the unknown +value. All other values are preserved. It accepts tags in the BCP 47 format +and extensions to this standard defined in +http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. +The resulting tag is canonicalized using the the canonicalization type c. +
+ + + + + + + + +type Confidence int+
+Confidence indicates the level of certainty for a given return value. +For example, Serbian may be written in Cyrillic or Latin script. +The confidence level indicates whether a value was explicitly specified, +whether it is typically the only possible value, or whether there is +an ambiguity. +
+ + + +const ( + No Confidence = iota // full confidence that there was no match + Low // most likely value picked out of a set of alternatives + High // value is generally assumed to be the correct match + Exact // exact match or explicitly specified value +)+ + + + + + + + + + + +
func Comprehends(speaker, alternative Tag) Confidence+
+Comprehends reports the confidence score for a speaker of a given language +to being able to comprehend the written form of an alternative language. +
+ +▹ Example
+func (c Confidence) String() string+ + + + + + + + +
type Coverage interface { + // Tags returns the list of supported tags. + Tags() []Tag + + // BaseLanguages returns the list of supported base languages. + BaseLanguages() []Base + + // Scripts returns the list of supported scripts. + Scripts() []Script + + // Regions returns the list of supported regions. + Regions() []Region +}+
+The Coverage interface is used to define the level of coverage of an +internationalization service. Note that not all types are supported by all +services. As lists may be generated on the fly, it is recommended that users +of a Coverage cache the results. +
+ + + + + +var ( + // Supported defines a Coverage that lists all supported subtags. Tags + // always returns nil. + Supported Coverage = allSubtags{} +)+ + + + + + + + + +
func NewCoverage(list ...interface{}) Coverage+
+NewCoverage returns a Coverage for the given lists. It is typically used by +packages providing internationalization services to define their level of +coverage. A list may be of type []T or func() []T, where T is either Tag, +Base, Script or Region. The returned Coverage derives the value for Bases +from Tags if no func or slice for []Base is specified. For other unspecified +types the returned Coverage will return nil for the respective methods. +
+ + + + + + + + + +type Extension struct {
+ // contains filtered or unexported fields
+}
+ +Extension is a single BCP 47 extension. +
+ + + + + + + + + + + + +func ParseExtension(s string) (e Extension, err error)+
+ParseExtension parses s as an extension and returns it on success. +
+ + + + + + + +func (e Extension) String() string+
+String returns the string representation of the extension, including the +type tag. +
+ + + + + + +func (e Extension) Tokens() []string+
+Tokens returns the list of tokens of e. +
+ + + + + + +func (e Extension) Type() byte+
+Type returns the one-byte extension type of e. It returns 0 for the zero +exception. +
+ + + + + + + + +type Matcher interface { + Match(t ...Tag) (tag Tag, index int, c Confidence) +}+
+Matcher is the interface that wraps the Match method. +
++Match returns the best match for any of the given tags, along with +a unique index associated with the returned tag and a confidence +score. +
+ + + + + + +▹ Example
+func NewMatcher(t []Tag) Matcher+
+NewMatcher returns a Matcher that matches an ordered list of preferred tags +against a list of supported tags based on written intelligibility, closeness +of dialect, equivalence of subtags and various other rules. It is initialized +with the list of supported tags. The first element is used as the default +value in case no match is found. +
++Its Match method matches the first of the given Tags to reach a certain +confidence threshold. The tags passed to Match should therefore be specified +in order of preference. Extensions are ignored for matching. +
++The index returned by the Match method corresponds to the index of the +matched tag in t, but is augmented with the Unicode extension ('u')of the +corresponding preferred tag. This allows user locale options to be passed +transparently. +
+ + + + + + + + + +type Region struct {
+ // contains filtered or unexported fields
+}
+ +Region is an ISO 3166-1 or UN M.49 code for representing countries and regions. +
+ + + + + + + + + + + + +func EncodeM49(r int) (Region, error)+
+EncodeM49 returns the Region for the given UN M.49 code. +It returns an error if r is not a valid code. +
+ + + + + +func MustParseRegion(s string) Region+
+MustParseRegion is like ParseRegion, but panics if the given region cannot be +parsed. It simplifies safe initialization of Region values. +
+ + + + + +func ParseRegion(s string) (Region, error)+
+ParseRegion parses a 2- or 3-letter ISO 3166-1 or a UN M.49 code. +It returns a ValueError if s is a well-formed but unknown region identifier +or another error if another error occurred. +
+ + + + + + + +func (r Region) Canonicalize() Region+
+Canonicalize returns the region or a possible replacement if the region is +deprecated. It will not return a replacement for deprecated regions that +are split into multiple regions. +
+ + + + + + +func (r Region) Contains(c Region) bool+
+Contains returns whether Region c is contained by Region r. It returns true +if c == r. +
+ + + + + + +func (r Region) ISO3() string+
+ISO3 returns the 3-letter ISO code of r. +Note that not all regions have a 3-letter ISO code. +In such cases this method returns "ZZZ". +
+ + + + + + +func (r Region) IsCountry() bool+
+IsCountry returns whether this region is a country or autonomous area. This +includes non-standard definitions from CLDR. +
+ + + + + + +func (r Region) IsGroup() bool+
+IsGroup returns whether this region defines a collection of regions. This +includes non-standard definitions from CLDR. +
+ + + + + + +func (r Region) IsPrivateUse() bool+
+IsPrivateUse reports whether r has the ISO 3166 User-assigned status. This +may include private-use tags that are assigned by CLDR and used in this +implementation. So IsPrivateUse and IsCountry can be simultaneously true. +
+ + + + + + +func (r Region) M49() int+
+M49 returns the UN M.49 encoding of r, or 0 if this encoding +is not defined for r. +
+ + + + + + +func (r Region) String() string+
+String returns the BCP 47 representation for the region. +It returns "ZZ" for an unspecified region. +
+ + + + + + +func (r Region) TLD() (Region, error)+
+TLD returns the country code top-level domain (ccTLD). UK is returned for GB. +In all other cases it returns either the region itself or an error. +
++This method may return an error for a region for which there exists a +canonical form with a ccTLD. To get that ccTLD canonicalize r first. The +region will already be canonicalized it was obtained from a Tag that was +obtained using any of the default methods. +
+ + +▹ Example
+type Script struct {
+ // contains filtered or unexported fields
+}
+ +Script is a 4-letter ISO 15924 code for representing scripts. +It is idiomatically represented in title case. +
+ + + + + + + + + + + + +func MustParseScript(s string) Script+
+MustParseScript is like ParseScript, but panics if the given script cannot be +parsed. It simplifies safe initialization of Script values. +
+ + + + + +func ParseScript(s string) (Script, error)+
+ParseScript parses a 4-letter ISO 15924 code. +It returns a ValueError if s is a well-formed but unknown script identifier +or another error if another error occurred. +
+ + + + + + + +func (s Script) IsPrivateUse() bool+
+IsPrivateUse reports whether this script code is reserved for private use. +
+ + + + + + +func (s Script) String() string+
+String returns the script code in title case. +It returns "Zzzz" for an unspecified script. +
+ + + + + + + + +type Tag struct {
+ // contains filtered or unexported fields
+}
+ +Tag represents a BCP 47 language tag. It is used to specify an instance of a +specific language or locale. All language tag values are guaranteed to be +well-formed. +
+ + + + + +var ( + Und Tag = Tag{} + + Afrikaans Tag = Tag{lang: _af} // af + Amharic Tag = Tag{lang: _am} // am + Arabic Tag = Tag{lang: _ar} // ar + ModernStandardArabic Tag = Tag{lang: _ar, region: _001} // ar-001 + Azerbaijani Tag = Tag{lang: _az} // az + Bulgarian Tag = Tag{lang: _bg} // bg + Bengali Tag = Tag{lang: _bn} // bn + Catalan Tag = Tag{lang: _ca} // ca + Czech Tag = Tag{lang: _cs} // cs + Danish Tag = Tag{lang: _da} // da + German Tag = Tag{lang: _de} // de + Greek Tag = Tag{lang: _el} // el + English Tag = Tag{lang: _en} // en + AmericanEnglish Tag = Tag{lang: _en, region: _US} // en-US + BritishEnglish Tag = Tag{lang: _en, region: _GB} // en-GB + Spanish Tag = Tag{lang: _es} // es + EuropeanSpanish Tag = Tag{lang: _es, region: _ES} // es-ES + LatinAmericanSpanish Tag = Tag{lang: _es, region: _419} // es-419 + Estonian Tag = Tag{lang: _et} // et + Persian Tag = Tag{lang: _fa} // fa + Finnish Tag = Tag{lang: _fi} // fi + Filipino Tag = Tag{lang: _fil} // fil + French Tag = Tag{lang: _fr} // fr + CanadianFrench Tag = Tag{lang: _fr, region: _CA} // fr-CA + Gujarati Tag = Tag{lang: _gu} // gu + Hebrew Tag = Tag{lang: _he} // he + Hindi Tag = Tag{lang: _hi} // hi + Croatian Tag = Tag{lang: _hr} // hr + Hungarian Tag = Tag{lang: _hu} // hu + Armenian Tag = Tag{lang: _hy} // hy + Indonesian Tag = Tag{lang: _id} // id + Icelandic Tag = Tag{lang: _is} // is + Italian Tag = Tag{lang: _it} // it + Japanese Tag = Tag{lang: _ja} // ja + Georgian Tag = Tag{lang: _ka} // ka + Kazakh Tag = Tag{lang: _kk} // kk + Khmer Tag = Tag{lang: _km} // km + Kannada Tag = Tag{lang: _kn} // kn + Korean Tag = Tag{lang: _ko} // ko + Kirghiz Tag = Tag{lang: _ky} // ky + Lao Tag = Tag{lang: _lo} // lo + Lithuanian Tag = Tag{lang: _lt} // lt + Latvian Tag = Tag{lang: _lv} // lv + Macedonian Tag = Tag{lang: _mk} // mk + Malayalam Tag = Tag{lang: _ml} // ml + Mongolian Tag = Tag{lang: _mn} // mn + Marathi Tag = Tag{lang: _mr} // mr + Malay Tag = Tag{lang: _ms} // ms + Burmese Tag = Tag{lang: _my} // my + Nepali Tag = Tag{lang: _ne} // ne + Dutch Tag = Tag{lang: _nl} // nl + Norwegian Tag = Tag{lang: _no} // no + Punjabi Tag = Tag{lang: _pa} // pa + Polish Tag = Tag{lang: _pl} // pl + Portuguese Tag = Tag{lang: _pt} // pt + BrazilianPortuguese Tag = Tag{lang: _pt, region: _BR} // pt-BR + EuropeanPortuguese Tag = Tag{lang: _pt, region: _PT} // pt-PT + Romanian Tag = Tag{lang: _ro} // ro + Russian Tag = Tag{lang: _ru} // ru + Sinhala Tag = Tag{lang: _si} // si + Slovak Tag = Tag{lang: _sk} // sk + Slovenian Tag = Tag{lang: _sl} // sl + Albanian Tag = Tag{lang: _sq} // sq + Serbian Tag = Tag{lang: _sr} // sr + SerbianLatin Tag = Tag{lang: _sr, script: _Latn} // sr-Latn + Swedish Tag = Tag{lang: _sv} // sv + Swahili Tag = Tag{lang: _sw} // sw + Tamil Tag = Tag{lang: _ta} // ta + Telugu Tag = Tag{lang: _te} // te + Thai Tag = Tag{lang: _th} // th + Turkish Tag = Tag{lang: _tr} // tr + Ukrainian Tag = Tag{lang: _uk} // uk + Urdu Tag = Tag{lang: _ur} // ur + Uzbek Tag = Tag{lang: _uz} // uz + Vietnamese Tag = Tag{lang: _vi} // vi + Chinese Tag = Tag{lang: _zh} // zh + SimplifiedChinese Tag = Tag{lang: _zh, script: _Hans} // zh-Hans + TraditionalChinese Tag = Tag{lang: _zh, script: _Hant} // zh-Hant + Zulu Tag = Tag{lang: _zu} // zu +)+ + + +
▹ Example (Values)
+func Compose(part ...interface{}) (t Tag, err error)+
+Compose creates a Tag from individual parts, which may be of type Tag, Base, +Script, Region, Variant, []Variant, Extension, []Extension or error. If a +Base, Script or Region or slice of type Variant or Extension is passed more +than once, the latter will overwrite the former. Variants and Extensions are +accumulated, but if two extensions of the same type are passed, the latter +will replace the former. A Tag overwrites all former values and typically +only makes sense as the first argument. The resulting tag is returned after +canonicalizing using the Default CanonType. If one or more errors are +encountered, one of the errors is returned. +
+ +▹ Example
+func Make(s string) Tag+
+Make is a convenience wrapper for Parse that omits the error. +In case of an error, a sensible default is returned. +
+ + + + + +func MustParse(s string) Tag+
+MustParse is like Parse, but panics if the given BCP 47 tag cannot be parsed. +It simplifies safe initialization of Tag values. +
+ + + + + +func Parse(s string) (t Tag, err error)+
+Parse parses the given BCP 47 string and returns a valid Tag. If parsing +failed it returns an error and any part of the tag that could be parsed. +If parsing succeeded but an unknown value was found, it returns +ValueError. The Tag returned in this case is just stripped of the unknown +value. All other values are preserved. It accepts tags in the BCP 47 format +and extensions to this standard defined in +http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. +The resulting tag is canonicalized using the default canonicalization type. +
+ +▹ Example (Errors)
+func (t Tag) Base() (Base, Confidence)+
+Base returns the base language of the language tag. If the base language is +unspecified, an attempt will be made to infer it from the context. +It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change. +
+ + +▹ Example
+func (t Tag) Extension(x byte) (ext Extension, ok bool)+
+Extension returns the extension of type x for tag t. It will return +false for ok if t does not have the requested extension. The returned +extension will be invalid in this case. +
+ + + + + + +func (t Tag) Extensions() []Extension+
+Extensions returns all extensions of t. +
+ + + + + + +func (t Tag) IsRoot() bool+
+IsRoot returns true if t is equal to language "und". +
+ + + + + + +func (t Tag) Parent() Tag+
+Parent returns the CLDR parent of t. In CLDR, missing fields in data for a +specific language are substituted with fields from the parent language. +The parent for a language may change for newer versions of CLDR. +
+ + + + + + +func (t Tag) Raw() (b Base, s Script, r Region)+
+Raw returns the raw base language, script and region, without making an +attempt to infer their values. +
+ + + + + + +func (t Tag) Region() (Region, Confidence)+
+Region returns the region for the language tag. If it was not explicitly given, it will +infer a most likely candidate from the context. +It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change. +
+ + +▹ Example
+func (t Tag) Script() (Script, Confidence)+
+Script infers the script for the language tag. If it was not explicitly given, it will infer +a most likely candidate. +If more than one script is commonly used for a language, the most likely one +is returned with a low confidence indication. For example, it returns (Cyrl, Low) +for Serbian. +If a script cannot be inferred (Zzzz, No) is returned. We do not use Zyyy (undetermined) +as one would suspect from the IANA registry for BCP 47. In a Unicode context Zyyy marks +common characters (like 1, 2, 3, '.', etc.) and is therefore more like multiple scripts. +See http://www.unicode.org/reports/tr24/#Values for more details. Zzzz is also used for +unknown value in CLDR. (Zzzz, Exact) is returned if Zzzz was explicitly specified. +Note that an inferred script is never guaranteed to be the correct one. Latin is +almost exclusively used for Afrikaans, but Arabic has been used for some texts +in the past. Also, the script that is commonly used may change over time. +It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change. +
+ + +▹ Example
+func (t Tag) SetTypeForKey(key, value string) (Tag, error)+
+SetTypeForKey returns a new Tag with the key set to type, where key and type +are of the allowed values defined for the Unicode locale extension ('u') in +http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. +An empty value removes an existing pair with the same key. +
+ + + + + + +func (t Tag) String() string+
+String returns the canonical string representation of the language tag. +
+ + + + + + +func (t Tag) TypeForKey(key string) string+
+TypeForKey returns the type associated with the given key, where key and type +are of the allowed values defined for the Unicode locale extension ('u') in +http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. +TypeForKey will traverse the inheritance chain to get the correct value. +
+ + + + + + +func (t Tag) Variants() []Variant+
+Variant returns the variants specified explicitly for this language tag. +or nil if no variant was specified. +
+ + + + + + + + +type ValueError struct {
+ // contains filtered or unexported fields
+}
+ +ValueError is returned by any of the parsing functions when the +input is well-formed but the respective subtag is not recognized +as a valid value. +
+ + + + + + + + + + + + + + +func (e ValueError) Error() string+
+Error implements the error interface. +
+ + + + + + +func (e ValueError) Subtag() string+
+Subtag returns the subtag for which the error occurred. +
+ + + + + + + + +type Variant struct {
+ // contains filtered or unexported fields
+}
+ +Variant represents a registered variant of a language as defined by BCP 47. +
+ + + + + + + + + + + + +func ParseVariant(s string) (Variant, error)+
+ParseVariant parses and returns a Variant. An error is returned if s is not +a valid variant. +
+ + + + + + + +func (v Variant) String() string+
+String returns the string representation of the variant. +
+ + + + + + + + + + + + + + + + +type Set interface { + // Contains returns true if r is contained in the set. + Contains(r rune) bool +}+
+A Set is a collection of runes. +
+ + + + + + + + + + + + +func In(rt *unicode.RangeTable) Set+
+In creates a Set with a Contains method that returns true for all runes in +the given RangeTable. +
+ +▹ Example
+func NotIn(rt *unicode.RangeTable) Set+
+In creates a Set with a Contains method that returns true for all runes not +in the given RangeTable. +
+ + + + + +func Predicate(f func(rune) bool) Set+
+Predicate creates a Set with a Contains method that returns f(r). +
+ + + + + + + + + +type Transformer struct {
+ // contains filtered or unexported fields
+}
+ +Transformer implements the transform.Transformer interface. +
+ + + + + + + + + + + + +func If(s Set, tIn, tNotIn transform.Transformer) Transformer+
+If returns a transformer that applies tIn to consecutive runes for which +s.Contains(r) and tNotIn to consecutive runes for which !s.Contains(r). Reset +is called on tIn and tNotIn at the start of each run. A Nop transformer will +substitute a nil value passed to tIn or tNotIn. Invalid UTF-8 is translated +to RuneError to determine which transformer to apply, but is passed as is to +the respective transformer. +
+ +▹ Example
+func Map(mapping func(rune) rune) Transformer+
+Map returns a Transformer that maps the runes in the input using the given +mapping. Illegal bytes in the input are converted to utf8.RuneError before +being passed to the mapping func. +
+ +▹ Example
+func Remove(s Set) Transformer+
+Remove returns a Transformer that removes runes r for which s.Contains(r). +Illegal input bytes are replaced by RuneError before being passed to f. +
+ +▹ Example
+func ReplaceIllFormed() Transformer+
+ReplaceIllFormed returns a transformer that replaces all input bytes that are +not part of a well-formed UTF-8 code sequence with utf8.RuneError. +
+ + + + + + + +func (t Transformer) Bytes(b []byte) []byte+
+Bytes returns a new byte slice with the result of converting b using t. It +calls Reset on t. It returns nil if any error was found. This can only happen +if an error-producing Transformer is passed to If. +
+ + + + + + +func (t Transformer) Reset()+ + + + + + +
func (t Transformer) Span(b []byte, atEOF bool) (n int, err error)+ + + + + + +
func (t Transformer) String(s string) string+
+String returns a string with the result of converting s using t. It calls +Reset on t. It returns the empty string if any error was found. This can only +happen if an error-producing Transformer is passed to If. +
+ + + + + + +func (t Transformer) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error)+ + + + + + + + + + + + + + + + + + +
var ( + // ErrShortDst means that the destination buffer was too short to + // receive all of the transformed bytes. + ErrShortDst = errors.New("transform: short destination buffer") + + // ErrShortSrc means that the source buffer has insufficient data to + // complete the transformation. + ErrShortSrc = errors.New("transform: short source buffer") + + // ErrEndOfSpan means that the input and output (the transformed input) + // are not identical. + ErrEndOfSpan = errors.New("transform: input and output are not identical") +)+ + +
var ( + // Discard is a Transformer for which all Transform calls succeed + // by consuming all bytes and writing nothing. + Discard Transformer = discard{} + + // Nop is a SpanningTransformer that copies src to dst. + Nop SpanningTransformer = nop{} +)+ + + + + + +
func Append(t Transformer, dst, src []byte) (result []byte, n int, err error)+
+Append appends the result of converting src[:n] using t to dst, where +n <= len(src), If err == nil, n will be len(src). It calls Reset on t. +
+ + + + + + + +func Bytes(t Transformer, b []byte) (result []byte, n int, err error)+
+Bytes returns a new byte slice with the result of converting b[:n] using t, +where n <= len(b). If err == nil, n will be len(b). It calls Reset on t. +
+ + + + + + + +func String(t Transformer, s string) (result string, n int, err error)+
+String returns a string with the result of converting s[:n] using t, where +n <= len(s). If err == nil, n will be len(s). It calls Reset on t. +
+ + + + + + + + +type NopResetter struct{}+
+NopResetter can be embedded by implementations of Transformer to add a nop +Reset method. +
+ + + + + + + + + + + + + + +func (NopResetter) Reset()+
+Reset implements the Reset method of the Transformer interface. +
+ + + + + + + + +type Reader struct {
+ // contains filtered or unexported fields
+}
+ +Reader wraps another io.Reader by transforming the bytes read. +
+ + + + + + + + + + + + +func NewReader(r io.Reader, t Transformer) *Reader+
+NewReader returns a new Reader that wraps r by transforming the bytes read +via t. It calls Reset on t. +
+ + + + + + + +func (r *Reader) Read(p []byte) (int, error)+
+Read implements the io.Reader interface. +
+ + + + + + + + +type SpanningTransformer interface { + Transformer + + // Span returns a position in src such that transforming src[:n] results in + // identical output src[:n] for these bytes. It does not necessarily return + // the largest such n. The atEOF argument tells whether src represents the + // last bytes of the input. + // + // Callers should always account for the n bytes consumed before + // considering the error err. + // + // A nil error means that all input bytes are known to be identical to the + // output produced by the Transformer. A nil error can be be returned + // regardless of whether atEOF is true. If err is nil, then then n must + // equal len(src); the converse is not necessarily true. + // + // ErrEndOfSpan means that the Transformer output may differ from the + // input after n bytes. Note that n may be len(src), meaning that the output + // would contain additional bytes after otherwise identical output. + // ErrShortSrc means that src had insufficient data to determine whether the + // remaining bytes would change. Other than the error conditions listed + // here, implementations are free to report other errors that arise. + // + // Calling Span can modify the Transformer state as a side effect. In + // effect, it does the transformation just as calling Transform would, only + // without copying to a destination buffer and only up to a point it can + // determine the input and output bytes are the same. This is obviously more + // limited than calling Transform, but can be more efficient in terms of + // copying and allocating buffers. Calls to Span and Transform may be + // interleaved. + Span(src []byte, atEOF bool) (n int, err error) +}+
+SpanningTransformer extends the Transformer interface with a Span method +that determines how much of the input already conforms to the Transformer. +
+ + + + + + + + + + + + + + + + +type Transformer interface { + // Transform writes to dst the transformed bytes read from src, and + // returns the number of dst bytes written and src bytes read. The + // atEOF argument tells whether src represents the last bytes of the + // input. + // + // Callers should always process the nDst bytes produced and account + // for the nSrc bytes consumed before considering the error err. + // + // A nil error means that all of the transformed bytes (whether freshly + // transformed from src or left over from previous Transform calls) + // were written to dst. A nil error can be returned regardless of + // whether atEOF is true. If err is nil then nSrc must equal len(src); + // the converse is not necessarily true. + // + // ErrShortDst means that dst was too short to receive all of the + // transformed bytes. ErrShortSrc means that src had insufficient data + // to complete the transformation. If both conditions apply, then + // either error may be returned. Other than the error conditions listed + // here, implementations are free to report other errors that arise. + Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) + + // Reset resets the state and allows a Transformer to be reused. + Reset() +}+
+Transformer transforms bytes. +
+ + + + + + + + + + + + +func Chain(t ...Transformer) Transformer+
+Chain returns a Transformer that applies t in sequence. +
+ + + + + +func RemoveFunc(f func(r rune) bool) Transformer+
+Deprecated: use runes.Remove instead. +
+ +▹ Example
+type Writer struct {
+ // contains filtered or unexported fields
+}
+ +Writer wraps another io.Writer by transforming the bytes read. +The user needs to call Close to flush unwritten bytes that may +be buffered. +
+ + + + + + + + + + + + +func NewWriter(w io.Writer, t Transformer) *Writer+
+NewWriter returns a new Writer that wraps w by transforming the bytes written +via t. It calls Reset on t. +
+ + + + + + + +func (w *Writer) Close() error+
+Close implements the io.Closer interface. +
+ + + + + + +func (w *Writer) Write(data []byte) (n int, err error)+
+Write implements the io.Writer interface. If there are not enough +bytes available to complete a Transform, the bytes will be buffered +for the next write. Call Close to convert the remaining bytes. +
+ + + + + + + + + + + + + + + + + + +const Size = 4
+ +The size of an Adler-32 checksum in bytes. +
+ + + + + + + +func Checksum(data []byte) uint32+
+Checksum returns the Adler-32 checksum of data. +
+ + + + + + + +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. +
+ + + + + + + + + + + + + + + + + + +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. + // http://dx.doi.org/10.1109/26.231911 + Castagnoli = 0x82f63b78 + + // Koopman's polynomial. + // Also has better error detection characteristics than IEEE. + // http://dx.doi.org/10.1109/DSN.2002.1028931 + Koopman = 0xeb31d82e +)+
+Predefined polynomials. +
+ + +const Size = 4
+ +The size of a CRC-32 checksum in bytes. +
+ + + + +var IEEETable = makeTable(IEEE)+
+IEEETable is the table for the IEEE polynomial. +
+ + + + + + +func Checksum(data []byte, tab *Table) uint32+
+Checksum returns the CRC-32 checksum of data +using the polynomial represented by the Table. +
+ + + + + + + +func ChecksumIEEE(data []byte) uint32+
+ChecksumIEEE returns the CRC-32 checksum of data +using the IEEE polynomial. +
+ + + + + + + +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. +
+ + + + + + + +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. +
+ + + + + + + +func Update(crc uint32, tab *Table, p []byte) uint32+
+Update returns the result of adding the bytes in p to the crc. +
+ + + + + + + + +type Table [256]uint32+
+Table is a 256-word table representing the polynomial for efficient processing. +
+ + + + + + + + + + + + +func MakeTable(poly uint32) *Table+
+MakeTable returns a Table constructed from the specified polynomial. +The contents of this Table must not be modified. +
+ +▹ Example
+const ( + // The ISO polynomial, defined in ISO 3309 and used in HDLC. + ISO = 0xD800000000000000 + + // The ECMA polynomial, defined in ECMA 182. + ECMA = 0xC96C5795D7870F42 +)+
+Predefined polynomials. +
+ + +const Size = 8
+ +The size of a CRC-64 checksum in bytes. +
+ + + + + + + +func Checksum(data []byte, tab *Table) uint64+
+Checksum returns the CRC-64 checksum of data +using the polynomial represented by the Table. +
+ + + + + + + +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. +
+ + + + + + + +func Update(crc uint64, tab *Table, p []byte) uint64+
+Update returns the result of adding the bytes in p to the crc. +
+ + + + + + + + +type Table [256]uint64+
+Table is a 256-word table representing the polynomial for efficient processing. +
+ + + + + + + + + + + + +func MakeTable(poly uint64) *Table+
+MakeTable returns a Table constructed from the specified polynomial. +The contents of this Table must not be modified. +
+ + + + + + + + + + + + + + + + + + + +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() 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() 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() 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. +
+ + + + + + + + + + + + + + + + + + +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 +}+
+Hash is the common interface implemented by all hash functions. +
+ + + + + + + + + + + + + + + + +type Hash32 interface { + Hash + Sum32() uint32 +}+
+Hash32 is the common interface implemented by all 32-bit hash functions. +
+ + + + + + + + + + + + + + + + +type Hash64 interface { + Hash + Sum64() uint64 +}+
+Hash64 is the common interface implemented by all 64-bit hash functions. +
+ + + + + + + + + + + + + + + + + + + + + + + + +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. + | +
var EOF = errors.New("EOF")+
+EOF is the error returned by Read when no more input is available. +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 ErrClosedPipe = errors.New("io: read/write on closed pipe")+
+ErrClosedPipe is the error used for read or write operations on a closed pipe. +
+ + +var ErrNoProgress = errors.New("multiple Read calls return no data or error")+
+ErrNoProgress is returned by some clients of an io.Reader when +many calls to Read have failed to return any data or error, +usually the sign of a broken io.Reader implementation. +
+ + +var ErrShortBuffer = errors.New("short buffer")+
+ErrShortBuffer means that a read required a longer buffer than was provided. +
+ + +var ErrShortWrite = errors.New("short write")+
+ErrShortWrite means that a write accepted fewer bytes than requested +but failed to return an explicit error. +
+ + +var ErrUnexpectedEOF = errors.New("unexpected EOF")+
+ErrUnexpectedEOF means that EOF was encountered in the +middle of reading a fixed-size block or data structure. +
+ + + + + + +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 the WriterTo interface, +the copy is implemented by calling src.WriteTo(dst). +Otherwise, if dst implements the ReaderFrom interface, +the copy is implemented by calling dst.ReadFrom(src). +
+ +▹ Example
+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. +
+ +▹ Example
+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 the ReaderFrom interface, +the copy is implemented using it. +
+ +▹ Example
+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. +
+ +▹ Example
+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. +
+ +▹ Example
+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 a WriteString method, it is invoked directly. +
+ +▹ Example
+type ByteReader interface { + ReadByte() (c byte, err error) +}+
+ByteReader is the interface that wraps the ReadByte method. +
++ReadByte reads and returns the next byte from the input. +
+ + + + + + + + + + + + + + + + +type ByteScanner interface { + ByteReader + UnreadByte() error +}+
+ByteScanner is the interface that adds the UnreadByte method to the +basic ReadByte method. +
++UnreadByte causes the next call to ReadByte to return the same byte +as the previous call to ReadByte. +It may be an error to call UnreadByte twice without an intervening +call to ReadByte. +
+ + + + + + + + + + + + + + + + +type ByteWriter interface { + WriteByte(c byte) error +}+
+ByteWriter is the interface that wraps the WriteByte method. +
+ + + + + + + + + + + + + + + + +type Closer interface { + Close() error +}+
+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 LimitedReader struct { + R Reader // underlying reader + N int64 // max bytes remaining +}+
+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. +
+ + + + + + + + + + + + + + +func (l *LimitedReader) Read(p []byte) (n int, err error)+ + + + + + + + +
type PipeReader struct {
+ // contains filtered or unexported fields
+}
+ +A PipeReader is the read half of a 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 on one end are matched with writes on the other, +copying data directly between the two; there is no internal buffering. +It is safe to call Read and Write in parallel with each other or with +Close. Close will complete once pending I/O is done. Parallel calls to +Read, and parallel calls to Write, are also safe: +the individual calls will be gated sequentially. +
+ + + + + + + +func (r *PipeReader) Close() error+
+Close closes the reader; subsequent writes to the +write half of the pipe will return the error ErrClosedPipe. +
+ + + + + + +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. +
+ + + + + + +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 struct {
+ // contains filtered or unexported fields
+}
+ +A PipeWriter is the write half of a pipe. +
+ + + + + + + + + + + + + + +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 (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 always returns nil. +
+ + + + + + +func (w *PipeWriter) Write(data []byte) (n int, err error)+
+Write implements the standard Write interface: +it writes data to the pipe, blocking until 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 interface { + Reader + Closer +}+
+ReadCloser is the interface that groups the basic Read and Close methods. +
+ + + + + + + + + + + + + + + + +type ReadSeeker interface { + Reader + Seeker +}+
+ReadSeeker is the interface that groups the basic Read and Seek methods. +
+ + + + + + + + + + + + + + + + +type ReadWriteCloser interface { + Reader + Writer + Closer +}+
+ReadWriteCloser is the interface that groups the basic Read, Write and Close methods. +
+ + + + + + + + + + + + + + + + +type ReadWriteSeeker interface { + Reader + Writer + Seeker +}+
+ReadWriteSeeker is the interface that groups the basic Read, Write and Seek methods. +
+ + + + + + + + + + + + + + + + +type ReadWriter interface { + Reader + Writer +}+
+ReadWriter is the interface that groups the basic Read and Write methods. +
+ + + + + + + + + + + + + + + + +type Reader interface { + Read(p []byte) (n int, err error) +}+
+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. +
++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. +
+ + + + + + + + + + + + +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
+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
+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
+type ReaderAt interface { + ReadAt(p []byte, off int64) (n int, err error) +}+
+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 ReaderFrom interface { + ReadFrom(r Reader) (n int64, err error) +}+
+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 io.EOF encountered during the read is also returned. +
++The Copy function uses ReaderFrom if available. +
+ + + + + + + + + + + + + + + + +type RuneReader interface { + ReadRune() (r rune, size int, err error) +}+
+RuneReader is the interface that wraps the ReadRune method. +
++ReadRune reads a single UTF-8 encoded Unicode character +and returns the rune and its size in bytes. If no character is +available, err will be set. +
+ + + + + + + + + + + + + + + + +type RuneScanner interface { + RuneReader + UnreadRune() error +}+
+RuneScanner is the interface that adds the UnreadRune method to the +basic ReadRune method. +
++UnreadRune causes the next call to ReadRune to return the same rune +as the previous call to ReadRune. +It may be an error to call UnreadRune twice without an intervening +call to ReadRune. +
+ + + + + + + + + + + + + + + + +type SectionReader struct {
+ // contains filtered or unexported fields
+}
+ +SectionReader implements Read, Seek, and ReadAt on a section +of an underlying ReaderAt. +
+ + + + + + +▹ Example
+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 (s *SectionReader) Read(p []byte) (n int, err error)+ + + + + + +
func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error)+ + +
▹ Example
+func (s *SectionReader) Seek(offset int64, whence int) (int64, error)+ + +
▹ Example
+func (s *SectionReader) Size() int64+
+Size returns the size of the section in bytes. +
+ + + + + + + + +type Seeker interface { + Seek(offset int64, whence int) (int64, error) +}+
+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: 0 means relative to the start of +the file, 1 means relative to the current offset, and 2 means +relative to the end. Seek returns the new offset relative to the +start of the file and an error, if any. +
++Seeking to an offset before the start of the file is an error. +Seeking to any positive offset is legal, but the behavior of subsequent +I/O operations on the underlying object is implementation-dependent. +
+ + + + + + + + + + + + + + + + +type WriteCloser interface { + Writer + Closer +}+
+WriteCloser is the interface that groups the basic Write and Close methods. +
+ + + + + + + + + + + + + + + + +type WriteSeeker interface { + Writer + Seeker +}+
+WriteSeeker is the interface that groups the basic Write and Seek methods. +
+ + + + + + + + + + + + + + + + +type Writer interface { + Write(p []byte) (n int, err error) +}+
+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. +
+ + + + + + + + + + + + +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. +
+ +▹ Example
+type WriterAt interface { + WriteAt(p []byte, off int64) (n int, err error) +}+
+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 WriterTo interface { + WriteTo(w Writer) (n int64, err error) +}+
+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. +
+ + + + + + + + + + + + + + + + + + + + + + + + +var Discard io.Writer = devNull(0)+
+Discard is an io.Writer on which all Write calls succeed +without doing anything. +
+ + + + + + +func NopCloser(r io.Reader) io.ReadCloser+
+NopCloser returns a ReadCloser with a no-op Close method wrapping +the provided Reader r. +
+ + + + + + + +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. +
+ +▹ Example
+func ReadDir(dirname string) ([]os.FileInfo, error)+
+ReadDir reads the directory named by dirname and returns +a list of directory entries sorted by filename. +
+ +▹ Example
+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. +
+ + + + + + + +func TempDir(dir, prefix string) (name string, err error)+
+TempDir creates a new temporary directory in the directory dir +with a name beginning with prefix and returns the path 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. +
+ +▹ Example
+func TempFile(dir, prefix string) (f *os.File, err error)+
+TempFile creates a new temporary file in the directory dir +with a name beginning with prefix, opens the file for reading +and writing, and returns the resulting *os.File. +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. +
+ +▹ Example
+func WriteFile(filename string, data []byte, perm os.FileMode) error+
+WriteFile writes data to a file named by filename. +If the file does not exist, WriteFile creates it with permissions perm; +otherwise WriteFile truncates it before writing. +
+ + + + + + + + + + + + + + + + + + +const ( + // Bits or'ed together to control what's printed. + // 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 + 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 + LstdFlags = Ldate | Ltime // initial values for the standard logger +)+
+These flags define which text to prefix to each log entry generated by the Logger. +
+ + + + + + + +func Fatal(v ...interface{})+
+Fatal is equivalent to Print() followed by a call to os.Exit(1). +
+ + + + + + + +func Fatalf(format string, v ...interface{})+
+Fatalf is equivalent to Printf() followed by a call to os.Exit(1). +
+ + + + + + + +func Fatalln(v ...interface{})+
+Fatalln is equivalent to Println() followed by a call to os.Exit(1). +
+ + + + + + + +func Flags() int+
+Flags returns the output flags for the standard logger. +
+ + + + + + + +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(v ...interface{})+
+Panic is equivalent to Print() followed by a call to panic(). +
+ + + + + + + +func Panicf(format string, v ...interface{})+
+Panicf is equivalent to Printf() followed by a call to panic(). +
+ + + + + + + +func Panicln(v ...interface{})+
+Panicln is equivalent to Println() followed by a call to panic(). +
+ + + + + + + +func Prefix() string+
+Prefix returns the output prefix for the standard logger. +
+ + + + + + + +func Print(v ...interface{})+
+Print calls Output to print to the standard logger. +Arguments are handled in the manner of fmt.Print. +
+ + + + + + + +func Printf(format string, v ...interface{})+
+Printf calls Output to print to the standard logger. +Arguments are handled in the manner of fmt.Printf. +
+ + + + + + + +func Println(v ...interface{})+
+Println calls Output to print to the standard logger. +Arguments are handled in the manner of fmt.Println. +
+ + + + + + + +func SetFlags(flag int)+
+SetFlags sets the output flags for the standard logger. +
+ + + + + + + +func SetOutput(w io.Writer)+
+SetOutput sets the output destination for the standard logger. +
+ + + + + + + +func SetPrefix(prefix string)+
+SetPrefix sets the output prefix for the standard logger. +
+ + + + + + + + +type Logger struct {
+ // contains filtered or unexported fields
+}
+ +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. +
+ + + + + + +▹ Example
+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. +The flag argument defines the logging properties. +
+ + + + + + + +func (l *Logger) Fatal(v ...interface{})+
+Fatal is equivalent to l.Print() followed by a call to os.Exit(1). +
+ + + + + + +func (l *Logger) Fatalf(format string, v ...interface{})+
+Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1). +
+ + + + + + +func (l *Logger) Fatalln(v ...interface{})+
+Fatalln is equivalent to l.Println() followed by a call to os.Exit(1). +
+ + + + + + +func (l *Logger) Flags() int+
+Flags returns the output flags for the logger. +
+ + + + + + +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. +
+ + + + + + +func (l *Logger) Panic(v ...interface{})+
+Panic is equivalent to l.Print() followed by a call to panic(). +
+ + + + + + +func (l *Logger) Panicf(format string, v ...interface{})+
+Panicf is equivalent to l.Printf() followed by a call to panic(). +
+ + + + + + +func (l *Logger) Panicln(v ...interface{})+
+Panicln is equivalent to l.Println() followed by a call to panic(). +
+ + + + + + +func (l *Logger) Prefix() string+
+Prefix returns the output prefix for the logger. +
+ + + + + + +func (l *Logger) Print(v ...interface{})+
+Print calls l.Output to print to the logger. +Arguments are handled in the manner of fmt.Print. +
+ + + + + + +func (l *Logger) Printf(format string, v ...interface{})+
+Printf calls l.Output to print to the logger. +Arguments are handled in the manner of fmt.Printf. +
+ + + + + + +func (l *Logger) Println(v ...interface{})+
+Println calls l.Output to print to the logger. +Arguments are handled in the manner of fmt.Println. +
+ + + + + + +func (l *Logger) SetFlags(flag int)+
+SetFlags sets the output flags for the logger. +
+ + + + + + +func (l *Logger) SetOutput(w io.Writer)+
+SetOutput sets the output destination for the logger. +
+ + + + + + +func (l *Logger) SetPrefix(prefix string)+
+SetPrefix sets the output prefix for the logger. +
+ + + + + + + + + + + + + + + + +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. The logFlag +argument is the flag set passed through to log.New to create +the Logger. +
+ + + + + + + + +type Priority int+
+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. +
+ + + +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 struct {
+ // contains filtered or unexported fields
+}
+ +A Writer is a connection to a syslog server. +
+ + + + + + + + + + + + +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 given facility, severity and +tag. +If network is empty, Dial will connect to the local syslog server. +
+ + + + + +func New(priority Priority, tag string) (w *Writer, err 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 and prefix. +
+ + + + + + + +func (w *Writer) Alert(m string) (err error)+
+Alert logs a message with severity LOG_ALERT, ignoring the severity +passed to New. +
+ + + + + + +func (w *Writer) Close() error+
+Close closes a connection to the syslog daemon. +
+ + + + + + +func (w *Writer) Crit(m string) (err error)+
+Crit logs a message with severity LOG_CRIT, ignoring the severity +passed to New. +
+ + + + + + +func (w *Writer) Debug(m string) (err error)+
+Debug logs a message with severity LOG_DEBUG, ignoring the severity +passed to New. +
+ + + + + + +func (w *Writer) Emerg(m string) (err error)+
+Emerg logs a message with severity LOG_EMERG, ignoring the severity +passed to New. +
+ + + + + + +func (w *Writer) Err(m string) (err error)+
+Err logs a message with severity LOG_ERR, ignoring the severity +passed to New. +
+ + + + + + +func (w *Writer) Info(m string) (err error)+
+Info logs a message with severity LOG_INFO, ignoring the severity +passed to New. +
+ + + + + + +func (w *Writer) Notice(m string) (err error)+
+Notice logs a message with severity LOG_NOTICE, ignoring the +severity passed to New. +
+ + + + + + +func (w *Writer) Warning(m string) (err error)+
+Warning logs a message with severity LOG_WARNING, ignoring the +severity passed to New. +
+ + + + + + +func (w *Writer) Write(b []byte) (int, error)+
+Write sends a log message to the syslog daemon. +
+ + + + + + + + + + +▹ Example (EConvergents)
+▹ Example (Fibonacci)
+▹ Example (Sqrt2)
+const ( + MaxExp = math.MaxInt32 // largest supported exponent + MinExp = math.MinInt32 // smallest supported exponent + MaxPrec = math.MaxUint32 // largest (theoretically) supported precision; likely memory-limited +)+
+Exponent and precision limits. +
+ + +const MaxBase = 'z' - 'a' + 10 + 1
+ +MaxBase is the largest number base accepted for string conversions. +
+ + + + + + + +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 int8+
+Accuracy describes the rounding error produced by the most recent +operation that generated a Float value, relative to the exact value. +
+ + + +const ( + Below Accuracy = -1 + Exact Accuracy = 0 + Above Accuracy = +1 +)+
+Constants describing the Accuracy of a Float. +
+ + + + + + + + + + + + + +func (i Accuracy) String() string+ + + + + + + + +
type ErrNaN struct {
+ // contains filtered or unexported fields
+}
+ +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. +
+ + + + + + + + + + + + + + +func (err ErrNaN) Error() string+ + + + + + + + +
type Float struct {
+ // contains filtered or unexported fields
+}
+ +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 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. +
+ + + + + + + + + + + + +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(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 (z *Float) Abs(x *Float) *Float+
+Abs sets z to the (possibly rounded) value |x| (the absolute value of x) +and returns z. +
+ + + + + + +func (x *Float) Acc() Accuracy+
+Acc returns the accuracy of x produced by the most recent operation. +
+ + + + + + +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. +
++BUG(gri) When rounding ToNegativeInf, the sign of Float values rounded to 0 is incorrect. +
+ + +▹ Example
+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 (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
+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 (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 (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 (x *Float) Format(s fmt.State, format rune)+
+Format implements fmt.Formatter. It accepts all the regular +formats for floating-point numbers ('e', 'E', 'f', 'F', 'g', +'G') as well as 'b', 'p', and 'v'. See (*Float).Text for the +interpretation of 'b' and '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 verbs +'+' and ' ' for sign control, '0' for space or zero padding, +and '-' for left or right justification. See the fmt package +for details. +
+ + + + + + +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 (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 (x *Float) IsInf() bool+
+IsInf reports whether x is +Inf or -Inf. +
+ + + + + + +func (x *Float) IsInt() bool+
+IsInt reports whether x is an integer. +±Inf values are not integers. +
+ + + + + + +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 (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 (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 (x *Float) Mode() RoundingMode+
+Mode returns the rounding mode of x. +
+ + + + + + +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 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 (z *Float) Neg(x *Float) *Float+
+Neg sets z to the (possibly rounded) value of x with its sign negated, +and returns z. +
+ + + + + + +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. +
++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. +If z's precision is 0, it is changed to 64 before rounding takes effect. +The number must be of the form: +
+number = [ sign ] [ prefix ] mantissa [ exponent ] | infinity . + sign = "+" | "-" . + prefix = "0" ( "x" | "X" | "b" | "B" ) . + mantissa = digits | digits "." [ digits ] | "." digits . + exponent = ( "E" | "e" | "p" ) [ sign ] digits . + digits = digit { digit } . + digit = "0" ... "9" | "a" ... "z" | "A" ... "Z" . + infinity = [ sign ] ( "inf" | "Inf" ) . ++
+The base argument must be 0, 2, 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 +"0x" or "0X" selects base 16, and a "0b" or "0B" prefix selects +base 2; 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" exponent indicates a binary (rather then decimal) exponent; +for instance "0x1.fffffffffffffp1023" (using base 0) represents the +maximum float64 value. For hexadecimal mantissae, the exponent must +be binary, 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 (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 (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 Add. +Quo panics with ErrNaN if both operands are zero or infinities. +The value of z is undefined in that case. +
+ + + + + + +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 (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 (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 (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 (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 (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 (z *Float) SetMantExp(mant *Float, exp int) *Float+
+SetMantExp sets z to mant × 2**exp and and returns z. +The result z has the same precision and rounding mode +as mant. SetMantExp is an inverse of MantExp but does +not require 0.5 <= |mant| < 1.0. Specifically: +
+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 (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 (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 (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 (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 Parse, with base argument 0. +
+ + + + + + +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 (x *Float) Sign() int+
+Sign returns: +
+-1 if x < 0 + 0 if x is ±0 ++1 if x > 0 ++ + + + + + +
func (x *Float) Signbit() bool+
+Signbit returns true if x is negative or negative zero. +
+ + + + + + +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 (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 Add. +Sub panics with ErrNaN if x and y are infinities with equal +signs. The value of z is undefined in that case. +
+ + + + + + +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 +'b' -ddddddp±dd, binary exponent +'p' -0x.dddp±dd, binary exponent, hexadecimal mantissa ++
+For the binary exponent formats, the mantissa is printed in normalized form: +
+'b' decimal integer mantissa using x.Prec() bits, or -0 +'p' hexadecimal fraction with 0.5 <= 0.mantissa < 1.0, or -0 ++
+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', and 'G' formats. For 'e', 'E', and 'f' +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' or 'p' format. +
+ + + + + + +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 (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 struct {
+ // contains filtered or unexported fields
+}
+ +An Int represents a signed multi-precision integer. +The zero value for an Int represents the value 0. +
+ + + + + + + + + + + + +func NewInt(x int64) *Int+
+NewInt allocates and returns a new Int set to x. +
+ + + + + + + +func (z *Int) Abs(x *Int) *Int+
+Abs sets z to |x| (the absolute value of x) and returns z. +
+ + + + + + +func (z *Int) Add(x, y *Int) *Int+
+Add sets z to the sum x+y and returns z. +
+ + + + + + +func (z *Int) And(x, y *Int) *Int+
+And sets z = x & y and returns z. +
+ + + + + + +func (z *Int) AndNot(x, y *Int) *Int+
+AndNot sets z = x &^ y and returns z. +
+ + + + + + +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 (z *Int) Binomial(n, k int64) *Int+
+Binomial sets z to the binomial coefficient of (n, k) and returns z. +
+ + + + + + +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 (x *Int) BitLen() int+
+BitLen returns the length of the absolute value of x in bits. +The bit length of 0 is 0. +
+ + + + + + +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 (x *Int) Bytes() []byte+
+Bytes returns the absolute value of x as a big-endian byte slice. +
+ + + + + + +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 (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 DivMod for more details. +
+ + + + + + +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 QuoRem for T-division and modulus (like Go). +
+ + + + + + +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 y <= 0, the result is 1 mod |m|; if m == nil or m == 0, z = x**y. +See Knuth, volume 2, section 4.6.3. +
+ + + + + + +func (x *Int) Format(s fmt.State, ch rune)+
+Format is a support routine for fmt.Formatter. It accepts +the formats 'b' (binary), 'o' (octal), 'd' (decimal), 'x' +(lowercase hexadecimal), and 'X' (uppercase hexadecimal). +Also supported are the full suite of package fmt's format +verbs 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 left or +right justification. +
+ + + + + + +func (z *Int) GCD(x, y, a, b *Int) *Int+
+GCD sets z to the greatest common divisor of a and b, which both must +be > 0, and returns z. +If x and y are not nil, GCD sets x and y such that z = a*x + b*y. +If either a or b is <= 0, GCD sets z = x = y = 0. +
+ + + + + + +func (z *Int) GobDecode(buf []byte) error+
+GobDecode implements the gob.GobDecoder interface. +
+ + + + + + +func (x *Int) GobEncode() ([]byte, error)+
+GobEncode implements the gob.GobEncoder interface. +
+ + + + + + +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 (z *Int) Lsh(x *Int, n uint) *Int+
+Lsh sets z = x << n and returns z. +
+ + + + + + +func (x *Int) MarshalJSON() ([]byte, error)+
+MarshalJSON implements the json.Marshaler interface. +
+ + + + + + +func (x *Int) MarshalText() (text []byte, err error)+
+MarshalText implements the encoding.TextMarshaler interface. +
+ + + + + + +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 DivMod for more details. +
+ + + + + + +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, the result is undefined. +
+ + + + + + +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. +
+ + + + + + +func (z *Int) Mul(x, y *Int) *Int+
+Mul sets z to the product x*y and returns z. +
+ + + + + + +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 (z *Int) Neg(x *Int) *Int+
+Neg sets z to -x and returns z. +
+ + + + + + +func (z *Int) Not(x *Int) *Int+
+Not sets z = ^x and returns z. +
+ + + + + + +func (z *Int) Or(x, y *Int) *Int+
+Or sets z = x | y and returns z. +
+ + + + + + +func (x *Int) ProbablyPrime(n int) bool+
+ProbablyPrime performs n Miller-Rabin tests to check whether x is prime. +If x is prime, it returns true. +If x is not prime, it returns false with probability at least 1 - ¼ⁿ. +
++It is not suitable for judging primes that an adversary may have crafted +to fool this test. +
+ + + + + + +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 QuoRem for more details. +
+ + + + + + +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 (z *Int) Rand(rnd *rand.Rand, n *Int) *Int+
+Rand sets z to a pseudo-random number in [0, n) and returns z. +
+ + + + + + +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 QuoRem for more details. +
+ + + + + + +func (z *Int) Rsh(x *Int, n uint) *Int+
+Rsh sets z = x >> n and returns z. +
+ + + + + + +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
+func (z *Int) Set(x *Int) *Int+
+Set sets z to x and returns z. +
+ + + + + + +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 (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 (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 (z *Int) SetInt64(x int64) *Int+
+SetInt64 sets z to x and returns z. +
+ + + + + + +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. 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. If the base +is 0, the string prefix determines the actual conversion base. A prefix of +“0x” or “0X” selects base 16; the “0” prefix selects base 8, and a +“0b” or “0B” prefix selects base 2. Otherwise the selected base is 10. +
+ + +▹ Example
+func (z *Int) SetUint64(x uint64) *Int+
+SetUint64 sets z to x and returns z. +
+ + + + + + +func (x *Int) Sign() int+
+Sign returns: +
+-1 if x < 0 + 0 if x == 0 ++1 if x > 0 ++ + + + + + +
func (x *Int) String() string+ + + + + + +
func (z *Int) Sub(x, y *Int) *Int+
+Sub sets z to the difference x-y and returns z. +
+ + + + + + +func (x *Int) Text(base int) string+
+Text returns the string representation of x in the given base. +Base must be between 2 and 36, inclusive. The result uses the +lower-case letters 'a' to 'z' for digit values >= 10. No base +prefix (such as "0x") is added to the string. +
+ + + + + + +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 (z *Int) UnmarshalJSON(text []byte) error+
+UnmarshalJSON implements the json.Unmarshaler interface. +
+ + + + + + +func (z *Int) UnmarshalText(text []byte) error+
+UnmarshalText implements the encoding.TextUnmarshaler interface. +
+ + + + + + +func (z *Int) Xor(x, y *Int) *Int+
+Xor sets z = x ^ y and returns z. +
+ + + + + + + + +type Rat struct {
+ // contains filtered or unexported fields
+}
+ +A Rat represents a quotient a/b of arbitrary precision. +The zero value for a Rat represents the value 0. +
+ + + + + + + + + + + + +func NewRat(a, b int64) *Rat+
+NewRat creates a new Rat with numerator a and denominator b. +
+ + + + + + + +func (z *Rat) Abs(x *Rat) *Rat+
+Abs sets z to |x| (the absolute value of x) and returns z. +
+ + + + + + +func (z *Rat) Add(x, y *Rat) *Rat+
+Add sets z to the sum x+y and returns z. +
+ + + + + + +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 (x *Rat) Denom() *Int+
+Denom returns the denominator of x; it is always > 0. +The result is a reference to x's denominator; it +may change if a new value is assigned to x, and vice versa. +
+ + + + + + +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 (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 (x *Rat) FloatString(prec int) string+
+FloatString returns a string representation of x in decimal form with prec +digits of precision after the decimal point. The last digit is rounded to +nearest, with halves rounded away from zero. +
+ + + + + + +func (z *Rat) GobDecode(buf []byte) error+
+GobDecode implements the gob.GobDecoder interface. +
+ + + + + + +func (x *Rat) GobEncode() ([]byte, error)+
+GobEncode implements the gob.GobEncoder interface. +
+ + + + + + +func (z *Rat) Inv(x *Rat) *Rat+
+Inv sets z to 1/x and returns z. +
+ + + + + + +func (x *Rat) IsInt() bool+
+IsInt reports whether the denominator of x is 1. +
+ + + + + + +func (x *Rat) MarshalText() (text []byte, err error)+
+MarshalText implements the encoding.TextMarshaler interface. +
+ + + + + + +func (z *Rat) Mul(x, y *Rat) *Rat+
+Mul sets z to the product x*y and returns z. +
+ + + + + + +func (z *Rat) Neg(x *Rat) *Rat+
+Neg sets z to -x and returns z. +
+ + + + + + +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 (z *Rat) Quo(x, y *Rat) *Rat+
+Quo sets z to the quotient x/y and returns z. +If y == 0, a division-by-zero run-time panic occurs. +
+ + + + + + +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 (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
+func (z *Rat) Set(x *Rat) *Rat+
+Set sets z to x (by making a copy of x) and returns z. +
+ + + + + + +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 (z *Rat) SetFrac(a, b *Int) *Rat+
+SetFrac sets z to a/b and returns z. +
+ + + + + + +func (z *Rat) SetFrac64(a, b int64) *Rat+
+SetFrac64 sets z to a/b and returns z. +
+ + + + + + +func (z *Rat) SetInt(x *Int) *Rat+
+SetInt sets z to x (by making a copy of x) and returns z. +
+ + + + + + +func (z *Rat) SetInt64(x int64) *Rat+
+SetInt64 sets z to x and returns z. +
+ + + + + + +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 fraction "a/b" or as a floating-point number +optionally followed by an exponent. If the operation failed, the value of +z is undefined but the returned value is nil. +
+ + +▹ Example
+func (x *Rat) Sign() int+
+Sign returns: +
+-1 if x < 0 + 0 if x == 0 ++1 if x > 0 ++ + + + + + +
func (x *Rat) String() string+
+String returns a string representation of x in the form "a/b" (even if b == 1). +
+ + + + + + +func (z *Rat) Sub(x, y *Rat) *Rat+
+Sub sets z to the difference x-y and returns z. +
+ + + + + + +func (z *Rat) UnmarshalText(text []byte) error+
+UnmarshalText implements the encoding.TextUnmarshaler interface. +
+ + + + + + + + +type RoundingMode byte+
+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. +
+ + + +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 +)+
+These constants define supported rounding modes. +
+ + + + + +▹ Example
+func (i RoundingMode) String() string+ + + + + + + + +
type Word uintptr+
+A Word represents a single digit of a multi-precision unsigned integer. +
+ + + + + + + + + + + + + + + + + + +func Abs(x complex128) float64+
+Abs returns the absolute value (also called the modulus) of x. +
+ + + + + + + +func Acos(x complex128) complex128+
+Acos returns the inverse cosine of x. +
+ + + + + + + +func Acosh(x complex128) complex128+
+Acosh returns the inverse hyperbolic cosine of x. +
+ + + + + + + +func Asin(x complex128) complex128+
+Asin returns the inverse sine of x. +
+ + + + + + + +func Asinh(x complex128) complex128+
+Asinh returns the inverse hyperbolic sine of x. +
+ + + + + + + +func Atan(x complex128) complex128+
+Atan returns the inverse tangent of x. +
+ + + + + + + +func Atanh(x complex128) complex128+
+Atanh returns the inverse hyperbolic tangent of x. +
+ + + + + + + +func Conj(x complex128) complex128+
+Conj returns the complex conjugate of x. +
+ + + + + + + +func Cos(x complex128) complex128+
+Cos returns the cosine of x. +
+ + + + + + + +func Cosh(x complex128) complex128+
+Cosh returns the hyperbolic cosine of x. +
+ + + + + + + +func Cot(x complex128) complex128+
+Cot returns the cotangent of x. +
+ + + + + + + +func Exp(x complex128) complex128+
+Exp returns e**x, the base-e exponential of x. +
+ + + + + + + +func Inf() complex128+
+Inf returns a complex infinity, complex(+Inf, +Inf). +
+ + + + + + + +func IsInf(x complex128) bool+
+IsInf returns true if either real(x) or imag(x) is an infinity. +
+ + + + + + + +func IsNaN(x complex128) bool+
+IsNaN returns true if either real(x) or imag(x) is NaN +and neither is an infinity. +
+ + + + + + + +func Log(x complex128) complex128+
+Log returns the natural logarithm of x. +
+ + + + + + + +func Log10(x complex128) complex128+
+Log10 returns the decimal logarithm of x. +
+ + + + + + + +func NaN() complex128+
+NaN returns a complex “not-a-number” value. +
+ + + + + + + +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(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]. +
+ + + + + + + +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(r, θ float64) complex128+
+Rect returns the complex number x with polar coordinates r, θ. +
+ + + + + + + +func Sin(x complex128) complex128+
+Sin returns the sine of x. +
+ + + + + + + +func Sinh(x complex128) complex128+
+Sinh returns the hyperbolic sine of x. +
+ + + + + + + +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(x complex128) complex128+
+Tan returns the tangent of x. +
+ + + + + + + +func Tanh(x complex128) complex128+
+Tanh returns the hyperbolic tangent of x. +
+ + + + + + + + + + + + + + + + + + +const ( + E = 2.71828182845904523536028747135266249775724709369995957496696763 // http://oeis.org/A001113 + Pi = 3.14159265358979323846264338327950288419716939937510582097494459 // http://oeis.org/A000796 + Phi = 1.61803398874989484820458683436563811772030917980576286213544862 // http://oeis.org/A001622 + + Sqrt2 = 1.41421356237309504880168872420969807856967187537694807317667974 // http://oeis.org/A002193 + SqrtE = 1.64872127070012814684865078781416357165377610071014801157507931 // http://oeis.org/A019774 + SqrtPi = 1.77245385090551602729816748334114518279754945612238712821380779 // http://oeis.org/A002161 + SqrtPhi = 1.27201964951406896425242246173749149171560804184009624861664038 // http://oeis.org/A139339 + + Ln2 = 0.693147180559945309417232121458176568075500134360255254120680009 // http://oeis.org/A002162 + Log2E = 1 / Ln2 + Ln10 = 2.30258509299404568401799145468436420760110148862877297603332790 // http://oeis.org/A002392 + Log10E = 1 / Ln10 +)+
+Mathematical constants. +
+ + +const ( + MaxFloat32 = 3.40282346638528859811704183484516925440e+38 // 2**127 * (2**24 - 1) / 2**23 + SmallestNonzeroFloat32 = 1.401298464324817070923729583289916131280e-45 // 1 / 2**(127 - 1 + 23) + + MaxFloat64 = 1.797693134862315708145274237317043567981e+308 // 2**1023 * (2**53 - 1) / 2**52 + SmallestNonzeroFloat64 = 4.940656458412465441765687928682213723651e-324 // 1 / 2**(1023 - 1 + 52) +)+
+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 ( + MaxInt8 = 1<<7 - 1 + MinInt8 = -1 << 7 + MaxInt16 = 1<<15 - 1 + MinInt16 = -1 << 15 + MaxInt32 = 1<<31 - 1 + MinInt32 = -1 << 31 + MaxInt64 = 1<<63 - 1 + MinInt64 = -1 << 63 + MaxUint8 = 1<<8 - 1 + MaxUint16 = 1<<16 - 1 + MaxUint32 = 1<<32 - 1 + MaxUint64 = 1<<64 - 1 +)+
+Integer limit values. +
+ + + + + + + +func Abs(x float64) float64+
+Abs returns the absolute value of x. +
++Special cases are: +
+Abs(±Inf) = +Inf +Abs(NaN) = NaN ++ + + + + + + +
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 ++ + + + + + + +
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 ++ + + + + + + +
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 ++ + + + + + + +
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 ++ + + + + + + +
func Atan(x float64) float64+
+Atan returns the arctangent, in radians, of x. +
++Special cases are: +
+Atan(±0) = ±0 +Atan(±Inf) = ±Pi/2 ++ + + + + + + +
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 ++ + + + + + + +
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 ++ + + + + + + +
func Cbrt(x float64) float64+
+Cbrt returns the cube root of x. +
++Special cases are: +
+Cbrt(±0) = ±0 +Cbrt(±Inf) = ±Inf +Cbrt(NaN) = NaN ++ + + + + + + +
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 ++ + + + + + + +
func Copysign(x, y float64) float64+
+Copysign returns a value with the magnitude +of x and the sign of y. +
+ + + + + + + +func Cos(x float64) float64+
+Cos returns the cosine of the radian argument x. +
++Special cases are: +
+Cos(±Inf) = NaN +Cos(NaN) = NaN ++ + + + + + + +
func Cosh(x float64) float64+
+Cosh returns the hyperbolic cosine of x. +
++Special cases are: +
+Cosh(±0) = 1 +Cosh(±Inf) = +Inf +Cosh(NaN) = NaN ++ + + + + + + +
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 ++ + + + + + + +
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(x float64) float64+
+Erfc returns the complementary error function of x. +
++Special cases are: +
+Erfc(+Inf) = 0 +Erfc(-Inf) = 2 +Erfc(NaN) = NaN ++ + + + + + + +
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. +
+ + + + + + + +func Exp2(x float64) float64+
+Exp2 returns 2**x, the base-2 exponential of x. +
++Special cases are the same as Exp. +
+ + + + + + + +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. +
+ + + + + + + +func Float32bits(f float32) uint32+
+Float32bits returns the IEEE 754 binary representation of f. +
+ + + + + + + +func Float32frombits(b uint32) float32+
+Float32frombits returns the floating point number corresponding +to the IEEE 754 binary representation b. +
+ + + + + + + +func Float64bits(f float64) uint64+
+Float64bits returns the IEEE 754 binary representation of f. +
+ + + + + + + +func Float64frombits(b uint64) float64+
+Float64frombits returns the floating point number corresponding +the IEEE 754 binary representation b. +
+ + + + + + + +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 ++ + + + + + + +
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(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(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(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(sign int) float64+
+Inf returns positive infinity if sign >= 0, negative infinity if sign < 0. +
+ + + + + + + +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(f float64) (is bool)+
+IsNaN reports whether f is an IEEE 754 “not-a-number” value. +
+ + + + + + + +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(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(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(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(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(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 ++ + + + + + + +
func Log10(x float64) float64+
+Log10 returns the decimal logarithm of x. +The special cases are the same as for Log. +
+ + + + + + + +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(x float64) float64+
+Log2 returns the binary logarithm of x. +The special cases are the same as for Log. +
+ + + + + + + +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(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 ++ + + + + + + +
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 ++ + + + + + + +
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 ++ + + + + + + +
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 ++ + + + + + + +
func NaN() float64+
+NaN returns an IEEE 754 “not-a-number” value. +
+ + + + + + + +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(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(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 ++ + + + + + + +
func Pow10(e int) float64+
+Pow10 returns 10**e, the base-10 exponential of e. +
++Special cases are: +
+Pow10(e) = +Inf for e > 309 +Pow10(e) = 0 for e < -324 ++ + + + + + + +
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 ++ + + + + + + +
func Signbit(x float64) bool+
+Signbit returns true if x is negative or negative zero. +
+ + + + + + + +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 ++ + + + + + + +
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 ++ + + + + + + +
func Sinh(x float64) float64+
+Sinh returns the hyperbolic sine of x. +
++Special cases are: +
+Sinh(±0) = ±0 +Sinh(±Inf) = ±Inf +Sinh(NaN) = NaN ++ + + + + + + +
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 ++ + + + + + + +
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 ++ + + + + + + +
func Tanh(x float64) float64+
+Tanh returns the hyperbolic tangent of x. +
++Special cases are: +
+Tanh(±0) = ±0 +Tanh(±Inf) = ±1 +Tanh(NaN) = NaN ++ + + + + + + +
func Trunc(x float64) float64+
+Trunc returns the integer value of x. +
++Special cases are: +
+Trunc(±0) = ±0 +Trunc(±Inf) = ±Inf +Trunc(NaN) = NaN ++ + + + + + + +
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(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(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 +Y1(n, x < 0) = NaN +Y1(n, NaN) = NaN ++ + + + + + + + + + + + + + + + +
Name | +Synopsis | +
---|---|
.. | +|
+ big + | ++ Package big implements arbitrary-precision arithmetic (big numbers). + | +
+ cmplx + | ++ Package cmplx provides basic constants and mathematical functions for complex numbers. + | +
+ rand + | ++ Package rand implements pseudo-random number generators. + | +
▹ Example
+▹ Example (Rand)
+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() float32+
+Float32 returns, as a float32, a pseudo-random number in [0.0,1.0) +from the default Source. +
+ + + + + + + +func Float64() float64+
+Float64 returns, as a float64, a pseudo-random number in [0.0,1.0) +from the default Source. +
+ + + + + + + +func Int() int+
+Int returns a non-negative pseudo-random int from the default Source. +
+ + + + + + + +func Int31() int32+
+Int31 returns a non-negative pseudo-random 31-bit integer as an int32 +from the default Source. +
+ + + + + + + +func Int31n(n int32) int32+
+Int31n returns, as an int32, a non-negative pseudo-random number in [0,n) +from the default Source. +It panics if n <= 0. +
+ + + + + + + +func Int63() int64+
+Int63 returns a non-negative pseudo-random 63-bit integer as an int64 +from the default Source. +
+ + + + + + + +func Int63n(n int64) int64+
+Int63n returns, as an int64, a non-negative pseudo-random number in [0,n) +from the default Source. +It panics if n <= 0. +
+ + + + + + + +func Intn(n int) int+
+Intn returns, as an int, a non-negative pseudo-random number in [0,n) +from the default Source. +It panics if n <= 0. +
+ + + + + + + +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(n int) []int+
+Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n) +from the default Source. +
+ + + + + + + +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. +
+ + + + + + + +func Seed(seed int64)+
+Seed uses the provided seed value to initialize the default Source to a +deterministic state. If Seed is not called, the generator behaves as +if seeded by Seed(1). +
+ + + + + + + +func Uint32() uint32+
+Uint32 returns a pseudo-random 32-bit value as a uint32 +from the default Source. +
+ + + + + + + + +type Rand struct {
+ // contains filtered or unexported fields
+}
+ +A Rand is a source of random numbers. +
+ + + + + + + + + + + + +func New(src Source) *Rand+
+New returns a new Rand that uses random values from src +to generate other random values. +
+ + + + + + + +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 (r *Rand) Float32() float32+
+Float32 returns, as a float32, a pseudo-random number in [0.0,1.0). +
+ + + + + + +func (r *Rand) Float64() float64+
+Float64 returns, as a float64, a pseudo-random number in [0.0,1.0). +
+ + + + + + +func (r *Rand) Int() int+
+Int returns a non-negative pseudo-random int. +
+ + + + + + +func (r *Rand) Int31() int32+
+Int31 returns a non-negative pseudo-random 31-bit integer as an int32. +
+ + + + + + +func (r *Rand) Int31n(n int32) int32+
+Int31n returns, as an int32, a non-negative pseudo-random number in [0,n). +It panics if n <= 0. +
+ + + + + + +func (r *Rand) Int63() int64+
+Int63 returns a non-negative pseudo-random 63-bit integer as an int64. +
+ + + + + + +func (r *Rand) Int63n(n int64) int64+
+Int63n returns, as an int64, a non-negative pseudo-random number in [0,n). +It panics if n <= 0. +
+ + + + + + +func (r *Rand) Intn(n int) int+
+Intn returns, as an int, a non-negative pseudo-random number in [0,n). +It panics if n <= 0. +
+ + + + + + +func (r *Rand) NormFloat64() float64+
+NormFloat64 returns a normally distributed float64 in the range +[-math.MaxFloat64, +math.MaxFloat64] 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 (r *Rand) Perm(n int) []int+
+Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n). +
+ + + + + + +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. +
+ + + + + + +func (r *Rand) Seed(seed int64)+
+Seed uses the provided seed value to initialize the generator to a deterministic state. +
+ + + + + + +func (r *Rand) Uint32() uint32+
+Uint32 returns a pseudo-random 32-bit value as a uint32. +
+ + + + + + + + +type Source interface { + Int63() int64 + Seed(seed int64) +}+
+A Source represents a source of uniformly-distributed +pseudo-random int64 values in the range [0, 1<<63). +
+ + + + + + + + + + + + +func NewSource(seed int64) Source+
+NewSource returns a new pseudo-random Source seeded with the given value. +
+ + + + + + + + + +type Zipf struct {
+ // contains filtered or unexported fields
+}
+ +A Zipf generates Zipf distributed variates. +
+ + + + + + + + + + + + +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 (z *Zipf) Uint64() uint64+
+Uint64 returns a value drawn from the Zipf distribution described +by the Zipf object. +
+ + + + + + + + + + + + + + + + + + +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') +)+ + + + + + + +
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(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(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. +
+ + + + + + + +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. +The returned map, params, maps from the lowercase +attribute to the attribute value with its case preserved. +
+ + + + + + + +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.types file(s) if available under one or more of these +names: +
+/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 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 the CharsetReader's result values must be non-nil. + CharsetReader func(charset string, input io.Reader) (io.Reader, error) +}+
+A WordDecoder decodes MIME headers containing RFC 2047 encoded-words. +
+ + + + + + + + + + + + + + +func (d *WordDecoder) Decode(word string) (string, error)+
+Decode decodes an RFC 2047 encoded-word. +
+ + +▹ Example
+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
+type WordEncoder byte+
+A WordEncoder is a RFC 2047 encoded-word encoder. +
+ + + + + + + + + + + + + + +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
+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. + | +
type File interface { + io.Reader + io.ReaderAt + io.Seeker + io.Closer +}+
+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 FileHeader struct { + Filename string + Header textproto.MIMEHeader + // contains filtered or unexported fields +}+
+A FileHeader describes a file part of a multipart request. +
+ + + + + + + + + + + + + + +func (fh *FileHeader) Open() (File, error)+
+Open opens and returns the FileHeader's associated File. +
+ + + + + + + + +type Form struct { + Value map[string][]string + File map[string][]*FileHeader +}+
+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. +
+ + + + + + + + + + + + + + +func (f *Form) RemoveAll() error+
+RemoveAll removes any temporary files associated with a Form. +
+ + + + + + + + +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" + // + // As a special case, if the "Content-Transfer-Encoding" header + // has a value of "quoted-printable", that header is instead + // hidden from this map and the body is transparently decoded + // during Read calls. + Header textproto.MIMEHeader + // contains filtered or unexported fields +}+
+A Part represents a single part in a multipart body. +
+ + + + + + + + + + + + + + +func (p *Part) Close() error+ + + + + + +
func (p *Part) FileName() string+
+FileName returns the filename parameter of the Part's +Content-Disposition header. +
+ + + + + + +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 (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 struct {
+ // contains filtered or unexported fields
+}
+ +Reader is an iterator over parts in a MIME multipart body. +Reader's underlying parser consumes its input as needed. Seeking +isn't supported. +
+ + + + + + + + + + + + +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
+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. +
+ + + + + + +func (r *Reader) ReadForm(maxMemory int64) (f *Form, err error)+
+ReadForm parses an entire multipart message whose parts have +a Content-Disposition of "form-data". +It stores up to maxMemory bytes of the file parts in memory +and the remainder on disk in temporary files. +
+ + + + + + + + +type Writer struct {
+ // contains filtered or unexported fields
+}
+ +A Writer generates multipart messages. +
+ + + + + + + + + + + + +func NewWriter(w io.Writer) *Writer+
+NewWriter returns a new multipart Writer with a random boundary, +writing to w. +
+ + + + + + + +func (w *Writer) Boundary() string+
+Boundary returns the Writer's boundary. +
+ + + + + + +func (w *Writer) Close() error+
+Close finishes the multipart message and writes the trailing +boundary end line to the output. +
+ + + + + + +func (w *Writer) CreateFormField(fieldname string) (io.Writer, error)+
+CreateFormField calls CreatePart with a header using the +given field name. +
+ + + + + + +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 (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 (w *Writer) FormDataContentType() string+
+FormDataContentType returns the Content-Type for an HTTP +multipart/form-data with this Writer's Boundary. +
+ + + + + + +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 69 bytes long. +
+ + + + + + +func (w *Writer) WriteField(fieldname, value string) error+
+WriteField calls CreateFormField and then writes the given value. +
+ + + + + + + + + + + + + + + + + + +type Reader struct {
+ // contains filtered or unexported fields
+}
+ +Reader is a quoted-printable decoder. +
+ + + + + + + + + + + + +func NewReader(r io.Reader) *Reader+
+NewReader returns a quoted-printable reader, decoding from r. +
+ + + + + + + +func (r *Reader) Read(p []byte) (n int, err error)+
+Read reads and decodes quoted-printable data from the underlying reader. +
+ + + + + + + + +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 +}+
+A Writer is a quoted-printable writer that implements io.WriteCloser. +
+ + + + + + + + + + + + +func NewWriter(w io.Writer) *Writer+
+NewWriter returns a new Writer that writes to w. +
+ + + + + + + +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 (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. +
+ + + + + + + + + + + + + + + + + + +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(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(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 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 + + // 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 +}+
+Handler runs an executable in a subprocess with a CGI environment. +
+ + + + + + + + + + + + + + +func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request)+ + + + + + + + + + + + + + + + + + +
type Jar struct {
+ // contains filtered or unexported fields
+}
+ +Jar implements the http.CookieJar interface from the net/http package. +
+ + + + + + + + + + + + +func New(o *Options) (*Jar, error)+
+New returns a new cookie jar. A nil *Options is equivalent to a zero +Options. +
+ + + + + + + +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 (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 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 +}+
+Options are the options for creating a new Jar. +
+ + + + + + + + + + + + + + + + +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 +}+
+PublicSuffixList provides the public suffix of a domain. For example: +
+- the public suffix of "example.com" is "com", +- the public suffix of "foo1.foo2.foo3.co.uk" is "co.uk", and +- the public suffix of "bar.pvt.k12.ma.us" is "pvt.k12.ma.us". ++
+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. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +var ErrConnClosed = errors.New("fcgi: connection to web server closed")+
+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 ErrRequestAborted = errors.New("fcgi: request aborted by web server")+
+ErrRequestAborted is returned by Read when a handler attempts to read the +body of a request that has been aborted by the web server. +
+ + + + + + +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. +
+ + + + + + + + + + + + + + + + + + +const DefaultRemoteAddr = "1.2.3.4"
+ +DefaultRemoteAddr is the default remote address to return in RemoteAddr if +an explicit DefaultRemoteAddr isn't set on ResponseRecorder. +
+ + + + + + + + +type ResponseRecorder struct { + Code int // the HTTP response code from WriteHeader + HeaderMap http.Header // the HTTP response headers + Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to + Flushed bool + // contains filtered or unexported fields +}+
+ResponseRecorder is an implementation of http.ResponseWriter that +records its mutations for later inspection in tests. +
+ + + + + + +▹ Example
+func NewRecorder() *ResponseRecorder+
+NewRecorder returns an initialized ResponseRecorder. +
+ + + + + + + +func (rw *ResponseRecorder) Flush()+
+Flush sets rw.Flushed to true. +
+ + + + + + +func (rw *ResponseRecorder) Header() http.Header+
+Header returns the response headers. +
+ + + + + + +func (rw *ResponseRecorder) Write(buf []byte) (int, error)+
+Write always succeeds and writes to rw.Body, if not nil. +
+ + + + + + +func (rw *ResponseRecorder) WriteHeader(code int)+
+WriteHeader sets rw.Code. +
+ + + + + + +func (rw *ResponseRecorder) WriteString(str string) (int, error)+
+WriteString always succeeds and writes to rw.Body, if not nil. +
+ + + + + + + + +type Server struct { + URL string // base URL of form http://ipaddr:port with no trailing slash + Listener net.Listener + + // 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 +}+
+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. +
+ + + + + + +▹ Example
+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(handler http.Handler) *Server+
+NewTLSServer starts and returns a new Server using TLS. +The caller should call Close when finished, to shut it down. +
+ + + + + +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 (s *Server) Close()+
+Close shuts down the server and blocks until all outstanding +requests on this server have completed. +
+ + + + + + +func (s *Server) CloseClientConnections()+
+CloseClientConnections closes any open HTTP connections to the test Server. +
+ + + + + + +func (s *Server) Start()+
+Start starts a server from NewUnstartedServer. +
+ + + + + + +func (s *Server) StartTLS()+
+StartTLS starts TLS on a server from NewUnstartedServer. +
+ + + + + + + + + + + + + + + + + + +var ( + ErrPersistEOF = &http.ProtocolError{ErrorString: "persistent connection closed"} + ErrClosed = &http.ProtocolError{ErrorString: "connection closed by user"} + ErrPipeline = &http.ProtocolError{ErrorString: "pipeline error"} +)+ + +
var ErrLineTooLong = internal.ErrLineTooLong+
+ErrLineTooLong is returned when reading malformed chunked data +with lines that are too long. +
+ + + + + + +func DumpRequest(req *http.Request, body bool) (dump []byte, err 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
+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
+func DumpResponse(resp *http.Response, body bool) (dump []byte, err error)+
+DumpResponse is like DumpRequest but dumps a response. +
+ +▹ Example
+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(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. +
++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 interface { + Get() []byte + Put([]byte) +}+
+A BufferPool is an interface for getting and returning temporary +byte slices for use by io.CopyBuffer. +
+ + + + + + + + + + + + + + + + +type ClientConn struct {
+ // contains filtered or unexported fields
+}
+ +A ClientConn sends request and receives headers over an underlying +connection, while respecting the HTTP keepalive logic. ClientConn +supports hijacking the connection calling Hijack to +regain control of the underlying net.Conn and deal with it as desired. +
++ClientConn is low-level and old. Applications should instead use +Client or Transport in the net/http package. +
+ + + + + + + + + + + + +func NewClientConn(c net.Conn, r *bufio.Reader) *ClientConn+
+NewClientConn returns a new ClientConn reading and writing c. If r is not +nil, it is the buffer to use when reading c. +
++ClientConn is low-level and old. Applications should use Client or +Transport in the net/http package. +
+ + + + + +func NewProxyClientConn(c net.Conn, r *bufio.Reader) *ClientConn+
+NewProxyClientConn works like NewClientConn but writes Requests +using Request's WriteProxy method. +
++New code should not use NewProxyClientConn. See Client or +Transport in the net/http package instead. +
+ + + + + + + +func (cc *ClientConn) Close() error+
+Close calls Hijack and then also closes the underlying connection +
+ + + + + + +func (cc *ClientConn) Do(req *http.Request) (resp *http.Response, err error)+
+Do is convenience method that writes a request and reads a response. +
+ + + + + + +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 Read or Write is in progress. +
+ + + + + + +func (cc *ClientConn) Pending() int+
+Pending returns the number of unanswered requests +that have been sent on the connection. +
+ + + + + + +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 Write, but not with another Read. +
+ + + + + + +func (cc *ClientConn) Write(req *http.Request) (err error)+
+Write writes a request. An ErrPersistEOF error is returned if the connection +has been closed in an HTTP keepalive sense. If req.Close equals true, the +keepalive 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 ReverseProxy struct { + // Director 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. + 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. + FlushInterval time.Duration + + // ErrorLog specifies an optional logger for errors + // that occur when attempting to proxy the request. + // If nil, logging goes to os.Stderr via the log package's + // standard logger. + ErrorLog *log.Logger + + // BufferPool optionally specifies a buffer pool to + // get byte slices for use by io.CopyBuffer when + // copying HTTP response bodies. + BufferPool BufferPool +}+
+ReverseProxy is an HTTP Handler that takes an incoming request and +sends it to another server, proxying the response back to the +client. +
+ + + + + + +▹ Example
+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 rewrite Host headers, use ReverseProxy directly with a custom +Director policy. +
+ + + + + + + +func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request)+ + + + + + + + +
type ServerConn struct {
+ // contains filtered or unexported fields
+}
+ +A ServerConn reads requests and sends responses over an underlying +connection, until the HTTP keepalive logic commands an end. ServerConn +also allows hijacking the underlying connection by calling Hijack +to regain control over the connection. ServerConn supports pipe-lining, +i.e. requests can be read out of sync (but in the same order) while the +respective responses are sent. +
++ServerConn is low-level and old. Applications should instead use Server +in the net/http package. +
+ + + + + + + + + + + + +func NewServerConn(c net.Conn, r *bufio.Reader) *ServerConn+
+NewServerConn returns a new ServerConn reading and writing c. If r is not +nil, it is the buffer to use when reading c. +
++ServerConn is low-level and old. Applications should instead use Server +in the net/http package. +
+ + + + + + + +func (sc *ServerConn) Close() error+
+Close calls Hijack and then also closes the underlying connection +
+ + + + + + +func (sc *ServerConn) Hijack() (c net.Conn, r *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 Read or Write is in progress. +
+ + + + + + +func (sc *ServerConn) Pending() int+
+Pending returns the number of unanswered requests +that have been received on the connection. +
+ + + + + + +func (sc *ServerConn) Read() (req *http.Request, err 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 (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 Read side. +
+ + + + + + + + + + + + + + + + + + +const ( + MethodGet = "GET" + MethodHead = "HEAD" + MethodPost = "POST" + MethodPut = "PUT" + MethodPatch = "PATCH" // RFC 5741 + MethodDelete = "DELETE" + MethodConnect = "CONNECT" + MethodOptions = "OPTIONS" + MethodTrace = "TRACE" +)+
+Common HTTP methods. +
++Unless otherwise noted, these are defined in RFC 7231 section 4.3. +
+ + +const ( + StatusContinue = 100 + StatusSwitchingProtocols = 101 + + StatusOK = 200 + StatusCreated = 201 + StatusAccepted = 202 + StatusNonAuthoritativeInfo = 203 + StatusNoContent = 204 + StatusResetContent = 205 + StatusPartialContent = 206 + + StatusMultipleChoices = 300 + StatusMovedPermanently = 301 + StatusFound = 302 + StatusSeeOther = 303 + StatusNotModified = 304 + StatusUseProxy = 305 + StatusTemporaryRedirect = 307 + + StatusBadRequest = 400 + = 401 + StatusPaymentRequired = 402 + StatusForbidden = 403 + StatusNotFound = 404 + StatusMethodNotAllowed = 405 + StatusNotAcceptable = 406 + StatusProxyAuthRequired = 407 + StatusRequestTimeout = 408 + StatusConflict = 409 + StatusGone = 410 + StatusLengthRequired = 411 + StatusPreconditionFailed = 412 + StatusRequestEntityTooLarge = 413 + StatusRequestURITooLong = 414 + StatusUnsupportedMediaType = 415 + StatusRequestedRangeNotSatisfiable = 416 + StatusExpectationFailed = 417 + StatusTeapot = 418 + StatusPreconditionRequired = 428 + StatusTooManyRequests = 429 + StatusRequestHeaderFieldsTooLarge = 431 + = 451 + + StatusInternalServerError = 500 + StatusNotImplemented = 501 + StatusBadGateway = 502 + = 503 + StatusGatewayTimeout = 504 + StatusHTTPVersionNotSupported = 505 + StatusNetworkAuthenticationRequired = 511 +)+
+HTTP status codes, defined in RFC 2616. +
+ + +const DefaultMaxHeaderBytes = 1 << 20 // 1 MB ++
+DefaultMaxHeaderBytes is the maximum permitted size of the headers +in an HTTP request. +This can be overridden by setting Server.MaxHeaderBytes. +
+ + +const DefaultMaxIdleConnsPerHost = 2
+ +DefaultMaxIdleConnsPerHost is the default value of Transport's +MaxIdleConnsPerHost. +
+ + +const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
+ +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. +
+ + + + +var ( + ErrHeaderTooLong = &ProtocolError{"header too long"} + ErrShortBody = &ProtocolError{"entity body too short"} + ErrNotSupported = &ProtocolError{"feature not supported"} + ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"} + ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"} + ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"} + ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"} +)+ + +
var ( + ErrWriteAfterFlush = errors.New("Conn.Write called after Flush") + ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body") + ErrHijacked = errors.New("Conn has been hijacked") + ErrContentLength = errors.New("Conn.Write wrote more than the declared Content-Length") +)+
+Errors introduced by the HTTP server. +
+ + +var DefaultClient = &Client{}+
+DefaultClient is the default Client and is used by Get, Head, and Post. +
+ + +var DefaultServeMux = NewServeMux()+
+DefaultServeMux is the default ServeMux used by Serve. +
+ + +var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")+
+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 ErrHandlerTimeout = errors.New("http: Handler timeout")+
+ErrHandlerTimeout is returned on ResponseWriter Write calls +in handlers which have timed out. +
+ + +var ErrLineTooLong = internal.ErrLineTooLong+
+ErrLineTooLong is returned when reading request or response bodies +with malformed chunked encoding. +
+ + +var ErrMissingFile = errors.New("http: no such file")+
+ErrMissingFile is returned by FormFile when the provided file field name +is either not present in the request or not a file field. +
+ + +var ErrNoCookie = errors.New("http: named cookie not present")+
+ErrNoCookie is returned by Request's Cookie method when a cookie is not found. +
+ + +var ErrNoLocation = errors.New("http: no Location header in response")+
+ErrNoLocation is returned by Response's Location method +when no Location header is present. +
+ + +var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")+
+ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol. +
+ + + + + + +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(data []byte) string+
+DetectContentType implements the algorithm described +at http://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(w ResponseWriter, error string, code int)+
+Error replies to the request with the specified error message and HTTP code. +The error message should be plain text. +
+ + + + + + + +func Handle(pattern string, handler Handler)+
+Handle registers the handler for the given pattern +in the DefaultServeMux. +The documentation for ServeMux explains how patterns are matched. +
+ + + + + + + +func HandleFunc(pattern string, handler func(ResponseWriter, *Request))+
+HandleFunc registers the handler function for the given pattern +in the DefaultServeMux. +The documentation for ServeMux explains how patterns are matched. +
+ + + + + + + +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. +Handler is typically nil, in which case the DefaultServeMux is +used. +
++A trivial example server is: +
+package main + +import ( + "io" + "net/http" + "log" +) + +// hello world, the web server +func HelloServer(w http.ResponseWriter, req *http.Request) { + io.WriteString(w, "hello, world!\n") +} + +func main() { + http.HandleFunc("/hello", HelloServer) + log.Fatal(http.ListenAndServe(":12345", nil)) +} ++
+ListenAndServe always returns a non-nil error. +
+ + + + + + + +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. +
++A trivial example server is: +
+import ( + "log" + "net/http" +) + +func handler(w http.ResponseWriter, req *http.Request) { + w.Header().Set("Content-Type", "text/plain") + w.Write([]byte("This is an example server.\n")) +} + +func main() { + http.HandleFunc("/", handler) + log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/") + err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil) + log.Fatal(err) +} ++
+One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem. +
++ListenAndServeTLS always returns a non-nil error. +
+ + + + + + + +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-EOF error 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. +
+ + + + + + + +func NotFound(w ResponseWriter, r *Request)+
+NotFound replies to the request with an HTTP 404 not found error. +
+ + + + + + + +func ParseHTTPVersion(vers string) (major, minor int, ok bool)+
+ParseHTTPVersion parses a HTTP version string. +"HTTP/1.0" returns (1, 0, true). +
+ + + + + + + +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(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). HTTPS_PROXY takes precedence over HTTP_PROXY for https +requests. +
++The environment values may be either a complete URL or a +"host[:port]", in which case the "http" scheme is assumed. +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(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(w ResponseWriter, r *Request, urlStr 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. +
+ + + + + + + +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. +Handler is typically nil, in which case the DefaultServeMux is used. +
+ + + + + + + +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-Modified-Since 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, ServeContent uses it to +handle requests using If-Range and If-None-Match. +
++Note that *os.File implements the io.ReadSeeker interface. +
+ + + + + + + +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 direcory 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. +
++As a 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. +
+ + + + + + + +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(code int) string+
+StatusText returns a text for the HTTP status code. It returns the empty +string if the code is unknown. +
+ + + + + + + + +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 and + // CheckRedirect's error (wrapped in a url.Error) instead of + // issuing the Request req. + // + // 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. + // If Jar is nil, cookies are not sent in requests and ignored + // in responses. + 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 + // using the Request.Cancel mechanism. Requests passed + // to Client.Do may still set Request.Cancel; both will + // cancel the request. + // + // For compatibility, the Client will also use the deprecated + // CancelRequest method on Transport if found. New + // RoundTripper implementations should use Request.Cancel + // instead of implementing CancelRequest. + Timeout time.Duration +}+
+A Client is an HTTP client. Its zero value (DefaultClient) is a +usable client that uses DefaultTransport. +
++The Client's 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. +
+ + + + + + + + + + + + + + +func (c *Client) Do(req *Request) (resp *Response, err error)+
+Do sends an HTTP request and returns an HTTP response, following +policy (e.g. redirects, cookies, auth) as configured on the client. +
++An error is returned if caused by client policy (such as +CheckRedirect), or if there was an HTTP protocol error. +A non-2xx response doesn't cause an error. +
++When err is nil, resp always contains a non-nil resp.Body. +
++Callers should close resp.Body when done reading from it. If +resp.Body is not 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. +
++Generally Get, Post, or PostForm will be used instead of Do. +
+ + + + + + +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's CheckRedirect function: +
+301 (Moved Permanently) +302 (Found) +303 (See Other) +307 (Temporary Redirect) ++
+An error is returned if the Client's CheckRedirect function fails +or if there was an HTTP protocol error. A non-2xx response doesn't +cause an error. +
++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. +
+ + + + + + +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's CheckRedirect function: +
+301 (Moved Permanently) +302 (Found) +303 (See Other) +307 (Temporary Redirect) ++ + + + + + +
func (c *Client) Post(url string, bodyType 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. +
+ + + + + + +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 DefaultClient.Do. +
++When err is nil, resp always contains a non-nil resp.Body. +Caller should close resp.Body when done reading from it. +
+ + + + + + + + +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 +}+
+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. +
+ + + + + + + + + + + + + + + + +type ConnState int+
+A ConnState represents the state of a client connection to a server. +It's used by the optional Server.ConnState hook. +
+ + + +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 + // can not 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 (c ConnState) String() string+ + + + + + + + +
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 + Raw string + Unparsed []string // Raw text of unparsed attribute-value pairs +}+
+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 http://tools.ietf.org/html/rfc6265 for details. +
+ + + + + + + + + + + + + + +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. +
+ + + + + + + + +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 +}+
+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 Dir string+
+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 '/'. +
++An empty Dir is treated as ".". +
+ + + + + + + + + + + + + + +func (d Dir) Open(name string) (File, error)+ + + + + + + + +
type File interface { + io.Closer + io.Reader + io.Seeker + Readdir(count int) ([]os.FileInfo, error) + Stat() (os.FileInfo, error) +}+
+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 FileSystem interface { + Open(name string) (File, error) +}+
+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. +
+ + + + + + + + + + + + + + + + +type Flusher interface {
+ // Flush sends any buffered data to the client.
+ Flush()
+}
+ +The Flusher interface is implemented by ResponseWriters that allow +an HTTP handler to flush buffered data to the client. +
++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 Handler interface { + ServeHTTP(ResponseWriter, *Request) +}+
+A Handler responds to an HTTP request. +
++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. +
++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 hangs up the connection. +
+ + + + + + + + + + + + +func FileServer(root FileSystem) Handler+
+FileServer returns a handler that serves HTTP requests +with the contents of the file system rooted at root. +
++To use the operating system's file system implementation, +use http.Dir: +
+http.Handle("/", http.FileServer(http.Dir("/tmp"))) ++
+As a special case, the returned file server redirects any request +ending in "/index.html" to the same path, without the final +"index.html". +
+ +▹ Example
+▹ Example (StripPrefix)
+func NotFoundHandler() Handler+
+NotFoundHandler returns a simple request handler +that replies to each request with a “404 page not found” reply. +
+ + + + + +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(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 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. +
+ +▹ Example
+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 buffers all Handler writes to memory and does not +support the Hijacker or Flusher interfaces. +
+ + + + + + + + + +type HandlerFunc func(ResponseWriter, *Request)+
+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. +
+ + + + + + + + + + + + + + +func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)+
+ServeHTTP calls f(w, r). +
+ + + + + + + + +type Header map[string][]string+
+A Header represents the key-value pairs in an HTTP header. +
+ + + + + + + + + + + + + + +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. +
+ + + + + + +func (h Header) Del(key string)+
+Del deletes the values associated with key. +
+ + + + + + +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 "". +To access multiple values of a key, access the map directly +with CanonicalHeaderKey. +
+ + + + + + +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. +
+ + + + + + +func (h Header) Write(w io.Writer) error+
+Write writes a header in wire format. +
+ + + + + + +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. +
+ + + + + + + + +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. + Hijack() (net.Conn, *bufio.ReadWriter, error) +}+
+The Hijacker interface is implemented by ResponseWriters that allow +an HTTP handler to take over the connection. +
+ + + + + + +▹ Example
+type ProtocolError struct { + ErrorString string +}+
+HTTP request parsing errors. +
+ + + + + + + + + + + + + + +func (err *ProtocolError) Error() string+ + + + + + + + +
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 2616, Section 5.1.2) + // + // 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 io.ReadCloser + + // 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 means unknown if Body is not nil. + 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. Per RFC 2616, this is either the value of + // the "Host" header or the host name given in the URL itself. + // It may be of the form "host:port". + // + // For client requests Host optionally overrides the Host + // header to send. If empty, the Request.Write method uses + // the value of URL.Host. + Host string + + // Form contains the parsed form data, including both the URL + // field's query parameters and the 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 POST, PATCH, + // 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 + + // 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-URI of the + // Request-Line (RFC 2616, Section 5.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. + Cancel <-chan struct{} +}+
+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. +
+ + + + + + + + + + + + +func NewRequest(method, urlStr string, body io.Reader) (*Request, error)+
+NewRequest 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 by the Client +methods Do, Post, and PostForm, and Transport.RoundTrip. +
++NewRequest returns a Request suitable for use with Client.Do or +Transport.RoundTrip. +To create a request for use with testing a Server Handler use either +ReadRequest or manually update the Request fields. See the Request +type's documentation for the difference between inbound and outbound +request fields. +
+ + + + + +func ReadRequest(b *bufio.Reader) (req *Request, err error)+
+ReadRequest reads and parses an incoming request from b. +
+ + + + + + + +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. +
+ + + + + + +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 (r *Request) Cookie(name string) (*Cookie, error)+
+Cookie returns the named cookie provided in the request or +ErrNoCookie if not found. +
+ + + + + + +func (r *Request) Cookies() []*Cookie+
+Cookies parses and returns the HTTP cookies sent with the request. +
+ + + + + + +func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)+
+FormFile returns the first file for the provided form key. +FormFile calls ParseMultipartForm and ParseForm if necessary. +
+ + + + + + +func (r *Request) FormValue(key string) string+
+FormValue returns the first value for the named component of the query. +POST and PUT body parameters take precedence over URL query string values. +FormValue calls ParseMultipartForm and 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 (r *Request) MultipartReader() (*multipart.Reader, error)+
+MultipartReader returns a MIME multipart reader if this is a +multipart/form-data POST request, else returns nil and an error. +Use this function instead of ParseMultipartForm to +process the request body as a stream. +
+ + + + + + +func (r *Request) ParseForm() error+
+ParseForm parses the raw query from the URL and updates r.Form. +
++For POST or PUT requests, it also parses the request body as a form and +put the results into both r.PostForm and r.Form. +POST and PUT 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. +
++ParseMultipartForm calls ParseForm automatically. +It is idempotent. +
+ + + + + + +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 ParseForm if necessary. +After one call to ParseMultipartForm, subsequent calls have no effect. +
+ + + + + + +func (r *Request) PostFormValue(key string) string+
+PostFormValue returns the first value for the named component of the POST +or PUT request body. URL query parameters are ignored. +PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores +any errors returned by these functions. +If key is not present, PostFormValue returns the empty string. +
+ + + + + + +func (r *Request) ProtoAtLeast(major, minor int) bool+
+ProtoAtLeast reports whether the HTTP protocol used +in the request is at least major.minor. +
+ + + + + + +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 (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. +
+ + + + + + +func (r *Request) UserAgent() string+
+UserAgent returns the client's User-Agent, if sent in the request. +
+ + + + + + +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 TransferEncoding +hasn't been set to "identity", Write adds "Transfer-Encoding: +chunked" to the header. Body is closed after it is sent. +
+ + + + + + +func (r *Request) WriteProxy(w io.Writer) error+
+WriteProxy is like Write but writes the request in the form +expected by an HTTP proxy. In particular, WriteProxy writes the +initial Request-URI line of the request with an absolute URI, per +section 5.1.2 of RFC 2616, including the scheme and host. +In either case, WriteProxy also writes a Host header, using +either r.Host or r.URL.Host. +
+ + + + + + + + +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. (Section 4.2 of RFC 2616 requires that multiple headers + // be semantically equivalent to a comma-delimited sequence.) Values + // duplicated by other fields in this struct (e.g., ContentLength) are + // omitted from Header. + // + // Keys in the map are canonicalized (see CanonicalHeaderKey). + Header Header + + // Body represents the response body. + // + // 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 does not + // attempt to reuse HTTP/1.0 or HTTP/1.1 TCP connections + // ("keep-alive") unless the Body is read to completion and is + // closed. + // + // The Body is automatically dechunked if the server replied + // with a "chunked" Transfer-Encoding. + 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 + + // 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 + + // 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 +}+
+Response represents the response from an HTTP request. +
+ + + + + + + + + + + + +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) ++
+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. +
++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. +
+ +▹ Example
+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) ++
+Head is a wrapper around DefaultClient.Head +
+ + + + + +func Post(url string, bodyType 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. +
+ + + + + +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. +
+ + + + + +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 (r *Response) Cookies() []*Cookie+
+Cookies parses and returns the cookies set in the Set-Cookie headers. +
+ + + + + + +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 +the Response's Request. ErrNoLocation is returned if no +Location header is present. +
+ + + + + + +func (r *Response) ProtoAtLeast(major, minor int) bool+
+ProtoAtLeast reports whether the HTTP protocol used +in the response is at least major.minor. +
+ + + + + + +func (r *Response) Write(w io.Writer) error+
+Write writes r to w in the HTTP/1.n 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 ResponseWriter interface { + // Header returns the header map that will be sent by + // WriteHeader. Changing the header after a call to + // WriteHeader (or Write) has no effect unless the modified + // headers were declared as trailers by setting the + // "Trailer" header before the call to WriteHeader (see example). + // To suppress implicit response headers, set their value to nil. + Header() Header + + // Write writes the data to the connection as part of an HTTP reply. + // If 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. + Write([]byte) (int, error) + + // WriteHeader sends an HTTP response header with 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. + WriteHeader(int) +}+
+A ResponseWriter interface is used by an HTTP handler to +construct an HTTP response. +
++A ResponseWriter may not be used after the Handler.ServeHTTP method +has returned. +
+ + + + + + +▹ Example (Trailers)
+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 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) +}+
+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. +
+ + + + + +var DefaultTransport RoundTripper = &Transport{ + Proxy: ProxyFromEnvironment, + Dial: (&net.Dialer{ + Timeout: 30 * time.Second, + KeepAlive: 30 * time.Second, + }).Dial, + TLSHandshakeTimeout: 10 * time.Second, + ExpectContinueTimeout: 1 * time.Second, +}+
+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 $HTTP_PROXY and $NO_PROXY (or $http_proxy and +$no_proxy) environment variables. +
+ + + + + + + + + +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") +... ++ + + + + + + + + +
type ServeMux struct {
+ // contains filtered or unexported fields
+}
+ +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 name fixed, rooted paths, like "/favicon.ico", +or rooted subtrees, like "/images/" (note the trailing slash). +Longer patterns take precedence over shorter ones, so that +if there are handlers registered for both "/images/" +and "/images/thumbnails/", the latter handler will be +called for paths beginning "/images/thumbnails/" and the +former will receive requests for any other paths in the +"/images/" subtree. +
++Note that since a pattern ending in a slash names a rooted subtree, +the pattern "/" matches all paths not matched by other registered +patterns, not just the URL with Path == "/". +
++If a subtree has been registered and a request is received naming the +subtree root without its trailing slash, ServeMux redirects that +request to the subtree root (adding the trailing slash). This behavior can +be overridden with a separate registration for the path without +the trailing slash. For example, registering "/images/" causes ServeMux +to redirect a request for "/images" to "/images/", unless "/images" has +been registered separately. +
++Patterns may optionally begin with a host name, restricting matches to +URLs on that host only. Host-specific patterns take precedence over +general patterns, so that a handler might register for the two patterns +"/codesearch" and "codesearch.google.com/" without also taking over +requests for "http://www.google.com/". +
++ServeMux also takes care of sanitizing the URL request path, +redirecting any request containing . or .. elements or repeated slashes +to an equivalent, cleaner URL. +
+ + + + + + + + + + + + +func NewServeMux() *ServeMux+
+NewServeMux allocates and returns a new ServeMux. +
+ + + + + + + +func (mux *ServeMux) Handle(pattern string, handler Handler)+
+Handle registers the handler for the given pattern. +If a handler already exists for pattern, Handle panics. +
+ + +▹ Example
+func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))+
+HandleFunc registers the handler function for the given pattern. +
+ + + + + + +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. +
++Handler also returns the registered pattern that matches the +request or, in the case of internally-generated redirects, +the pattern 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 (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)+
+ServeHTTP dispatches the request to the handler whose +pattern most closely matches the request URL. +
+ + + + + + + + +type Server struct { + Addr string // TCP address to listen on, ":http" if empty + Handler Handler // handler to invoke, http.DefaultServeMux if nil + ReadTimeout time.Duration // maximum duration before timing out read of the request + WriteTimeout time.Duration // maximum duration before timing out write of the response + MaxHeaderBytes int // maximum size of request headers, DefaultMaxHeaderBytes if 0 + TLSConfig *tls.Config // optional TLS config, used by ListenAndServeTLS + + // TLSNextProto optionally specifies a function to take over + // ownership of the provided TLS connection when an NPN + // 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 nil, HTTP/2 support is enabled automatically. + TLSNextProto map[string]func(*Server, *tls.Conn, Handler) + + // 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) + + // ErrorLog specifies an optional logger for errors accepting + // connections and unexpected behavior from handlers. + // If nil, logging goes to os.Stderr via the log package's + // standard logger. + ErrorLog *log.Logger + // contains filtered or unexported fields +}+
+A Server defines parameters for running an HTTP server. +The zero value for Server is a valid configuration. +
+ + + + + + + + + + + + + + +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. +
+ + + + + + +func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error+
+ListenAndServeTLS listens on the TCP network address srv.Addr and +then calls Serve 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. +
+ + + + + + +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. +Serve always returns a non-nil error. +
+ + + + + + +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. +
+ + + + + + + + +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. + // If Proxy is nil or returns a nil *URL, no proxy is used. + Proxy func(*Request) (*url.URL, error) + + // Dial specifies the dial function for creating unencrypted + // TCP connections. + // If Dial is nil, net.Dial is used. + Dial func(network, addr string) (net.Conn, error) + + // DialTLS specifies an optional dial function for creating + // TLS connections for non-proxied HTTPS requests. + // + // If DialTLS is nil, Dial and TLSClientConfig are used. + // + // If DialTLS is set, the Dial hook is 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. + DialTLS func(network, addr string) (net.Conn, error) + + // TLSClientConfig specifies the TLS configuration to use with + // tls.Client. If nil, the default configuration is used. + TLSClientConfig *tls.Config + + // TLSHandshakeTimeout specifies the maximum amount of time waiting to + // wait for a TLS handshake. Zero means no timeout. + TLSHandshakeTimeout time.Duration + + // DisableKeepAlives, if true, prevents re-use of TCP connections + // between different HTTP requests. + 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 + + // MaxIdleConnsPerHost, if non-zero, controls the maximum idle + // (keep-alive) to keep per-host. If zero, + // DefaultMaxIdleConnsPerHost is used. + MaxIdleConnsPerHost int + + // 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 + + // 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. + // This time does not include the time to send the request header. + ExpectContinueTimeout time.Duration + + // TLSNextProto specifies how the Transport switches to an + // alternate protocol (such as HTTP/2) after a TLS NPN/ALPN + // protocol negotiation. If Transport dials an 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 nil, HTTP/2 support is enabled automatically. + TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper + // contains filtered or unexported fields +}+
+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's CloseIdleConnections method +and the MaxIdleConnsPerHost and 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. +See the package docs for more about HTTP/2. +
+ + + + + + + + + + + + + + +func (t *Transport) CancelRequest(req *Request)+
+CancelRequest cancels an in-flight request by closing its connection. +CancelRequest should only be called after RoundTrip has returned. +
++Deprecated: Use Request.Cancel instead. CancelRequest can not cancel +HTTP/2 requests. +
+ + + + + + +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 (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 RoundTrip itself for that one request, as if the +protocol were not registered. +
+ + + + + + +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. +
+ + + + + + + + + + + + + + + + +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. + | +
+ 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. + | +
var ErrLineTooLong = errors.New("header line too long")+ + +
var LocalhostCert = []byte(`-----BEGIN CERTIFICATE----- +MIICEzCCAXygAwIBAgIQMIMChMLGrR+QvmQvpwAU6zANBgkqhkiG9w0BAQsFADAS +MRAwDgYDVQQKEwdBY21lIENvMCAXDTcwMDEwMTAwMDAwMFoYDzIwODQwMTI5MTYw +MDAwWjASMRAwDgYDVQQKEwdBY21lIENvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB +iQKBgQDuLnQAI3mDgey3VBzWnB2L39JUU4txjeVE6myuDqkM/uGlfjb9SjY1bIw4 +iA5sBBZzHi3z0h1YV8QPuxEbi4nW91IJm2gsvvZhIrCHS3l6afab4pZBl2+XsDul +rKBxKKtD1rGxlG4LjncdabFn9gvLZad2bSysqz/qTAUStTvqJQIDAQABo2gwZjAO +BgNVHQ8BAf8EBAMCAqQwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUw +AwEB/zAuBgNVHREEJzAlggtleGFtcGxlLmNvbYcEfwAAAYcQAAAAAAAAAAAAAAAA +AAAAATANBgkqhkiG9w0BAQsFAAOBgQCEcetwO59EWk7WiJsG4x8SY+UIAA+flUI9 +tyC4lNhbcF2Idq9greZwbYCqTTTr2XiRNSMLCOjKyI7ukPoPjo16ocHj+P3vZGfs +h1fIw3cSS2OolhloGw/XM6RWPWtPAlGykKLciQrBru5NAPvCMsb/I1DAceTiotQM +fblo6RBxUQ== +-----END CERTIFICATE-----`)+
+LocalhostCert is a PEM-encoded TLS cert with SAN IPs +"127.0.0.1" and "[::1]", expiring at Jan 29 16:00:00 2084 GMT. +generated from src/crypto/tls: +go run generate_cert.go --rsa-bits 1024 --host 127.0.0.1,::1,example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h +
+ + +var LocalhostKey = []byte(`-----BEGIN RSA PRIVATE KEY----- +MIICXgIBAAKBgQDuLnQAI3mDgey3VBzWnB2L39JUU4txjeVE6myuDqkM/uGlfjb9 +SjY1bIw4iA5sBBZzHi3z0h1YV8QPuxEbi4nW91IJm2gsvvZhIrCHS3l6afab4pZB +l2+XsDulrKBxKKtD1rGxlG4LjncdabFn9gvLZad2bSysqz/qTAUStTvqJQIDAQAB +AoGAGRzwwir7XvBOAy5tM/uV6e+Zf6anZzus1s1Y1ClbjbE6HXbnWWF/wbZGOpet +3Zm4vD6MXc7jpTLryzTQIvVdfQbRc6+MUVeLKwZatTXtdZrhu+Jk7hx0nTPy8Jcb +uJqFk541aEw+mMogY/xEcfbWd6IOkp+4xqjlFLBEDytgbIECQQDvH/E6nk+hgN4H +qzzVtxxr397vWrjrIgPbJpQvBsafG7b0dA4AFjwVbFLmQcj2PprIMmPcQrooz8vp +jy4SHEg1AkEA/v13/5M47K9vCxmb8QeD/asydfsgS5TeuNi8DoUBEmiSJwma7FXY +fFUtxuvL7XvjwjN5B30pNEbc6Iuyt7y4MQJBAIt21su4b3sjXNueLKH85Q+phy2U +fQtuUE9txblTu14q3N7gHRZB4ZMhFYyDy8CKrN2cPg/Fvyt0Xlp/DoCzjA0CQQDU +y2ptGsuSmgUtWj3NM9xuwYPm+Z/F84K6+ARYiZ6PYj013sovGKUFfYAqVXVlxtIX +qyUBnu3X9ps8ZfjLZO7BAkEAlT4R5Yl6cGhaJQYZHOde3JEMhNRcVFMO8dJDaFeo +f9Oeos0UUothgiDktdQHxdNEwLjQf7lJJBzV+5OtwswCWA== +-----END RSA PRIVATE KEY-----`)+
+LocalhostKey is the private key for localhostCert. +
+ + + + + + +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(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. +
++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 struct { + *bufio.Writer +}+
+FlushAfterChunkWriter signals from the caller of NewChunkedWriter +that each chunk should be followed by a flush. It is used by the +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. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +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(name string) http.Handler+
+Handler returns an HTTP handler that serves the named profile. +
+ + + + + + + +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(w http.ResponseWriter, r *http.Request)+
+Profile responds with the pprof-formatted cpu profile. +The package initialization registers it as /debug/pprof/profile. +
+ + + + + + + +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(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. +
+ + + + + + + + + + + + + + + + + + +const ( + IPv4len = 4 + IPv6len = 16 +)+
+IP address lengths (bytes). +
+ + + + +var ( + IPv4bcast = IPv4(255, 255, 255, 255) // 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 IPv4 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} +)+
+Well-known IPv6 addresses +
+ + +var ( + ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection") +)+
+Various errors contained in OpError. +
+ + + + + + +func InterfaceAddrs() ([]Addr, error)+
+InterfaceAddrs returns a list of the system's network interface +addresses. +
+ + + + + + + +func Interfaces() ([]Interface, error)+
+Interfaces returns a list of the system's network interfaces. +
+ + + + + + + +func JoinHostPort(host, port string) string+
+JoinHostPort combines host and port into a network address of the +form "host:port" or, if host contains a colon or a percent sign, +"[host]:port". +
+ + + + + + + +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. +
+ + + + + + + +func LookupCNAME(name string) (cname string, err error)+
+LookupCNAME returns the canonical DNS host for the given name. +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. +
+ + + + + + + +func LookupHost(host string) (addrs []string, err error)+
+LookupHost looks up the given host using the local resolver. +It returns an array of that host's addresses. +
+ + + + + + + +func LookupIP(host string) (ips []IP, err error)+
+LookupIP looks up host using the local resolver. +It returns an array of that host's IPv4 and IPv6 addresses. +
+ + + + + + + +func LookupMX(name string) (mxs []*MX, err error)+
+LookupMX returns the DNS MX records for the given domain name sorted by preference. +
+ + + + + + + +func LookupNS(name string) (nss []*NS, err error)+
+LookupNS returns the DNS NS records for the given domain name. +
+ + + + + + + +func LookupPort(network, service string) (port int, err error)+
+LookupPort looks up the port for the given network and service. +
+ + + + + + + +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. +
+ + + + + + + +func LookupTXT(name string) (txts []string, err error)+
+LookupTXT returns the DNS TXT records for the given domain name. +
+ + + + + + + +func SplitHostPort(hostport string) (host, port string, err error)+
+SplitHostPort splits a network address of the form "host:port", +"[host]:port" or "[ipv6-host%zone]:port" into host or +ipv6-host%zone and port. A literal address or host name for IPv6 +must be enclosed in square brackets, as in "[::1]:80", +"[ipv6-host]:http" or "[ipv6-host%zone]:80". +
+ + + + + + + + +type Addr interface { + Network() string // name of the network + String() string // string form of address +}+
+Addr represents a network end point address. +
+ + + + + + + + + + + + + + + + +type AddrError struct { + Err string + Addr string +}+ + + + + + + + + + + + + + +
func (e *AddrError) Error() string+ + + + + + +
func (e *AddrError) Temporary() bool+ + + + + + +
func (e *AddrError) Timeout() bool+ + + + + + + + +
type Conn interface { + // Read reads data from the connection. + // Read can be made to time out and return a Error with Timeout() == true + // 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 a Error with Timeout() == true + // 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. + LocalAddr() Addr + + // RemoteAddr returns the remote network address. + 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 with a timeout (see type Error) instead of + // blocking. The deadline applies to all future I/O, not just + // the immediately following call to Read or Write. + // + // 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. + // A zero value for t means Read will not time out. + SetReadDeadline(t time.Time) error + + // SetWriteDeadline sets the deadline for future Write calls. + // 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 +}+
+Conn is a generic stream-oriented network connection. +
++Multiple goroutines may invoke methods on a Conn simultaneously. +
+ + + + + + + + + + + + +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, addresses have the form host:port. +If host is a literal IPv6 address it must be enclosed +in square brackets as in "[::1]:80" or "[ipv6-host%zone]:80". +The functions JoinHostPort and SplitHostPort manipulate addresses +in this form. +If the host is empty, as in ":80", the local system is assumed. +
++Examples: +
+Dial("tcp", "12.34.56.78:80") +Dial("tcp", "google.com:http") +Dial("tcp", "[2001:db8::1]:http") +Dial("tcp", "[fe80::1%lo0]:80") +Dial("tcp", ":80") ++
+For IP networks, the network must be "ip", "ip4" or "ip6" followed +by a colon and a protocol number or name and the addr must be a +literal IP address. +
++Examples: +
+Dial("ip4:1", "127.0.0.1") +Dial("ip6:ospf", "::1") ++
+For Unix networks, the address must be a file system path. +
+ + + + + +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. +
+ + + + + +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. +
+ + + + + +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. +
+ + + + + + + + + +type DNSConfigError struct { + Err error +}+
+DNSConfigError represents an error reading the machine's DNS configuration. +(No longer used; kept for compatibility.) +
+ + + + + + + + + + + + + + +func (e *DNSConfigError) Error() string+ + + + + + +
func (e *DNSConfigError) Temporary() bool+ + + + + + +
func (e *DNSConfigError) Timeout() bool+ + + + + + + + +
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 +}+
+DNSError represents a DNS lookup error. +
+ + + + + + + + + + + + + + +func (e *DNSError) Error() string+ + + + + + +
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 (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 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 dialing a 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 enables RFC 6555-compliant "Happy Eyeballs" dialing + // when the network is "tcp" and the destination is a host name + // with both IPv4 and IPv6 addresses. This allows a client to + // tolerate networks where one address family is silently broken. + DualStack bool + + // FallbackDelay specifies the length of time to wait before + // spawning a fallback connection, when DualStack is enabled. + // If zero, a default delay of 300ms is used. + FallbackDelay time.Duration + + // KeepAlive specifies the keep-alive period for an active + // network connection. + // If zero, keep-alives are not enabled. Network protocols + // that do not support keep-alives ignore this field. + KeepAlive time.Duration + + // Cancel is an optional channel whose closure indicates that + // the dial should be canceled. Not all types of dials support + // cancelation. + Cancel <-chan struct{} +}+
+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. +
+ + + + + + + + + + + + + + +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. +
+ + + + + + + + +type Error interface { + error + Timeout() bool // Is the error a timeout? + Temporary() bool // Is the error temporary? +}+
+An Error represents a network error. +
+ + + + + + + + + + + + + + + + +type Flags uint+ + + +
const ( + FlagUp Flags = 1 << iota // interface is 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 +)+ + + + + + + + + + + + + +
func (f Flags) String() string+ + + + + + + + +
type HardwareAddr []byte+
+A HardwareAddr represents a physical hardware address. +
+ + + + + + + + + + + + +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: +
+01:23:45:67:89:ab +01:23:45:67:89:ab:cd:ef +01:23:45:67:89:ab:cd:ef:00:00:01:23:45:67:89:ab:cd:ef:00:00 +01-23-45-67-89-ab +01-23-45-67-89-ab-cd-ef +01-23-45-67-89-ab-cd-ef-00-00-01-23-45-67-89-ab-cd-ef-00-00 +0123.4567.89ab +0123.4567.89ab.cdef +0123.4567.89ab.cdef.0000.0123.4567.89ab.cdef.0000 ++ + + + + + + +
func (a HardwareAddr) String() string+ + + + + + + + +
type IP []byte+
+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. +
+ + + + + + + + + + + + +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. +
+ + + + + +func ParseCIDR(s string) (IP, *IPNet, error)+
+ParseCIDR parses s as a CIDR notation IP address and mask, +like "192.168.100.1/24" or "2001:DB8::/48", as defined in +RFC 4632 and RFC 4291. +
++It returns the IP address and the network implied by the IP +and mask. For example, ParseCIDR("192.168.100.1/16") returns +the IP address 192.168.100.1 and the network 192.168.0.0/16. +
+ + + + + +func ParseIP(s string) IP+
+ParseIP parses s as an IP address, returning the result. +The string s can be in dotted decimal ("74.125.19.99") +or IPv6 ("2001:4860:0:2001::68") form. +If s is not a valid textual representation of an IP address, +ParseIP returns nil. +
+ + + + + + + +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. +
+ + + + + + +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. +
+ + + + + + +func (ip IP) IsGlobalUnicast() bool+
+IsGlobalUnicast reports whether ip is a global unicast +address. +
+ + + + + + +func (ip IP) IsInterfaceLocalMulticast() bool+
+IsInterfaceLocalMulticast reports whether ip is +an interface-local multicast address. +
+ + + + + + +func (ip IP) IsLinkLocalMulticast() bool+
+IsLinkLocalMulticast reports whether ip is a link-local +multicast address. +
+ + + + + + +func (ip IP) IsLinkLocalUnicast() bool+
+IsLinkLocalUnicast reports whether ip is a link-local +unicast address. +
+ + + + + + +func (ip IP) IsLoopback() bool+
+IsLoopback reports whether ip is a loopback address. +
+ + + + + + +func (ip IP) IsMulticast() bool+
+IsMulticast reports whether ip is a multicast address. +
+ + + + + + +func (ip IP) IsUnspecified() bool+
+IsUnspecified reports whether ip is an unspecified address. +
+ + + + + + +func (ip IP) MarshalText() ([]byte, error)+
+MarshalText implements the encoding.TextMarshaler interface. +The encoding is the same as returned by String. +
+ + + + + + +func (ip IP) Mask(mask IPMask) IP+
+Mask returns the result of masking the IP address ip with mask. +
+ + + + + + +func (ip IP) String() string+
+String returns the string form of the IP address ip. +If the address is an IPv4 address, the string representation +is dotted decimal ("74.125.19.99"). Otherwise the representation +is IPv6 ("2001:4860:0:2001::68"). +
+ + + + + + +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. +
+ + + + + + +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 *IP) UnmarshalText(text []byte) error+
+UnmarshalText implements the encoding.TextUnmarshaler interface. +The IP address is expected in a form accepted by ParseIP. +
+ + + + + + + + +type IPAddr struct { + IP IP + Zone string // IPv6 scoped addressing zone +}+
+IPAddr represents the address of an IP end point. +
+ + + + + + + + + + + + +func ResolveIPAddr(net, addr string) (*IPAddr, error)+
+ResolveIPAddr parses addr as an IP address of the form "host" or +"ipv6-host%zone" and resolves the domain name on the network net, +which must be "ip", "ip4" or "ip6". +
+ + + + + + + +func (a *IPAddr) Network() string+
+Network returns the address's network name, "ip". +
+ + + + + + +func (a *IPAddr) String() string+ + + + + + + + +
type IPConn struct {
+ // contains filtered or unexported fields
+}
+ +IPConn is the implementation of the Conn and PacketConn interfaces +for IP network connections. +
+ + + + + + + + + + + + +func DialIP(netProto string, laddr, raddr *IPAddr) (*IPConn, error)+
+DialIP connects to the remote address raddr on the network protocol +netProto, which must be "ip", "ip4", or "ip6" followed by a colon +and a protocol number or name. +
+ + + + + +func ListenIP(netProto string, laddr *IPAddr) (*IPConn, error)+
+ListenIP listens for incoming IP packets addressed to the local +address laddr. The returned connection's ReadFrom and WriteTo +methods can be used to receive and send IP packets with per-packet +addressing. +
+ + + + + + + +func (c *IPConn) Close() error+
+Close closes the connection. +
+ + + + + + +func (c *IPConn) File() (f *os.File, err error)+
+File sets the underlying os.File to blocking mode and returns a copy. +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 (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 (c *IPConn) Read(b []byte) (int, error)+
+Read implements the Conn Read method. +
+ + + + + + +func (c *IPConn) ReadFrom(b []byte) (int, Addr, error)+
+ReadFrom implements the PacketConn ReadFrom method. +
+ + + + + + +func (c *IPConn) ReadFromIP(b []byte) (int, *IPAddr, error)+
+ReadFromIP reads an IP packet from c, copying the payload into b. +It returns the number of bytes copied into b and the return address +that was on the packet. +
++ReadFromIP can be made to time out and return an error with +Timeout() == true after a fixed time limit; see SetDeadline and +SetReadDeadline. +
+ + + + + + +func (c *IPConn) ReadMsgIP(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error)+
+ReadMsgIP reads a packet 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 packet and the source address of the packet. +
+ + + + + + +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 (c *IPConn) SetDeadline(t time.Time) error+
+SetDeadline implements the Conn SetDeadline method. +
+ + + + + + +func (c *IPConn) SetReadBuffer(bytes int) error+
+SetReadBuffer sets the size of the operating system's +receive buffer associated with the connection. +
+ + + + + + +func (c *IPConn) SetReadDeadline(t time.Time) error+
+SetReadDeadline implements the Conn SetReadDeadline method. +
+ + + + + + +func (c *IPConn) SetWriteBuffer(bytes int) error+
+SetWriteBuffer sets the size of the operating system's +transmit buffer associated with the connection. +
+ + + + + + +func (c *IPConn) SetWriteDeadline(t time.Time) error+
+SetWriteDeadline implements the Conn SetWriteDeadline method. +
+ + + + + + +func (c *IPConn) Write(b []byte) (int, error)+
+Write implements the Conn Write method. +
+ + + + + + +func (c *IPConn) WriteMsgIP(b, oob []byte, addr *IPAddr) (n, oobn int, err error)+
+WriteMsgIP writes a packet 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. +
+ + + + + + +func (c *IPConn) WriteTo(b []byte, addr Addr) (int, error)+
+WriteTo implements the PacketConn WriteTo method. +
+ + + + + + +func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (int, error)+
+WriteToIP writes an IP packet to addr via c, copying the payload +from b. +
++WriteToIP can be made to time out and return an error with +Timeout() == true after a fixed time limit; see SetDeadline and +SetWriteDeadline. On packet-oriented connections, write timeouts +are rare. +
+ + + + + + + + +type IPMask []byte+
+An IP mask is an IP address. +
+ + + + + + + + + + + + +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. +
+ + + + + +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. +
+ + + + + + + +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 (m IPMask) String() string+
+String returns the hexadecimal form of m, with no punctuation. +
+ + + + + + + + +type IPNet struct { + IP IP // network number + Mask IPMask // network mask +}+
+An IPNet represents an IP network. +
+ + + + + + + + + + + + + + +func (n *IPNet) Contains(ip IP) bool+
+Contains reports whether the network includes ip. +
+ + + + + + +func (n *IPNet) Network() string+
+Network returns the address's network name, "ip+net". +
+ + + + + + +func (n *IPNet) String() string+
+String returns the CIDR notation of n like "192.168.100.1/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 "192.168.100.1/c000ff00". +
+ + + + + + + + +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 +}+
+Interface represents a mapping between network interface name +and index. It also represents network interface facility +information. +
+ + + + + + + + + + + + +func InterfaceByIndex(index int) (*Interface, error)+
+InterfaceByIndex returns the interface specified by index. +
+ + + + + +func InterfaceByName(name string) (*Interface, error)+
+InterfaceByName returns the interface specified by name. +
+ + + + + + + +func (ifi *Interface) Addrs() ([]Addr, error)+
+Addrs returns interface addresses for a specific interface. +
+ + + + + + +func (ifi *Interface) MulticastAddrs() ([]Addr, error)+
+MulticastAddrs returns multicast, joined group addresses for +a specific interface. +
+ + + + + + + + +type InvalidAddrError string+ + + + + + + + + + + + + + +
func (e InvalidAddrError) Error() string+ + + + + + +
func (e InvalidAddrError) Temporary() bool+ + + + + + +
func (e InvalidAddrError) Timeout() bool+ + + + + + + + +
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 +}+
+A Listener is a generic network listener for stream-oriented protocols. +
++Multiple goroutines may invoke methods on a Listener simultaneously. +
+ + + + + + +▹ Example
+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(net, laddr string) (Listener, error)+
+Listen announces on the local network address laddr. +The network net must be a stream-oriented network: "tcp", "tcp4", +"tcp6", "unix" or "unixpacket". +For TCP and UDP, the syntax of laddr is "host:port", like "127.0.0.1:8080". +If host is omitted, as in ":8080", Listen listens on all available interfaces +instead of just the interface with the given host address. +See Dial for more details about address syntax. +
+ + + + + + + + + +type MX struct { + Host string + Pref uint16 +}+
+An MX represents a single DNS MX record. +
+ + + + + + + + + + + + + + + + +type NS struct { + Host string +}+
+An NS represents a single DNS NS record. +
+ + + + + + + + + + + + + + + + +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 + + // 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. + Err error +}+
+OpError is the error type usually returned by functions in the net +package. It describes the operation, network type, and address of +an error. +
+ + + + + + + + + + + + + + +func (e *OpError) Error() string+ + + + + + +
func (e *OpError) Temporary() bool+ + + + + + +
func (e *OpError) Timeout() bool+ + + + + + + + +
type PacketConn interface { + // ReadFrom reads a packet from the connection, + // copying the payload into b. It returns the number of + // bytes copied into b and the return address that + // was on the packet. + // ReadFrom can be made to time out and return + // an error with Timeout() == true after a fixed time limit; + // see SetDeadline and SetReadDeadline. + ReadFrom(b []byte) (n int, addr Addr, err error) + + // WriteTo writes a packet with payload b to addr. + // WriteTo can be made to time out and return + // an error with Timeout() == true after a fixed time limit; + // see SetDeadline and SetWriteDeadline. + // On packet-oriented connections, write timeouts are rare. + WriteTo(b []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. + LocalAddr() Addr + + // SetDeadline sets the read and write deadlines associated + // with the connection. + SetDeadline(t time.Time) error + + // SetReadDeadline sets the deadline for future Read calls. + // If the deadline is reached, Read will fail with a timeout + // (see type Error) instead of blocking. + // A zero value for t means Read will not time out. + SetReadDeadline(t time.Time) error + + // SetWriteDeadline sets the deadline for future Write calls. + // If the deadline is reached, Write will fail with a timeout + // (see type Error) instead of blocking. + // A zero value for t means Write will not time out. + // Even if write times out, it may return n > 0, indicating that + // some of the data was successfully written. + SetWriteDeadline(t time.Time) error +}+
+PacketConn is a generic packet-oriented network connection. +
++Multiple goroutines may invoke methods on a PacketConn simultaneously. +
+ + + + + + + + + + + + +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(net, laddr string) (PacketConn, error)+
+ListenPacket announces on the local network address laddr. +The network net must be a packet-oriented network: "udp", "udp4", +"udp6", "ip", "ip4", "ip6" or "unixgram". +For TCP and UDP, the syntax of laddr is "host:port", like "127.0.0.1:8080". +If host is omitted, as in ":8080", ListenPacket listens on all available interfaces +instead of just the interface with the given host address. +See Dial for the syntax of laddr. +
+ + + + + + + + + +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 +}+
+A ParseError is the error type of literal network address parsers. +
+ + + + + + + + + + + + + + +func (e *ParseError) Error() string+ + + + + + + + +
type SRV struct { + Target string + Port uint16 + Priority uint16 + Weight uint16 +}+
+An SRV represents a single DNS SRV record. +
+ + + + + + + + + + + + + + + + +type TCPAddr struct { + IP IP + Port int + Zone string // IPv6 scoped addressing zone +}+
+TCPAddr represents the address of a TCP end point. +
+ + + + + + + + + + + + +func ResolveTCPAddr(net, addr string) (*TCPAddr, error)+
+ResolveTCPAddr parses addr as a TCP address of the form "host:port" +or "[ipv6-host%zone]:port" and resolves a pair of domain name and +port name on the network net, which must be "tcp", "tcp4" or +"tcp6". A literal address or host name for IPv6 must be enclosed +in square brackets, as in "[::1]:80", "[ipv6-host]:http" or +"[ipv6-host%zone]:80". +
+ + + + + + + +func (a *TCPAddr) Network() string+
+Network returns the address's network name, "tcp". +
+ + + + + + +func (a *TCPAddr) String() string+ + + + + + + + +
type TCPConn struct {
+ // contains filtered or unexported fields
+}
+ +TCPConn is an implementation of the Conn interface for TCP network +connections. +
+ + + + + + + + + + + + +func DialTCP(net string, laddr, raddr *TCPAddr) (*TCPConn, error)+
+DialTCP connects to the remote address raddr on the network net, +which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is +used as the local address for the connection. +
+ + + + + + + +func (c *TCPConn) Close() error+
+Close closes the connection. +
+ + + + + + +func (c *TCPConn) CloseRead() error+
+CloseRead shuts down the reading side of the TCP connection. +Most callers should just use Close. +
+ + + + + + +func (c *TCPConn) CloseWrite() error+
+CloseWrite shuts down the writing side of the TCP connection. +Most callers should just use Close. +
+ + + + + + +func (c *TCPConn) File() (f *os.File, err error)+
+File sets the underlying os.File to blocking mode and returns a copy. +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 (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 (c *TCPConn) Read(b []byte) (int, error)+
+Read implements the Conn Read method. +
+ + + + + + +func (c *TCPConn) ReadFrom(r io.Reader) (int64, error)+
+ReadFrom implements the io.ReaderFrom ReadFrom method. +
+ + + + + + +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 (c *TCPConn) SetDeadline(t time.Time) error+
+SetDeadline implements the Conn SetDeadline method. +
+ + + + + + +func (c *TCPConn) SetKeepAlive(keepalive bool) error+
+SetKeepAlive sets whether the operating system should send +keepalive messages on the connection. +
+ + + + + + +func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error+
+SetKeepAlivePeriod sets period between keep alives. +
+ + + + + + +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 after sec seconds have elapsed any remaining +unsent data may be discarded. +
+ + + + + + +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 (c *TCPConn) SetReadBuffer(bytes int) error+
+SetReadBuffer sets the size of the operating system's +receive buffer associated with the connection. +
+ + + + + + +func (c *TCPConn) SetReadDeadline(t time.Time) error+
+SetReadDeadline implements the Conn SetReadDeadline method. +
+ + + + + + +func (c *TCPConn) SetWriteBuffer(bytes int) error+
+SetWriteBuffer sets the size of the operating system's +transmit buffer associated with the connection. +
+ + + + + + +func (c *TCPConn) SetWriteDeadline(t time.Time) error+
+SetWriteDeadline implements the Conn SetWriteDeadline method. +
+ + + + + + +func (c *TCPConn) Write(b []byte) (int, error)+
+Write implements the Conn Write method. +
+ + + + + + + + +type TCPListener struct {
+ // contains filtered or unexported fields
+}
+ +TCPListener is a TCP network listener. Clients should typically +use variables of type Listener instead of assuming TCP. +
+ + + + + + + + + + + + +func ListenTCP(net string, laddr *TCPAddr) (*TCPListener, error)+
+ListenTCP announces on the TCP address laddr and returns a TCP +listener. Net must be "tcp", "tcp4", or "tcp6". If laddr has a +port of 0, ListenTCP will choose an available port. The caller can +use the Addr method of TCPListener to retrieve the chosen address. +
+ + + + + + + +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 (l *TCPListener) AcceptTCP() (*TCPConn, error)+
+AcceptTCP accepts the next incoming call and returns the new +connection. +
+ + + + + + +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 (l *TCPListener) Close() error+
+Close stops listening on the TCP address. +Already Accepted connections are not closed. +
+ + + + + + +func (l *TCPListener) File() (f *os.File, err error)+
+File returns a copy of the underlying os.File, set to blocking +mode. 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 (l *TCPListener) SetDeadline(t time.Time) error+
+SetDeadline sets the deadline associated with the listener. +A zero time value disables the deadline. +
+ + + + + + + + +type UDPAddr struct { + IP IP + Port int + Zone string // IPv6 scoped addressing zone +}+
+UDPAddr represents the address of a UDP end point. +
+ + + + + + + + + + + + +func ResolveUDPAddr(net, addr string) (*UDPAddr, error)+
+ResolveUDPAddr parses addr as a UDP address of the form "host:port" +or "[ipv6-host%zone]:port" and resolves a pair of domain name and +port name on the network net, which must be "udp", "udp4" or +"udp6". A literal address or host name for IPv6 must be enclosed +in square brackets, as in "[::1]:80", "[ipv6-host]:http" or +"[ipv6-host%zone]:80". +
+ + + + + + + +func (a *UDPAddr) Network() string+
+Network returns the address's network name, "udp". +
+ + + + + + +func (a *UDPAddr) String() string+ + + + + + + + +
type UDPConn struct {
+ // contains filtered or unexported fields
+}
+ +UDPConn is the implementation of the Conn and PacketConn interfaces +for UDP network connections. +
+ + + + + + + + + + + + +func DialUDP(net string, laddr, raddr *UDPAddr) (*UDPConn, error)+
+DialUDP connects to the remote address raddr on the network net, +which must be "udp", "udp4", or "udp6". If laddr is not nil, it is +used as the local address for the connection. +
+ + + + + +func ListenMulticastUDP(network string, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error)+
+ListenMulticastUDP listens for incoming multicast UDP packets +addressed to the group address gaddr on the interface ifi. +Network must be "udp", "udp4" or "udp6". +ListenMulticastUDP uses the system-assigned multicast interface +when ifi is nil, although this is not recommended because the +assignment depends on platforms and sometimes it might require +routing configuration. +
++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. +
+ + + + + +func ListenUDP(net string, laddr *UDPAddr) (*UDPConn, error)+
+ListenUDP listens for incoming UDP packets addressed to the local +address laddr. Net must be "udp", "udp4", or "udp6". If laddr has +a port of 0, ListenUDP will choose an available port. +The LocalAddr method of the returned UDPConn can be used to +discover the port. The returned connection's ReadFrom and WriteTo +methods can be used to receive and send UDP packets with per-packet +addressing. +
+ + + + + + + +func (c *UDPConn) Close() error+
+Close closes the connection. +
+ + + + + + +func (c *UDPConn) File() (f *os.File, err error)+
+File sets the underlying os.File to blocking mode and returns a copy. +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 (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 (c *UDPConn) Read(b []byte) (int, error)+
+Read implements the Conn Read method. +
+ + + + + + +func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error)+
+ReadFrom implements the PacketConn ReadFrom method. +
+ + + + + + +func (c *UDPConn) ReadFromUDP(b []byte) (int, *UDPAddr, error)+
+ReadFromUDP reads a UDP packet from c, copying the payload into b. +It returns the number of bytes copied into b and the return address +that was on the packet. +
++ReadFromUDP can be made to time out and return an error with +Timeout() == true after a fixed time limit; see SetDeadline and +SetReadDeadline. +
+ + + + + + +func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)+
+ReadMsgUDP reads a packet 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 packet and the source address of the +packet. +
+ + + + + + +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 (c *UDPConn) SetDeadline(t time.Time) error+
+SetDeadline implements the Conn SetDeadline method. +
+ + + + + + +func (c *UDPConn) SetReadBuffer(bytes int) error+
+SetReadBuffer sets the size of the operating system's +receive buffer associated with the connection. +
+ + + + + + +func (c *UDPConn) SetReadDeadline(t time.Time) error+
+SetReadDeadline implements the Conn SetReadDeadline method. +
+ + + + + + +func (c *UDPConn) SetWriteBuffer(bytes int) error+
+SetWriteBuffer sets the size of the operating system's +transmit buffer associated with the connection. +
+ + + + + + +func (c *UDPConn) SetWriteDeadline(t time.Time) error+
+SetWriteDeadline implements the Conn SetWriteDeadline method. +
+ + + + + + +func (c *UDPConn) Write(b []byte) (int, error)+
+Write implements the Conn Write method. +
+ + + + + + +func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobn int, err error)+
+WriteMsgUDP writes a packet to addr via c if c isn't connected, or +to c's remote destination 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. +
+ + + + + + +func (c *UDPConn) WriteTo(b []byte, addr Addr) (int, error)+
+WriteTo implements the PacketConn WriteTo method. +
+ + + + + + +func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (int, error)+
+WriteToUDP writes a UDP packet to addr via c, copying the payload +from b. +
++WriteToUDP can be made to time out and return an error with +Timeout() == true after a fixed time limit; see SetDeadline and +SetWriteDeadline. On packet-oriented connections, write timeouts +are rare. +
+ + + + + + + + +type UnixAddr struct { + Name string + Net string +}+
+UnixAddr represents the address of a Unix domain socket end point. +
+ + + + + + + + + + + + +func ResolveUnixAddr(net, addr string) (*UnixAddr, error)+
+ResolveUnixAddr parses addr as a Unix domain socket address. +The string net gives the network name, "unix", "unixgram" or +"unixpacket". +
+ + + + + + + +func (a *UnixAddr) Network() string+
+Network returns the address's network name, "unix", "unixgram" or +"unixpacket". +
+ + + + + + +func (a *UnixAddr) String() string+ + + + + + + + +
type UnixConn struct {
+ // contains filtered or unexported fields
+}
+ +UnixConn is an implementation of the Conn interface for connections +to Unix domain sockets. +
+ + + + + + + + + + + + +func DialUnix(net string, laddr, raddr *UnixAddr) (*UnixConn, error)+
+DialUnix connects to the remote address raddr on the network net, +which must be "unix", "unixgram" or "unixpacket". If laddr is not +nil, it is used as the local address for the connection. +
+ + + + + +func ListenUnixgram(net string, laddr *UnixAddr) (*UnixConn, error)+
+ListenUnixgram listens for incoming Unix datagram packets addressed +to the local address laddr. The network net must be "unixgram". +The returned connection's ReadFrom and WriteTo methods can be used +to receive and send packets with per-packet addressing. +
+ + + + + + + +func (c *UnixConn) Close() error+
+Close closes the connection. +
+ + + + + + +func (c *UnixConn) CloseRead() error+
+CloseRead shuts down the reading side of the Unix domain connection. +Most callers should just use Close. +
+ + + + + + +func (c *UnixConn) CloseWrite() error+
+CloseWrite shuts down the writing side of the Unix domain connection. +Most callers should just use Close. +
+ + + + + + +func (c *UnixConn) File() (f *os.File, err error)+
+File sets the underlying os.File to blocking mode and returns a copy. +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 (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 (c *UnixConn) Read(b []byte) (int, error)+
+Read implements the Conn Read method. +
+ + + + + + +func (c *UnixConn) ReadFrom(b []byte) (int, Addr, error)+
+ReadFrom implements the PacketConn ReadFrom method. +
+ + + + + + +func (c *UnixConn) ReadFromUnix(b []byte) (int, *UnixAddr, error)+
+ReadFromUnix reads a packet from c, copying the payload into b. It +returns the number of bytes copied into b and the source address of +the packet. +
++ReadFromUnix can be made to time out and return an error with +Timeout() == true after a fixed time limit; see SetDeadline and +SetReadDeadline. +
+ + + + + + +func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error)+
+ReadMsgUnix reads a packet 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 packet, and the source address of the packet. +
+ + + + + + +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 (c *UnixConn) SetDeadline(t time.Time) error+
+SetDeadline implements the Conn SetDeadline method. +
+ + + + + + +func (c *UnixConn) SetReadBuffer(bytes int) error+
+SetReadBuffer sets the size of the operating system's +receive buffer associated with the connection. +
+ + + + + + +func (c *UnixConn) SetReadDeadline(t time.Time) error+
+SetReadDeadline implements the Conn SetReadDeadline method. +
+ + + + + + +func (c *UnixConn) SetWriteBuffer(bytes int) error+
+SetWriteBuffer sets the size of the operating system's +transmit buffer associated with the connection. +
+ + + + + + +func (c *UnixConn) SetWriteDeadline(t time.Time) error+
+SetWriteDeadline implements the Conn SetWriteDeadline method. +
+ + + + + + +func (c *UnixConn) Write(b []byte) (int, error)+
+Write implements the Conn Write method. +
+ + + + + + +func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err error)+
+WriteMsgUnix writes a packet 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. +
+ + + + + + +func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err error)+
+WriteTo implements the PacketConn WriteTo method. +
+ + + + + + +func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (int, error)+
+WriteToUnix writes a packet to addr via c, copying the payload from b. +
++WriteToUnix can be made to time out and return an error with +Timeout() == true after a fixed time limit; see SetDeadline and +SetWriteDeadline. On packet-oriented connections, write timeouts +are rare. +
+ + + + + + + + +type UnixListener struct {
+ // contains filtered or unexported fields
+}
+ +UnixListener is a Unix domain socket listener. Clients should +typically use variables of type Listener instead of assuming Unix +domain sockets. +
+ + + + + + + + + + + + +func ListenUnix(net string, laddr *UnixAddr) (*UnixListener, error)+
+ListenUnix announces on the Unix domain socket laddr and returns a +Unix listener. The network net must be "unix" or "unixpacket". +
+ + + + + + + +func (l *UnixListener) Accept() (c Conn, err error)+
+Accept implements the Accept method in the Listener interface; it +waits for the next call and returns a generic Conn. +
+ + + + + + +func (l *UnixListener) AcceptUnix() (*UnixConn, error)+
+AcceptUnix accepts the next incoming call and returns the new +connection. +
+ + + + + + +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 (l *UnixListener) Close() error+
+Close stops listening on the Unix address. Already accepted +connections are not closed. +
+ + + + + + +func (l *UnixListener) File() (f *os.File, err error)+
+File returns a copy of the underlying os.File, set to blocking +mode. 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 (l *UnixListener) SetDeadline(t time.Time) error+
+SetDeadline sets the deadline associated with the listener. +A zero time value disables the deadline. +
+ + + + + + + + +type UnknownNetworkError string+ + + + + + + + + + + + + + +
func (e UnknownNetworkError) Error() string+ + + + + + +
func (e UnknownNetworkError) Temporary() bool+ + + + + + +
func (e UnknownNetworkError) Timeout() bool+ + + + + + + + + + +
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. + | +
+ 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. + | +
+ 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 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. + | +
var ErrHeaderNotPresent = errors.New("mail: header not in message")+ + + + + + +
func ParseAddressList(list string) ([]*Address, error)+
+ParseAddressList parses the given string as a list of addresses. +
+ +▹ Example
+type Address struct { + Name string // Proper name; may be empty. + Address string // user@domain +}+
+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"}. +
+ + + + + + + + + + + + +func ParseAddress(address string) (*Address, error)+
+Parses a single RFC 5322 address, e.g. "Barry Gibbs <bg@example.com>" +
+ +▹ Example
+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 struct { + // WordDecoder optionally specifies a decoder for RFC 2047 encoded-words. + WordDecoder *mime.WordDecoder +}+
+An AddressParser is an RFC 5322 address parser. +
+ + + + + + + + + + + + + + +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 (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". +
+ + + + + + + + +type Header map[string][]string+
+A Header represents the key-value pairs in a mail message header. +
+ + + + + + + + + + + + + + +func (h Header) AddressList(key string) ([]*Address, error)+
+AddressList parses the named header field as a list of addresses. +
+ + + + + + +func (h Header) Date() (time.Time, error)+
+Date parses the Date header field. +
+ + + + + + +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 "". +
+ + + + + + + + +type Message struct { + Header Header + Body io.Reader +}+
+A Message represents a parsed mail message. +
+ + + + + + + + + + + + +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 r. +
+ +▹ Example
+const ( + // Defaults used by HandleHTTP + DefaultRPCPath = "/_goRPC_" + DefaultDebugPath = "/debug/rpc" +)+ + + + +
var DefaultServer = NewServer()+
+DefaultServer is the default instance of *Server. +
+ + +var ErrShutdown = errors.New("connection is shut down")+ + + + + + +
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()+
+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(rcvr interface{}) error+
+Register publishes the receiver's methods in the DefaultServer. +
+ + + + + + + +func RegisterName(name string, rcvr interface{}) error+
+RegisterName is like Register but uses the provided name for the type +instead of the receiver's concrete type. +
+ + + + + + + +func ServeCodec(codec ServerCodec)+
+ServeCodec is like ServeConn but uses the specified codec to +decode requests and encode responses. +
+ + + + + + + +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. +
+ + + + + + + +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 struct { + ServiceMethod string // The name of the service and method to call. + Args interface{} // The argument to the function (*struct). + Reply interface{} // The reply from the function (*struct). + Error error // After completion, the error status. + Done chan *Call // Strobes when call is complete. +}+
+Call represents an active RPC. +
+ + + + + + + + + + + + + + + + +type Client struct {
+ // contains filtered or unexported fields
+}
+ +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. +
+ + + + + + + + + + + + +func Dial(network, address string) (*Client, error)+
+Dial connects to an RPC server at the specified network address. +
+ + + + + +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(network, address, path string) (*Client, error)+
+DialHTTPPath connects to an HTTP RPC server +at the specified network address and path. +
+ + + + + +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. +
+ + + + + +func NewClientWithCodec(codec ClientCodec) *Client+
+NewClientWithCodec is like NewClient but uses the specified +codec to encode requests and decode responses. +
+ + + + + + + +func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) error+
+Call invokes the named function, waits for it to complete, and returns its error status. +
+ + + + + + +func (client *Client) Close() error+ + + + + + +
func (client *Client) Go(serviceMethod string, args interface{}, reply interface{}, 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 interface { + // WriteRequest must be safe for concurrent use by multiple goroutines. + WriteRequest(*Request, interface{}) error + ReadResponseHeader(*Response) error + ReadResponseBody(interface{}) error + + Close() error +}+
+A ClientCodec implements writing of RPC requests and +reading of RPC responses for the client side of an RPC session. +The client calls WriteRequest to write a request to the connection +and calls ReadResponseHeader and ReadResponseBody in pairs +to read responses. The client calls 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. +
+ + + + + + + + + + + + + + + + +type Request struct { + ServiceMethod string // format: "Service.Method" + Seq uint64 // sequence number chosen by client + // contains filtered or unexported fields +}+
+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 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 +}+
+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 Server struct {
+ // contains filtered or unexported fields
+}
+ +Server represents an RPC Server. +
+ + + + + + + + + + + + +func NewServer() *Server+
+NewServer returns a new Server. +
+ + + + + + + +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 *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 *Server) Register(rcvr interface{}) error+
+Register publishes in the server the set of methods of the +receiver value that satisfy the following conditions: +
+- exported method of exported type +- two arguments, both of exported type +- the second argument is a pointer +- one return value, of type error ++
+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 *Server) RegisterName(name string, rcvr interface{}) error+
+RegisterName is like Register but uses the provided name for the type +instead of the receiver's concrete type. +
+ + + + + + +func (server *Server) ServeCodec(codec ServerCodec)+
+ServeCodec is like ServeConn but uses the specified codec to +decode requests and encode responses. +
+ + + + + + +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. +
+ + + + + + +func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)+
+ServeHTTP implements an http.Handler that answers RPC requests. +
+ + + + + + +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 interface { + ReadRequestHeader(*Request) error + ReadRequestBody(interface{}) error + // WriteResponse must be safe for concurrent use by multiple goroutines. + WriteResponse(*Response, interface{}) error + + Close() error +}+
+A ServerCodec implements reading of RPC requests and writing of +RPC responses for the server side of an RPC session. +The server calls ReadRequestHeader and ReadRequestBody in pairs +to read requests from the connection, and it calls WriteResponse to +write a response back. The server calls 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. +
+ + + + + + + + + + + + + + + + +type ServerError string+
+ServerError represents an error that has been returned from +the remote side of the RPC connection. +
+ + + + + + + + + + + + + + +func (e ServerError) Error() string+ + + + + + + + + + + + + + + + +
func Dial(network, address string) (*rpc.Client, error)+
+Dial connects to a JSON-RPC server at the specified network address. +
+ + + + + + + +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(conn io.ReadWriteCloser) rpc.ClientCodec+
+NewClientCodec returns a new rpc.ClientCodec using JSON-RPC on conn. +
+ + + + + + + +func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec+
+NewServerCodec returns a new rpc.ServerCodec using JSON-RPC on conn. +
+ + + + + + + +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. +
+ + + + + + + + + + + + + + + + + + +▹ Example
+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 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
+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. It can return proto == "" to indicate + // that the authentication should be skipped. + // 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) +}+
+Auth is implemented by an SMTP authentication mechanism. +
+ + + + + + + + + + + + +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(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 +on TLS connections to host and act as identity. Usually identity will be +left blank to act as username. +
+ +▹ Example
+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 +}+
+A Client represents a client connection to an SMTP server. +
+ + + + + + + + + + + + +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(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 (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 (c *Client) Close() error+
+Close closes the connection. +
+ + + + + + +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 Rcpt. +
+ + + + + + +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 (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 (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. +This initiates a mail transaction and is followed by one or more Rcpt calls. +
+ + + + + + +func (c *Client) Quit() error+
+Quit sends the QUIT command and closes the connection to the server. +
+ + + + + + +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 Mail and may be followed by +a Data call or another Rcpt call. +
+ + + + + + +func (c *Client) Reset() error+
+Reset sends the RSET command to the server, aborting the current mail +transaction. +
+ + + + + + +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 (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool)+
+TLSConnectionState returns the client's TLS connection state. +The return values are their zero values if StartTLS did +not succeed. +
+ + + + + + +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 struct { + Name string // SMTP server name + TLS bool // using TLS, with valid certificate for Name + Auth []string // advertised authentication mechanisms +}+
+ServerInfo records information about an SMTP server. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +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(b []byte) []byte+
+TrimBytes returns b without leading and trailing ASCII space. +
+ + + + + + + +func TrimString(s string) string+
+TrimString returns s without leading and trailing ASCII space. +
+ + + + + + + + +type Conn struct { + Reader + Writer + Pipeline + // contains filtered or unexported fields +}+
+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. +
+ + + + + + + + + + + + +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(conn io.ReadWriteCloser) *Conn+
+NewConn returns a new Conn using conn for I/O. +
+ + + + + + + +func (c *Conn) Close() error+
+Close closes the connection. +
+ + + + + + +func (c *Conn) Cmd(format string, args ...interface{}) (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 struct { + Code int + Msg string +}+
+An Error represents a numeric error response from a server. +
+ + + + + + + + + + + + + + +func (e *Error) Error() string+ + + + + + + + +
type MIMEHeader map[string][]string+
+A MIMEHeader represents a MIME-style header mapping +keys to sets of values. +
+ + + + + + + + + + + + + + +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 (h MIMEHeader) Del(key string)+
+Del deletes the values associated with key. +
+ + + + + + +func (h MIMEHeader) 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 "". +Get is a convenience method. For more complex queries, +access the map directly. +
+ + + + + + +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. +
+ + + + + + + + +type Pipeline struct {
+ // contains filtered or unexported fields
+}
+ +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. +
+ + + + + + + + + + + + + + +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 (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 (p *Pipeline) Next() uint+
+Next returns the next id for a request/response pair. +
+ + + + + + +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 (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 string+
+A ProtocolError describes a protocol violation such +as an invalid response or a hung-up connection. +
+ + + + + + + + + + + + + + +func (p ProtocolError) Error() string+ + + + + + + + +
type Reader struct { + R *bufio.Reader + // contains filtered or unexported fields +}+
+A Reader implements convenience methods for reading requests +or responses from a text protocol network connection. +
+ + + + + + + + + + + + +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 (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 (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 (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". +
++A line consisting of only white space is never continued. +
+ + + + + + +func (r *Reader) ReadContinuedLineBytes() ([]byte, error)+
+ReadContinuedLineBytes is like ReadContinuedLine but +returns a []byte instead of a string. +
+ + + + + + +func (r *Reader) ReadDotBytes() ([]byte, error)+
+ReadDotBytes reads a dot-encoding and returns the decoded data. +
++See the documentation for the DotReader method for details about dot-encoding. +
+ + + + + + +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 DotReader method for details about dot-encoding. +
+ + + + + + +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 (r *Reader) ReadLineBytes() ([]byte, error)+
+ReadLineBytes is like ReadLine but returns a []byte instead of a string. +
+ + + + + + +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 (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 (http://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 struct { + W *bufio.Writer + // contains filtered or unexported fields +}+
+A Writer implements convenience methods for writing +requests or responses to a text protocol network connection. +
+ + + + + + + + + + + + +func NewWriter(w *bufio.Writer) *Writer+
+NewWriter returns a new Writer writing to w. +
+ + + + + + + +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 Reader's DotReader method for details about dot-encoding. +
+ + + + + + +func (w *Writer) PrintfLine(format string, args ...interface{}) error+
+PrintfLine writes the formatted output followed by \r\n. +
+ + + + + + + + + + + + + + + + + + +func QueryEscape(s string) string+
+QueryEscape escapes the string so it can be safely placed +inside a URL query. +
+ + + + + + + +func QueryUnescape(s string) (string, error)+
+QueryUnescape does the inverse transformation of QueryEscape, converting +%AB into the byte 0xAB and '+' into ' ' (space). It returns an error if +any % is not followed by two hexadecimal digits. +
+ + + + + + + + +type Error struct { + Op string + URL string + Err error +}+
+Error reports an error and the operation and URL that caused it. +
+ + + + + + + + + + + + + + +func (e *Error) Error() string+ + + + + + +
func (e *Error) Temporary() bool+ + + + + + +
func (e *Error) Timeout() bool+ + + + + + + + +
type EscapeError string+ + + + + + + + + + + + + + +
func (e EscapeError) Error() string+ + + + + + + + +
type InvalidHostError string+ + + + + + + + + + + + + + +
func (e InvalidHostError) Error() string+ + + + + + + + +
type URL struct { + Scheme string + Opaque string // encoded opaque data + User *Userinfo // username and password information + Host string // host or host:port + Path string + RawPath string // encoded path hint (Go 1.5 and later only; see EscapedPath method) + RawQuery string // encoded query values, without '?' + Fragment string // fragment for references, without '#' +}+
+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] ++
+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, code must not use Path directly. +
++Go 1.5 introduced the RawPath field to hold the encoded form of Path. +The Parse function sets both Path and RawPath in the URL it returns, +and URL's String method uses RawPath if it is a valid encoding of Path, +by calling the EscapedPath method. +
++In earlier versions of Go, the more indirect workarounds were that an +HTTP server could consult req.RequestURI and an HTTP client could +construct a URL struct directly and set the Opaque field instead of Path. +These still work as well. +
+ + + + + + +▹ Example
+▹ Example (Opaque)
+▹ Example (Roundtrip)
+func Parse(rawurl string) (url *URL, err error)+
+Parse parses rawurl into a URL structure. +The rawurl may be relative or absolute. +
+ + + + + +func ParseRequestURI(rawurl string) (url *URL, err error)+
+ParseRequestURI parses rawurl into a URL structure. It assumes that +rawurl was received in an HTTP request, so the rawurl is interpreted +only as an absolute URI or an absolute path. +The string rawurl is assumed not to have a #fragment suffix. +(Web browsers strip #fragment before sending the URL to a web server.) +
+ + + + + + + +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 String and RequestURI methods use EscapedPath to construct +their results. +In general, code should call EscapedPath instead of +reading u.RawPath directly. +
+ + + + + + +func (u *URL) IsAbs() bool+
+IsAbs reports whether the URL is absolute. +
+ + + + + + +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 ResolveReference. +
+ + + + + + +func (u *URL) Query() Values+
+Query parses RawQuery and returns the corresponding values. +
+ + + + + + +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. +
+ + + + + + +func (u *URL) ResolveReference(ref *URL) *URL+
+ResolveReference resolves a URI reference to an absolute URI from +an absolute base URI, 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
+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. +To obtain the path, String uses u.EscapedPath(). +
++In the second form, the following rules apply: +
+- if u.Scheme is empty, scheme: is omitted. +- if u.User is nil, userinfo@ is omitted. +- if u.Host is empty, host/ is omitted. +- if u.Scheme and u.Host are empty and u.User is nil, + the entire scheme://userinfo@host/ is omitted. +- if u.Host is non-empty and u.Path begins with a /, + the form host/path does not add its own /. +- if u.RawQuery is empty, ?query is omitted. +- if u.Fragment is empty, #fragment is omitted. ++ + + + + + + + +
type Userinfo struct {
+ // contains filtered or unexported fields
+}
+ +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. +
+ + + + + + + + + + + + +func User(username string) *Userinfo+
+User returns a Userinfo containing the provided username +and no password set. +
+ + + + + +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 (u *Userinfo) Password() (string, bool)+
+Password returns the password in case it is set, and whether it is set. +
+ + + + + + +func (u *Userinfo) String() string+
+String returns the encoded userinfo information in the standard form +of "username[:password]". +
+ + + + + + +func (u *Userinfo) Username() string+
+Username returns the username. +
+ + + + + + + + +type Values map[string][]string+
+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. +
+ + + + + + +▹ Example
+func ParseQuery(query string) (m Values, err 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. +
+ + + + + + + +func (v Values) Add(key, value string)+
+Add adds the value to key. It appends to any existing +values associated with key. +
+ + + + + + +func (v Values) Del(key string)+
+Del deletes the values associated with key. +
+ + + + + + +func (v Values) Encode() string+
+Encode encodes the values into “URL encoded” form +("bar=baz&foo=quux") sorted by key. +
+ + + + + + +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. +
+ + + + + + +func (v Values) Set(key, value string)+
+Set sets the key to value. It replaces any existing +values. +
+ + + + + + + + + + + + + + + + + + +var ErrNotFound = errors.New("executable file not found in $PATH")+
+ErrNotFound is the error resulting if a path search failed to find an executable file. +
+ + + + + + +func LookPath(file string) (string, error)+
+LookPath searches for an executable binary 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. +The result may be an absolute path or a path relative to the current directory. +
+ +▹ Example
+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. + // If Env is nil, Run uses the current process's environment. + 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. + 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 Stdout and Stderr are the same writer, 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. + // + // BUG(rsc): On OS X 10.6, child processes may sometimes inherit unwanted fds. + // https://golang.org/issue/2603 + 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, + // available after a call to Wait or Run. + ProcessState *os.ProcessState + // contains filtered or unexported fields +}+
+Cmd represents an external command being prepared or run. +
++A Cmd cannot be reused after calling its Run, Output or CombinedOutput +methods. +
+ + + + + + + + + + + + +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 the path to a complete name if possible. Otherwise it uses +name directly. +
++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") +
+ +▹ Example
+func (c *Cmd) CombinedOutput() ([]byte, error)+
+CombinedOutput runs the command and returns its combined standard +output and standard error. +
+ + + + + + +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
+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 fails to run or doesn't complete successfully, the +error is of type *ExitError. Other error types may be +returned for I/O problems. +
+ + + + + + +func (c *Cmd) Start() error+
+Start starts the specified command but does not wait for it to complete. +
++The Wait method will return the exit code and release associated resources +once the command exits. +
+ + +▹ Example
+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; however, an implication is that +it is 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. +
+ + + + + + +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. +
+ + + + + + +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; however, an implication is that +it is 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
+func (c *Cmd) Wait() error+
+Wait waits for the command to exit. +It 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 c.Stdin is not an *os.File, Wait also waits for the I/O loop +copying from c.Stdin into the process's standard input +to complete. +
++Wait releases any resources associated with the Cmd. +
+ + + + + + + + +type Error struct { + Name string + Err error +}+
+Error records the name of a binary that failed to be executed +and the reason it failed. +
+ + + + + + + + + + + + + + +func (e *Error) Error() string+ + + + + + + + +
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 +}+
+An ExitError reports an unsuccessful exit by a command. +
+ + + + + + + + + + + + + + +func (e *ExitError) Error() string+ + + + + + + + + + +
const ( + 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. + 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 // if possible, truncate file when opened. +)+
+Flags to OpenFile wrapping those of the underlying system. Not all +flags may be implemented on a given system. +
+ + +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 +)+
+Seek whence values. +
+ + +const ( + PathSeparator = '/' // OS-specific path separator + PathListSeparator = ':' // OS-specific path list separator +)+ + +
const DevNull = "/dev/null"
+ +DevNull is the name of the operating system's “null device.” +On Unix-like systems, it is "/dev/null"; on Windows, "NUL". +
+ + + + +var ( + ErrInvalid = errors.New("invalid argument") // methods on File will return this error when the receiver is nil + ErrPermission = errors.New("permission denied") + ErrExist = errors.New("file already exists") + ErrNotExist = errors.New("file does not exist") +)+
+Portable analogs of some common system call errors. +
+ + +var ( + Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin") + Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout") + Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr") +)+
+Stdin, Stdout, and Stderr are open Files pointing to the standard input, +standard output, and standard error file descriptors. +
+ + +var Args []string+
+Args hold the command-line arguments, starting with the program name. +
+ + + + + + +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(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. +
+ + + + + + + +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. +If there is an error, it will be of type *PathError. +
+ + + + + + + +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. +
++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. +
+ + + + + + + +func Clearenv()+
+Clearenv deletes all environment variables. +
+ + + + + + + +func Environ() []string+
+Environ returns a copy of strings representing the environment, +in the form "key=value". +
+ + + + + + + +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. +
+ + + + + + + +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). +
+ + + + + + + +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. +
+ + + + + + + +func Getegid() int+
+Getegid returns the numeric effective group id of the caller. +
+ + + + + + + +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. +
+ + + + + + + +func Geteuid() int+
+Geteuid returns the numeric effective user id of the caller. +
+ + + + + + + +func Getgid() int+
+Getgid returns the numeric group id of the caller. +
+ + + + + + + +func Getgroups() ([]int, error)+
+Getgroups returns a list of the numeric ids of groups that the caller belongs to. +
+ + + + + + + +func Getpagesize() int+
+Getpagesize returns the underlying system's memory page size. +
+ + + + + + + +func Getpid() int+
+Getpid returns the process id of the caller. +
+ + + + + + + +func Getppid() int+
+Getppid returns the process id of the caller's parent. +
+ + + + + + + +func Getuid() int+
+Getuid returns the numeric user id of the caller. +
+ + + + + + + +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() (name string, err error)+
+Hostname returns the host name reported by the kernel. +
+ + + + + + + +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. +
+ + + + + + + +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. +
+ + + + + + + +func IsPathSeparator(c uint8) bool+
+IsPathSeparator reports whether c is a directory separator character. +
+ + + + + + + +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. +
+ + + + + + + +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. +
+ + + + + + + +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(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. +
+ + + + + + + +func Mkdir(name string, perm FileMode) error+
+Mkdir creates a new directory with the specified name and permission bits. +If there is an error, it will be of type *PathError. +
+ + + + + + + +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 are used for all +directories that MkdirAll creates. +If path is already a directory, MkdirAll does nothing +and returns nil. +
+ + + + + + + +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 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. +
+ + + + + + + +func Remove(name string) error+
+Remove removes the named file or directory. +If there is an error, it will be of type *PathError. +
+ + + + + + + +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). +
+ + + + + + + +func Rename(oldpath, newpath string) error+
+Rename renames (moves) oldpath to newpath. +If newpath already exists, Rename replaces it. +OS-specific restrictions may apply when oldpath and newpath are in different directories. +If there is an error, it will be of type *LinkError. +
+ + + + + + + +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(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. +If there is an error, it will be of type *LinkError. +
+ + + + + + + +func TempDir() string+
+TempDir returns the default directory to use for temporary files. +
+ + + + + + + +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(key string) error+
+Unsetenv unsets a single environment variable. +
+ + + + + + + + +type File struct {
+ // contains filtered or unexported fields
+}
+ +File represents an open file descriptor. +
+ + + + + + + + + + + + +func Create(name string) (*File, error)+
+Create creates the named file with mode 0666 (before umask), truncating +it if it already exists. 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 NewFile(fd uintptr, name string) *File+
+NewFile returns a new File with the given file descriptor and name. +
+ + + + + +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(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.) and perm, (0666 etc.) if applicable. If successful, +methods on the returned File can be used for I/O. +If there is an error, it will be of type *PathError. +
+ + + + + +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 (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 (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 (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. +
+ + + + + + +func (f *File) Close() error+
+Close closes the File, rendering it unusable for I/O. +It returns an error, if any. +
+ + + + + + +func (f *File) Fd() uintptr+
+Fd returns the integer Unix file descriptor referencing the open file. +The file descriptor is valid only until f.Close is called or f is garbage collected. +
+ + + + + + +func (f *File) Name() string+
+Name returns the name of the file as presented to Open. +
+ + + + + + +func (f *File) Read(b []byte) (n int, err error)+
+Read reads up to len(b) bytes from the File. +It returns the number of bytes read and an error, if any. +EOF is signaled by a zero count with err set to io.EOF. +
+ + + + + + +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 (f *File) Readdir(n int) (fi []FileInfo, err 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. +
+ + + + + + +func (f *File) Readdirnames(n int) (names []string, err error)+
+Readdirnames reads and returns a slice of names from the directory f. +
++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 (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 (f *File) Stat() (FileInfo, error)+
+Stat returns the FileInfo structure describing file. +If there is an error, it will be of type *PathError. +
+ + + + + + +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 (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 (f *File) Write(b []byte) (n int, err error)+
+Write writes len(b) bytes 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 (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). +
+ + + + + + +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. +
+ + + + + + + + +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() interface{} // underlying data source (can return nil) +}+
+A FileInfo describes a file and is returned by Stat and 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. +
+ + + + + +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 uint32+
+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. +
+ + + +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 (not backed up) + 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 + + // Mask for the type bits. For regular files, none will be set. + ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice + + ModePerm FileMode = 0777 // Unix permission bits +)+
+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. +
+ + + + + + + + + + + + + +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 (m FileMode) IsRegular() bool+
+IsRegular reports whether m describes a regular file. +That is, it tests that no mode type bits are set. +
+ + + + + + +func (m FileMode) Perm() FileMode+
+Perm returns the Unix permission bits in m. +
+ + + + + + +func (m FileMode) String() string+ + + + + + + + +
type LinkError struct { + Op string + Old string + New string + Err error +}+
+LinkError records an error during a link or symlink or rename +system call and the paths that caused it. +
+ + + + + + + + + + + + + + +func (e *LinkError) Error() string+ + + + + + + + +
type PathError struct { + Op string + Path string + Err error +}+
+PathError records an error and the operation and file path that caused it. +
+ + + + + + + + + + + + + + +func (e *PathError) Error() string+ + + + + + + + +
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. + 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 +}+
+ProcAttr holds the attributes that will be applied to a new process +started by StartProcess. +
+ + + + + + + + + + + + + + + + +type Process struct { + Pid int + // contains filtered or unexported fields +}+
+Process stores the information about a process created by StartProcess. +
+ + + + + + + + + + + + +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. +
+ + + + + +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. +
++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 (p *Process) Kill() error+
+Kill causes the Process to exit immediately. +
+ + + + + + +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 (p *Process) Signal(sig Signal) error+
+Signal sends a signal to the Process. +Sending Interrupt on Windows is not implemented. +
+ + + + + + +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 struct {
+ // contains filtered or unexported fields
+}
+ +ProcessState stores information about a process, as reported by Wait. +
+ + + + + + + + + + + + + + +func (p *ProcessState) Exited() bool+
+Exited reports whether the program has exited. +
+ + + + + + +func (p *ProcessState) Pid() int+
+Pid returns the process id of the exited process. +
+ + + + + + +func (p *ProcessState) String() string+ + + + + + +
func (p *ProcessState) Success() bool+
+Success reports whether the program exited successfully, +such as with exit status 0 on Unix. +
+ + + + + + +func (p *ProcessState) Sys() interface{}+
+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 (p *ProcessState) SysUsage() interface{}+
+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 (p *ProcessState) SystemTime() time.Duration+
+SystemTime returns the system CPU time of the exited process and its children. +
+ + + + + + +func (p *ProcessState) UserTime() time.Duration+
+UserTime returns the user CPU time of the exited process and its children. +
+ + + + + + + + +type Signal interface { + String() string + Signal() // to distinguish from other Stringers +}+
+A Signal represents an operating system signal. +The usual underlying implementation is operating system-dependent: +on Unix it is syscall.Signal. +
+ + + + + +var ( + Interrupt Signal = syscall.SIGINT + Kill Signal = syscall.SIGKILL +)+
+The only signal values guaranteed to be present on all systems +are Interrupt (send the process an interrupt) and Kill (force +the process to exit). +
+ + + + + + + + + + + + + +type SyscallError struct { + Syscall string + Err error +}+
+SyscallError records an error from a specific system call. +
+ + + + + + + + + + + + + + +func (e *SyscallError) Error() string+ + + + + + + + + + + + + + + + +
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 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
+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(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. +
+ + + + + + + + + + + + + + + + + + +type UnknownUserError string+
+UnknownUserError is returned by Lookup when +a user cannot be found. +
+ + + + + + + + + + + + + + +func (e UnknownUserError) Error() string+ + + + + + + + +
type UnknownUserIdError int+
+UnknownUserIdError is returned by LookupId when +a user cannot be found. +
+ + + + + + + + + + + + + + +func (e UnknownUserIdError) Error() string+ + + + + + + + +
type User struct { + Uid string // user id + Gid string // primary group id + Username string + Name string + HomeDir string +}+
+User represents a user account. +
++On posix systems Uid and Gid contain a decimal number +representing uid and gid. On windows Uid and Gid +contain security identifier (SID) in a string format. +On Plan 9, Uid, Gid, Username, and Name will be the +contents of /dev/user. +
+ + + + + + + + + + + + +func Current() (*User, error)+
+Current returns the current user. +
+ + + + + +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(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 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. +
+ + + + + + + +func DeepEqual(x, y interface{}) 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 if they are the same map object +or if they have the same length and 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. +
+ + + + + + + +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). +
+ + + + + + + + +type ChanDir int+
+ChanDir represents a channel type's direction. +
+ + + +const ( + RecvDir ChanDir = 1 << iota // <-chan + SendDir // chan<- + BothDir = RecvDir | SendDir // chan +)+ + + + + + + + + + + + + +
func (d ChanDir) String() string+ + + + + + + + +
type Kind uint+
+A Kind represents the specific kind of type that a Type represents. +The zero Kind is not a valid kind. +
+ + + +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 + Ptr + Slice + String + Struct + UnsafePointer +)+ + + + + + + + + + + + + +
func (k Kind) String() string+ + + + + + + + +
type Method struct { + // Name is the method name. + // 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 + Name string + PkgPath string + + Type Type // method type + Func Value // func with receiver as first argument + Index int // index for Type.Method +}+
+Method represents a single method. +
+ + + + + + + + + + + + + + + + +type SelectCase struct { + Dir SelectDir // direction of case + Chan Value // channel to use (for send or receive) + Send Value // value to send (for send) +}+
+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 SelectDir int+
+A SelectDir describes the communication direction of a select case. +
+ + + +const ( + SelectSend SelectDir // case Chan <- Send + SelectRecv // case <-Chan: + SelectDefault // default +)+ + + + + + + + + + + + + + + +
type SliceHeader struct { + Data uintptr + Len int + Cap int +}+
+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. +
+ + + + + + + + + + + + + + + + +type StringHeader struct { + Data uintptr + Len int +}+
+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. +
+ + + + + + + + + + + + + + + + +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 +}+
+A StructField describes a single field in a struct. +
+ + + + + + + + + + + + + + + + +type StructTag string+
+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. +
+ + + + + + +▹ Example
+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. +
+ + + + + + + + +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. + // + // For an interface type, the returned Method's Type field gives the + // method signature, without a receiver, and the Func field is nil. + 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 in the type's method set. + NumMethod() int + + // Name returns the type's name within its package. + // It returns an empty string for unnamed types. + Name() string + + // PkgPath returns a named 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 unnamed (*T, struct{}, []int), + // 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 equality, + // 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. + ConvertibleTo(u Type) bool + + // Comparable reports whether values of this type are 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, Ptr, 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. + FieldByName(name string) (StructField, bool) + + // FieldByNameFunc returns the first struct field with a name + // that satisfies the match function and a boolean indicating if + // the field was found. + 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 +}+
+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. +
+ + + + + + + + + + + + +func ArrayOf(count int, elem Type) Type+
+ArrayOf returns the array type with the given count 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(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(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(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 PtrTo(t Type) Type+
+PtrTo returns the pointer type with element t. +For example, if t represents type Foo, PtrTo(t) represents *Foo. +
+ + + + + +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 TypeOf(i interface{}) Type+
+TypeOf returns the reflection Type that represents the dynamic type of i. +If i is a nil interface value, TypeOf returns nil. +
+ +▹ Example
+type Value struct {
+ // contains filtered or unexported fields
+}
+ +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. +
++Using == on two Values does not compare the underlying values +they represent, but rather the contents of the Value structs. +To compare two Values, compare the results of the Interface method. +
+ + + + + + + + + + + + +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(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(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(typ Type, buffer int) Value+
+MakeChan creates a new channel with the specified type and buffer size. +
+ + + + + +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: +
+- converts its arguments to a slice of Values. +- runs results := fn(args). +- returns the results as a slice of Values, one per formal result. ++
+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
+func MakeMap(typ Type) Value+
+MakeMap creates a new map of the specified type. +
+ + + + + +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(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 PtrTo(typ). +
+ + + + + +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 ValueOf(i interface{}) Value+
+ValueOf returns a new Value initialized to the concrete value +stored in the interface i. ValueOf(nil) returns the zero Value. +
+ + + + + +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 (v Value) Addr() Value+
+Addr returns a pointer value representing the address of v. +It panics if 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 (v Value) Bool() bool+
+Bool returns v's underlying value. +It panics if v's kind is not Bool. +
+ + + + + + +func (v Value) Bytes() []byte+
+Bytes returns v's underlying value. +It panics if v's underlying value is not a slice of bytes. +
+ + + + + + +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 (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 (v Value) CanAddr() bool+
+CanAddr reports whether the value's address can be obtained with 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 Addr will panic. +
+ + + + + + +func (v Value) CanInterface() bool+
+CanInterface reports whether Interface can be used without panicking. +
+ + + + + + +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 Set or any type-specific +setter (e.g., SetBool, SetInt) will panic. +
+ + + + + + +func (v Value) Cap() int+
+Cap returns v's capacity. +It panics if v's Kind is not Array, Chan, or Slice. +
+ + + + + + +func (v Value) Close()+
+Close closes the channel v. +It panics if v's Kind is not Chan. +
+ + + + + + +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 (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, Convert panics. +
+ + + + + + +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 Ptr. +It returns the zero Value if v is nil. +
+ + + + + + +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 (v Value) FieldByIndex(index []int) Value+
+FieldByIndex returns the nested field corresponding to index. +It panics if v's Kind is not struct. +
+ + + + + + +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. +
+ + + + + + +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 (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 (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 (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 (v Value) Interface() (i interface{})+
+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 (v Value) InterfaceData() [2]uintptr+
+InterfaceData returns the interface v's value as a uintptr pair. +It panics if v's Kind is not Interface. +
+ + + + + + +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 (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 (v Value) Kind() Kind+
+Kind returns v's Kind. +If v is the zero Value (IsValid returns false), Kind returns Invalid. +
+ + + + + + +func (v Value) Len() int+
+Len returns v's length. +It panics if v's Kind is not Array, Chan, Map, Slice, or String. +
+ + + + + + +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 (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 (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 (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 (v Value) NumField() int+
+NumField returns the number of fields in the struct v. +It panics if v's Kind is not Struct. +
+ + + + + + +func (v Value) NumMethod() int+
+NumMethod returns the number of methods in the value's method set. +
+ + + + + + +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 (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 (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 (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 (v Value) Pointer() uintptr+
+Pointer returns v's value as a uintptr. +It returns uintptr instead of unsafe.Pointer so that +code using reflect cannot obtain unsafe.Pointers +without importing the unsafe package explicitly. +It panics if v's Kind is not Chan, Func, Map, Ptr, 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. +
+ + + + + + +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 (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 (v Value) Set(x Value)+
+Set assigns x to the value v. +It panics if CanSet returns false. +As in Go, x's value must be assignable to v's type. +
+ + + + + + +func (v Value) SetBool(x bool)+
+SetBool sets v's underlying value. +It panics if v's Kind is not Bool or if CanSet() is false. +
+ + + + + + +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 (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 (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 CanSet() is false. +
+ + + + + + +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 CanSet() is false. +
+ + + + + + +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 CanSet() is false. +
+ + + + + + +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 (v Value) SetMapIndex(key, val Value)+
+SetMapIndex sets the value associated with key in the map v to val. +It panics if v's Kind is not Map. +If val 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 value must be assignable to the map's key type, +and val's value must be assignable to the map's value type. +
+ + + + + + +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 (v Value) SetString(x string)+
+SetString sets v's underlying value to x. +It panics if v's Kind is not String or if CanSet() is false. +
+ + + + + + +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 CanSet() is false. +
+ + + + + + +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 (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 (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 (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 (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 (v Value) Type() Type+
+Type returns v's type. +
+ + + + + + +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 (v Value) UnsafeAddr() uintptr+
+UnsafeAddr returns a pointer to v's data. +It is for advanced clients that also import the "unsafe" package. +It panics if v is not addressable. +
+ + + + + + + + +type ValueError struct { + Method string + Kind Kind +}+
+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. +
+ + + + + + + + + + + + + + +func (e *ValueError) Error() string+ + + + + + + + + + +
▹ Example
+func Match(pattern string, b []byte) (matched bool, err error)+
+Match checks whether a textual regular expression +matches a byte slice. More complicated queries need +to use Compile and the full Regexp interface. +
+ + + + + + + +func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)+
+MatchReader checks whether a textual regular expression matches the text +read by the RuneReader. More complicated queries need to use Compile and +the full Regexp interface. +
+ + + + + + + +func MatchString(pattern string, s string) (matched bool, err error)+
+MatchString checks whether a textual regular expression +matches a string. More complicated queries need +to use Compile and the full Regexp interface. +
+ +▹ Example
+func QuoteMeta(s string) string+
+QuoteMeta returns a string that quotes all regular expression metacharacters +inside the argument text; the returned string is a regular expression matching +the literal text. For example, QuoteMeta(`[foo]`) returns `\[foo\]`. +
+ + + + + + + + +type Regexp struct {
+ // contains filtered or unexported fields
+}
+ +Regexp is the representation of a compiled regular expression. +A Regexp is safe for concurrent use by multiple goroutines. +
+ + + + + + + + + + + + +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(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 http://swtch.com/~rsc/regexp/regexp2.html#posix for details. +
+ + + + + +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(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 (re *Regexp) Copy() *Regexp+
+Copy returns a new Regexp object copied from re. +
++When using a Regexp in multiple goroutines, giving each goroutine +its own copy helps to avoid lock contention. +
+ + + + + + +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 +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. +
+ + + + + + +func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte+
+ExpandString is like 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. +
+ + + + + + +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. +
+ + + + + + +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. +
+ + + + + + +func (re *Regexp) FindAllIndex(b []byte, n int) [][]int+
+FindAllIndex is the 'All' version of 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. +
+ + + + + + +func (re *Regexp) FindAllString(s string, n int) []string+
+FindAllString is the 'All' version of 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
+func (re *Regexp) FindAllStringIndex(s string, n int) [][]int+
+FindAllStringIndex is the 'All' version of 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 (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string+
+FindAllStringSubmatch is the 'All' version of 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
+func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int+
+FindAllStringSubmatchIndex is the 'All' version of +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
+func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte+
+FindAllSubmatch is the 'All' version of 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. +
+ + + + + + +func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int+
+FindAllSubmatchIndex is the 'All' version of 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. +
+ + + + + + +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. +
+ + + + + + +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 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 (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 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 (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 FindStringIndex or FindStringSubmatch if it is +necessary to distinguish these cases. +
+ + +▹ Example
+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
+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
+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 (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. +
+ + + + + + +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. +
+ + + + + + +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 (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. +
+ + + + + + +func (re *Regexp) Match(b []byte) bool+
+Match reports whether the Regexp matches the byte slice b. +
+ + + + + + +func (re *Regexp) MatchReader(r io.RuneReader) bool+
+MatchReader reports whether the Regexp matches the text read by the +RuneReader. +
+ + + + + + +func (re *Regexp) MatchString(s string) bool+
+MatchString reports whether the Regexp matches the string s. +
+ + + + + + +func (re *Regexp) NumSubexp() int+
+NumSubexp returns the number of parenthesized subexpressions in this Regexp. +
+ + + + + + +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 Expand, so for instance $1 represents the text of the first submatch. +
+ + + + + + +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 Expand. +
+ + + + + + +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 Expand. +
+ + + + + + +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 Expand. +
+ + +▹ Example
+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 Expand, so for instance $1 represents the text of the first submatch. +
+ + +▹ Example
+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 Expand. +
+ + + + + + +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 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
+func (re *Regexp) String() string+
+String returns the source text used to compile the regular expression. +
+ + + + + + +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
+func IsWordChar(r rune) bool+
+IsWordChar reports whether r is consider 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 uint8+
+An EmptyOp specifies a kind or mixture of zero-width assertions. +
+ + + +const ( + EmptyBeginLine EmptyOp = 1 << iota + EmptyEndLine + EmptyBeginText + EmptyEndText + EmptyWordBoundary + EmptyNoWordBoundary +)+ + + + + + + + + + + +
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 struct { + Code ErrorCode + Expr string +}+
+An Error describes a failure to parse a regular expression +and gives the offending expression. +
+ + + + + + + + + + + + + + +func (e *Error) Error() string+ + + + + + + + +
type ErrorCode string+
+An ErrorCode describes a failure to parse a regular expression. +
+ + + +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 )" +)+ + + + + + + + + + + + + +
func (e ErrorCode) String() string+ + + + + + + + +
type Flags uint16+
+Flags control the behavior of the parser and record information about regexp context. +
+ + + +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 struct { + Op InstOp + Out uint32 // all but InstMatch, InstFail + Arg uint32 // InstAlt, InstAltMatch, InstCapture, InstEmptyWidth + Rune []rune +}+
+An Inst is a single instruction in a regular expression program. +
+ + + + + + + + + + + + + + +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 (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 (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 (i *Inst) String() string+ + + + + + + + +
type InstOp uint8+
+An InstOp is an instruction opcode. +
+ + + +const ( + InstAlt InstOp = iota + InstAltMatch + InstCapture + InstEmptyWidth + InstMatch + InstFail + InstNop + InstRune + InstRune1 + InstRuneAny + InstRuneAnyNotNL +)+ + + + + + + + + + + + + +
func (i InstOp) String() string+ + + + + + + + +
type Op uint8+
+An Op is a single regular expression operator. +
+ + + +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 +)+ + + + + + + + + + + + + + + +
type Prog struct { + Inst []Inst + Start int // index of start instruction + NumCap int // number of InstCapture insts in re +}+
+A Prog is a compiled regular expression program. +
+ + + + + + + + + + + + +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 (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 (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 (p *Prog) String() string+ + + + + + + + +
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 +}+
+A Regexp is a node in a regular expression syntax tree. +
+ + + + + + + + + + + + +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 (re *Regexp) CapNames() []string+
+CapNames walks the regexp to find the names of capturing groups. +
+ + + + + + +func (x *Regexp) Equal(y *Regexp) bool+
+Equal returns true if x and y have identical structure. +
+ + + + + + +func (re *Regexp) MaxCap() int+
+MaxCap walks the regexp to find the maximum capture index. +
+ + + + + + +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 (re *Regexp) String() string+ + + + + + + + + + + + + + + + + + +
func AddInt32(addr *int32, delta int32) (new int32)+
+AddInt32 atomically adds delta to *addr and returns the new value. +
+ + + + + + + +func AddInt64(addr *int64, delta int64) (new int64)+
+AddInt64 atomically adds delta to *addr and returns the new value. +
+ + + + + + + +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)). +
+ + + + + + + +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)). +
+ + + + + + + +func AddUintptr(addr *uintptr, delta uintptr) (new uintptr)+
+AddUintptr atomically adds delta to *addr and returns the new value. +
+ + + + + + + +func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)+
+CompareAndSwapInt32 executes the compare-and-swap operation for an int32 value. +
+ + + + + + + +func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)+
+CompareAndSwapInt64 executes the compare-and-swap operation for an int64 value. +
+ + + + + + + +func CompareAndSwapPointer(addr *unsafe.Pointer, old, new unsafe.Pointer) (swapped bool)+
+CompareAndSwapPointer executes the compare-and-swap operation for a unsafe.Pointer value. +
+ + + + + + + +func CompareAndSwapUint32(addr *uint32, old, new uint32) (swapped bool)+
+CompareAndSwapUint32 executes the compare-and-swap operation for a uint32 value. +
+ + + + + + + +func CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool)+
+CompareAndSwapUint64 executes the compare-and-swap operation for a uint64 value. +
+ + + + + + + +func CompareAndSwapUintptr(addr *uintptr, old, new uintptr) (swapped bool)+
+CompareAndSwapUintptr executes the compare-and-swap operation for a uintptr value. +
+ + + + + + + +func LoadInt32(addr *int32) (val int32)+
+LoadInt32 atomically loads *addr. +
+ + + + + + + +func LoadInt64(addr *int64) (val int64)+
+LoadInt64 atomically loads *addr. +
+ + + + + + + +func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer)+
+LoadPointer atomically loads *addr. +
+ + + + + + + +func LoadUint32(addr *uint32) (val uint32)+
+LoadUint32 atomically loads *addr. +
+ + + + + + + +func LoadUint64(addr *uint64) (val uint64)+
+LoadUint64 atomically loads *addr. +
+ + + + + + + +func LoadUintptr(addr *uintptr) (val uintptr)+
+LoadUintptr atomically loads *addr. +
+ + + + + + + +func StoreInt32(addr *int32, val int32)+
+StoreInt32 atomically stores val into *addr. +
+ + + + + + + +func StoreInt64(addr *int64, val int64)+
+StoreInt64 atomically stores val into *addr. +
+ + + + + + + +func StorePointer(addr *unsafe.Pointer, val unsafe.Pointer)+
+StorePointer atomically stores val into *addr. +
+ + + + + + + +func StoreUint32(addr *uint32, val uint32)+
+StoreUint32 atomically stores val into *addr. +
+ + + + + + + +func StoreUint64(addr *uint64, val uint64)+
+StoreUint64 atomically stores val into *addr. +
+ + + + + + + +func StoreUintptr(addr *uintptr, val uintptr)+
+StoreUintptr atomically stores val into *addr. +
+ + + + + + + +func SwapInt32(addr *int32, new int32) (old int32)+
+SwapInt32 atomically stores new into *addr and returns the previous *addr value. +
+ + + + + + + +func SwapInt64(addr *int64, new int64) (old int64)+
+SwapInt64 atomically stores new into *addr and returns the previous *addr value. +
+ + + + + + + +func SwapPointer(addr *unsafe.Pointer, new unsafe.Pointer) (old unsafe.Pointer)+
+SwapPointer atomically stores new into *addr and returns the previous *addr value. +
+ + + + + + + +func SwapUint32(addr *uint32, new uint32) (old uint32)+
+SwapUint32 atomically stores new into *addr and returns the previous *addr value. +
+ + + + + + + +func SwapUint64(addr *uint64, new uint64) (old uint64)+
+SwapUint64 atomically stores new into *addr and returns the previous *addr value. +
+ + + + + + + +func SwapUintptr(addr *uintptr, new uintptr) (old uintptr)+
+SwapUintptr atomically stores new into *addr and returns the previous *addr value. +
+ + + + + + + + +type Value struct {
+ // contains filtered or unexported fields
+}
+ +A Value provides an atomic load and store of a consistently typed value. +Values can be created as part of other data structures. +The zero value for a Value returns nil from Load. +Once Store has been called, a Value must not be copied. +
+ + + + + + +▹ Example (Config)
+▹ Example (ReadMostly)
+func (v *Value) Load() (x interface{})+
+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 (v *Value) Store(x interface{})+
+Store sets the value of the Value to x. +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). +
+ + + + + + + + + + +type Cond struct { + // L is held while observing or changing the condition + L Locker + // contains filtered or unexported fields +}+
+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 can be created as part of other structures. +A Cond must not be copied after first use. +
+ + + + + + + + + + + + +func NewCond(l Locker) *Cond+
+NewCond returns a new Cond with Locker l. +
+ + + + + + + +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 (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. +
+ + + + + + +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 when Wait first resumes, 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 interface { + Lock() + Unlock() +}+
+A Locker represents an object that can be locked and unlocked. +
+ + + + + + + + + + + + + + + + +type Mutex struct {
+ // contains filtered or unexported fields
+}
+ +A Mutex is a mutual exclusion lock. +Mutexes can be created as part of other structures; +the zero value for a Mutex is an unlocked mutex. +
+ + + + + + + + + + + + + + +func (m *Mutex) Lock()+
+Lock locks m. +If the lock is already in use, the calling goroutine +blocks until the mutex is available. +
+ + + + + + +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 struct {
+ // contains filtered or unexported fields
+}
+ +Once is an object that will perform exactly one action. +
+ + + + + + +▹ Example
+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 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() interface{} + // contains filtered or unexported fields +}+
+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. +
+ + + + + + + + + + + + + + +func (p *Pool) Get() interface{}+
+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 (p *Pool) Put(x interface{})+
+Put adds x to the pool. +
+ + + + + + + + +type RWMutex struct {
+ // contains filtered or unexported fields
+}
+ +An RWMutex is a reader/writer mutual exclusion lock. +The lock can be held by an arbitrary number of readers +or a single writer. +RWMutexes can be created as part of other +structures; the zero value for a RWMutex is +an unlocked mutex. +
+ + + + + + + + + + + + + + +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. +To ensure that the lock eventually becomes available, +a blocked Lock call excludes new readers from acquiring +the lock. +
+ + + + + + +func (rw *RWMutex) RLock()+
+RLock locks rw for reading. +
+ + + + + + +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 (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 (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) an RWMutex and then +arrange for another goroutine to RUnlock (Unlock) it. +
+ + + + + + + + +type WaitGroup struct {
+ // contains filtered or unexported fields
+}
+ +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. +
+ + + + + + +▹ Example
+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 (wg *WaitGroup) Done()+
+Done decrements the WaitGroup counter. +
+ + + + + + +func (wg *WaitGroup) Wait()+
+Wait blocks until the WaitGroup counter is zero. +
+ + + + + + + + + + + + + + + + +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 + CLONE_CHILD_CLEARTID = 0x200000 + CLONE_CHILD_SETTID = 0x1000000 + CLONE_DETACHED = 0x400000 + CLONE_FILES = 0x400 + CLONE_FS = 0x200 + CLONE_IO = 0x80000000 + CLONE_NEWIPC = 0x8000000 + CLONE_NEWNET = 0x40000000 + CLONE_NEWNS = 0x20000 + CLONE_NEWPID = 0x20000000 + CLONE_NEWUSER = 0x10000000 + CLONE_NEWUTS = 0x4000000 + CLONE_PARENT = 0x8000 + CLONE_PARENT_SETTID = 0x100000 + CLONE_PTRACE = 0x2000 + CLONE_SETTLS = 0x80000 + CLONE_SIGHAND = 0x800 + CLONE_SYSVSEM = 0x40000 + CLONE_THREAD = 0x10000 + CLONE_UNTRACED = 0x800000 + CLONE_VFORK = 0x4000 + CLONE_VM = 0x100 + 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 +)+ + +
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) +)+
+Errors +
+ + +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) +)+
+Signals +
+ + +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
+
+
+
+
+ var ( + Stdin = 0 + Stdout = 1 + Stderr = 2 +)+ + +
var ForkLock sync.RWMutex+ + +
var SocketDisableIPv6 bool+
+For testing: clients can set this flag to force +creation of IPv6 sockets to return EAFNOSUPPORT. +
+ + + + + + +func Accept(fd int) (nfd int, sa Sockaddr, err error)+ + + + + + + +
func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error)+ + + + + + + +
func Access(path string, mode uint32) (err error)+ + + + + + + +
func Acct(path string) (err error)+ + + + + + + +
func Adjtimex(buf *Timex) (state int, err error)+ + + + + + + +
func AttachLsf(fd int, i []SockFilter) error+ + + + + + + +
func Bind(fd int, sa Sockaddr) (err error)+ + + + + + + +
func BindToDevice(fd int, device string) (err error)+
+BindToDevice binds the socket associated with fd to device. +
+ + + + + + + +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(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(path string) (err error)+ + + + + + + +
func Chmod(path string, mode uint32) (err error)+ + + + + + + +
func Chown(path string, uid int, gid int) (err error)+ + + + + + + +
func Chroot(path string) (err error)+ + + + + + + +
func Clearenv()+ + + + + + + +
func Close(fd int) (err error)+ + + + + + + +
func CloseOnExec(fd int)+ + + + + + + +
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(datalen int) int+
+CmsgSpace returns the number of bytes an ancillary element with +payload of the passed data length occupies. +
+ + + + + + + +func Connect(fd int, sa Sockaddr) (err error)+ + + + + + + +
func Creat(path string, mode uint32) (fd int, err error)+ + + + + + + +
func DetachLsf(fd int) error+ + + + + + + +
func Dup(oldfd int) (fd int, err error)+ + + + + + + +
func Dup2(oldfd int, newfd int) (err error)+ + + + + + + +
func Dup3(oldfd int, newfd int, flags int) (err error)+ + + + + + + +
func Environ() []string+ + + + + + + +
func EpollCreate(size int) (fd int, err error)+ + + + + + + +
func EpollCreate1(flag int) (fd int, err error)+ + + + + + + +
func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)+ + + + + + + +
func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)+ + + + + + + +
func Exec(argv0 string, argv []string, envv []string) (err error)+
+Ordinary exec. +
+ + + + + + + +func Exit(code int)+ + + + + + + +
func Faccessat(dirfd int, path string, mode uint32, flags int) (err error)+ + + + + + + +
func Fallocate(fd int, mode uint32, off int64, len int64) (err error)+ + + + + + + +
func Fchdir(fd int) (err error)+ + + + + + + +
func Fchmod(fd int, mode uint32) (err error)+ + + + + + + +
func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)+ + + + + + + +
func Fchown(fd int, uid int, gid int) (err error)+ + + + + + + +
func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)+ + + + + + + +
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(fd int) (err error)+ + + + + + + +
func Flock(fd int, how int) (err error)+ + + + + + + +
func ForkExec(argv0 string, argv []string, attr *ProcAttr) (pid int, err error)+
+Combination of fork and exec, careful to be thread safe. +
+ + + + + + + +func Fstat(fd int, stat *Stat_t) (err error)+ + + + + + + +
func Fstatfs(fd int, buf *Statfs_t) (err error)+ + + + + + + +
func Fsync(fd int) (err error)+ + + + + + + +
func Ftruncate(fd int, length int64) (err error)+ + + + + + + +
func Futimes(fd int, tv []Timeval) (err error)+ + + + + + + +
func Futimesat(dirfd int, path string, tv []Timeval) (err error)+ + + + + + + +
func Getcwd(buf []byte) (n int, err error)+ + + + + + + +
func Getdents(fd int, buf []byte) (n int, err error)+ + + + + + + +
func Getegid() (egid int)+ + + + + + + +
func Getenv(key string) (value string, found bool)+ + + + + + + +
func Geteuid() (euid int)+ + + + + + + +
func Getgid() (gid int)+ + + + + + + +
func Getgroups() (gids []int, err error)+ + + + + + + +
func Getpagesize() int+ + + + + + + +
func Getpgid(pid int) (pgid int, err error)+ + + + + + + +
func Getpgrp() (pid int)+ + + + + + + +
func Getpid() (pid int)+ + + + + + + +
func Getppid() (ppid int)+ + + + + + + +
func Getpriority(which int, who int) (prio int, err error)+ + + + + + + +
func Getrlimit(resource int, rlim *Rlimit) (err error)+ + + + + + + +
func Getrusage(who int, rusage *Rusage) (err error)+ + + + + + + +
func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error)+ + + + + + + +
func GetsockoptInt(fd, level, opt int) (value int, err error)+ + + + + + + +
func Gettid() (tid int)+ + + + + + + +
func Gettimeofday(tv *Timeval) (err error)+ + + + + + + +
func Getuid() (uid int)+ + + + + + + +
func Getwd() (wd string, err error)+ + + + + + + +
func Getxattr(path string, attr string, dest []byte) (sz int, err error)+ + + + + + + +
func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)+ + + + + + + +
func InotifyInit() (fd int, err error)+ + + + + + + +
func InotifyInit1(flags int) (fd int, err error)+ + + + + + + +
func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)+ + + + + + + +
func Ioperm(from int, num int, on int) (err error)+ + + + + + + +
func Iopl(level int) (err error)+ + + + + + + +
func Kill(pid int, sig Signal) (err error)+ + + + + + + +
func Klogctl(typ int, buf []byte) (n int, err error)+ + + + + + + +
func Lchown(path string, uid int, gid int) (err error)+ + + + + + + +
func Link(oldpath string, newpath string) (err error)+ + + + + + + +
func Listen(s int, n int) (err error)+ + + + + + + +
func Listxattr(path string, dest []byte) (sz int, err error)+ + + + + + + +
func LsfSocket(ifindex, proto int) (int, error)+ + + + + + + +
func Lstat(path string, stat *Stat_t) (err error)+ + + + + + + +
func Madvise(b []byte, advice int) (err error)+ + + + + + + +
func Mkdir(path string, mode uint32) (err error)+ + + + + + + +
func Mkdirat(dirfd int, path string, mode uint32) (err error)+ + + + + + + +
func Mkfifo(path string, mode uint32) (err error)+ + + + + + + +
func Mknod(path string, mode uint32, dev int) (err error)+ + + + + + + +
func Mknodat(dirfd int, path string, mode uint32, dev int) (err error)+ + + + + + + +
func Mlock(b []byte) (err error)+ + + + + + + +
func Mlockall(flags int) (err error)+ + + + + + + +
func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error)+ + + + + + + +
func Mount(source string, target string, fstype string, flags uintptr, data string) (err error)+ + + + + + + +
func Mprotect(b []byte, prot int) (err error)+ + + + + + + +
func Munlock(b []byte) (err error)+ + + + + + + +
func Munlockall() (err error)+ + + + + + + +
func Munmap(b []byte) (err error)+ + + + + + + +
func Nanosleep(time *Timespec, leftover *Timespec) (err error)+ + + + + + + +
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(path string, mode int, perm uint32) (fd int, err error)+ + + + + + + +
func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)+ + + + + + + +
func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string)+ + + + + + + +
func ParseNetlinkMessage(b []byte) ([]NetlinkMessage, error)+
+ParseNetlinkMessage parses b as an array of netlink messages and +returns the slice containing the NetlinkMessage structures. +
+ + + + + + + +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. +
+ + + + + + + +func ParseSocketControlMessage(b []byte) ([]SocketControlMessage, error)+
+ParseSocketControlMessage parses b as an array of socket control +messages. +
+ + + + + + + +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() (err error)+ + + + + + + +
func Pipe(p []int) (err error)+ + + + + + + +
func Pipe2(p []int, flags int) (err error)+ + + + + + + +
func PivotRoot(newroot string, putold string) (err error)+ + + + + + + +
func Pread(fd int, p []byte, offset int64) (n int, err error)+ + + + + + + +
func PtraceAttach(pid int) (err error)+ + + + + + + +
func PtraceCont(pid int, signal int) (err error)+ + + + + + + +
func PtraceDetach(pid int) (err error)+ + + + + + + +
func PtraceGetEventMsg(pid int) (msg uint, err error)+ + + + + + + +
func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error)+ + + + + + + +
func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error)+ + + + + + + +
func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error)+ + + + + + + +
func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error)+ + + + + + + +
func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error)+ + + + + + + +
func PtraceSetOptions(pid int, options int) (err error)+ + + + + + + +
func PtraceSetRegs(pid int, regs *PtraceRegs) (err error)+ + + + + + + +
func PtraceSingleStep(pid int) (err error)+ + + + + + + +
func PtraceSyscall(pid int, signal int) (err error)+ + + + + + + +
func Pwrite(fd int, p []byte, offset int64) (n int, err error)+ + + + + + + +
func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)+ + + + + + + +
func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)+ + + + + + + +
func Read(fd int, p []byte) (n int, err error)+ + + + + + + +
func ReadDirent(fd int, buf []byte) (n int, err error)+ + + + + + + +
func Readlink(path string, buf []byte) (n int, err error)+ + + + + + + +
func Reboot(cmd int) (err error)+ + + + + + + +
func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error)+ + + + + + + +
func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error)+ + + + + + + +
func Removexattr(path string, attr string) (err error)+ + + + + + + +
func Rename(oldpath string, newpath string) (err error)+ + + + + + + +
func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)+ + + + + + + +
func Rmdir(path string) error+ + + + + + + +
func Seek(fd int, offset int64, whence int) (off int64, err error)+ + + + + + + +
func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)+ + + + + + + +
func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)+ + + + + + + +
func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error)+ + + + + + + +
func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error)+ + + + + + + +
func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error)+ + + + + + + +
func SetLsfPromisc(name string, m bool) error+ + + + + + + +
func SetNonblock(fd int, nonblocking bool) (err error)+ + + + + + + +
func Setdomainname(p []byte) (err error)+ + + + + + + +
func Setenv(key, value string) error+ + + + + + + +
func Setfsgid(gid int) (err error)+ + + + + + + +
func Setfsuid(uid int) (err error)+ + + + + + + +
func Setgid(gid int) (err error)+ + + + + + + +
func Setgroups(gids []int) (err error)+ + + + + + + +
func Sethostname(p []byte) (err error)+ + + + + + + +
func Setpgid(pid int, pgid int) (err error)+ + + + + + + +
func Setpriority(which int, who int, prio int) (err error)+ + + + + + + +
func Setregid(rgid int, egid int) (err error)+ + + + + + + +
func Setresgid(rgid int, egid int, sgid int) (err error)+ + + + + + + +
func Setresuid(ruid int, euid int, suid int) (err error)+ + + + + + + +
func Setreuid(ruid int, euid int) (err error)+ + + + + + + +
func Setrlimit(resource int, rlim *Rlimit) (err error)+ + + + + + + +
func Setsid() (pid int, err error)+ + + + + + + +
func SetsockoptByte(fd, level, opt int, value byte) (err error)+ + + + + + + +
func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error+ + + + + + + +
func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) (err error)+ + + + + + + +
func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error)+ + + + + + + +
func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) (err error)+ + + + + + + +
func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) (err error)+ + + + + + + +
func SetsockoptInt(fd, level, opt int, value int) (err error)+ + + + + + + +
func SetsockoptLinger(fd, level, opt int, l *Linger) (err error)+ + + + + + + +
func SetsockoptString(fd, level, opt int, s string) (err error)+ + + + + + + +
func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error)+ + + + + + + +
func Settimeofday(tv *Timeval) (err error)+ + + + + + + +
func Setuid(uid int) (err error)+ + + + + + + +
func Setxattr(path string, attr string, data []byte, flags int) (err error)+ + + + + + + +
func Shutdown(fd int, how int) (err error)+ + + + + + + +
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(domain, typ, proto int) (fd int, err error)+ + + + + + + +
func Socketpair(domain, typ, proto int) (fd [2]int, err error)+ + + + + + + +
func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)+ + + + + + + +
func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error)+
+StartProcess wraps ForkExec for package os. +
+ + + + + + + +func Stat(path string, stat *Stat_t) (err error)+ + + + + + + +
func Statfs(path string, buf *Statfs_t) (err error)+ + + + + + + +
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(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(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 SyncFileRange(fd int, off int64, n int64, flags int) (err error)+ + + + + + + +
func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)+ + + + + + + +
func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)+ + + + + + + +
func Sysinfo(info *Sysinfo_t) (err error)+ + + + + + + +
func Tee(rfd int, wfd int, len int, flags int) (n int64, err error)+ + + + + + + +
func Tgkill(tgid int, tid int, sig Signal) (err error)+ + + + + + + +
func Times(tms *Tms) (ticks uintptr, err error)+ + + + + + + +
func TimespecToNsec(ts Timespec) int64+ + + + + + + +
func TimevalToNsec(tv Timeval) int64+ + + + + + + +
func Truncate(path string, length int64) (err error)+ + + + + + + +
func Umask(mask int) (oldmask int)+ + + + + + + +
func Uname(buf *Utsname) (err error)+ + + + + + + +
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(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(dirfd int, path string) error+ + + + + + + +
func Unmount(target string, flags int) (err error)+ + + + + + + +
func Unsetenv(key string) error+ + + + + + + +
func Unshare(flags int) (err error)+ + + + + + + +
func Ustat(dev int, ubuf *Ustat_t) (err error)+ + + + + + + +
func Utime(path string, buf *Utimbuf) (err error)+ + + + + + + +
func Utimes(path string, tv []Timeval) (err error)+ + + + + + + +
func UtimesNano(path string, ts []Timespec) (err error)+ + + + + + + +
func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error)+ + + + + + + +
func Write(fd int, p []byte) (n int, err error)+ + + + + + + + +
type Cmsghdr struct { + Len uint64 + Level int32 + Type int32 + X__cmsg_data [0]uint8 +}+ + + + + + + + + + + + + + +
func (cmsg *Cmsghdr) SetLen(length int)+ + + + + + + + +
type Credential struct { + Uid uint32 // User ID. + Gid uint32 // Group ID. + Groups []uint32 // Supplementary group IDs. +}+
+Credential holds user and group identities to be assumed +by a child process started by StartProcess. +
+ + + + + + + + + + + + + + + + +type Dirent struct { + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]int8 + Pad_cgo_0 [5]byte +}+ + + + + + + + + + + + + + + + +
type EpollEvent struct { + Events uint32 + Fd int32 + Pad int32 +}+ + + + + + + + + + + + + + + + +
type Errno uintptr+
+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 +} ++ + + + + + + + + + + + + + +
func (e Errno) Error() string+ + + + + + +
func (e Errno) Temporary() bool+ + + + + + +
func (e Errno) Timeout() bool+ + + + + + + + +
type FdSet struct { + Bits [16]int64 +}+ + + + + + + + + + + + + + + + +
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 struct { + X__val [2]int32 +}+ + + + + + + + + + + + + + + + +
type ICMPv6Filter struct { + Data [8]uint32 +}+ + + + + + + + + + + + +
func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error)+ + + + + + + + + +
type IPMreq struct { + Multiaddr [4]byte /* in_addr */ + Interface [4]byte /* in_addr */ +}+ + + + + + + + + + + + +
func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error)+ + + + + + + + + +
type IPMreqn struct { + Multiaddr [4]byte /* in_addr */ + Address [4]byte /* in_addr */ + Ifindex int32 +}+ + + + + + + + + + + + +
func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error)+ + + + + + + + + +
type IPv6MTUInfo struct { + Addr RawSockaddrInet6 + Mtu uint32 +}+ + + + + + + + + + + + +
func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error)+ + + + + + + + + +
type IPv6Mreq struct { + Multiaddr [16]byte /* in6_addr */ + Interface uint32 +}+ + + + + + + + + + + + +
func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error)+ + + + + + + + + +
type IfAddrmsg struct { + Family uint8 + Prefixlen uint8 + Flags uint8 + Scope uint8 + Index uint32 +}+ + + + + + + + + + + + + + + + +
type IfInfomsg struct { + Family uint8 + X__ifi_pad uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 +}+ + + + + + + + + + + + + + + + +
type Inet4Pktinfo struct { + Ifindex int32 + Spec_dst [4]byte /* in_addr */ + Addr [4]byte /* in_addr */ +}+ + + + + + + + + + + + + + + + +
type Inet6Pktinfo struct { + Addr [16]byte /* in6_addr */ + Ifindex uint32 +}+ + + + + + + + + + + + + + + + +
type InotifyEvent struct { + Wd int32 + Mask uint32 + Cookie uint32 + Len uint32 + Name [0]uint8 +}+ + + + + + + + + + + + + + + + +
type Iovec struct { + Base *byte + Len uint64 +}+ + + + + + + + + + + + + + +
func (iov *Iovec) SetLen(length int)+ + + + + + + + +
type Linger struct { + Onoff int32 + Linger int32 +}+ + + + + + + + + + + + + + + + +
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 *Msghdr) SetControllen(length int)+ + + + + + + + +
type NetlinkMessage struct { + Header NlMsghdr + Data []byte +}+
+NetlinkMessage represents a netlink message. +
+ + + + + + + + + + + + + + + + +type NetlinkRouteAttr struct { + Attr RtAttr + Value []byte +}+
+NetlinkRouteAttr represents a netlink route attribute. +
+ + + + + + + + + + + + + + + + +type NetlinkRouteRequest struct { + Header NlMsghdr + Data RtGenmsg +}+
+NetlinkRouteRequest represents a request message to receive routing +and link states from the kernel. +
+ + + + + + + + + + + + + + + + +type NlAttr struct { + Len uint16 + Type uint16 +}+ + + + + + + + + + + + + + + + +
type NlMsgerr struct { + Error int32 + Msg NlMsghdr +}+ + + + + + + + + + + + + + + + +
type NlMsghdr struct { + Len uint32 + Type uint16 + Flags uint16 + Seq uint32 + Pid uint32 +}+ + + + + + + + + + + + + + + + +
type ProcAttr struct { + Dir string // Current working directory. + Env []string // Environment. + Files []uintptr // File descriptors. + Sys *SysProcAttr +}+
+ProcAttr holds attributes that will be applied to a new process started +by StartProcess. +
+ + + + + + + + + + + + + + + + +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 (r *PtraceRegs) PC() uint64+ + + + + + +
func (r *PtraceRegs) SetPC(pc uint64)+ + + + + + + + +
type RawSockaddr struct { + Family uint16 + Data [14]int8 +}+ + + + + + + + + + + + + + + + +
type RawSockaddrAny struct { + Addr RawSockaddr + Pad [96]int8 +}+ + + + + + + + + + + + + + + + +
type RawSockaddrInet4 struct { + Family uint16 + Port uint16 + Addr [4]byte /* in_addr */ + Zero [8]uint8 +}+ + + + + + + + + + + + + + + + +
type RawSockaddrInet6 struct { + Family uint16 + Port uint16 + Flowinfo uint32 + Addr [16]byte /* in6_addr */ + Scope_id uint32 +}+ + + + + + + + + + + + + + + + +
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 struct { + Family uint16 + Path [108]int8 +}+ + + + + + + + + + + + + + + + +
type Rlimit struct { + Cur uint64 + Max uint64 +}+ + + + + + + + + + + + + + + + +
type RtAttr struct { + Len uint16 + Type uint16 +}+ + + + + + + + + + + + + + + + +
type RtGenmsg struct { + Family uint8 +}+ + + + + + + + + + + + + + + + +
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 struct { + Len uint16 + Flags uint8 + Hops uint8 + Ifindex int32 +}+ + + + + + + + + + + + + + + + +
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 int+
+A Signal is a number describing a process signal. +It implements the os.Signal interface. +
+ + + + + + + + + + + + + + +func (s Signal) Signal()+ + + + + + +
func (s Signal) String() string+ + + + + + + + +
type SockFilter struct { + Code uint16 + Jt uint8 + Jf uint8 + K uint32 +}+ + + + + + + + + + + + +
func LsfJump(code, k, jt, jf int) *SockFilter+ + + + + +
func LsfStmt(code, k int) *SockFilter+ + + + + + + + + +
type SockFprog struct { + Len uint16 + Pad_cgo_0 [6]byte + Filter *SockFilter +}+ + + + + + + + + + + + + + + + +
type Sockaddr interface {
+ // contains filtered or unexported methods
+}
+
+
+
+
+
+
+
+
+
+
+
+
+ func Getpeername(fd int) (sa Sockaddr, err error)+ + + + + +
func Getsockname(fd int) (sa Sockaddr, err error)+ + + + + + + + + +
type SockaddrInet4 struct { + Port int + Addr [4]byte + // contains filtered or unexported fields +}+ + + + + + + + + + + + + + + + +
type SockaddrInet6 struct { + Port int + ZoneId uint32 + Addr [16]byte + // contains filtered or unexported fields +}+ + + + + + + + + + + + + + + + +
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 struct { + Name string + // contains filtered or unexported fields +}+ + + + + + + + + + + + + + + + +
type SocketControlMessage struct { + Header Cmsghdr + Data []byte +}+
+SocketControlMessage represents a socket control message. +
+ + + + + + + + + + + + + + + + +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 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 struct { + Chroot string // Chroot. + Credential *Credential // Credential. + Ptrace bool // Enable tracing. + Setsid bool // Create session. + Setpgid bool // Set process group ID to Pgid, or, if Pgid == 0, to new pid. + Setctty bool // Set controlling terminal to fd Ctty (only meaningful if Setsid is set) + Noctty bool // Detach fd 0 from controlling terminal + Ctty int // Controlling TTY fd + Foreground bool // Place child's process group in foreground. (Implies Setpgid. Uses Ctty as fd of controlling TTY) + Pgid int // Child's process group ID if Setpgid. + Pdeathsig Signal // Signal that the process will get when its parent dies (Linux only) + Cloneflags uintptr // Flags for clone calls (Linux only) + 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 +}+ + + + + + + + + + + + + + + + +
type SysProcIDMap struct { + ContainerID int // Container ID. + HostID int // Host ID. + Size int // Size. +}+
+SysProcIDMap holds Container ID to Host ID mappings used for User Namespaces in Linux. +See user_namespaces(7). +
+ + + + + + + + + + + + + + + + +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 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 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 int64+ + + + + + + + + + + + +
func Time(t *Time_t) (tt Time_t, err error)+ + + + + + + + + +
type Timespec struct { + Sec int64 + Nsec int64 +}+ + + + + + + + + + + + +
func NsecToTimespec(nsec int64) (ts Timespec)+ + + + + + + +
func (ts *Timespec) Nano() int64+ + + + + + +
func (ts *Timespec) Unix() (sec int64, nsec int64)+ + + + + + + + +
type Timeval struct { + Sec int64 + Usec int64 +}+ + + + + + + + + + + + +
func NsecToTimeval(nsec int64) (tv Timeval)+ + + + + + + +
func (tv *Timeval) Nano() int64+ + + + + + +
func (tv *Timeval) Unix() (sec int64, nsec int64)+ + + + + + + + +
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 struct { + Utime int64 + Stime int64 + Cutime int64 + Cstime int64 +}+ + + + + + + + + + + + + + + + +
type Ucred struct { + Pid int32 + Uid uint32 + Gid uint32 +}+ + + + + + + + + + + + +
func GetsockoptUcred(fd, level, opt int) (*Ucred, error)+ + + + + +
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 struct { + Tfree int32 + Pad_cgo_0 [4]byte + Tinode uint64 + Fname [6]int8 + Fpack [6]int8 + Pad_cgo_1 [4]byte +}+ + + + + + + + + + + + + + + + +
type Utimbuf struct { + Actime int64 + Modtime int64 +}+ + + + + + + + + + + + + + + + +
type Utsname struct { + Sysname [65]int8 + Nodename [65]int8 + Release [65]int8 + Version [65]int8 + Machine [65]int8 + Domainname [65]int8 +}+ + + + + + + + + + + + + + + + +
type WaitStatus uint32+ + + + + + + + + + + + + + +
func (w WaitStatus) Continued() bool+ + + + + + +
func (w WaitStatus) CoreDump() bool+ + + + + + +
func (w WaitStatus) ExitStatus() int+ + + + + + +
func (w WaitStatus) Exited() bool+ + + + + + +
func (w WaitStatus) Signal() Signal+ + + + + + +
func (w WaitStatus) Signaled() bool+ + + + + + +
func (w WaitStatus) StopSignal() Signal+ + + + + + +
func (w WaitStatus) Stopped() bool+ + + + + + +
func (w WaitStatus) TrapCause() int+ + + + + + + + + + + + + + + + + + +
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 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 Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample)+
+An internal function but exported because it is cross-package; part of the implementation +of the "go test" command. +
+ + + + + + + +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(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark)+
+An internal function but exported because it is cross-package; part of the implementation +of the "go test" command. +
+ + + + + + + +func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool)+ + + + + + + +
func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool)+ + + + + + + +
func Short() bool+
+Short reports whether the -test.short flag is set. +
+ + + + + + + +func Verbose() bool+
+Verbose reports whether the -test.v flag is set. +
+ + + + + + + + +type B struct { + N int + // contains filtered or unexported fields +}+
+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 error when done. Unlike in tests, benchmark logs +are always printed, so as not to hide output whose existence may be +affecting benchmark results. +
+ + + + + + + + + + + + + + +func (c *B) Error(args ...interface{})+
+Error is equivalent to Log followed by Fail. +
+ + + + + + +func (c *B) Errorf(format string, args ...interface{})+
+Errorf is equivalent to Logf followed by Fail. +
+ + + + + + +func (c *B) Fail()+
+Fail marks the function as having failed but continues execution. +
+ + + + + + +func (c *B) FailNow()+
+FailNow marks the function as having failed and stops its execution. +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 (c *B) Failed() bool+
+Failed reports whether the function has failed. +
+ + + + + + +func (c *B) Fatal(args ...interface{})+
+Fatal is equivalent to Log followed by FailNow. +
+ + + + + + +func (c *B) Fatalf(format string, args ...interface{})+
+Fatalf is equivalent to Logf followed by FailNow. +
+ + + + + + +func (c *B) Log(args ...interface{})+
+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 (c *B) Logf(format string, args ...interface{})+
+Logf formats its arguments according to the format, analogous to Printf, +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 *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 *B) ResetTimer()+
+ResetTimer zeros the elapsed benchmark time and memory allocation counters. +It does not affect whether the timer is running. +
+ + + + + + +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 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 StartTimer, StopTimer, or ResetTimer functions, +because they have global effect. +
+ + +▹ Example
+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 *B) SetParallelism(p int)+
+SetParallelism sets the number of goroutines used by 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 (c *B) Skip(args ...interface{})+
+Skip is equivalent to Log followed by SkipNow. +
+ + + + + + +func (c *B) SkipNow()+
+SkipNow marks the test as having been skipped and stops its execution. +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 (c *B) Skipf(format string, args ...interface{})+
+Skipf is equivalent to Logf followed by SkipNow. +
+ + + + + + +func (c *B) Skipped() bool+
+Skipped reports whether the test was skipped. +
+ + + + + + +func (b *B) StartTimer()+
+StartTimer starts timing a test. This function is called automatically +before a benchmark starts, but it can also used to resume timing after +a call to 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. +
+ + + + + + + + +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. + MemBytes uint64 // The total number of bytes allocated. +}+
+The results of a benchmark run. +
+ + + + + + + + + + + + +func Benchmark(f func(b *B)) BenchmarkResult+
+Benchmark benchmarks a single function. Useful for creating +custom benchmarks that do not use the "go test" command. +
+ + + + + + + +func (r BenchmarkResult) AllocedBytesPerOp() int64+ + + + + + +
func (r BenchmarkResult) AllocsPerOp() int64+ + + + + + +
func (r BenchmarkResult) MemString() string+ + + + + + +
func (r BenchmarkResult) NsPerOp() int64+ + + + + + +
func (r BenchmarkResult) String() string+ + + + + + + + +
type Cover struct { + Mode string + Counters map[string][]uint32 + Blocks map[string][]CoverBlock + CoveredPackages string +}+
+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 CoverBlock struct { + Line0 uint32 + Col0 uint16 + Line1 uint32 + Col1 uint16 + Stmts uint16 +}+
+CoverBlock records the coverage data for a single basic block. +NOTE: This struct is internal to the testing infrastructure and may change. +It is not covered (yet) by the Go 1 compatibility guidelines. +
+ + + + + + + + + + + + + + + + +type InternalBenchmark struct { + Name string + F func(b *B) +}+
+An internal type but exported because it is cross-package; part of the implementation +of the "go test" command. +
+ + + + + + + + + + + + + + + + +type InternalExample struct { + Name string + F func() + Output string +}+ + + + + + + + + + + + + + + + +
type InternalTest struct { + Name string + F func(*T) +}+
+An internal type but exported because it is cross-package; part of the implementation +of the "go test" command. +
+ + + + + + + + + + + + + + + + +type M struct {
+ // contains filtered or unexported fields
+}
+ +M is a type passed to a TestMain function to run the actual tests. +
+ + + + + + + + + + + + +func MainStart(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, 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 *M) Run() int+
+Run runs the tests. It returns an exit code to pass to os.Exit. +
+ + + + + + + + +type PB struct {
+ // contains filtered or unexported fields
+}
+ +A PB is used by RunParallel for running parallel benchmarks. +
+ + + + + + + + + + + + + + +func (pb *PB) Next() bool+
+Next reports whether there are more iterations to execute. +
+ + + + + + + + +type T struct {
+ // contains filtered or unexported fields
+}
+ +T is a type passed to Test functions to manage test state and support formatted test logs. +Logs are accumulated during execution and dumped to standard error when done. +
++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. +
+ + + + + + + + + + + + + + +func (c *T) Error(args ...interface{})+
+Error is equivalent to Log followed by Fail. +
+ + + + + + +func (c *T) Errorf(format string, args ...interface{})+
+Errorf is equivalent to Logf followed by Fail. +
+ + + + + + +func (c *T) Fail()+
+Fail marks the function as having failed but continues execution. +
+ + + + + + +func (c *T) FailNow()+
+FailNow marks the function as having failed and stops its execution. +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 (c *T) Failed() bool+
+Failed reports whether the function has failed. +
+ + + + + + +func (c *T) Fatal(args ...interface{})+
+Fatal is equivalent to Log followed by FailNow. +
+ + + + + + +func (c *T) Fatalf(format string, args ...interface{})+
+Fatalf is equivalent to Logf followed by FailNow. +
+ + + + + + +func (c *T) Log(args ...interface{})+
+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 (c *T) Logf(format string, args ...interface{})+
+Logf formats its arguments according to the format, analogous to Printf, +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 *T) Parallel()+
+Parallel signals that this test is to be run in parallel with (and only with) +other parallel tests. +
+ + + + + + +func (c *T) Skip(args ...interface{})+
+Skip is equivalent to Log followed by SkipNow. +
+ + + + + + +func (c *T) SkipNow()+
+SkipNow marks the test as having been skipped and stops its execution. +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 (c *T) Skipf(format string, args ...interface{})+
+Skipf is equivalent to Logf followed by SkipNow. +
+ + + + + + +func (c *T) Skipped() bool+
+Skipped reports whether the test was skipped. +
+ + + + + + + + +type TB interface { + Error(args ...interface{}) + Errorf(format string, args ...interface{}) + Fail() + FailNow() + Failed() bool + Fatal(args ...interface{}) + Fatalf(format string, args ...interface{}) + Log(args ...interface{}) + Logf(format string, args ...interface{}) + Skip(args ...interface{}) + SkipNow() + Skipf(format string, args ...interface{}) + Skipped() bool + // contains filtered or unexported methods +}+
+TB is the interface common to T and B. +
+ + + + + + + + + + + + + + + + + + + + + + + + +var ErrTimeout = errors.New("timeout")+ + + + + + +
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 HalfReader(r io.Reader) io.Reader+
+HalfReader returns a Reader that implements Read +by reading half as many requested bytes from r. +
+ + + + + + + +func NewReadLogger(prefix string, r io.Reader) io.Reader+
+NewReadLogger returns a reader that behaves like r except +that it logs (using log.Print) each read to standard error, +printing the prefix and the hexadecimal data read. +
+ + + + + + + +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(r io.Reader) io.Reader+
+OneByteReader returns a Reader that implements +each non-empty Read by reading one byte from r. +
+ + + + + + + +func TimeoutReader(r io.Reader) io.Reader+
+TimeoutReader returns ErrTimeout on the second read +with no data. Subsequent calls to read succeed. +
+ + + + + + + +func TruncateWriter(w io.Writer, n int64) io.Writer+
+TruncateWriter returns a Writer that writes to w +but stops silently after n bytes. +
+ + + + + + + + + + + + + + + + + + +func Check(f interface{}, config *Config) (err 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(f, g interface{}, config *Config) (err 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(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 struct { + CheckError + Out1 []interface{} + Out2 []interface{} +}+
+A CheckEqualError is the result CheckEqual finding an error. +
+ + + + + + + + + + + + + + +func (s *CheckEqualError) Error() string+ + + + + + + + +
type CheckError struct { + Count int + In []interface{} +}+
+A CheckError is the result of Check finding an error. +
+ + + + + + + + + + + + + + +func (s *CheckError) Error() string+ + + + + + + + +
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. If zero, the default is unchanged. + MaxCountScale float64 + // If non-nil, rand is a source of random numbers. Otherwise a default + // pseudo-random source will be used. + Rand *rand.Rand + // If non-nil, the Values function generates a slice of arbitrary + // reflect.Values that are congruent with the arguments to the function + // being tested. Otherwise, the top-level Value function is used + // to generate them. + Values func([]reflect.Value, *rand.Rand) +}+
+A Config structure contains options for running a test. +
+ + + + + + + + + + + + + + + + +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 +}+
+A Generator can generate random values of its own type. +
+ + + + + + + + + + + + + + + + +type SetupError string+
+A SetupError is the result of an error in the way that check is being +used, independent of the functions being tested. +
+ + + + + + + + + + + + + + +func (s SetupError) Error() string+ + + + + + + + + + + + + + + + + + +
const ( + 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" +)+
+These are predefined layouts for use in Time.Format and Time.Parse. +The reference time used in the layouts is the specific time: +
+Mon Jan 2 15:04:05 MST 2006 ++
+which is Unix time 1136239445. Since MST is GMT-0700, +the reference time can be thought of as +
+01/02 03:04:05PM '06 -0700 ++
+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. +
++Within the format string, an underscore _ represents a space that may be +replaced by a digit if the following number (a day) has two digits; for +compatibility with fixed-width Unix time formats. +
++A decimal point followed by one or more zeros represents a fractional +second, printed to the given number of decimal places. A decimal point +followed by one or more nines represents a fractional second, printed to +the given number of decimal places, with trailing zeros removed. +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 a decimal point followed by a maximal +series of digits is parsed as a fractional second. +
++Numeric time zone offsets format as follows: +
+-0700 ±hhmm +-07:00 ±hh:mm +-07 ±hh ++
+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 ++
+The executable 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. +
+ + + + + + + +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. +
+ +▹ Example
+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
+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". +
+ +▹ Example
+type Duration int64+
+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. +
+ + + +const ( + Nanosecond Duration = 1 + Microsecond = 1000 * Nanosecond + Millisecond = 1000 * Microsecond + Second = 1000 * Millisecond + Minute = 60 * Second + Hour = 60 * Minute +)+
+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 ++ + + + + +
▹ Example
+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". +
+ + + + + +func Since(t Time) Duration+
+Since returns the time elapsed since t. +It is shorthand for time.Now().Sub(t). +
+ + + + + + + +func (d Duration) Hours() float64+
+Hours returns the duration as a floating point number of hours. +
+ + + + + + +func (d Duration) Minutes() float64+
+Minutes returns the duration as a floating point number of minutes. +
+ + + + + + +func (d Duration) Nanoseconds() int64+
+Nanoseconds returns the duration as an integer nanosecond count. +
+ + + + + + +func (d Duration) Seconds() float64+
+Seconds returns the duration as a floating point number of seconds. +
+ + + + + + +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 0, +with no unit. +
+ + + + + + + + +type Location struct {
+ // contains filtered or unexported fields
+}
+ +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, such as CEST and CET for central Europe. +
+ + + + + +var Local *Location = &localLoc+
+Local represents the system's local time zone. +
+ + +var UTC *Location = &utcLoc+
+UTC represents Universal Coordinated Time (UTC). +
+ + + + + + + + + +func FixedZone(name string, offset int) *Location+
+FixedZone returns a Location that always uses +the given zone name and offset (seconds east of UTC). +
+ + + + + +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". +
++The time zone database needed by LoadLocation may not be +present on all systems, especially non-Unix systems. +LoadLocation looks in the directory or uncompressed zip file +named by the ZONEINFO environment variable, if any, then looks in +known installation locations on Unix systems, +and finally looks in $GOROOT/lib/time/zoneinfo.zip. +
+ + + + + + + +func (l *Location) String() string+
+String returns a descriptive name for the time zone information, +corresponding to the argument to LoadLocation. +
+ + + + + + + + +type Month int+
+A Month specifies a month of the year (January = 1, ...). +
+ + + +const ( + January Month = 1 + iota + February + March + April + May + June + July + August + September + October + November + December +)+ + + + + +
▹ Example
+func (m Month) String() string+
+String returns the English name of the month ("January", "February", ...). +
+ + + + + + + + +type ParseError struct { + Layout string + Value string + LayoutElem string + ValueElem string + Message string +}+
+ParseError describes a problem parsing a time string. +
+ + + + + + + + + + + + + + +func (e *ParseError) Error() string+
+Error returns the string representation of a ParseError. +
+ + + + + + + + +type Ticker struct { + C <-chan Time // The channel on which the ticks are delivered. + // contains filtered or unexported fields +}+
+A Ticker holds a channel that delivers `ticks' of a clock +at intervals. +
+ + + + + + + + + + + + +func NewTicker(d Duration) *Ticker+
+NewTicker returns a new Ticker containing a channel that will send the +time with a period specified by the duration argument. +It adjusts the intervals or drops 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. +
+ + + + + + + +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 read from the channel succeeding +incorrectly. +
+ + + + + + + + +type Time struct {
+ // contains filtered or unexported fields
+}
+ +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. +
++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 associated with it a Location, consulted when computing the +presentation form of the time, such as in the Format, Hour, and Year methods. +The methods Local, UTC, and In return a Time with a specific location. +Changing the location in this way changes only the presentation; it does not +change the instant in time being denoted and therefore does not affect the +computations described in earlier paragraphs. +
++Note that the Go == operator compares not just the time instant but also the +Location. 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. +
+ + + + + + + + + + + + +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
+func Now() Time+
+Now returns the current local time. +
+ + + + + +func Parse(layout, value string) (Time, error)+
+Parse parses a formatted string and returns the time value it represents. +The layout defines the format by showing how the reference time, +defined to be +
+Mon Jan 2 15:04:05 -0700 MST 2006 ++
+would be interpreted if it were the value; it serves as an example of +the input format. The same interpretation will then be made to the +input string. +
++Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard +and convenient representations of the reference time. For more information +about the formats and the definition of the reference time, see the +documentation for ANSIC and the other constants defined by this package. +Also, the executable example for time.Format demonstrates the working +of the layout string in detail and is a good reference. +
++Elements omitted from the value 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. +
++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. +
++No checking is done that the day of the month is within the month's +valid dates; any one- or two-digit value is accepted. For example +February 31 and even February 99 are valid dates, specifying dates +in March and May. This behavior is consistent with time.Date. +
++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
+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
+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). +
+ + + + + + + +func (t Time) Add(d Duration) Time+
+Add returns the time t+d. +
+ + + + + + +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. +
++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. +
+ + + + + + +func (t Time) After(u Time) bool+
+After reports whether the time instant t is after u. +
+ + + + + + +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. +
+ + + + + + +func (t Time) Before(u Time) bool+
+Before reports whether the time instant t is before u. +
+ + + + + + +func (t Time) Clock() (hour, min, sec int)+
+Clock returns the hour, minute, and second within the day specified by t. +
+ + + + + + +func (t Time) Date() (year int, month Month, day int)+
+Date returns the year, month, and day in which t occurs. +
+ + + + + + +func (t Time) Day() int+
+Day returns the day of the month specified by t. +
+ + + + + + +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 CEST and 4:00 UTC are Equal. +This comparison is different from using t == u, which also compares +the locations. +
+ + + + + + +func (t Time) Format(layout string) string+
+Format returns a textual representation of the time value formatted +according to layout, which defines the format by showing how the reference +time, defined to be +
+Mon Jan 2 15:04:05 -0700 MST 2006 ++
+would be displayed if it were the value; it serves as an example of the +desired output. The same display rules will then be applied to the time +value. +
++A fractional second is represented by adding a period and zeros +to the end of the seconds section of layout string, as in "15:04:05.000" +to format a time stamp with millisecond precision. +
++Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard +and convenient representations of the reference time. For more information +about the formats and the definition of the reference time, see the +documentation for ANSIC and the other constants defined by this package. +
+ + +▹ Example
+func (t *Time) GobDecode(data []byte) error+
+GobDecode implements the gob.GobDecoder interface. +
+ + + + + + +func (t Time) GobEncode() ([]byte, error)+
+GobEncode implements the gob.GobEncoder interface. +
+ + + + + + +func (t Time) Hour() int+
+Hour returns the hour within the day specified by t, in the range [0, 23]. +
+ + + + + + +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 (t Time) In(loc *Location) Time+
+In returns t with the location information set to loc. +
++In panics if loc is nil. +
+ + + + + + +func (t Time) IsZero() bool+
+IsZero reports whether t represents the zero time instant, +January 1, year 1, 00:00:00 UTC. +
+ + + + + + +func (t Time) Local() Time+
+Local returns t with the location set to local time. +
+ + + + + + +func (t Time) Location() *Location+
+Location returns the time zone information associated with t. +
+ + + + + + +func (t Time) MarshalBinary() ([]byte, error)+
+MarshalBinary implements the encoding.BinaryMarshaler interface. +
+ + + + + + +func (t Time) MarshalJSON() ([]byte, error)+
+MarshalJSON implements the json.Marshaler interface. +The time is a quoted string in RFC 3339 format, with sub-second precision added if present. +
+ + + + + + +func (t Time) MarshalText() ([]byte, error)+
+MarshalText implements the encoding.TextMarshaler interface. +The time is formatted in RFC 3339 format, with sub-second precision added if present. +
+ + + + + + +func (t Time) Minute() int+
+Minute returns the minute offset within the hour specified by t, in the range [0, 59]. +
+ + + + + + +func (t Time) Month() Month+
+Month returns the month of the year specified by t. +
+ + + + + + +func (t Time) Nanosecond() int+
+Nanosecond returns the nanosecond offset within the second specified by t, +in the range [0, 999999999]. +
+ + + + + + +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 unchanged. +
+ + +▹ Example
+func (t Time) Second() int+
+Second returns the second offset within the minute specified by t, in the range [0, 59]. +
+ + + + + + +func (t Time) String() string+
+String returns the time formatted using the format string +
+"2006-01-02 15:04:05.999999999 -0700 MST" ++ + + + + + +
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). +
+ + + + + + +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 unchanged. +
+ + +▹ Example
+func (t Time) UTC() Time+
+UTC returns t with the location set to UTC. +
+ + + + + + +func (t Time) Unix() int64+
+Unix returns t as a Unix time, the number of seconds elapsed +since January 1, 1970 UTC. +
+ + + + + + +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. Note that this +means the result of calling UnixNano on the zero Time is undefined. +
+ + + + + + +func (t *Time) UnmarshalBinary(data []byte) error+
+UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. +
+ + + + + + +func (t *Time) UnmarshalJSON(data []byte) (err error)+
+UnmarshalJSON implements the json.Unmarshaler interface. +The time is expected to be a quoted string in RFC 3339 format. +
+ + + + + + +func (t *Time) UnmarshalText(data []byte) (err error)+
+UnmarshalText implements the encoding.TextUnmarshaler interface. +The time is expected to be in RFC 3339 format. +
+ + + + + + +func (t Time) Weekday() Weekday+
+Weekday returns the day of the week specified by t. +
+ + + + + + +func (t Time) Year() int+
+Year returns the year in which t occurs. +
+ + + + + + +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 (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. +
+ + + + + + + + +type Timer struct { + C <-chan Time + // contains filtered or unexported fields +}+
+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. +
+ + + + + + + + + + + + +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. +
+ + + + + +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 (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. +
+ + + + + + +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. +
+ + + + + + + + +type Weekday int+
+A Weekday specifies a day of the week (Sunday = 0, ...). +
+ + + +const ( + Sunday Weekday = iota + Monday + Tuesday + Wednesday + Thursday + Friday + Saturday +)+ + + + + + + + + + + + + +
func (d Weekday) String() string+
+String returns the English name of the day ("Sunday", "Monday", ...). +
+ + + + + + + + + + + + + + + + + + +▹ Example (Is)
+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. +)+ + +
const ( + UpperCase = iota + LowerCase + TitleCase + MaxCase +)+
+Indices into the Delta arrays inside CaseRanges for case mapping. +
+ + +const ( + UpperLower = MaxRune + 1 // (Cannot be a valid delta.) +)+
+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 Version = "8.0.0"
+ +Version is the Unicode edition from which the tables are derived. +
+ + + + +var ( + Cc = _Cc // Cc is the set of Unicode characters in category Cc. + Cf = _Cf // Cf is the set of Unicode characters in category Cf. + Co = _Co // Co is the set of Unicode characters in category Co. + Cs = _Cs // Cs is the set of Unicode characters in category Cs. + 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. + 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. + Lo = _Lo // Lo is the set of Unicode characters in category Lo. + Lower = _Ll // Lower is the set of Unicode lower case letters. + Ll = _Ll // Ll is the set of Unicode characters in category Ll. + 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. + Me = _Me // Me is the set of Unicode characters in category Me. + Mn = _Mn // Mn is the set of Unicode characters in category Mn. + Nl = _Nl // Nl is the set of Unicode characters in category Nl. + No = _No // No is the set of Unicode characters in category No. + 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. + Pd = _Pd // Pd is the set of Unicode characters in category Pd. + Pe = _Pe // Pe is the set of Unicode characters in category Pe. + Pf = _Pf // Pf is the set of Unicode characters in category Pf. + Pi = _Pi // Pi is the set of Unicode characters in category Pi. + Po = _Po // Po is the set of Unicode characters in category Po. + Ps = _Ps // Ps is the set of Unicode characters in category Ps. + 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. + Sk = _Sk // Sk is the set of Unicode characters in category Sk. + Sm = _Sm // Sm is the set of Unicode characters in category Sm. + So = _So // So is the set of Unicode characters in category So. + 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. + Upper = _Lu // Upper is the set of Unicode upper case letters. + Lu = _Lu // Lu is the set of Unicode characters in category Lu. + Zl = _Zl // Zl is the set of Unicode characters in category Zl. + Zp = _Zp // Zp is the set of Unicode characters in category Zp. + Zs = _Zs // Zs is the set of Unicode characters in category Zs. +)+
+These variables have type *RangeTable. +
+ + +var ( + 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. + 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. + 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. + 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. + 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. + 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. + 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. + 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. + 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. + 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. + 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. + 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. + New_Tai_Lue = _New_Tai_Lue // New_Tai_Lue is the set of Unicode characters in script New_Tai_Lue. + Nko = _Nko // Nko is the set of Unicode characters in script Nko. + 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_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. + Oriya = _Oriya // Oriya is the set of Unicode characters in script Oriya. + 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. + Sora_Sompeng = _Sora_Sompeng // Sora_Sompeng is the set of Unicode characters in script Sora_Sompeng. + 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. + 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. + Ugaritic = _Ugaritic // Ugaritic is the set of Unicode characters in script Ugaritic. + Vai = _Vai // Vai is the set of Unicode characters in script Vai. + Warang_Citi = _Warang_Citi // Warang_Citi is the set of Unicode characters in script Warang_Citi. + Yi = _Yi // Yi is the set of Unicode characters in script Yi. +)+
+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. + 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. + STerm = _STerm // STerm is the set of Unicode characters with property STerm. + 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. +)+
+These variables have type *RangeTable. +
+ + +var CaseRanges = _CaseRanges
+ +CaseRanges is the table describing case mappings for all letters with +non-self mappings. +
+ + +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, +}+
+Categories is the set of Unicode category tables. +
+ + +var FoldCategory = map[string]*RangeTable{ + "Common": foldCommon, + "Greek": foldGreek, + "Inherited": foldInherited, + "L": foldL, + "Ll": foldLl, + "Lt": foldLt, + "Lu": foldLu, + "M": foldM, + "Mn": foldMn, +}+
+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 FoldScript = map[string]*RangeTable{}+
+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 GraphicRanges = []*RangeTable{ + L, M, N, P, S, Zs, +}+
+GraphicRanges defines the set of graphic characters according to Unicode. +
+ + +var PrintRanges = []*RangeTable{ + L, M, N, P, S, +}+
+PrintRanges defines the set of printable characters according to Go. +ASCII space, U+0020, is handled separately. +
+ + +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, + "Quotation_Mark": Quotation_Mark, + "Radical": Radical, + "STerm": STerm, + "Soft_Dotted": Soft_Dotted, + "Terminal_Punctuation": Terminal_Punctuation, + "Unified_Ideograph": Unified_Ideograph, + "Variation_Selector": Variation_Selector, + "White_Space": White_Space, +}+
+Properties is the set of Unicode property tables. +
+ + +var Scripts = map[string]*RangeTable{ + "Ahom": Ahom, + "Anatolian_Hieroglyphs": Anatolian_Hieroglyphs, + "Arabic": Arabic, + "Armenian": Armenian, + "Avestan": Avestan, + "Balinese": Balinese, + "Bamum": Bamum, + "Bassa_Vah": Bassa_Vah, + "Batak": Batak, + "Bengali": Bengali, + "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, + "Common": Common, + "Coptic": Coptic, + "Cuneiform": Cuneiform, + "Cypriot": Cypriot, + "Cyrillic": Cyrillic, + "Deseret": Deseret, + "Devanagari": Devanagari, + "Duployan": Duployan, + "Egyptian_Hieroglyphs": Egyptian_Hieroglyphs, + "Elbasan": Elbasan, + "Ethiopic": Ethiopic, + "Georgian": Georgian, + "Glagolitic": Glagolitic, + "Gothic": Gothic, + "Grantha": Grantha, + "Greek": Greek, + "Gujarati": Gujarati, + "Gurmukhi": Gurmukhi, + "Han": Han, + "Hangul": Hangul, + "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, + "Kayah_Li": Kayah_Li, + "Kharoshthi": Kharoshthi, + "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, + "Malayalam": Malayalam, + "Mandaic": Mandaic, + "Manichaean": Manichaean, + "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, + "New_Tai_Lue": New_Tai_Lue, + "Nko": Nko, + "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_South_Arabian": Old_South_Arabian, + "Old_Turkic": Old_Turkic, + "Oriya": Oriya, + "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, + "Sora_Sompeng": Sora_Sompeng, + "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, + "Telugu": Telugu, + "Thaana": Thaana, + "Thai": Thai, + "Tibetan": Tibetan, + "Tifinagh": Tifinagh, + "Tirhuta": Tirhuta, + "Ugaritic": Ugaritic, + "Vai": Vai, + "Warang_Citi": Warang_Citi, + "Yi": Yi, +}+
+Scripts is the set of Unicode script tables. +
+ + + + + + +func In(r rune, ranges ...*RangeTable) bool+
+In reports whether the rune is a member of one of the ranges. +
+ + + + + + + +func Is(rangeTab *RangeTable, r rune) bool+
+Is reports whether the rune is in the specified table of ranges. +
+ + + + + + + +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(r rune) bool+
+IsDigit reports whether the rune is a decimal digit. +
+ + + + + + + +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(r rune) bool+
+IsLetter reports whether the rune is a letter (category L). +
+ + + + + + + +func IsLower(r rune) bool+
+IsLower reports whether the rune is a lower case letter. +
+ + + + + + + +func IsMark(r rune) bool+
+IsMark reports whether the rune is a mark character (category M). +
+ + + + + + + +func IsNumber(r rune) bool+
+IsNumber reports whether the rune is a number (category N). +
+ + + + + + + +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(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(r rune) bool+
+IsPunct reports whether the rune is a Unicode punctuation character +(category P). +
+ + + + + + + +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. +
+ + + + + + + +func IsSymbol(r rune) bool+
+IsSymbol reports whether the rune is a symbolic character. +
+ + + + + + + +func IsTitle(r rune) bool+
+IsTitle reports whether the rune is a title case letter. +
+ + + + + + + +func IsUpper(r rune) bool+
+IsUpper reports whether the rune is an upper case letter. +
+ + + + + + + +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. +
++For example: +
+SimpleFold('A') = 'a' +SimpleFold('a') = 'A' + +SimpleFold('K') = 'k' +SimpleFold('k') = '\u212A' (Kelvin symbol, K) +SimpleFold('\u212A') = 'K' + +SimpleFold('1') = '1' ++ +
▹ Example
+func To(_case int, r rune) rune+
+To maps the rune to the specified case: UpperCase, LowerCase, or TitleCase. +
+ +▹ Example
+func ToLower(r rune) rune+
+ToLower maps the rune to lower case. +
+ +▹ Example
+func ToTitle(r rune) rune+
+ToTitle maps the rune to title case. +
+ +▹ Example
+func ToUpper(r rune) rune+
+ToUpper maps the rune to upper case. +
+ +▹ Example
+type CaseRange struct { + Lo uint32 + Hi uint32 + Delta d +}+
+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 Range16 struct { + Lo uint16 + Hi uint16 + Stride uint16 +}+
+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 Range32 struct { + Lo uint32 + Hi uint32 + Stride uint32 +}+
+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 RangeTable struct { + R16 []Range16 + R32 []Range32 + LatinOffset int // number of entries in R16 with Hi <= MaxLatin1 +}+
+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 SpecialCase []CaseRange+
+SpecialCase represents language-specific case mappings such as Turkish. +Methods of SpecialCase customize (by overriding) the standard mappings. +
+ + + + + +var AzeriCase SpecialCase = _TurkishCase+ + +
var TurkishCase SpecialCase = _TurkishCase+ + + +
▹ Example
+func (special SpecialCase) ToLower(r rune) rune+
+ToLower maps the rune to lower case giving priority to the special mapping. +
+ + + + + + +func (special SpecialCase) ToTitle(r rune) rune+
+ToTitle maps the rune to title case giving priority to the special mapping. +
+ + + + + + +func (special SpecialCase) ToUpper(r rune) rune+
+ToUpper maps the rune to upper case giving priority to the special mapping. +
+ + + + + + + + + + +func Decode(s []uint16) []rune+
+Decode returns the Unicode code point sequence represented +by the UTF-16 encoding s. +
+ + + + + + + +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(s []rune) []uint16+
+Encode returns the UTF-16 encoding of the Unicode code point sequence s. +
+ + + + + + + +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(r rune) bool+
+IsSurrogate reports whether the specified Unicode code point +can appear in a surrogate pair. +
+ + + + + + + + + + + + + + + + + + +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. +)+
+Numbers fundamental to the encoding. +
+ + + + + + + +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
+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
+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
+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
+func EncodeRune(p []byte, r rune) int+
+EncodeRune writes into p (which must be large enough) the UTF-8 encoding of the rune. +It returns the number of bytes written. +
+ +▹ Example
+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
+func FullRuneInString(s string) bool+
+FullRuneInString is like FullRune but its input is a string. +
+ +▹ Example
+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
+func RuneCountInString(s string) (n int)+
+RuneCountInString is like RuneCount but its input is a string. +
+ +▹ Example
+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
+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
+func Valid(p []byte) bool+
+Valid reports whether p consists entirely of valid UTF-8-encoded runes. +
+ +▹ Example
+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
+func ValidString(s string) bool+
+ValidString reports whether s consists entirely of valid UTF-8-encoded runes. +
+ +▹ Example
+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(). +
+ + + + + + + +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. +
+ + + + + + + +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. +
+ + + + + + + + +type ArbitraryType int+
+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 Pointer *ArbitraryType+
+Pointer represents a pointer to an arbitrary type. There are four special operations +available for type Pointer that are not available for other types: +
+- A pointer value of any type can be converted to a Pointer. +- A Pointer can be converted to a pointer value of any type. +- A uintptr can be converted to a Pointer. +- A Pointer can be converted to a uintptr. ++
+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, +but 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) ++
+(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 = uintptr(n) ++
+In this usage hdr.Data is really an alternate way to refer to the underlying +pointer in the slice 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 = uintptr(n) +s := *(*string)(unsafe.Pointer(&hdr)) // p possibly already lost ++ + + + + + + + + + + + + + + + + + + + + + + + + + +