id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
149,600 | btcsuite/btcutil | block.go | TxLoc | func (b *Block) TxLoc() ([]wire.TxLoc, error) {
rawMsg, err := b.Bytes()
if err != nil {
return nil, err
}
rbuf := bytes.NewBuffer(rawMsg)
var mblock wire.MsgBlock
txLocs, err := mblock.DeserializeTxLoc(rbuf)
if err != nil {
return nil, err
}
return txLocs, err
} | go | func (b *Block) TxLoc() ([]wire.TxLoc, error) {
rawMsg, err := b.Bytes()
if err != nil {
return nil, err
}
rbuf := bytes.NewBuffer(rawMsg)
var mblock wire.MsgBlock
txLocs, err := mblock.DeserializeTxLoc(rbuf)
if err != nil {
return nil, err
}
return txLocs, err
} | [
"func",
"(",
"b",
"*",
"Block",
")",
"TxLoc",
"(",
")",
"(",
"[",
"]",
"wire",
".",
"TxLoc",
",",
"error",
")",
"{",
"rawMsg",
",",
"err",
":=",
"b",
".",
"Bytes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"rbuf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"rawMsg",
")",
"\n\n",
"var",
"mblock",
"wire",
".",
"MsgBlock",
"\n",
"txLocs",
",",
"err",
":=",
"mblock",
".",
"DeserializeTxLoc",
"(",
"rbuf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"txLocs",
",",
"err",
"\n",
"}"
]
| // TxLoc returns the offsets and lengths of each transaction in a raw block.
// It is used to allow fast indexing into transactions within the raw byte
// stream. | [
"TxLoc",
"returns",
"the",
"offsets",
"and",
"lengths",
"of",
"each",
"transaction",
"in",
"a",
"raw",
"block",
".",
"It",
"is",
"used",
"to",
"allow",
"fast",
"indexing",
"into",
"transactions",
"within",
"the",
"raw",
"byte",
"stream",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L193-L206 |
149,601 | btcsuite/btcutil | block.go | NewBlock | func NewBlock(msgBlock *wire.MsgBlock) *Block {
return &Block{
msgBlock: msgBlock,
blockHeight: BlockHeightUnknown,
}
} | go | func NewBlock(msgBlock *wire.MsgBlock) *Block {
return &Block{
msgBlock: msgBlock,
blockHeight: BlockHeightUnknown,
}
} | [
"func",
"NewBlock",
"(",
"msgBlock",
"*",
"wire",
".",
"MsgBlock",
")",
"*",
"Block",
"{",
"return",
"&",
"Block",
"{",
"msgBlock",
":",
"msgBlock",
",",
"blockHeight",
":",
"BlockHeightUnknown",
",",
"}",
"\n",
"}"
]
| // NewBlock returns a new instance of a bitcoin block given an underlying
// wire.MsgBlock. See Block. | [
"NewBlock",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"block",
"given",
"an",
"underlying",
"wire",
".",
"MsgBlock",
".",
"See",
"Block",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L221-L226 |
149,602 | btcsuite/btcutil | block.go | NewBlockFromBytes | func NewBlockFromBytes(serializedBlock []byte) (*Block, error) {
br := bytes.NewReader(serializedBlock)
b, err := NewBlockFromReader(br)
if err != nil {
return nil, err
}
b.serializedBlock = serializedBlock
return b, nil
} | go | func NewBlockFromBytes(serializedBlock []byte) (*Block, error) {
br := bytes.NewReader(serializedBlock)
b, err := NewBlockFromReader(br)
if err != nil {
return nil, err
}
b.serializedBlock = serializedBlock
return b, nil
} | [
"func",
"NewBlockFromBytes",
"(",
"serializedBlock",
"[",
"]",
"byte",
")",
"(",
"*",
"Block",
",",
"error",
")",
"{",
"br",
":=",
"bytes",
".",
"NewReader",
"(",
"serializedBlock",
")",
"\n",
"b",
",",
"err",
":=",
"NewBlockFromReader",
"(",
"br",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"b",
".",
"serializedBlock",
"=",
"serializedBlock",
"\n",
"return",
"b",
",",
"nil",
"\n",
"}"
]
| // NewBlockFromBytes returns a new instance of a bitcoin block given the
// serialized bytes. See Block. | [
"NewBlockFromBytes",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"block",
"given",
"the",
"serialized",
"bytes",
".",
"See",
"Block",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L230-L238 |
149,603 | btcsuite/btcutil | block.go | NewBlockFromReader | func NewBlockFromReader(r io.Reader) (*Block, error) {
// Deserialize the bytes into a MsgBlock.
var msgBlock wire.MsgBlock
err := msgBlock.Deserialize(r)
if err != nil {
return nil, err
}
b := Block{
msgBlock: &msgBlock,
blockHeight: BlockHeightUnknown,
}
return &b, nil
} | go | func NewBlockFromReader(r io.Reader) (*Block, error) {
// Deserialize the bytes into a MsgBlock.
var msgBlock wire.MsgBlock
err := msgBlock.Deserialize(r)
if err != nil {
return nil, err
}
b := Block{
msgBlock: &msgBlock,
blockHeight: BlockHeightUnknown,
}
return &b, nil
} | [
"func",
"NewBlockFromReader",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"Block",
",",
"error",
")",
"{",
"// Deserialize the bytes into a MsgBlock.",
"var",
"msgBlock",
"wire",
".",
"MsgBlock",
"\n",
"err",
":=",
"msgBlock",
".",
"Deserialize",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"b",
":=",
"Block",
"{",
"msgBlock",
":",
"&",
"msgBlock",
",",
"blockHeight",
":",
"BlockHeightUnknown",
",",
"}",
"\n",
"return",
"&",
"b",
",",
"nil",
"\n",
"}"
]
| // NewBlockFromReader returns a new instance of a bitcoin block given a
// Reader to deserialize the block. See Block. | [
"NewBlockFromReader",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"block",
"given",
"a",
"Reader",
"to",
"deserialize",
"the",
"block",
".",
"See",
"Block",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L242-L255 |
149,604 | btcsuite/btcutil | block.go | NewBlockFromBlockAndBytes | func NewBlockFromBlockAndBytes(msgBlock *wire.MsgBlock, serializedBlock []byte) *Block {
return &Block{
msgBlock: msgBlock,
serializedBlock: serializedBlock,
blockHeight: BlockHeightUnknown,
}
} | go | func NewBlockFromBlockAndBytes(msgBlock *wire.MsgBlock, serializedBlock []byte) *Block {
return &Block{
msgBlock: msgBlock,
serializedBlock: serializedBlock,
blockHeight: BlockHeightUnknown,
}
} | [
"func",
"NewBlockFromBlockAndBytes",
"(",
"msgBlock",
"*",
"wire",
".",
"MsgBlock",
",",
"serializedBlock",
"[",
"]",
"byte",
")",
"*",
"Block",
"{",
"return",
"&",
"Block",
"{",
"msgBlock",
":",
"msgBlock",
",",
"serializedBlock",
":",
"serializedBlock",
",",
"blockHeight",
":",
"BlockHeightUnknown",
",",
"}",
"\n",
"}"
]
| // NewBlockFromBlockAndBytes returns a new instance of a bitcoin block given
// an underlying wire.MsgBlock and the serialized bytes for it. See Block. | [
"NewBlockFromBlockAndBytes",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"block",
"given",
"an",
"underlying",
"wire",
".",
"MsgBlock",
"and",
"the",
"serialized",
"bytes",
"for",
"it",
".",
"See",
"Block",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L259-L265 |
149,605 | btcsuite/btcutil | base58/base58.go | Decode | func Decode(b string) []byte {
answer := big.NewInt(0)
j := big.NewInt(1)
scratch := new(big.Int)
for i := len(b) - 1; i >= 0; i-- {
tmp := b58[b[i]]
if tmp == 255 {
return []byte("")
}
scratch.SetInt64(int64(tmp))
scratch.Mul(j, scratch)
answer.Add(answer, scratch)
j.Mul(j, bigRadix)
}
tmpval := answer.Bytes()
var numZeros int
for numZeros = 0; numZeros < len(b); numZeros++ {
if b[numZeros] != alphabetIdx0 {
break
}
}
flen := numZeros + len(tmpval)
val := make([]byte, flen)
copy(val[numZeros:], tmpval)
return val
} | go | func Decode(b string) []byte {
answer := big.NewInt(0)
j := big.NewInt(1)
scratch := new(big.Int)
for i := len(b) - 1; i >= 0; i-- {
tmp := b58[b[i]]
if tmp == 255 {
return []byte("")
}
scratch.SetInt64(int64(tmp))
scratch.Mul(j, scratch)
answer.Add(answer, scratch)
j.Mul(j, bigRadix)
}
tmpval := answer.Bytes()
var numZeros int
for numZeros = 0; numZeros < len(b); numZeros++ {
if b[numZeros] != alphabetIdx0 {
break
}
}
flen := numZeros + len(tmpval)
val := make([]byte, flen)
copy(val[numZeros:], tmpval)
return val
} | [
"func",
"Decode",
"(",
"b",
"string",
")",
"[",
"]",
"byte",
"{",
"answer",
":=",
"big",
".",
"NewInt",
"(",
"0",
")",
"\n",
"j",
":=",
"big",
".",
"NewInt",
"(",
"1",
")",
"\n\n",
"scratch",
":=",
"new",
"(",
"big",
".",
"Int",
")",
"\n",
"for",
"i",
":=",
"len",
"(",
"b",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"tmp",
":=",
"b58",
"[",
"b",
"[",
"i",
"]",
"]",
"\n",
"if",
"tmp",
"==",
"255",
"{",
"return",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"scratch",
".",
"SetInt64",
"(",
"int64",
"(",
"tmp",
")",
")",
"\n",
"scratch",
".",
"Mul",
"(",
"j",
",",
"scratch",
")",
"\n",
"answer",
".",
"Add",
"(",
"answer",
",",
"scratch",
")",
"\n",
"j",
".",
"Mul",
"(",
"j",
",",
"bigRadix",
")",
"\n",
"}",
"\n\n",
"tmpval",
":=",
"answer",
".",
"Bytes",
"(",
")",
"\n\n",
"var",
"numZeros",
"int",
"\n",
"for",
"numZeros",
"=",
"0",
";",
"numZeros",
"<",
"len",
"(",
"b",
")",
";",
"numZeros",
"++",
"{",
"if",
"b",
"[",
"numZeros",
"]",
"!=",
"alphabetIdx0",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"flen",
":=",
"numZeros",
"+",
"len",
"(",
"tmpval",
")",
"\n",
"val",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"flen",
")",
"\n",
"copy",
"(",
"val",
"[",
"numZeros",
":",
"]",
",",
"tmpval",
")",
"\n\n",
"return",
"val",
"\n",
"}"
]
| // Decode decodes a modified base58 string to a byte slice. | [
"Decode",
"decodes",
"a",
"modified",
"base58",
"string",
"to",
"a",
"byte",
"slice",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/base58/base58.go#L17-L46 |
149,606 | btcsuite/btcutil | wif.go | NewWIF | func NewWIF(privKey *btcec.PrivateKey, net *chaincfg.Params, compress bool) (*WIF, error) {
if net == nil {
return nil, errors.New("no network")
}
return &WIF{privKey, compress, net.PrivateKeyID}, nil
} | go | func NewWIF(privKey *btcec.PrivateKey, net *chaincfg.Params, compress bool) (*WIF, error) {
if net == nil {
return nil, errors.New("no network")
}
return &WIF{privKey, compress, net.PrivateKeyID}, nil
} | [
"func",
"NewWIF",
"(",
"privKey",
"*",
"btcec",
".",
"PrivateKey",
",",
"net",
"*",
"chaincfg",
".",
"Params",
",",
"compress",
"bool",
")",
"(",
"*",
"WIF",
",",
"error",
")",
"{",
"if",
"net",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"WIF",
"{",
"privKey",
",",
"compress",
",",
"net",
".",
"PrivateKeyID",
"}",
",",
"nil",
"\n",
"}"
]
| // NewWIF creates a new WIF structure to export an address and its private key
// as a string encoded in the Wallet Import Format. The compress argument
// specifies whether the address intended to be imported or exported was created
// by serializing the public key compressed rather than uncompressed. | [
"NewWIF",
"creates",
"a",
"new",
"WIF",
"structure",
"to",
"export",
"an",
"address",
"and",
"its",
"private",
"key",
"as",
"a",
"string",
"encoded",
"in",
"the",
"Wallet",
"Import",
"Format",
".",
"The",
"compress",
"argument",
"specifies",
"whether",
"the",
"address",
"intended",
"to",
"be",
"imported",
"or",
"exported",
"was",
"created",
"by",
"serializing",
"the",
"public",
"key",
"compressed",
"rather",
"than",
"uncompressed",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/wif.go#L52-L57 |
149,607 | btcsuite/btcutil | wif.go | IsForNet | func (w *WIF) IsForNet(net *chaincfg.Params) bool {
return w.netID == net.PrivateKeyID
} | go | func (w *WIF) IsForNet(net *chaincfg.Params) bool {
return w.netID == net.PrivateKeyID
} | [
"func",
"(",
"w",
"*",
"WIF",
")",
"IsForNet",
"(",
"net",
"*",
"chaincfg",
".",
"Params",
")",
"bool",
"{",
"return",
"w",
".",
"netID",
"==",
"net",
".",
"PrivateKeyID",
"\n",
"}"
]
| // IsForNet returns whether or not the decoded WIF structure is associated
// with the passed bitcoin network. | [
"IsForNet",
"returns",
"whether",
"or",
"not",
"the",
"decoded",
"WIF",
"structure",
"is",
"associated",
"with",
"the",
"passed",
"bitcoin",
"network",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/wif.go#L61-L63 |
149,608 | btcsuite/btcutil | wif.go | SerializePubKey | func (w *WIF) SerializePubKey() []byte {
pk := (*btcec.PublicKey)(&w.PrivKey.PublicKey)
if w.CompressPubKey {
return pk.SerializeCompressed()
}
return pk.SerializeUncompressed()
} | go | func (w *WIF) SerializePubKey() []byte {
pk := (*btcec.PublicKey)(&w.PrivKey.PublicKey)
if w.CompressPubKey {
return pk.SerializeCompressed()
}
return pk.SerializeUncompressed()
} | [
"func",
"(",
"w",
"*",
"WIF",
")",
"SerializePubKey",
"(",
")",
"[",
"]",
"byte",
"{",
"pk",
":=",
"(",
"*",
"btcec",
".",
"PublicKey",
")",
"(",
"&",
"w",
".",
"PrivKey",
".",
"PublicKey",
")",
"\n",
"if",
"w",
".",
"CompressPubKey",
"{",
"return",
"pk",
".",
"SerializeCompressed",
"(",
")",
"\n",
"}",
"\n",
"return",
"pk",
".",
"SerializeUncompressed",
"(",
")",
"\n",
"}"
]
| // SerializePubKey serializes the associated public key of the imported or
// exported private key in either a compressed or uncompressed format. The
// serialization format chosen depends on the value of w.CompressPubKey. | [
"SerializePubKey",
"serializes",
"the",
"associated",
"public",
"key",
"of",
"the",
"imported",
"or",
"exported",
"private",
"key",
"in",
"either",
"a",
"compressed",
"or",
"uncompressed",
"format",
".",
"The",
"serialization",
"format",
"chosen",
"depends",
"on",
"the",
"value",
"of",
"w",
".",
"CompressPubKey",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/wif.go#L153-L159 |
149,609 | btcsuite/btcutil | bech32/bech32.go | Decode | func Decode(bech string) (string, []byte, error) {
// The maximum allowed length for a bech32 string is 90. It must also
// be at least 8 characters, since it needs a non-empty HRP, a
// separator, and a 6 character checksum.
if len(bech) < 8 || len(bech) > 90 {
return "", nil, fmt.Errorf("invalid bech32 string length %d",
len(bech))
}
// Only ASCII characters between 33 and 126 are allowed.
for i := 0; i < len(bech); i++ {
if bech[i] < 33 || bech[i] > 126 {
return "", nil, fmt.Errorf("invalid character in "+
"string: '%c'", bech[i])
}
}
// The characters must be either all lowercase or all uppercase.
lower := strings.ToLower(bech)
upper := strings.ToUpper(bech)
if bech != lower && bech != upper {
return "", nil, fmt.Errorf("string not all lowercase or all " +
"uppercase")
}
// We'll work with the lowercase string from now on.
bech = lower
// The string is invalid if the last '1' is non-existent, it is the
// first character of the string (no human-readable part) or one of the
// last 6 characters of the string (since checksum cannot contain '1'),
// or if the string is more than 90 characters in total.
one := strings.LastIndexByte(bech, '1')
if one < 1 || one+7 > len(bech) {
return "", nil, fmt.Errorf("invalid index of 1")
}
// The human-readable part is everything before the last '1'.
hrp := bech[:one]
data := bech[one+1:]
// Each character corresponds to the byte with value of the index in
// 'charset'.
decoded, err := toBytes(data)
if err != nil {
return "", nil, fmt.Errorf("failed converting data to bytes: "+
"%v", err)
}
if !bech32VerifyChecksum(hrp, decoded) {
moreInfo := ""
checksum := bech[len(bech)-6:]
expected, err := toChars(bech32Checksum(hrp,
decoded[:len(decoded)-6]))
if err == nil {
moreInfo = fmt.Sprintf("Expected %v, got %v.",
expected, checksum)
}
return "", nil, fmt.Errorf("checksum failed. " + moreInfo)
}
// We exclude the last 6 bytes, which is the checksum.
return hrp, decoded[:len(decoded)-6], nil
} | go | func Decode(bech string) (string, []byte, error) {
// The maximum allowed length for a bech32 string is 90. It must also
// be at least 8 characters, since it needs a non-empty HRP, a
// separator, and a 6 character checksum.
if len(bech) < 8 || len(bech) > 90 {
return "", nil, fmt.Errorf("invalid bech32 string length %d",
len(bech))
}
// Only ASCII characters between 33 and 126 are allowed.
for i := 0; i < len(bech); i++ {
if bech[i] < 33 || bech[i] > 126 {
return "", nil, fmt.Errorf("invalid character in "+
"string: '%c'", bech[i])
}
}
// The characters must be either all lowercase or all uppercase.
lower := strings.ToLower(bech)
upper := strings.ToUpper(bech)
if bech != lower && bech != upper {
return "", nil, fmt.Errorf("string not all lowercase or all " +
"uppercase")
}
// We'll work with the lowercase string from now on.
bech = lower
// The string is invalid if the last '1' is non-existent, it is the
// first character of the string (no human-readable part) or one of the
// last 6 characters of the string (since checksum cannot contain '1'),
// or if the string is more than 90 characters in total.
one := strings.LastIndexByte(bech, '1')
if one < 1 || one+7 > len(bech) {
return "", nil, fmt.Errorf("invalid index of 1")
}
// The human-readable part is everything before the last '1'.
hrp := bech[:one]
data := bech[one+1:]
// Each character corresponds to the byte with value of the index in
// 'charset'.
decoded, err := toBytes(data)
if err != nil {
return "", nil, fmt.Errorf("failed converting data to bytes: "+
"%v", err)
}
if !bech32VerifyChecksum(hrp, decoded) {
moreInfo := ""
checksum := bech[len(bech)-6:]
expected, err := toChars(bech32Checksum(hrp,
decoded[:len(decoded)-6]))
if err == nil {
moreInfo = fmt.Sprintf("Expected %v, got %v.",
expected, checksum)
}
return "", nil, fmt.Errorf("checksum failed. " + moreInfo)
}
// We exclude the last 6 bytes, which is the checksum.
return hrp, decoded[:len(decoded)-6], nil
} | [
"func",
"Decode",
"(",
"bech",
"string",
")",
"(",
"string",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// The maximum allowed length for a bech32 string is 90. It must also",
"// be at least 8 characters, since it needs a non-empty HRP, a",
"// separator, and a 6 character checksum.",
"if",
"len",
"(",
"bech",
")",
"<",
"8",
"||",
"len",
"(",
"bech",
")",
">",
"90",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"bech",
")",
")",
"\n",
"}",
"\n",
"// Only\tASCII characters between 33 and 126 are allowed.",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"bech",
")",
";",
"i",
"++",
"{",
"if",
"bech",
"[",
"i",
"]",
"<",
"33",
"||",
"bech",
"[",
"i",
"]",
">",
"126",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"bech",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// The characters must be either all lowercase or all uppercase.",
"lower",
":=",
"strings",
".",
"ToLower",
"(",
"bech",
")",
"\n",
"upper",
":=",
"strings",
".",
"ToUpper",
"(",
"bech",
")",
"\n",
"if",
"bech",
"!=",
"lower",
"&&",
"bech",
"!=",
"upper",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// We'll work with the lowercase string from now on.",
"bech",
"=",
"lower",
"\n\n",
"// The string is invalid if the last '1' is non-existent, it is the",
"// first character of the string (no human-readable part) or one of the",
"// last 6 characters of the string (since checksum cannot contain '1'),",
"// or if the string is more than 90 characters in total.",
"one",
":=",
"strings",
".",
"LastIndexByte",
"(",
"bech",
",",
"'1'",
")",
"\n",
"if",
"one",
"<",
"1",
"||",
"one",
"+",
"7",
">",
"len",
"(",
"bech",
")",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// The human-readable part is everything before the last '1'.",
"hrp",
":=",
"bech",
"[",
":",
"one",
"]",
"\n",
"data",
":=",
"bech",
"[",
"one",
"+",
"1",
":",
"]",
"\n\n",
"// Each character corresponds to the byte with value of the index in",
"// 'charset'.",
"decoded",
",",
"err",
":=",
"toBytes",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"bech32VerifyChecksum",
"(",
"hrp",
",",
"decoded",
")",
"{",
"moreInfo",
":=",
"\"",
"\"",
"\n",
"checksum",
":=",
"bech",
"[",
"len",
"(",
"bech",
")",
"-",
"6",
":",
"]",
"\n",
"expected",
",",
"err",
":=",
"toChars",
"(",
"bech32Checksum",
"(",
"hrp",
",",
"decoded",
"[",
":",
"len",
"(",
"decoded",
")",
"-",
"6",
"]",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"moreInfo",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"expected",
",",
"checksum",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"moreInfo",
")",
"\n",
"}",
"\n\n",
"// We exclude the last 6 bytes, which is the checksum.",
"return",
"hrp",
",",
"decoded",
"[",
":",
"len",
"(",
"decoded",
")",
"-",
"6",
"]",
",",
"nil",
"\n",
"}"
]
| // Decode decodes a bech32 encoded string, returning the human-readable
// part and the data part excluding the checksum. | [
"Decode",
"decodes",
"a",
"bech32",
"encoded",
"string",
"returning",
"the",
"human",
"-",
"readable",
"part",
"and",
"the",
"data",
"part",
"excluding",
"the",
"checksum",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bech32/bech32.go#L18-L80 |
149,610 | btcsuite/btcutil | bech32/bech32.go | ConvertBits | func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error) {
if fromBits < 1 || fromBits > 8 || toBits < 1 || toBits > 8 {
return nil, fmt.Errorf("only bit groups between 1 and 8 allowed")
}
// The final bytes, each byte encoding toBits bits.
var regrouped []byte
// Keep track of the next byte we create and how many bits we have
// added to it out of the toBits goal.
nextByte := byte(0)
filledBits := uint8(0)
for _, b := range data {
// Discard unused bits.
b = b << (8 - fromBits)
// How many bits remaining to extract from the input data.
remFromBits := fromBits
for remFromBits > 0 {
// How many bits remaining to be added to the next byte.
remToBits := toBits - filledBits
// The number of bytes to next extract is the minimum of
// remFromBits and remToBits.
toExtract := remFromBits
if remToBits < toExtract {
toExtract = remToBits
}
// Add the next bits to nextByte, shifting the already
// added bits to the left.
nextByte = (nextByte << toExtract) | (b >> (8 - toExtract))
// Discard the bits we just extracted and get ready for
// next iteration.
b = b << toExtract
remFromBits -= toExtract
filledBits += toExtract
// If the nextByte is completely filled, we add it to
// our regrouped bytes and start on the next byte.
if filledBits == toBits {
regrouped = append(regrouped, nextByte)
filledBits = 0
nextByte = 0
}
}
}
// We pad any unfinished group if specified.
if pad && filledBits > 0 {
nextByte = nextByte << (toBits - filledBits)
regrouped = append(regrouped, nextByte)
filledBits = 0
nextByte = 0
}
// Any incomplete group must be <= 4 bits, and all zeroes.
if filledBits > 0 && (filledBits > 4 || nextByte != 0) {
return nil, fmt.Errorf("invalid incomplete group")
}
return regrouped, nil
} | go | func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error) {
if fromBits < 1 || fromBits > 8 || toBits < 1 || toBits > 8 {
return nil, fmt.Errorf("only bit groups between 1 and 8 allowed")
}
// The final bytes, each byte encoding toBits bits.
var regrouped []byte
// Keep track of the next byte we create and how many bits we have
// added to it out of the toBits goal.
nextByte := byte(0)
filledBits := uint8(0)
for _, b := range data {
// Discard unused bits.
b = b << (8 - fromBits)
// How many bits remaining to extract from the input data.
remFromBits := fromBits
for remFromBits > 0 {
// How many bits remaining to be added to the next byte.
remToBits := toBits - filledBits
// The number of bytes to next extract is the minimum of
// remFromBits and remToBits.
toExtract := remFromBits
if remToBits < toExtract {
toExtract = remToBits
}
// Add the next bits to nextByte, shifting the already
// added bits to the left.
nextByte = (nextByte << toExtract) | (b >> (8 - toExtract))
// Discard the bits we just extracted and get ready for
// next iteration.
b = b << toExtract
remFromBits -= toExtract
filledBits += toExtract
// If the nextByte is completely filled, we add it to
// our regrouped bytes and start on the next byte.
if filledBits == toBits {
regrouped = append(regrouped, nextByte)
filledBits = 0
nextByte = 0
}
}
}
// We pad any unfinished group if specified.
if pad && filledBits > 0 {
nextByte = nextByte << (toBits - filledBits)
regrouped = append(regrouped, nextByte)
filledBits = 0
nextByte = 0
}
// Any incomplete group must be <= 4 bits, and all zeroes.
if filledBits > 0 && (filledBits > 4 || nextByte != 0) {
return nil, fmt.Errorf("invalid incomplete group")
}
return regrouped, nil
} | [
"func",
"ConvertBits",
"(",
"data",
"[",
"]",
"byte",
",",
"fromBits",
",",
"toBits",
"uint8",
",",
"pad",
"bool",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"fromBits",
"<",
"1",
"||",
"fromBits",
">",
"8",
"||",
"toBits",
"<",
"1",
"||",
"toBits",
">",
"8",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// The final bytes, each byte encoding toBits bits.",
"var",
"regrouped",
"[",
"]",
"byte",
"\n\n",
"// Keep track of the next byte we create and how many bits we have",
"// added to it out of the toBits goal.",
"nextByte",
":=",
"byte",
"(",
"0",
")",
"\n",
"filledBits",
":=",
"uint8",
"(",
"0",
")",
"\n\n",
"for",
"_",
",",
"b",
":=",
"range",
"data",
"{",
"// Discard unused bits.",
"b",
"=",
"b",
"<<",
"(",
"8",
"-",
"fromBits",
")",
"\n\n",
"// How many bits remaining to extract from the input data.",
"remFromBits",
":=",
"fromBits",
"\n",
"for",
"remFromBits",
">",
"0",
"{",
"// How many bits remaining to be added to the next byte.",
"remToBits",
":=",
"toBits",
"-",
"filledBits",
"\n\n",
"// The number of bytes to next extract is the minimum of",
"// remFromBits and remToBits.",
"toExtract",
":=",
"remFromBits",
"\n",
"if",
"remToBits",
"<",
"toExtract",
"{",
"toExtract",
"=",
"remToBits",
"\n",
"}",
"\n\n",
"// Add the next bits to nextByte, shifting the already",
"// added bits to the left.",
"nextByte",
"=",
"(",
"nextByte",
"<<",
"toExtract",
")",
"|",
"(",
"b",
">>",
"(",
"8",
"-",
"toExtract",
")",
")",
"\n\n",
"// Discard the bits we just extracted and get ready for",
"// next iteration.",
"b",
"=",
"b",
"<<",
"toExtract",
"\n",
"remFromBits",
"-=",
"toExtract",
"\n",
"filledBits",
"+=",
"toExtract",
"\n\n",
"// If the nextByte is completely filled, we add it to",
"// our regrouped bytes and start on the next byte.",
"if",
"filledBits",
"==",
"toBits",
"{",
"regrouped",
"=",
"append",
"(",
"regrouped",
",",
"nextByte",
")",
"\n",
"filledBits",
"=",
"0",
"\n",
"nextByte",
"=",
"0",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// We pad any unfinished group if specified.",
"if",
"pad",
"&&",
"filledBits",
">",
"0",
"{",
"nextByte",
"=",
"nextByte",
"<<",
"(",
"toBits",
"-",
"filledBits",
")",
"\n",
"regrouped",
"=",
"append",
"(",
"regrouped",
",",
"nextByte",
")",
"\n",
"filledBits",
"=",
"0",
"\n",
"nextByte",
"=",
"0",
"\n",
"}",
"\n\n",
"// Any incomplete group must be <= 4 bits, and all zeroes.",
"if",
"filledBits",
">",
"0",
"&&",
"(",
"filledBits",
">",
"4",
"||",
"nextByte",
"!=",
"0",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"regrouped",
",",
"nil",
"\n",
"}"
]
| // ConvertBits converts a byte slice where each byte is encoding fromBits bits,
// to a byte slice where each byte is encoding toBits bits. | [
"ConvertBits",
"converts",
"a",
"byte",
"slice",
"where",
"each",
"byte",
"is",
"encoding",
"fromBits",
"bits",
"to",
"a",
"byte",
"slice",
"where",
"each",
"byte",
"is",
"encoding",
"toBits",
"bits",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bech32/bech32.go#L131-L196 |
149,611 | btcsuite/btcutil | tx.go | Hash | func (t *Tx) Hash() *chainhash.Hash {
// Return the cached hash if it has already been generated.
if t.txHash != nil {
return t.txHash
}
// Cache the hash and return it.
hash := t.msgTx.TxHash()
t.txHash = &hash
return &hash
} | go | func (t *Tx) Hash() *chainhash.Hash {
// Return the cached hash if it has already been generated.
if t.txHash != nil {
return t.txHash
}
// Cache the hash and return it.
hash := t.msgTx.TxHash()
t.txHash = &hash
return &hash
} | [
"func",
"(",
"t",
"*",
"Tx",
")",
"Hash",
"(",
")",
"*",
"chainhash",
".",
"Hash",
"{",
"// Return the cached hash if it has already been generated.",
"if",
"t",
".",
"txHash",
"!=",
"nil",
"{",
"return",
"t",
".",
"txHash",
"\n",
"}",
"\n\n",
"// Cache the hash and return it.",
"hash",
":=",
"t",
".",
"msgTx",
".",
"TxHash",
"(",
")",
"\n",
"t",
".",
"txHash",
"=",
"&",
"hash",
"\n",
"return",
"&",
"hash",
"\n",
"}"
]
| // Hash returns the hash of the transaction. This is equivalent to
// calling TxHash on the underlying wire.MsgTx, however it caches the
// result so subsequent calls are more efficient. | [
"Hash",
"returns",
"the",
"hash",
"of",
"the",
"transaction",
".",
"This",
"is",
"equivalent",
"to",
"calling",
"TxHash",
"on",
"the",
"underlying",
"wire",
".",
"MsgTx",
"however",
"it",
"caches",
"the",
"result",
"so",
"subsequent",
"calls",
"are",
"more",
"efficient",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/tx.go#L41-L51 |
149,612 | btcsuite/btcutil | tx.go | HasWitness | func (t *Tx) HasWitness() bool {
if t.txHashWitness != nil {
return *t.txHasWitness
}
hasWitness := t.msgTx.HasWitness()
t.txHasWitness = &hasWitness
return hasWitness
} | go | func (t *Tx) HasWitness() bool {
if t.txHashWitness != nil {
return *t.txHasWitness
}
hasWitness := t.msgTx.HasWitness()
t.txHasWitness = &hasWitness
return hasWitness
} | [
"func",
"(",
"t",
"*",
"Tx",
")",
"HasWitness",
"(",
")",
"bool",
"{",
"if",
"t",
".",
"txHashWitness",
"!=",
"nil",
"{",
"return",
"*",
"t",
".",
"txHasWitness",
"\n",
"}",
"\n\n",
"hasWitness",
":=",
"t",
".",
"msgTx",
".",
"HasWitness",
"(",
")",
"\n",
"t",
".",
"txHasWitness",
"=",
"&",
"hasWitness",
"\n",
"return",
"hasWitness",
"\n",
"}"
]
| // HasWitness returns false if none of the inputs within the transaction
// contain witness data, true false otherwise. This equivalent to calling
// HasWitness on the underlying wire.MsgTx, however it caches the result so
// subsequent calls are more efficient. | [
"HasWitness",
"returns",
"false",
"if",
"none",
"of",
"the",
"inputs",
"within",
"the",
"transaction",
"contain",
"witness",
"data",
"true",
"false",
"otherwise",
".",
"This",
"equivalent",
"to",
"calling",
"HasWitness",
"on",
"the",
"underlying",
"wire",
".",
"MsgTx",
"however",
"it",
"caches",
"the",
"result",
"so",
"subsequent",
"calls",
"are",
"more",
"efficient",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/tx.go#L72-L80 |
149,613 | btcsuite/btcutil | tx.go | NewTx | func NewTx(msgTx *wire.MsgTx) *Tx {
return &Tx{
msgTx: msgTx,
txIndex: TxIndexUnknown,
}
} | go | func NewTx(msgTx *wire.MsgTx) *Tx {
return &Tx{
msgTx: msgTx,
txIndex: TxIndexUnknown,
}
} | [
"func",
"NewTx",
"(",
"msgTx",
"*",
"wire",
".",
"MsgTx",
")",
"*",
"Tx",
"{",
"return",
"&",
"Tx",
"{",
"msgTx",
":",
"msgTx",
",",
"txIndex",
":",
"TxIndexUnknown",
",",
"}",
"\n",
"}"
]
| // NewTx returns a new instance of a bitcoin transaction given an underlying
// wire.MsgTx. See Tx. | [
"NewTx",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"transaction",
"given",
"an",
"underlying",
"wire",
".",
"MsgTx",
".",
"See",
"Tx",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/tx.go#L95-L100 |
149,614 | btcsuite/btcutil | tx.go | NewTxFromBytes | func NewTxFromBytes(serializedTx []byte) (*Tx, error) {
br := bytes.NewReader(serializedTx)
return NewTxFromReader(br)
} | go | func NewTxFromBytes(serializedTx []byte) (*Tx, error) {
br := bytes.NewReader(serializedTx)
return NewTxFromReader(br)
} | [
"func",
"NewTxFromBytes",
"(",
"serializedTx",
"[",
"]",
"byte",
")",
"(",
"*",
"Tx",
",",
"error",
")",
"{",
"br",
":=",
"bytes",
".",
"NewReader",
"(",
"serializedTx",
")",
"\n",
"return",
"NewTxFromReader",
"(",
"br",
")",
"\n",
"}"
]
| // NewTxFromBytes returns a new instance of a bitcoin transaction given the
// serialized bytes. See Tx. | [
"NewTxFromBytes",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"transaction",
"given",
"the",
"serialized",
"bytes",
".",
"See",
"Tx",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/tx.go#L104-L107 |
149,615 | btcsuite/btcutil | tx.go | NewTxFromReader | func NewTxFromReader(r io.Reader) (*Tx, error) {
// Deserialize the bytes into a MsgTx.
var msgTx wire.MsgTx
err := msgTx.Deserialize(r)
if err != nil {
return nil, err
}
t := Tx{
msgTx: &msgTx,
txIndex: TxIndexUnknown,
}
return &t, nil
} | go | func NewTxFromReader(r io.Reader) (*Tx, error) {
// Deserialize the bytes into a MsgTx.
var msgTx wire.MsgTx
err := msgTx.Deserialize(r)
if err != nil {
return nil, err
}
t := Tx{
msgTx: &msgTx,
txIndex: TxIndexUnknown,
}
return &t, nil
} | [
"func",
"NewTxFromReader",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"Tx",
",",
"error",
")",
"{",
"// Deserialize the bytes into a MsgTx.",
"var",
"msgTx",
"wire",
".",
"MsgTx",
"\n",
"err",
":=",
"msgTx",
".",
"Deserialize",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"t",
":=",
"Tx",
"{",
"msgTx",
":",
"&",
"msgTx",
",",
"txIndex",
":",
"TxIndexUnknown",
",",
"}",
"\n",
"return",
"&",
"t",
",",
"nil",
"\n",
"}"
]
| // NewTxFromReader returns a new instance of a bitcoin transaction given a
// Reader to deserialize the transaction. See Tx. | [
"NewTxFromReader",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"transaction",
"given",
"a",
"Reader",
"to",
"deserialize",
"the",
"transaction",
".",
"See",
"Tx",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/tx.go#L111-L124 |
149,616 | btcsuite/btcutil | txsort/txsort.go | Sort | func Sort(tx *wire.MsgTx) *wire.MsgTx {
txCopy := tx.Copy()
sort.Sort(sortableInputSlice(txCopy.TxIn))
sort.Sort(sortableOutputSlice(txCopy.TxOut))
return txCopy
} | go | func Sort(tx *wire.MsgTx) *wire.MsgTx {
txCopy := tx.Copy()
sort.Sort(sortableInputSlice(txCopy.TxIn))
sort.Sort(sortableOutputSlice(txCopy.TxOut))
return txCopy
} | [
"func",
"Sort",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
")",
"*",
"wire",
".",
"MsgTx",
"{",
"txCopy",
":=",
"tx",
".",
"Copy",
"(",
")",
"\n",
"sort",
".",
"Sort",
"(",
"sortableInputSlice",
"(",
"txCopy",
".",
"TxIn",
")",
")",
"\n",
"sort",
".",
"Sort",
"(",
"sortableOutputSlice",
"(",
"txCopy",
".",
"TxOut",
")",
")",
"\n",
"return",
"txCopy",
"\n",
"}"
]
| // Sort returns a new transaction with the inputs and outputs sorted based on
// BIP 69. The passed transaction is not modified and the new transaction
// might have a different hash if any sorting was done. | [
"Sort",
"returns",
"a",
"new",
"transaction",
"with",
"the",
"inputs",
"and",
"outputs",
"sorted",
"based",
"on",
"BIP",
"69",
".",
"The",
"passed",
"transaction",
"is",
"not",
"modified",
"and",
"the",
"new",
"transaction",
"might",
"have",
"a",
"different",
"hash",
"if",
"any",
"sorting",
"was",
"done",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/txsort/txsort.go#L38-L43 |
149,617 | btcsuite/btcutil | txsort/txsort.go | IsSorted | func IsSorted(tx *wire.MsgTx) bool {
if !sort.IsSorted(sortableInputSlice(tx.TxIn)) {
return false
}
if !sort.IsSorted(sortableOutputSlice(tx.TxOut)) {
return false
}
return true
} | go | func IsSorted(tx *wire.MsgTx) bool {
if !sort.IsSorted(sortableInputSlice(tx.TxIn)) {
return false
}
if !sort.IsSorted(sortableOutputSlice(tx.TxOut)) {
return false
}
return true
} | [
"func",
"IsSorted",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
")",
"bool",
"{",
"if",
"!",
"sort",
".",
"IsSorted",
"(",
"sortableInputSlice",
"(",
"tx",
".",
"TxIn",
")",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"sort",
".",
"IsSorted",
"(",
"sortableOutputSlice",
"(",
"tx",
".",
"TxOut",
")",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
]
| // IsSorted checks whether tx has inputs and outputs sorted according to BIP
// 69. | [
"IsSorted",
"checks",
"whether",
"tx",
"has",
"inputs",
"and",
"outputs",
"sorted",
"according",
"to",
"BIP",
"69",
"."
]
| 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/txsort/txsort.go#L47-L55 |
149,618 | logpacker/PayPal-Go-SDK | types.go | MarshalJSON | func (t JSONTime) MarshalJSON() ([]byte, error) {
stamp := fmt.Sprintf(`"%s"`, time.Time(t).UTC().Format(time.RFC3339))
return []byte(stamp), nil
} | go | func (t JSONTime) MarshalJSON() ([]byte, error) {
stamp := fmt.Sprintf(`"%s"`, time.Time(t).UTC().Format(time.RFC3339))
return []byte(stamp), nil
} | [
"func",
"(",
"t",
"JSONTime",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"stamp",
":=",
"fmt",
".",
"Sprintf",
"(",
"`\"%s\"`",
",",
"time",
".",
"Time",
"(",
"t",
")",
".",
"UTC",
"(",
")",
".",
"Format",
"(",
"time",
".",
"RFC3339",
")",
")",
"\n",
"return",
"[",
"]",
"byte",
"(",
"stamp",
")",
",",
"nil",
"\n",
"}"
]
| // MarshalJSON for JSONTime | [
"MarshalJSON",
"for",
"JSONTime"
]
| 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/types.go#L607-L610 |
149,619 | logpacker/PayPal-Go-SDK | client.go | NewClient | func NewClient(clientID string, secret string, APIBase string) (*Client, error) {
if clientID == "" || secret == "" || APIBase == "" {
return nil, errors.New("ClientID, Secret and APIBase are required to create a Client")
}
return &Client{
Client: &http.Client{},
ClientID: clientID,
Secret: secret,
APIBase: APIBase,
}, nil
} | go | func NewClient(clientID string, secret string, APIBase string) (*Client, error) {
if clientID == "" || secret == "" || APIBase == "" {
return nil, errors.New("ClientID, Secret and APIBase are required to create a Client")
}
return &Client{
Client: &http.Client{},
ClientID: clientID,
Secret: secret,
APIBase: APIBase,
}, nil
} | [
"func",
"NewClient",
"(",
"clientID",
"string",
",",
"secret",
"string",
",",
"APIBase",
"string",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"if",
"clientID",
"==",
"\"",
"\"",
"||",
"secret",
"==",
"\"",
"\"",
"||",
"APIBase",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"Client",
"{",
"Client",
":",
"&",
"http",
".",
"Client",
"{",
"}",
",",
"ClientID",
":",
"clientID",
",",
"Secret",
":",
"secret",
",",
"APIBase",
":",
"APIBase",
",",
"}",
",",
"nil",
"\n",
"}"
]
| // NewClient returns new Client struct
// APIBase is a base API URL, for testing you can use paypalsdk.APIBaseSandBox | [
"NewClient",
"returns",
"new",
"Client",
"struct",
"APIBase",
"is",
"a",
"base",
"API",
"URL",
"for",
"testing",
"you",
"can",
"use",
"paypalsdk",
".",
"APIBaseSandBox"
]
| 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/client.go#L17-L28 |
149,620 | logpacker/PayPal-Go-SDK | client.go | SetAccessToken | func (c *Client) SetAccessToken(token string) {
c.Token = &TokenResponse{
Token: token,
}
c.tokenExpiresAt = time.Time{}
} | go | func (c *Client) SetAccessToken(token string) {
c.Token = &TokenResponse{
Token: token,
}
c.tokenExpiresAt = time.Time{}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SetAccessToken",
"(",
"token",
"string",
")",
"{",
"c",
".",
"Token",
"=",
"&",
"TokenResponse",
"{",
"Token",
":",
"token",
",",
"}",
"\n",
"c",
".",
"tokenExpiresAt",
"=",
"time",
".",
"Time",
"{",
"}",
"\n",
"}"
]
| // SetAccessToken sets saved token to current client | [
"SetAccessToken",
"sets",
"saved",
"token",
"to",
"current",
"client"
]
| 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/client.go#L60-L65 |
149,621 | logpacker/PayPal-Go-SDK | client.go | Send | func (c *Client) Send(req *http.Request, v interface{}) error {
var (
err error
resp *http.Response
data []byte
)
// Set default headers
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Language", "en_US")
// Default values for headers
if req.Header.Get("Content-type") == "" {
req.Header.Set("Content-type", "application/json")
}
resp, err = c.Client.Do(req)
c.log(req, resp)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
errResp := &ErrorResponse{Response: resp}
data, err = ioutil.ReadAll(resp.Body)
if err == nil && len(data) > 0 {
json.Unmarshal(data, errResp)
}
return errResp
}
if v == nil {
return nil
}
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
return nil
}
return json.NewDecoder(resp.Body).Decode(v)
} | go | func (c *Client) Send(req *http.Request, v interface{}) error {
var (
err error
resp *http.Response
data []byte
)
// Set default headers
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Language", "en_US")
// Default values for headers
if req.Header.Get("Content-type") == "" {
req.Header.Set("Content-type", "application/json")
}
resp, err = c.Client.Do(req)
c.log(req, resp)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
errResp := &ErrorResponse{Response: resp}
data, err = ioutil.ReadAll(resp.Body)
if err == nil && len(data) > 0 {
json.Unmarshal(data, errResp)
}
return errResp
}
if v == nil {
return nil
}
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
return nil
}
return json.NewDecoder(resp.Body).Decode(v)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Send",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"var",
"(",
"err",
"error",
"\n",
"resp",
"*",
"http",
".",
"Response",
"\n",
"data",
"[",
"]",
"byte",
"\n",
")",
"\n\n",
"// Set default headers",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// Default values for headers",
"if",
"req",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
"=",
"c",
".",
"Client",
".",
"Do",
"(",
"req",
")",
"\n",
"c",
".",
"log",
"(",
"req",
",",
"resp",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"<",
"200",
"||",
"resp",
".",
"StatusCode",
">",
"299",
"{",
"errResp",
":=",
"&",
"ErrorResponse",
"{",
"Response",
":",
"resp",
"}",
"\n",
"data",
",",
"err",
"=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n\n",
"if",
"err",
"==",
"nil",
"&&",
"len",
"(",
"data",
")",
">",
"0",
"{",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"errResp",
")",
"\n",
"}",
"\n\n",
"return",
"errResp",
"\n",
"}",
"\n\n",
"if",
"v",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"w",
",",
"ok",
":=",
"v",
".",
"(",
"io",
".",
"Writer",
")",
";",
"ok",
"{",
"io",
".",
"Copy",
"(",
"w",
",",
"resp",
".",
"Body",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
".",
"Decode",
"(",
"v",
")",
"\n",
"}"
]
| // Send makes a request to the API, the response body will be
// unmarshaled into v, or if v is an io.Writer, the response will
// be written to it without decoding | [
"Send",
"makes",
"a",
"request",
"to",
"the",
"API",
"the",
"response",
"body",
"will",
"be",
"unmarshaled",
"into",
"v",
"or",
"if",
"v",
"is",
"an",
"io",
".",
"Writer",
"the",
"response",
"will",
"be",
"written",
"to",
"it",
"without",
"decoding"
]
| 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/client.go#L76-L121 |
149,622 | logpacker/PayPal-Go-SDK | client.go | SendWithAuth | func (c *Client) SendWithAuth(req *http.Request, v interface{}) error {
c.Lock()
// Note: Here we do not want to `defer c.Unlock()` because we need `c.Send(...)`
// to happen outside of the locked section.
if c.Token != nil {
if !c.tokenExpiresAt.IsZero() && c.tokenExpiresAt.Sub(time.Now()) < RequestNewTokenBeforeExpiresIn {
// c.Token will be updated in GetAccessToken call
if _, err := c.GetAccessToken(); err != nil {
c.Unlock()
return err
}
}
req.Header.Set("Authorization", "Bearer "+c.Token.Token)
}
// Unlock the client mutex before sending the request, this allows multiple requests
// to be in progress at the same time.
c.Unlock()
return c.Send(req, v)
} | go | func (c *Client) SendWithAuth(req *http.Request, v interface{}) error {
c.Lock()
// Note: Here we do not want to `defer c.Unlock()` because we need `c.Send(...)`
// to happen outside of the locked section.
if c.Token != nil {
if !c.tokenExpiresAt.IsZero() && c.tokenExpiresAt.Sub(time.Now()) < RequestNewTokenBeforeExpiresIn {
// c.Token will be updated in GetAccessToken call
if _, err := c.GetAccessToken(); err != nil {
c.Unlock()
return err
}
}
req.Header.Set("Authorization", "Bearer "+c.Token.Token)
}
// Unlock the client mutex before sending the request, this allows multiple requests
// to be in progress at the same time.
c.Unlock()
return c.Send(req, v)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SendWithAuth",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"// Note: Here we do not want to `defer c.Unlock()` because we need `c.Send(...)`",
"// to happen outside of the locked section.",
"if",
"c",
".",
"Token",
"!=",
"nil",
"{",
"if",
"!",
"c",
".",
"tokenExpiresAt",
".",
"IsZero",
"(",
")",
"&&",
"c",
".",
"tokenExpiresAt",
".",
"Sub",
"(",
"time",
".",
"Now",
"(",
")",
")",
"<",
"RequestNewTokenBeforeExpiresIn",
"{",
"// c.Token will be updated in GetAccessToken call",
"if",
"_",
",",
"err",
":=",
"c",
".",
"GetAccessToken",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"c",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"c",
".",
"Token",
".",
"Token",
")",
"\n",
"}",
"\n\n",
"// Unlock the client mutex before sending the request, this allows multiple requests",
"// to be in progress at the same time.",
"c",
".",
"Unlock",
"(",
")",
"\n",
"return",
"c",
".",
"Send",
"(",
"req",
",",
"v",
")",
"\n",
"}"
]
| // SendWithAuth makes a request to the API and apply OAuth2 header automatically.
// If the access token soon to be expired or already expired, it will try to get a new one before
// making the main request
// client.Token will be updated when changed | [
"SendWithAuth",
"makes",
"a",
"request",
"to",
"the",
"API",
"and",
"apply",
"OAuth2",
"header",
"automatically",
".",
"If",
"the",
"access",
"token",
"soon",
"to",
"be",
"expired",
"or",
"already",
"expired",
"it",
"will",
"try",
"to",
"get",
"a",
"new",
"one",
"before",
"making",
"the",
"main",
"request",
"client",
".",
"Token",
"will",
"be",
"updated",
"when",
"changed"
]
| 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/client.go#L127-L148 |
149,623 | logpacker/PayPal-Go-SDK | client.go | NewRequest | func (c *Client) NewRequest(method, url string, payload interface{}) (*http.Request, error) {
var buf io.Reader
if payload != nil {
var b []byte
b, err := json.Marshal(&payload)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(b)
}
return http.NewRequest(method, url, buf)
} | go | func (c *Client) NewRequest(method, url string, payload interface{}) (*http.Request, error) {
var buf io.Reader
if payload != nil {
var b []byte
b, err := json.Marshal(&payload)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(b)
}
return http.NewRequest(method, url, buf)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"NewRequest",
"(",
"method",
",",
"url",
"string",
",",
"payload",
"interface",
"{",
"}",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"var",
"buf",
"io",
".",
"Reader",
"\n",
"if",
"payload",
"!=",
"nil",
"{",
"var",
"b",
"[",
"]",
"byte",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"&",
"payload",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"buf",
"=",
"bytes",
".",
"NewBuffer",
"(",
"b",
")",
"\n",
"}",
"\n",
"return",
"http",
".",
"NewRequest",
"(",
"method",
",",
"url",
",",
"buf",
")",
"\n",
"}"
]
| // NewRequest constructs a request
// Convert payload to a JSON | [
"NewRequest",
"constructs",
"a",
"request",
"Convert",
"payload",
"to",
"a",
"JSON"
]
| 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/client.go#L159-L170 |
149,624 | logpacker/PayPal-Go-SDK | client.go | log | func (c *Client) log(r *http.Request, resp *http.Response) {
if c.Log != nil {
var (
reqDump string
respDump []byte
)
if r != nil {
reqDump = fmt.Sprintf("%s %s. Data: %s", r.Method, r.URL.String(), r.Form.Encode())
}
if resp != nil {
respDump, _ = httputil.DumpResponse(resp, true)
}
c.Log.Write([]byte(fmt.Sprintf("Request: %s\nResponse: %s\n", reqDump, string(respDump))))
}
} | go | func (c *Client) log(r *http.Request, resp *http.Response) {
if c.Log != nil {
var (
reqDump string
respDump []byte
)
if r != nil {
reqDump = fmt.Sprintf("%s %s. Data: %s", r.Method, r.URL.String(), r.Form.Encode())
}
if resp != nil {
respDump, _ = httputil.DumpResponse(resp, true)
}
c.Log.Write([]byte(fmt.Sprintf("Request: %s\nResponse: %s\n", reqDump, string(respDump))))
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"log",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"resp",
"*",
"http",
".",
"Response",
")",
"{",
"if",
"c",
".",
"Log",
"!=",
"nil",
"{",
"var",
"(",
"reqDump",
"string",
"\n",
"respDump",
"[",
"]",
"byte",
"\n",
")",
"\n\n",
"if",
"r",
"!=",
"nil",
"{",
"reqDump",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"r",
".",
"Method",
",",
"r",
".",
"URL",
".",
"String",
"(",
")",
",",
"r",
".",
"Form",
".",
"Encode",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"resp",
"!=",
"nil",
"{",
"respDump",
",",
"_",
"=",
"httputil",
".",
"DumpResponse",
"(",
"resp",
",",
"true",
")",
"\n",
"}",
"\n\n",
"c",
".",
"Log",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\\n",
"\"",
",",
"reqDump",
",",
"string",
"(",
"respDump",
")",
")",
")",
")",
"\n",
"}",
"\n",
"}"
]
| // log will dump request and response to the log file | [
"log",
"will",
"dump",
"request",
"and",
"response",
"to",
"the",
"log",
"file"
]
| 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/client.go#L173-L189 |
149,625 | didip/tollbooth | libstring/libstring.go | StringInSlice | func StringInSlice(sliceString []string, needle string) bool {
for _, b := range sliceString {
if b == needle {
return true
}
}
return false
} | go | func StringInSlice(sliceString []string, needle string) bool {
for _, b := range sliceString {
if b == needle {
return true
}
}
return false
} | [
"func",
"StringInSlice",
"(",
"sliceString",
"[",
"]",
"string",
",",
"needle",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"b",
":=",
"range",
"sliceString",
"{",
"if",
"b",
"==",
"needle",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
]
| // StringInSlice finds needle in a slice of strings. | [
"StringInSlice",
"finds",
"needle",
"in",
"a",
"slice",
"of",
"strings",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/libstring/libstring.go#L11-L18 |
149,626 | didip/tollbooth | tollbooth.go | setResponseHeaders | func setResponseHeaders(lmt *limiter.Limiter, w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-Rate-Limit-Limit", fmt.Sprintf("%.2f", lmt.GetMax()))
w.Header().Add("X-Rate-Limit-Duration", "1")
w.Header().Add("X-Rate-Limit-Request-Forwarded-For", r.Header.Get("X-Forwarded-For"))
w.Header().Add("X-Rate-Limit-Request-Remote-Addr", r.RemoteAddr)
} | go | func setResponseHeaders(lmt *limiter.Limiter, w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-Rate-Limit-Limit", fmt.Sprintf("%.2f", lmt.GetMax()))
w.Header().Add("X-Rate-Limit-Duration", "1")
w.Header().Add("X-Rate-Limit-Request-Forwarded-For", r.Header.Get("X-Forwarded-For"))
w.Header().Add("X-Rate-Limit-Request-Remote-Addr", r.RemoteAddr)
} | [
"func",
"setResponseHeaders",
"(",
"lmt",
"*",
"limiter",
".",
"Limiter",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"lmt",
".",
"GetMax",
"(",
")",
")",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"r",
".",
"RemoteAddr",
")",
"\n",
"}"
]
| // setResponseHeaders configures X-Rate-Limit-Limit and X-Rate-Limit-Duration | [
"setResponseHeaders",
"configures",
"X",
"-",
"Rate",
"-",
"Limit",
"-",
"Limit",
"and",
"X",
"-",
"Rate",
"-",
"Limit",
"-",
"Duration"
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/tollbooth.go#L16-L21 |
149,627 | didip/tollbooth | tollbooth.go | NewLimiter | func NewLimiter(max float64, tbOptions *limiter.ExpirableOptions) *limiter.Limiter {
return limiter.New(tbOptions).SetMax(max).SetBurst(int(math.Max(1, max)))
} | go | func NewLimiter(max float64, tbOptions *limiter.ExpirableOptions) *limiter.Limiter {
return limiter.New(tbOptions).SetMax(max).SetBurst(int(math.Max(1, max)))
} | [
"func",
"NewLimiter",
"(",
"max",
"float64",
",",
"tbOptions",
"*",
"limiter",
".",
"ExpirableOptions",
")",
"*",
"limiter",
".",
"Limiter",
"{",
"return",
"limiter",
".",
"New",
"(",
"tbOptions",
")",
".",
"SetMax",
"(",
"max",
")",
".",
"SetBurst",
"(",
"int",
"(",
"math",
".",
"Max",
"(",
"1",
",",
"max",
")",
")",
")",
"\n",
"}"
]
| // NewLimiter is a convenience function to limiter.New. | [
"NewLimiter",
"is",
"a",
"convenience",
"function",
"to",
"limiter",
".",
"New",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/tollbooth.go#L24-L26 |
149,628 | didip/tollbooth | tollbooth.go | LimitHandler | func LimitHandler(lmt *limiter.Limiter, next http.Handler) http.Handler {
middle := func(w http.ResponseWriter, r *http.Request) {
httpError := LimitByRequest(lmt, w, r)
if httpError != nil {
lmt.ExecOnLimitReached(w, r)
w.Header().Add("Content-Type", lmt.GetMessageContentType())
w.WriteHeader(httpError.StatusCode)
w.Write([]byte(httpError.Message))
return
}
// There's no rate-limit error, serve the next handler.
next.ServeHTTP(w, r)
}
return http.HandlerFunc(middle)
} | go | func LimitHandler(lmt *limiter.Limiter, next http.Handler) http.Handler {
middle := func(w http.ResponseWriter, r *http.Request) {
httpError := LimitByRequest(lmt, w, r)
if httpError != nil {
lmt.ExecOnLimitReached(w, r)
w.Header().Add("Content-Type", lmt.GetMessageContentType())
w.WriteHeader(httpError.StatusCode)
w.Write([]byte(httpError.Message))
return
}
// There's no rate-limit error, serve the next handler.
next.ServeHTTP(w, r)
}
return http.HandlerFunc(middle)
} | [
"func",
"LimitHandler",
"(",
"lmt",
"*",
"limiter",
".",
"Limiter",
",",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"middle",
":=",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"httpError",
":=",
"LimitByRequest",
"(",
"lmt",
",",
"w",
",",
"r",
")",
"\n",
"if",
"httpError",
"!=",
"nil",
"{",
"lmt",
".",
"ExecOnLimitReached",
"(",
"w",
",",
"r",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"lmt",
".",
"GetMessageContentType",
"(",
")",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"httpError",
".",
"StatusCode",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"httpError",
".",
"Message",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// There's no rate-limit error, serve the next handler.",
"next",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n\n",
"return",
"http",
".",
"HandlerFunc",
"(",
"middle",
")",
"\n",
"}"
]
| // LimitHandler is a middleware that performs rate-limiting given http.Handler struct. | [
"LimitHandler",
"is",
"a",
"middleware",
"that",
"performs",
"rate",
"-",
"limiting",
"given",
"http",
".",
"Handler",
"struct",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/tollbooth.go#L159-L175 |
149,629 | didip/tollbooth | tollbooth.go | LimitFuncHandler | func LimitFuncHandler(lmt *limiter.Limiter, nextFunc func(http.ResponseWriter, *http.Request)) http.Handler {
return LimitHandler(lmt, http.HandlerFunc(nextFunc))
} | go | func LimitFuncHandler(lmt *limiter.Limiter, nextFunc func(http.ResponseWriter, *http.Request)) http.Handler {
return LimitHandler(lmt, http.HandlerFunc(nextFunc))
} | [
"func",
"LimitFuncHandler",
"(",
"lmt",
"*",
"limiter",
".",
"Limiter",
",",
"nextFunc",
"func",
"(",
"http",
".",
"ResponseWriter",
",",
"*",
"http",
".",
"Request",
")",
")",
"http",
".",
"Handler",
"{",
"return",
"LimitHandler",
"(",
"lmt",
",",
"http",
".",
"HandlerFunc",
"(",
"nextFunc",
")",
")",
"\n",
"}"
]
| // LimitFuncHandler is a middleware that performs rate-limiting given request handler function. | [
"LimitFuncHandler",
"is",
"a",
"middleware",
"that",
"performs",
"rate",
"-",
"limiting",
"given",
"request",
"handler",
"function",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/tollbooth.go#L178-L180 |
149,630 | didip/tollbooth | errors/errors.go | Error | func (httperror *HTTPError) Error() string {
return fmt.Sprintf("%v: %v", httperror.StatusCode, httperror.Message)
} | go | func (httperror *HTTPError) Error() string {
return fmt.Sprintf("%v: %v", httperror.StatusCode, httperror.Message)
} | [
"func",
"(",
"httperror",
"*",
"HTTPError",
")",
"Error",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"httperror",
".",
"StatusCode",
",",
"httperror",
".",
"Message",
")",
"\n",
"}"
]
| // Error returns error message. | [
"Error",
"returns",
"error",
"message",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/errors/errors.go#L13-L15 |
149,631 | didip/tollbooth | limiter/limiter.go | New | func New(generalExpirableOptions *ExpirableOptions) *Limiter {
lmt := &Limiter{}
lmt.SetMessageContentType("text/plain; charset=utf-8").
SetMessage("You have reached maximum request limit.").
SetStatusCode(429).
SetOnLimitReached(nil).
SetIPLookups([]string{"RemoteAddr", "X-Forwarded-For", "X-Real-IP"}).
SetForwardedForIndexFromBehind(0).
SetHeaders(make(map[string][]string))
if generalExpirableOptions != nil {
lmt.generalExpirableOptions = generalExpirableOptions
} else {
lmt.generalExpirableOptions = &ExpirableOptions{}
}
// Default for ExpireJobInterval is every minute.
if lmt.generalExpirableOptions.ExpireJobInterval <= 0 {
lmt.generalExpirableOptions.ExpireJobInterval = time.Minute
}
// Default for DefaultExpirationTTL is 10 years.
if lmt.generalExpirableOptions.DefaultExpirationTTL <= 0 {
lmt.generalExpirableOptions.DefaultExpirationTTL = 87600 * time.Hour
}
lmt.tokenBuckets = gocache.New(
lmt.generalExpirableOptions.DefaultExpirationTTL,
lmt.generalExpirableOptions.ExpireJobInterval,
)
lmt.basicAuthUsers = gocache.New(
lmt.generalExpirableOptions.DefaultExpirationTTL,
lmt.generalExpirableOptions.ExpireJobInterval,
)
return lmt
} | go | func New(generalExpirableOptions *ExpirableOptions) *Limiter {
lmt := &Limiter{}
lmt.SetMessageContentType("text/plain; charset=utf-8").
SetMessage("You have reached maximum request limit.").
SetStatusCode(429).
SetOnLimitReached(nil).
SetIPLookups([]string{"RemoteAddr", "X-Forwarded-For", "X-Real-IP"}).
SetForwardedForIndexFromBehind(0).
SetHeaders(make(map[string][]string))
if generalExpirableOptions != nil {
lmt.generalExpirableOptions = generalExpirableOptions
} else {
lmt.generalExpirableOptions = &ExpirableOptions{}
}
// Default for ExpireJobInterval is every minute.
if lmt.generalExpirableOptions.ExpireJobInterval <= 0 {
lmt.generalExpirableOptions.ExpireJobInterval = time.Minute
}
// Default for DefaultExpirationTTL is 10 years.
if lmt.generalExpirableOptions.DefaultExpirationTTL <= 0 {
lmt.generalExpirableOptions.DefaultExpirationTTL = 87600 * time.Hour
}
lmt.tokenBuckets = gocache.New(
lmt.generalExpirableOptions.DefaultExpirationTTL,
lmt.generalExpirableOptions.ExpireJobInterval,
)
lmt.basicAuthUsers = gocache.New(
lmt.generalExpirableOptions.DefaultExpirationTTL,
lmt.generalExpirableOptions.ExpireJobInterval,
)
return lmt
} | [
"func",
"New",
"(",
"generalExpirableOptions",
"*",
"ExpirableOptions",
")",
"*",
"Limiter",
"{",
"lmt",
":=",
"&",
"Limiter",
"{",
"}",
"\n\n",
"lmt",
".",
"SetMessageContentType",
"(",
"\"",
"\"",
")",
".",
"SetMessage",
"(",
"\"",
"\"",
")",
".",
"SetStatusCode",
"(",
"429",
")",
".",
"SetOnLimitReached",
"(",
"nil",
")",
".",
"SetIPLookups",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
".",
"SetForwardedForIndexFromBehind",
"(",
"0",
")",
".",
"SetHeaders",
"(",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
")",
"\n\n",
"if",
"generalExpirableOptions",
"!=",
"nil",
"{",
"lmt",
".",
"generalExpirableOptions",
"=",
"generalExpirableOptions",
"\n",
"}",
"else",
"{",
"lmt",
".",
"generalExpirableOptions",
"=",
"&",
"ExpirableOptions",
"{",
"}",
"\n",
"}",
"\n\n",
"// Default for ExpireJobInterval is every minute.",
"if",
"lmt",
".",
"generalExpirableOptions",
".",
"ExpireJobInterval",
"<=",
"0",
"{",
"lmt",
".",
"generalExpirableOptions",
".",
"ExpireJobInterval",
"=",
"time",
".",
"Minute",
"\n",
"}",
"\n\n",
"// Default for DefaultExpirationTTL is 10 years.",
"if",
"lmt",
".",
"generalExpirableOptions",
".",
"DefaultExpirationTTL",
"<=",
"0",
"{",
"lmt",
".",
"generalExpirableOptions",
".",
"DefaultExpirationTTL",
"=",
"87600",
"*",
"time",
".",
"Hour",
"\n",
"}",
"\n\n",
"lmt",
".",
"tokenBuckets",
"=",
"gocache",
".",
"New",
"(",
"lmt",
".",
"generalExpirableOptions",
".",
"DefaultExpirationTTL",
",",
"lmt",
".",
"generalExpirableOptions",
".",
"ExpireJobInterval",
",",
")",
"\n\n",
"lmt",
".",
"basicAuthUsers",
"=",
"gocache",
".",
"New",
"(",
"lmt",
".",
"generalExpirableOptions",
".",
"DefaultExpirationTTL",
",",
"lmt",
".",
"generalExpirableOptions",
".",
"ExpireJobInterval",
",",
")",
"\n\n",
"return",
"lmt",
"\n",
"}"
]
| // New is a constructor for Limiter. | [
"New",
"is",
"a",
"constructor",
"for",
"Limiter",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L14-L52 |
149,632 | didip/tollbooth | limiter/limiter.go | SetTokenBucketExpirationTTL | func (l *Limiter) SetTokenBucketExpirationTTL(ttl time.Duration) *Limiter {
l.Lock()
l.tokenBucketExpirationTTL = ttl
l.Unlock()
return l
} | go | func (l *Limiter) SetTokenBucketExpirationTTL(ttl time.Duration) *Limiter {
l.Lock()
l.tokenBucketExpirationTTL = ttl
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetTokenBucketExpirationTTL",
"(",
"ttl",
"time",
".",
"Duration",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"tokenBucketExpirationTTL",
"=",
"ttl",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetTokenBucketExpirationTTL is thread-safe way of setting custom token bucket expiration TTL. | [
"SetTokenBucketExpirationTTL",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"custom",
"token",
"bucket",
"expiration",
"TTL",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L106-L112 |
149,633 | didip/tollbooth | limiter/limiter.go | GetTokenBucketExpirationTTL | func (l *Limiter) GetTokenBucketExpirationTTL() time.Duration {
l.RLock()
defer l.RUnlock()
return l.tokenBucketExpirationTTL
} | go | func (l *Limiter) GetTokenBucketExpirationTTL() time.Duration {
l.RLock()
defer l.RUnlock()
return l.tokenBucketExpirationTTL
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetTokenBucketExpirationTTL",
"(",
")",
"time",
".",
"Duration",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"tokenBucketExpirationTTL",
"\n",
"}"
]
| // GettokenBucketExpirationTTL is thread-safe way of getting custom token bucket expiration TTL. | [
"GettokenBucketExpirationTTL",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"custom",
"token",
"bucket",
"expiration",
"TTL",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L115-L119 |
149,634 | didip/tollbooth | limiter/limiter.go | SetBasicAuthExpirationTTL | func (l *Limiter) SetBasicAuthExpirationTTL(ttl time.Duration) *Limiter {
l.Lock()
l.basicAuthExpirationTTL = ttl
l.Unlock()
return l
} | go | func (l *Limiter) SetBasicAuthExpirationTTL(ttl time.Duration) *Limiter {
l.Lock()
l.basicAuthExpirationTTL = ttl
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetBasicAuthExpirationTTL",
"(",
"ttl",
"time",
".",
"Duration",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"basicAuthExpirationTTL",
"=",
"ttl",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetBasicAuthExpirationTTL is thread-safe way of setting custom basic auth expiration TTL. | [
"SetBasicAuthExpirationTTL",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"custom",
"basic",
"auth",
"expiration",
"TTL",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L122-L128 |
149,635 | didip/tollbooth | limiter/limiter.go | GetBasicAuthExpirationTTL | func (l *Limiter) GetBasicAuthExpirationTTL() time.Duration {
l.RLock()
defer l.RUnlock()
return l.basicAuthExpirationTTL
} | go | func (l *Limiter) GetBasicAuthExpirationTTL() time.Duration {
l.RLock()
defer l.RUnlock()
return l.basicAuthExpirationTTL
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetBasicAuthExpirationTTL",
"(",
")",
"time",
".",
"Duration",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"basicAuthExpirationTTL",
"\n",
"}"
]
| // GetBasicAuthExpirationTTL is thread-safe way of getting custom basic auth expiration TTL. | [
"GetBasicAuthExpirationTTL",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"custom",
"basic",
"auth",
"expiration",
"TTL",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L131-L135 |
149,636 | didip/tollbooth | limiter/limiter.go | SetHeaderEntryExpirationTTL | func (l *Limiter) SetHeaderEntryExpirationTTL(ttl time.Duration) *Limiter {
l.Lock()
l.headerEntryExpirationTTL = ttl
l.Unlock()
return l
} | go | func (l *Limiter) SetHeaderEntryExpirationTTL(ttl time.Duration) *Limiter {
l.Lock()
l.headerEntryExpirationTTL = ttl
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetHeaderEntryExpirationTTL",
"(",
"ttl",
"time",
".",
"Duration",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"headerEntryExpirationTTL",
"=",
"ttl",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetHeaderEntryExpirationTTL is thread-safe way of setting custom basic auth expiration TTL. | [
"SetHeaderEntryExpirationTTL",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"custom",
"basic",
"auth",
"expiration",
"TTL",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L138-L144 |
149,637 | didip/tollbooth | limiter/limiter.go | GetHeaderEntryExpirationTTL | func (l *Limiter) GetHeaderEntryExpirationTTL() time.Duration {
l.RLock()
defer l.RUnlock()
return l.headerEntryExpirationTTL
} | go | func (l *Limiter) GetHeaderEntryExpirationTTL() time.Duration {
l.RLock()
defer l.RUnlock()
return l.headerEntryExpirationTTL
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetHeaderEntryExpirationTTL",
"(",
")",
"time",
".",
"Duration",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"headerEntryExpirationTTL",
"\n",
"}"
]
| // GetHeaderEntryExpirationTTL is thread-safe way of getting custom basic auth expiration TTL. | [
"GetHeaderEntryExpirationTTL",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"custom",
"basic",
"auth",
"expiration",
"TTL",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L147-L151 |
149,638 | didip/tollbooth | limiter/limiter.go | SetMax | func (l *Limiter) SetMax(max float64) *Limiter {
l.Lock()
l.max = max
l.Unlock()
return l
} | go | func (l *Limiter) SetMax(max float64) *Limiter {
l.Lock()
l.max = max
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetMax",
"(",
"max",
"float64",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"max",
"=",
"max",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetMax is thread-safe way of setting maximum number of requests to limit per duration. | [
"SetMax",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"maximum",
"number",
"of",
"requests",
"to",
"limit",
"per",
"duration",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L154-L160 |
149,639 | didip/tollbooth | limiter/limiter.go | GetMax | func (l *Limiter) GetMax() float64 {
l.RLock()
defer l.RUnlock()
return l.max
} | go | func (l *Limiter) GetMax() float64 {
l.RLock()
defer l.RUnlock()
return l.max
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetMax",
"(",
")",
"float64",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"max",
"\n",
"}"
]
| // GetMax is thread-safe way of getting maximum number of requests to limit per duration. | [
"GetMax",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"maximum",
"number",
"of",
"requests",
"to",
"limit",
"per",
"duration",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L163-L167 |
149,640 | didip/tollbooth | limiter/limiter.go | SetBurst | func (l *Limiter) SetBurst(burst int) *Limiter {
l.Lock()
l.burst = burst
l.Unlock()
return l
} | go | func (l *Limiter) SetBurst(burst int) *Limiter {
l.Lock()
l.burst = burst
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetBurst",
"(",
"burst",
"int",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"burst",
"=",
"burst",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetBurst is thread-safe way of setting maximum burst size. | [
"SetBurst",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"maximum",
"burst",
"size",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L170-L176 |
149,641 | didip/tollbooth | limiter/limiter.go | GetBurst | func (l *Limiter) GetBurst() int {
l.RLock()
defer l.RUnlock()
return l.burst
} | go | func (l *Limiter) GetBurst() int {
l.RLock()
defer l.RUnlock()
return l.burst
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetBurst",
"(",
")",
"int",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"l",
".",
"burst",
"\n",
"}"
]
| // GetBurst is thread-safe way of setting maximum burst size. | [
"GetBurst",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"maximum",
"burst",
"size",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L179-L184 |
149,642 | didip/tollbooth | limiter/limiter.go | SetMessage | func (l *Limiter) SetMessage(msg string) *Limiter {
l.Lock()
l.message = msg
l.Unlock()
return l
} | go | func (l *Limiter) SetMessage(msg string) *Limiter {
l.Lock()
l.message = msg
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetMessage",
"(",
"msg",
"string",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"message",
"=",
"msg",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetMessage is thread-safe way of setting HTTP message when limit is reached. | [
"SetMessage",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"HTTP",
"message",
"when",
"limit",
"is",
"reached",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L187-L193 |
149,643 | didip/tollbooth | limiter/limiter.go | GetMessage | func (l *Limiter) GetMessage() string {
l.RLock()
defer l.RUnlock()
return l.message
} | go | func (l *Limiter) GetMessage() string {
l.RLock()
defer l.RUnlock()
return l.message
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetMessage",
"(",
")",
"string",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"message",
"\n",
"}"
]
| // GetMessage is thread-safe way of getting HTTP message when limit is reached. | [
"GetMessage",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"HTTP",
"message",
"when",
"limit",
"is",
"reached",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L196-L200 |
149,644 | didip/tollbooth | limiter/limiter.go | SetMessageContentType | func (l *Limiter) SetMessageContentType(contentType string) *Limiter {
l.Lock()
l.messageContentType = contentType
l.Unlock()
return l
} | go | func (l *Limiter) SetMessageContentType(contentType string) *Limiter {
l.Lock()
l.messageContentType = contentType
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetMessageContentType",
"(",
"contentType",
"string",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"messageContentType",
"=",
"contentType",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetMessageContentType is thread-safe way of setting HTTP message Content-Type when limit is reached. | [
"SetMessageContentType",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"HTTP",
"message",
"Content",
"-",
"Type",
"when",
"limit",
"is",
"reached",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L203-L209 |
149,645 | didip/tollbooth | limiter/limiter.go | GetMessageContentType | func (l *Limiter) GetMessageContentType() string {
l.RLock()
defer l.RUnlock()
return l.messageContentType
} | go | func (l *Limiter) GetMessageContentType() string {
l.RLock()
defer l.RUnlock()
return l.messageContentType
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetMessageContentType",
"(",
")",
"string",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"messageContentType",
"\n",
"}"
]
| // GetMessageContentType is thread-safe way of getting HTTP message Content-Type when limit is reached. | [
"GetMessageContentType",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"HTTP",
"message",
"Content",
"-",
"Type",
"when",
"limit",
"is",
"reached",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L212-L216 |
149,646 | didip/tollbooth | limiter/limiter.go | SetStatusCode | func (l *Limiter) SetStatusCode(statusCode int) *Limiter {
l.Lock()
l.statusCode = statusCode
l.Unlock()
return l
} | go | func (l *Limiter) SetStatusCode(statusCode int) *Limiter {
l.Lock()
l.statusCode = statusCode
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetStatusCode",
"(",
"statusCode",
"int",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"statusCode",
"=",
"statusCode",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetStatusCode is thread-safe way of setting HTTP status code when limit is reached. | [
"SetStatusCode",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"HTTP",
"status",
"code",
"when",
"limit",
"is",
"reached",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L219-L225 |
149,647 | didip/tollbooth | limiter/limiter.go | GetStatusCode | func (l *Limiter) GetStatusCode() int {
l.RLock()
defer l.RUnlock()
return l.statusCode
} | go | func (l *Limiter) GetStatusCode() int {
l.RLock()
defer l.RUnlock()
return l.statusCode
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetStatusCode",
"(",
")",
"int",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"statusCode",
"\n",
"}"
]
| // GetStatusCode is thread-safe way of getting HTTP status code when limit is reached. | [
"GetStatusCode",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"HTTP",
"status",
"code",
"when",
"limit",
"is",
"reached",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L228-L232 |
149,648 | didip/tollbooth | limiter/limiter.go | SetOnLimitReached | func (l *Limiter) SetOnLimitReached(fn func(w http.ResponseWriter, r *http.Request)) *Limiter {
l.Lock()
l.onLimitReached = fn
l.Unlock()
return l
} | go | func (l *Limiter) SetOnLimitReached(fn func(w http.ResponseWriter, r *http.Request)) *Limiter {
l.Lock()
l.onLimitReached = fn
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetOnLimitReached",
"(",
"fn",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"onLimitReached",
"=",
"fn",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetOnLimitReached is thread-safe way of setting after-rejection function when limit is reached. | [
"SetOnLimitReached",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"after",
"-",
"rejection",
"function",
"when",
"limit",
"is",
"reached",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L235-L241 |
149,649 | didip/tollbooth | limiter/limiter.go | ExecOnLimitReached | func (l *Limiter) ExecOnLimitReached(w http.ResponseWriter, r *http.Request) {
l.RLock()
defer l.RUnlock()
fn := l.onLimitReached
if fn != nil {
fn(w, r)
}
} | go | func (l *Limiter) ExecOnLimitReached(w http.ResponseWriter, r *http.Request) {
l.RLock()
defer l.RUnlock()
fn := l.onLimitReached
if fn != nil {
fn(w, r)
}
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"ExecOnLimitReached",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n\n",
"fn",
":=",
"l",
".",
"onLimitReached",
"\n",
"if",
"fn",
"!=",
"nil",
"{",
"fn",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}"
]
| // ExecOnLimitReached is thread-safe way of executing after-rejection function when limit is reached. | [
"ExecOnLimitReached",
"is",
"thread",
"-",
"safe",
"way",
"of",
"executing",
"after",
"-",
"rejection",
"function",
"when",
"limit",
"is",
"reached",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L244-L252 |
149,650 | didip/tollbooth | limiter/limiter.go | SetIPLookups | func (l *Limiter) SetIPLookups(ipLookups []string) *Limiter {
l.Lock()
l.ipLookups = ipLookups
l.Unlock()
return l
} | go | func (l *Limiter) SetIPLookups(ipLookups []string) *Limiter {
l.Lock()
l.ipLookups = ipLookups
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetIPLookups",
"(",
"ipLookups",
"[",
"]",
"string",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"ipLookups",
"=",
"ipLookups",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetIPLookups is thread-safe way of setting list of places to look up IP address. | [
"SetIPLookups",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"list",
"of",
"places",
"to",
"look",
"up",
"IP",
"address",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L255-L261 |
149,651 | didip/tollbooth | limiter/limiter.go | GetIPLookups | func (l *Limiter) GetIPLookups() []string {
l.RLock()
defer l.RUnlock()
return l.ipLookups
} | go | func (l *Limiter) GetIPLookups() []string {
l.RLock()
defer l.RUnlock()
return l.ipLookups
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetIPLookups",
"(",
")",
"[",
"]",
"string",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"ipLookups",
"\n",
"}"
]
| // GetIPLookups is thread-safe way of getting list of places to look up IP address. | [
"GetIPLookups",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"list",
"of",
"places",
"to",
"look",
"up",
"IP",
"address",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L264-L268 |
149,652 | didip/tollbooth | limiter/limiter.go | SetForwardedForIndexFromBehind | func (l *Limiter) SetForwardedForIndexFromBehind(forwardedForIndex int) *Limiter {
l.Lock()
l.forwardedForIndex = forwardedForIndex
l.Unlock()
return l
} | go | func (l *Limiter) SetForwardedForIndexFromBehind(forwardedForIndex int) *Limiter {
l.Lock()
l.forwardedForIndex = forwardedForIndex
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetForwardedForIndexFromBehind",
"(",
"forwardedForIndex",
"int",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"forwardedForIndex",
"=",
"forwardedForIndex",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetForwardedForIndexFromBehind is thread-safe way of setting which X-Forwarded-For index to choose. | [
"SetForwardedForIndexFromBehind",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"which",
"X",
"-",
"Forwarded",
"-",
"For",
"index",
"to",
"choose",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L271-L277 |
149,653 | didip/tollbooth | limiter/limiter.go | GetForwardedForIndexFromBehind | func (l *Limiter) GetForwardedForIndexFromBehind() int {
l.RLock()
defer l.RUnlock()
return l.forwardedForIndex
} | go | func (l *Limiter) GetForwardedForIndexFromBehind() int {
l.RLock()
defer l.RUnlock()
return l.forwardedForIndex
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetForwardedForIndexFromBehind",
"(",
")",
"int",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"forwardedForIndex",
"\n",
"}"
]
| // GetForwardedForIndexFromBehind is thread-safe way of getting which X-Forwarded-For index to choose. | [
"GetForwardedForIndexFromBehind",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"which",
"X",
"-",
"Forwarded",
"-",
"For",
"index",
"to",
"choose",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L280-L284 |
149,654 | didip/tollbooth | limiter/limiter.go | SetBasicAuthUsers | func (l *Limiter) SetBasicAuthUsers(basicAuthUsers []string) *Limiter {
ttl := l.GetBasicAuthExpirationTTL()
if ttl <= 0 {
ttl = l.generalExpirableOptions.DefaultExpirationTTL
}
for _, basicAuthUser := range basicAuthUsers {
l.basicAuthUsers.Set(basicAuthUser, true, ttl)
}
return l
} | go | func (l *Limiter) SetBasicAuthUsers(basicAuthUsers []string) *Limiter {
ttl := l.GetBasicAuthExpirationTTL()
if ttl <= 0 {
ttl = l.generalExpirableOptions.DefaultExpirationTTL
}
for _, basicAuthUser := range basicAuthUsers {
l.basicAuthUsers.Set(basicAuthUser, true, ttl)
}
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetBasicAuthUsers",
"(",
"basicAuthUsers",
"[",
"]",
"string",
")",
"*",
"Limiter",
"{",
"ttl",
":=",
"l",
".",
"GetBasicAuthExpirationTTL",
"(",
")",
"\n",
"if",
"ttl",
"<=",
"0",
"{",
"ttl",
"=",
"l",
".",
"generalExpirableOptions",
".",
"DefaultExpirationTTL",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"basicAuthUser",
":=",
"range",
"basicAuthUsers",
"{",
"l",
".",
"basicAuthUsers",
".",
"Set",
"(",
"basicAuthUser",
",",
"true",
",",
"ttl",
")",
"\n",
"}",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetBasicAuthUsers is thread-safe way of setting list of basic auth usernames to limit. | [
"SetBasicAuthUsers",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"list",
"of",
"basic",
"auth",
"usernames",
"to",
"limit",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L303-L314 |
149,655 | didip/tollbooth | limiter/limiter.go | GetBasicAuthUsers | func (l *Limiter) GetBasicAuthUsers() []string {
asMap := l.basicAuthUsers.Items()
var basicAuthUsers []string
for basicAuthUser, _ := range asMap {
basicAuthUsers = append(basicAuthUsers, basicAuthUser)
}
return basicAuthUsers
} | go | func (l *Limiter) GetBasicAuthUsers() []string {
asMap := l.basicAuthUsers.Items()
var basicAuthUsers []string
for basicAuthUser, _ := range asMap {
basicAuthUsers = append(basicAuthUsers, basicAuthUser)
}
return basicAuthUsers
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetBasicAuthUsers",
"(",
")",
"[",
"]",
"string",
"{",
"asMap",
":=",
"l",
".",
"basicAuthUsers",
".",
"Items",
"(",
")",
"\n\n",
"var",
"basicAuthUsers",
"[",
"]",
"string",
"\n",
"for",
"basicAuthUser",
",",
"_",
":=",
"range",
"asMap",
"{",
"basicAuthUsers",
"=",
"append",
"(",
"basicAuthUsers",
",",
"basicAuthUser",
")",
"\n",
"}",
"\n\n",
"return",
"basicAuthUsers",
"\n",
"}"
]
| // GetBasicAuthUsers is thread-safe way of getting list of basic auth usernames to limit. | [
"GetBasicAuthUsers",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"list",
"of",
"basic",
"auth",
"usernames",
"to",
"limit",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L317-L326 |
149,656 | didip/tollbooth | limiter/limiter.go | RemoveBasicAuthUsers | func (l *Limiter) RemoveBasicAuthUsers(basicAuthUsers []string) *Limiter {
for _, toBeRemoved := range basicAuthUsers {
l.basicAuthUsers.Delete(toBeRemoved)
}
return l
} | go | func (l *Limiter) RemoveBasicAuthUsers(basicAuthUsers []string) *Limiter {
for _, toBeRemoved := range basicAuthUsers {
l.basicAuthUsers.Delete(toBeRemoved)
}
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"RemoveBasicAuthUsers",
"(",
"basicAuthUsers",
"[",
"]",
"string",
")",
"*",
"Limiter",
"{",
"for",
"_",
",",
"toBeRemoved",
":=",
"range",
"basicAuthUsers",
"{",
"l",
".",
"basicAuthUsers",
".",
"Delete",
"(",
"toBeRemoved",
")",
"\n",
"}",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // RemoveBasicAuthUsers is thread-safe way of removing basic auth usernames from existing list. | [
"RemoveBasicAuthUsers",
"is",
"thread",
"-",
"safe",
"way",
"of",
"removing",
"basic",
"auth",
"usernames",
"from",
"existing",
"list",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L329-L335 |
149,657 | didip/tollbooth | limiter/limiter.go | SetHeaders | func (l *Limiter) SetHeaders(headers map[string][]string) *Limiter {
if l.headers == nil {
l.headers = make(map[string]*gocache.Cache)
}
for header, entries := range headers {
l.SetHeader(header, entries)
}
return l
} | go | func (l *Limiter) SetHeaders(headers map[string][]string) *Limiter {
if l.headers == nil {
l.headers = make(map[string]*gocache.Cache)
}
for header, entries := range headers {
l.SetHeader(header, entries)
}
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetHeaders",
"(",
"headers",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"*",
"Limiter",
"{",
"if",
"l",
".",
"headers",
"==",
"nil",
"{",
"l",
".",
"headers",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"gocache",
".",
"Cache",
")",
"\n",
"}",
"\n\n",
"for",
"header",
",",
"entries",
":=",
"range",
"headers",
"{",
"l",
".",
"SetHeader",
"(",
"header",
",",
"entries",
")",
"\n",
"}",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetHeaders is thread-safe way of setting map of HTTP headers to limit. | [
"SetHeaders",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"map",
"of",
"HTTP",
"headers",
"to",
"limit",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L338-L348 |
149,658 | didip/tollbooth | limiter/limiter.go | GetHeaders | func (l *Limiter) GetHeaders() map[string][]string {
results := make(map[string][]string)
l.RLock()
defer l.RUnlock()
for header, entriesAsGoCache := range l.headers {
entries := make([]string, 0)
for entry, _ := range entriesAsGoCache.Items() {
entries = append(entries, entry)
}
results[header] = entries
}
return results
} | go | func (l *Limiter) GetHeaders() map[string][]string {
results := make(map[string][]string)
l.RLock()
defer l.RUnlock()
for header, entriesAsGoCache := range l.headers {
entries := make([]string, 0)
for entry, _ := range entriesAsGoCache.Items() {
entries = append(entries, entry)
}
results[header] = entries
}
return results
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetHeaders",
"(",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"results",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n\n",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n\n",
"for",
"header",
",",
"entriesAsGoCache",
":=",
"range",
"l",
".",
"headers",
"{",
"entries",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n\n",
"for",
"entry",
",",
"_",
":=",
"range",
"entriesAsGoCache",
".",
"Items",
"(",
")",
"{",
"entries",
"=",
"append",
"(",
"entries",
",",
"entry",
")",
"\n",
"}",
"\n\n",
"results",
"[",
"header",
"]",
"=",
"entries",
"\n",
"}",
"\n\n",
"return",
"results",
"\n",
"}"
]
| // GetHeaders is thread-safe way of getting map of HTTP headers to limit. | [
"GetHeaders",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"map",
"of",
"HTTP",
"headers",
"to",
"limit",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L351-L368 |
149,659 | didip/tollbooth | limiter/limiter.go | SetHeader | func (l *Limiter) SetHeader(header string, entries []string) *Limiter {
l.RLock()
existing, found := l.headers[header]
l.RUnlock()
ttl := l.GetHeaderEntryExpirationTTL()
if ttl <= 0 {
ttl = l.generalExpirableOptions.DefaultExpirationTTL
}
if !found {
existing = gocache.New(ttl, l.generalExpirableOptions.ExpireJobInterval)
}
for _, entry := range entries {
existing.Set(entry, true, ttl)
}
l.Lock()
l.headers[header] = existing
l.Unlock()
return l
} | go | func (l *Limiter) SetHeader(header string, entries []string) *Limiter {
l.RLock()
existing, found := l.headers[header]
l.RUnlock()
ttl := l.GetHeaderEntryExpirationTTL()
if ttl <= 0 {
ttl = l.generalExpirableOptions.DefaultExpirationTTL
}
if !found {
existing = gocache.New(ttl, l.generalExpirableOptions.ExpireJobInterval)
}
for _, entry := range entries {
existing.Set(entry, true, ttl)
}
l.Lock()
l.headers[header] = existing
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetHeader",
"(",
"header",
"string",
",",
"entries",
"[",
"]",
"string",
")",
"*",
"Limiter",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"existing",
",",
"found",
":=",
"l",
".",
"headers",
"[",
"header",
"]",
"\n",
"l",
".",
"RUnlock",
"(",
")",
"\n\n",
"ttl",
":=",
"l",
".",
"GetHeaderEntryExpirationTTL",
"(",
")",
"\n",
"if",
"ttl",
"<=",
"0",
"{",
"ttl",
"=",
"l",
".",
"generalExpirableOptions",
".",
"DefaultExpirationTTL",
"\n",
"}",
"\n\n",
"if",
"!",
"found",
"{",
"existing",
"=",
"gocache",
".",
"New",
"(",
"ttl",
",",
"l",
".",
"generalExpirableOptions",
".",
"ExpireJobInterval",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"entry",
":=",
"range",
"entries",
"{",
"existing",
".",
"Set",
"(",
"entry",
",",
"true",
",",
"ttl",
")",
"\n",
"}",
"\n\n",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"headers",
"[",
"header",
"]",
"=",
"existing",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // SetHeader is thread-safe way of setting entries of 1 HTTP header. | [
"SetHeader",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"entries",
"of",
"1",
"HTTP",
"header",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L371-L394 |
149,660 | didip/tollbooth | limiter/limiter.go | GetHeader | func (l *Limiter) GetHeader(header string) []string {
l.RLock()
entriesAsGoCache := l.headers[header]
l.RUnlock()
entriesAsMap := entriesAsGoCache.Items()
entries := make([]string, 0)
for entry, _ := range entriesAsMap {
entries = append(entries, entry)
}
return entries
} | go | func (l *Limiter) GetHeader(header string) []string {
l.RLock()
entriesAsGoCache := l.headers[header]
l.RUnlock()
entriesAsMap := entriesAsGoCache.Items()
entries := make([]string, 0)
for entry, _ := range entriesAsMap {
entries = append(entries, entry)
}
return entries
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetHeader",
"(",
"header",
"string",
")",
"[",
"]",
"string",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"entriesAsGoCache",
":=",
"l",
".",
"headers",
"[",
"header",
"]",
"\n",
"l",
".",
"RUnlock",
"(",
")",
"\n\n",
"entriesAsMap",
":=",
"entriesAsGoCache",
".",
"Items",
"(",
")",
"\n",
"entries",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n\n",
"for",
"entry",
",",
"_",
":=",
"range",
"entriesAsMap",
"{",
"entries",
"=",
"append",
"(",
"entries",
",",
"entry",
")",
"\n",
"}",
"\n\n",
"return",
"entries",
"\n",
"}"
]
| // GetHeader is thread-safe way of getting entries of 1 HTTP header. | [
"GetHeader",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"entries",
"of",
"1",
"HTTP",
"header",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L397-L410 |
149,661 | didip/tollbooth | limiter/limiter.go | RemoveHeader | func (l *Limiter) RemoveHeader(header string) *Limiter {
ttl := l.GetHeaderEntryExpirationTTL()
if ttl <= 0 {
ttl = l.generalExpirableOptions.DefaultExpirationTTL
}
l.Lock()
l.headers[header] = gocache.New(ttl, l.generalExpirableOptions.ExpireJobInterval)
l.Unlock()
return l
} | go | func (l *Limiter) RemoveHeader(header string) *Limiter {
ttl := l.GetHeaderEntryExpirationTTL()
if ttl <= 0 {
ttl = l.generalExpirableOptions.DefaultExpirationTTL
}
l.Lock()
l.headers[header] = gocache.New(ttl, l.generalExpirableOptions.ExpireJobInterval)
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"RemoveHeader",
"(",
"header",
"string",
")",
"*",
"Limiter",
"{",
"ttl",
":=",
"l",
".",
"GetHeaderEntryExpirationTTL",
"(",
")",
"\n",
"if",
"ttl",
"<=",
"0",
"{",
"ttl",
"=",
"l",
".",
"generalExpirableOptions",
".",
"DefaultExpirationTTL",
"\n",
"}",
"\n\n",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"headers",
"[",
"header",
"]",
"=",
"gocache",
".",
"New",
"(",
"ttl",
",",
"l",
".",
"generalExpirableOptions",
".",
"ExpireJobInterval",
")",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // RemoveHeader is thread-safe way of removing entries of 1 HTTP header. | [
"RemoveHeader",
"is",
"thread",
"-",
"safe",
"way",
"of",
"removing",
"entries",
"of",
"1",
"HTTP",
"header",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L413-L424 |
149,662 | didip/tollbooth | limiter/limiter.go | RemoveHeaderEntries | func (l *Limiter) RemoveHeaderEntries(header string, entriesForRemoval []string) *Limiter {
l.RLock()
entries, found := l.headers[header]
l.RUnlock()
if !found {
return l
}
for _, toBeRemoved := range entriesForRemoval {
entries.Delete(toBeRemoved)
}
return l
} | go | func (l *Limiter) RemoveHeaderEntries(header string, entriesForRemoval []string) *Limiter {
l.RLock()
entries, found := l.headers[header]
l.RUnlock()
if !found {
return l
}
for _, toBeRemoved := range entriesForRemoval {
entries.Delete(toBeRemoved)
}
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"RemoveHeaderEntries",
"(",
"header",
"string",
",",
"entriesForRemoval",
"[",
"]",
"string",
")",
"*",
"Limiter",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"entries",
",",
"found",
":=",
"l",
".",
"headers",
"[",
"header",
"]",
"\n",
"l",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"!",
"found",
"{",
"return",
"l",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"toBeRemoved",
":=",
"range",
"entriesForRemoval",
"{",
"entries",
".",
"Delete",
"(",
"toBeRemoved",
")",
"\n",
"}",
"\n\n",
"return",
"l",
"\n",
"}"
]
| // RemoveHeaderEntries is thread-safe way of adding new entries to 1 HTTP header rule. | [
"RemoveHeaderEntries",
"is",
"thread",
"-",
"safe",
"way",
"of",
"adding",
"new",
"entries",
"to",
"1",
"HTTP",
"header",
"rule",
"."
]
| b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L427-L441 |
149,663 | AlecAivazis/survey | survey.go | WithStdio | func WithStdio(in terminal.FileReader, out terminal.FileWriter, err io.Writer) AskOpt {
return func(options *AskOptions) error {
options.Stdio.In = in
options.Stdio.Out = out
options.Stdio.Err = err
return nil
}
} | go | func WithStdio(in terminal.FileReader, out terminal.FileWriter, err io.Writer) AskOpt {
return func(options *AskOptions) error {
options.Stdio.In = in
options.Stdio.Out = out
options.Stdio.Err = err
return nil
}
} | [
"func",
"WithStdio",
"(",
"in",
"terminal",
".",
"FileReader",
",",
"out",
"terminal",
".",
"FileWriter",
",",
"err",
"io",
".",
"Writer",
")",
"AskOpt",
"{",
"return",
"func",
"(",
"options",
"*",
"AskOptions",
")",
"error",
"{",
"options",
".",
"Stdio",
".",
"In",
"=",
"in",
"\n",
"options",
".",
"Stdio",
".",
"Out",
"=",
"out",
"\n",
"options",
".",
"Stdio",
".",
"Err",
"=",
"err",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
]
| // WithStdio specifies the standard input, output and error files survey
// interacts with. By default, these are os.Stdin, os.Stdout, and os.Stderr. | [
"WithStdio",
"specifies",
"the",
"standard",
"input",
"output",
"and",
"error",
"files",
"survey",
"interacts",
"with",
".",
"By",
"default",
"these",
"are",
"os",
".",
"Stdin",
"os",
".",
"Stdout",
"and",
"os",
".",
"Stderr",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/survey.go#L67-L74 |
149,664 | AlecAivazis/survey | survey.go | paginate | func paginate(page int, choices []string, sel int) ([]string, int) {
// the number of elements to show in a single page
var pageSize int
// if the select has a specific page size
if page != 0 {
// use the specified one
pageSize = page
// otherwise the select does not have a page size
} else {
// use the package default
pageSize = PageSize
}
var start, end, cursor int
if len(choices) < pageSize {
// if we dont have enough options to fill a page
start = 0
end = len(choices)
cursor = sel
} else if sel < pageSize/2 {
// if we are in the first half page
start = 0
end = pageSize
cursor = sel
} else if len(choices)-sel-1 < pageSize/2 {
// if we are in the last half page
start = len(choices) - pageSize
end = len(choices)
cursor = sel - start
} else {
// somewhere in the middle
above := pageSize / 2
below := pageSize - above
cursor = pageSize / 2
start = sel - above
end = sel + below
}
// return the subset we care about and the index
return choices[start:end], cursor
} | go | func paginate(page int, choices []string, sel int) ([]string, int) {
// the number of elements to show in a single page
var pageSize int
// if the select has a specific page size
if page != 0 {
// use the specified one
pageSize = page
// otherwise the select does not have a page size
} else {
// use the package default
pageSize = PageSize
}
var start, end, cursor int
if len(choices) < pageSize {
// if we dont have enough options to fill a page
start = 0
end = len(choices)
cursor = sel
} else if sel < pageSize/2 {
// if we are in the first half page
start = 0
end = pageSize
cursor = sel
} else if len(choices)-sel-1 < pageSize/2 {
// if we are in the last half page
start = len(choices) - pageSize
end = len(choices)
cursor = sel - start
} else {
// somewhere in the middle
above := pageSize / 2
below := pageSize - above
cursor = pageSize / 2
start = sel - above
end = sel + below
}
// return the subset we care about and the index
return choices[start:end], cursor
} | [
"func",
"paginate",
"(",
"page",
"int",
",",
"choices",
"[",
"]",
"string",
",",
"sel",
"int",
")",
"(",
"[",
"]",
"string",
",",
"int",
")",
"{",
"// the number of elements to show in a single page",
"var",
"pageSize",
"int",
"\n",
"// if the select has a specific page size",
"if",
"page",
"!=",
"0",
"{",
"// use the specified one",
"pageSize",
"=",
"page",
"\n",
"// otherwise the select does not have a page size",
"}",
"else",
"{",
"// use the package default",
"pageSize",
"=",
"PageSize",
"\n",
"}",
"\n\n",
"var",
"start",
",",
"end",
",",
"cursor",
"int",
"\n\n",
"if",
"len",
"(",
"choices",
")",
"<",
"pageSize",
"{",
"// if we dont have enough options to fill a page",
"start",
"=",
"0",
"\n",
"end",
"=",
"len",
"(",
"choices",
")",
"\n",
"cursor",
"=",
"sel",
"\n\n",
"}",
"else",
"if",
"sel",
"<",
"pageSize",
"/",
"2",
"{",
"// if we are in the first half page",
"start",
"=",
"0",
"\n",
"end",
"=",
"pageSize",
"\n",
"cursor",
"=",
"sel",
"\n\n",
"}",
"else",
"if",
"len",
"(",
"choices",
")",
"-",
"sel",
"-",
"1",
"<",
"pageSize",
"/",
"2",
"{",
"// if we are in the last half page",
"start",
"=",
"len",
"(",
"choices",
")",
"-",
"pageSize",
"\n",
"end",
"=",
"len",
"(",
"choices",
")",
"\n",
"cursor",
"=",
"sel",
"-",
"start",
"\n\n",
"}",
"else",
"{",
"// somewhere in the middle",
"above",
":=",
"pageSize",
"/",
"2",
"\n",
"below",
":=",
"pageSize",
"-",
"above",
"\n\n",
"cursor",
"=",
"pageSize",
"/",
"2",
"\n",
"start",
"=",
"sel",
"-",
"above",
"\n",
"end",
"=",
"sel",
"+",
"below",
"\n",
"}",
"\n\n",
"// return the subset we care about and the index",
"return",
"choices",
"[",
"start",
":",
"end",
"]",
",",
"cursor",
"\n",
"}"
]
| // paginate returns a single page of choices given the page size, the total list of
// possible choices, and the current selected index in the total list. | [
"paginate",
"returns",
"a",
"single",
"page",
"of",
"choices",
"given",
"the",
"page",
"size",
"the",
"total",
"list",
"of",
"possible",
"choices",
"and",
"the",
"current",
"selected",
"index",
"in",
"the",
"total",
"list",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/survey.go#L210-L255 |
149,665 | AlecAivazis/survey | transform.go | ComposeTransformers | func ComposeTransformers(transformers ...Transformer) Transformer {
// return a transformer that calls each one sequentially
return func(ans interface{}) interface{} {
// execute each transformer
for _, t := range transformers {
ans = t(ans)
}
return ans
}
} | go | func ComposeTransformers(transformers ...Transformer) Transformer {
// return a transformer that calls each one sequentially
return func(ans interface{}) interface{} {
// execute each transformer
for _, t := range transformers {
ans = t(ans)
}
return ans
}
} | [
"func",
"ComposeTransformers",
"(",
"transformers",
"...",
"Transformer",
")",
"Transformer",
"{",
"// return a transformer that calls each one sequentially",
"return",
"func",
"(",
"ans",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
"{",
"// execute each transformer",
"for",
"_",
",",
"t",
":=",
"range",
"transformers",
"{",
"ans",
"=",
"t",
"(",
"ans",
")",
"\n",
"}",
"\n",
"return",
"ans",
"\n",
"}",
"\n",
"}"
]
| // ComposeTransformers is a variadic function used to create one transformer from many. | [
"ComposeTransformers",
"is",
"a",
"variadic",
"function",
"used",
"to",
"create",
"one",
"transformer",
"from",
"many",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/transform.go#L67-L76 |
149,666 | AlecAivazis/survey | validate.go | Required | func Required(val interface{}) error {
// the reflect value of the result
value := reflect.ValueOf(val)
// if the value passed in is the zero value of the appropriate type
if isZero(value) && value.Kind() != reflect.Bool {
return errors.New("Value is required")
}
return nil
} | go | func Required(val interface{}) error {
// the reflect value of the result
value := reflect.ValueOf(val)
// if the value passed in is the zero value of the appropriate type
if isZero(value) && value.Kind() != reflect.Bool {
return errors.New("Value is required")
}
return nil
} | [
"func",
"Required",
"(",
"val",
"interface",
"{",
"}",
")",
"error",
"{",
"// the reflect value of the result",
"value",
":=",
"reflect",
".",
"ValueOf",
"(",
"val",
")",
"\n\n",
"// if the value passed in is the zero value of the appropriate type",
"if",
"isZero",
"(",
"value",
")",
"&&",
"value",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Bool",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
]
| // Required does not allow an empty value | [
"Required",
"does",
"not",
"allow",
"an",
"empty",
"value"
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/validate.go#L10-L19 |
149,667 | AlecAivazis/survey | validate.go | MaxLength | func MaxLength(length int) Validator {
// return a validator that checks the length of the string
return func(val interface{}) error {
if str, ok := val.(string); ok {
// if the string is longer than the given value
if len([]rune(str)) > length {
// yell loudly
return fmt.Errorf("value is too long. Max length is %v", length)
}
} else {
// otherwise we cannot convert the value into a string and cannot enforce length
return fmt.Errorf("cannot enforce length on response of type %v", reflect.TypeOf(val).Name())
}
// the input is fine
return nil
}
} | go | func MaxLength(length int) Validator {
// return a validator that checks the length of the string
return func(val interface{}) error {
if str, ok := val.(string); ok {
// if the string is longer than the given value
if len([]rune(str)) > length {
// yell loudly
return fmt.Errorf("value is too long. Max length is %v", length)
}
} else {
// otherwise we cannot convert the value into a string and cannot enforce length
return fmt.Errorf("cannot enforce length on response of type %v", reflect.TypeOf(val).Name())
}
// the input is fine
return nil
}
} | [
"func",
"MaxLength",
"(",
"length",
"int",
")",
"Validator",
"{",
"// return a validator that checks the length of the string",
"return",
"func",
"(",
"val",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"str",
",",
"ok",
":=",
"val",
".",
"(",
"string",
")",
";",
"ok",
"{",
"// if the string is longer than the given value",
"if",
"len",
"(",
"[",
"]",
"rune",
"(",
"str",
")",
")",
">",
"length",
"{",
"// yell loudly",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"length",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// otherwise we cannot convert the value into a string and cannot enforce length",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"val",
")",
".",
"Name",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// the input is fine",
"return",
"nil",
"\n",
"}",
"\n",
"}"
]
| // MaxLength requires that the string is no longer than the specified value | [
"MaxLength",
"requires",
"that",
"the",
"string",
"is",
"no",
"longer",
"than",
"the",
"specified",
"value"
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/validate.go#L22-L39 |
149,668 | AlecAivazis/survey | validate.go | ComposeValidators | func ComposeValidators(validators ...Validator) Validator {
// return a validator that calls each one sequentially
return func(val interface{}) error {
// execute each validator
for _, validator := range validators {
// if the answer's value is not valid
if err := validator(val); err != nil {
// return the error
return err
}
}
// we passed all validators, the answer is valid
return nil
}
} | go | func ComposeValidators(validators ...Validator) Validator {
// return a validator that calls each one sequentially
return func(val interface{}) error {
// execute each validator
for _, validator := range validators {
// if the answer's value is not valid
if err := validator(val); err != nil {
// return the error
return err
}
}
// we passed all validators, the answer is valid
return nil
}
} | [
"func",
"ComposeValidators",
"(",
"validators",
"...",
"Validator",
")",
"Validator",
"{",
"// return a validator that calls each one sequentially",
"return",
"func",
"(",
"val",
"interface",
"{",
"}",
")",
"error",
"{",
"// execute each validator",
"for",
"_",
",",
"validator",
":=",
"range",
"validators",
"{",
"// if the answer's value is not valid",
"if",
"err",
":=",
"validator",
"(",
"val",
")",
";",
"err",
"!=",
"nil",
"{",
"// return the error",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// we passed all validators, the answer is valid",
"return",
"nil",
"\n",
"}",
"\n",
"}"
]
| // ComposeValidators is a variadic function used to create one validator from many. | [
"ComposeValidators",
"is",
"a",
"variadic",
"function",
"used",
"to",
"create",
"one",
"validator",
"from",
"many",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/validate.go#L62-L76 |
149,669 | AlecAivazis/survey | validate.go | isZero | func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Slice, reflect.Map:
return v.Len() == 0
}
// compare the types directly with more general coverage
return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface())
} | go | func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Slice, reflect.Map:
return v.Len() == 0
}
// compare the types directly with more general coverage
return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface())
} | [
"func",
"isZero",
"(",
"v",
"reflect",
".",
"Value",
")",
"bool",
"{",
"switch",
"v",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Map",
":",
"return",
"v",
".",
"Len",
"(",
")",
"==",
"0",
"\n",
"}",
"\n\n",
"// compare the types directly with more general coverage",
"return",
"reflect",
".",
"DeepEqual",
"(",
"v",
".",
"Interface",
"(",
")",
",",
"reflect",
".",
"Zero",
"(",
"v",
".",
"Type",
"(",
")",
")",
".",
"Interface",
"(",
")",
")",
"\n",
"}"
]
| // isZero returns true if the passed value is the zero object | [
"isZero",
"returns",
"true",
"if",
"the",
"passed",
"value",
"is",
"the",
"zero",
"object"
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/validate.go#L79-L87 |
149,670 | AlecAivazis/survey | terminal/cursor.go | Up | func (c *Cursor) Up(n int) {
fmt.Fprintf(c.Out, "\x1b[%dA", n)
} | go | func (c *Cursor) Up(n int) {
fmt.Fprintf(c.Out, "\x1b[%dA", n)
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"Up",
"(",
"n",
"int",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
".",
"Out",
",",
"\"",
"\\x1b",
"\"",
",",
"n",
")",
"\n",
"}"
]
| // Up moves the cursor n cells to up. | [
"Up",
"moves",
"the",
"cursor",
"n",
"cells",
"to",
"up",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L23-L25 |
149,671 | AlecAivazis/survey | terminal/cursor.go | Down | func (c *Cursor) Down(n int) {
fmt.Fprintf(c.Out, "\x1b[%dB", n)
} | go | func (c *Cursor) Down(n int) {
fmt.Fprintf(c.Out, "\x1b[%dB", n)
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"Down",
"(",
"n",
"int",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
".",
"Out",
",",
"\"",
"\\x1b",
"\"",
",",
"n",
")",
"\n",
"}"
]
| // Down moves the cursor n cells to down. | [
"Down",
"moves",
"the",
"cursor",
"n",
"cells",
"to",
"down",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L28-L30 |
149,672 | AlecAivazis/survey | terminal/cursor.go | Forward | func (c *Cursor) Forward(n int) {
fmt.Fprintf(c.Out, "\x1b[%dC", n)
} | go | func (c *Cursor) Forward(n int) {
fmt.Fprintf(c.Out, "\x1b[%dC", n)
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"Forward",
"(",
"n",
"int",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
".",
"Out",
",",
"\"",
"\\x1b",
"\"",
",",
"n",
")",
"\n",
"}"
]
| // Forward moves the cursor n cells to right. | [
"Forward",
"moves",
"the",
"cursor",
"n",
"cells",
"to",
"right",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L33-L35 |
149,673 | AlecAivazis/survey | terminal/cursor.go | Back | func (c *Cursor) Back(n int) {
fmt.Fprintf(c.Out, "\x1b[%dD", n)
} | go | func (c *Cursor) Back(n int) {
fmt.Fprintf(c.Out, "\x1b[%dD", n)
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"Back",
"(",
"n",
"int",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
".",
"Out",
",",
"\"",
"\\x1b",
"\"",
",",
"n",
")",
"\n",
"}"
]
| // Back moves the cursor n cells to left. | [
"Back",
"moves",
"the",
"cursor",
"n",
"cells",
"to",
"left",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L38-L40 |
149,674 | AlecAivazis/survey | terminal/cursor.go | NextLine | func (c *Cursor) NextLine(n int) {
fmt.Fprintf(c.Out, "\x1b[%dE", n)
} | go | func (c *Cursor) NextLine(n int) {
fmt.Fprintf(c.Out, "\x1b[%dE", n)
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"NextLine",
"(",
"n",
"int",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
".",
"Out",
",",
"\"",
"\\x1b",
"\"",
",",
"n",
")",
"\n",
"}"
]
| // NextLine moves cursor to beginning of the line n lines down. | [
"NextLine",
"moves",
"cursor",
"to",
"beginning",
"of",
"the",
"line",
"n",
"lines",
"down",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L43-L45 |
149,675 | AlecAivazis/survey | terminal/cursor.go | PreviousLine | func (c *Cursor) PreviousLine(n int) {
fmt.Fprintf(c.Out, "\x1b[%dF", n)
} | go | func (c *Cursor) PreviousLine(n int) {
fmt.Fprintf(c.Out, "\x1b[%dF", n)
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"PreviousLine",
"(",
"n",
"int",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
".",
"Out",
",",
"\"",
"\\x1b",
"\"",
",",
"n",
")",
"\n",
"}"
]
| // PreviousLine moves cursor to beginning of the line n lines up. | [
"PreviousLine",
"moves",
"cursor",
"to",
"beginning",
"of",
"the",
"line",
"n",
"lines",
"up",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L48-L50 |
149,676 | AlecAivazis/survey | terminal/cursor.go | HorizontalAbsolute | func (c *Cursor) HorizontalAbsolute(x int) {
fmt.Fprintf(c.Out, "\x1b[%dG", x)
} | go | func (c *Cursor) HorizontalAbsolute(x int) {
fmt.Fprintf(c.Out, "\x1b[%dG", x)
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"HorizontalAbsolute",
"(",
"x",
"int",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
".",
"Out",
",",
"\"",
"\\x1b",
"\"",
",",
"x",
")",
"\n",
"}"
]
| // HorizontalAbsolute moves cursor horizontally to x. | [
"HorizontalAbsolute",
"moves",
"cursor",
"horizontally",
"to",
"x",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L53-L55 |
149,677 | AlecAivazis/survey | terminal/cursor.go | Move | func (c *Cursor) Move(x int, y int) {
fmt.Fprintf(c.Out, "\x1b[%d;%df", x, y)
} | go | func (c *Cursor) Move(x int, y int) {
fmt.Fprintf(c.Out, "\x1b[%d;%df", x, y)
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"Move",
"(",
"x",
"int",
",",
"y",
"int",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
".",
"Out",
",",
"\"",
"\\x1b",
"\"",
",",
"x",
",",
"y",
")",
"\n",
"}"
]
| // Move moves the cursor to a specific x,y location. | [
"Move",
"moves",
"the",
"cursor",
"to",
"a",
"specific",
"x",
"y",
"location",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L68-L70 |
149,678 | AlecAivazis/survey | terminal/cursor.go | MoveNextLine | func (c *Cursor) MoveNextLine(cur *Coord, terminalSize *Coord) {
if cur.Y == terminalSize.Y {
fmt.Fprintln(c.Out)
}
c.NextLine(1)
} | go | func (c *Cursor) MoveNextLine(cur *Coord, terminalSize *Coord) {
if cur.Y == terminalSize.Y {
fmt.Fprintln(c.Out)
}
c.NextLine(1)
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"MoveNextLine",
"(",
"cur",
"*",
"Coord",
",",
"terminalSize",
"*",
"Coord",
")",
"{",
"if",
"cur",
".",
"Y",
"==",
"terminalSize",
".",
"Y",
"{",
"fmt",
".",
"Fprintln",
"(",
"c",
".",
"Out",
")",
"\n",
"}",
"\n",
"c",
".",
"NextLine",
"(",
"1",
")",
"\n",
"}"
]
| // for comparability purposes between windows
// in unix we need to print out a new line on some terminals | [
"for",
"comparability",
"purposes",
"between",
"windows",
"in",
"unix",
"we",
"need",
"to",
"print",
"out",
"a",
"new",
"line",
"on",
"some",
"terminals"
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L84-L89 |
149,679 | AlecAivazis/survey | terminal/cursor.go | Location | func (c *Cursor) Location(buf *bytes.Buffer) (*Coord, error) {
// ANSI escape sequence for DSR - Device Status Report
// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences
fmt.Fprint(c.Out, "\x1b[6n")
// There may be input in Stdin prior to CursorLocation so make sure we don't
// drop those bytes.
var loc []int
var match string
for loc == nil {
// Reports the cursor position (CPR) to the application as (as though typed at
// the keyboard) ESC[n;mR, where n is the row and m is the column.
reader := bufio.NewReader(c.In)
text, err := reader.ReadSlice('R')
if err != nil {
return nil, err
}
loc = dsrPattern.FindStringIndex(string(text))
if loc == nil {
// Stdin contains R that doesn't match DSR.
buf.Write(text)
} else {
buf.Write(text[:loc[0]])
match = string(text[loc[0]:loc[1]])
}
}
matches := dsrPattern.FindStringSubmatch(string(match))
if len(matches) != 3 {
return nil, fmt.Errorf("incorrect number of matches: %d", len(matches))
}
col, err := strconv.Atoi(matches[2])
if err != nil {
return nil, err
}
row, err := strconv.Atoi(matches[1])
if err != nil {
return nil, err
}
return &Coord{Short(col), Short(row)}, nil
} | go | func (c *Cursor) Location(buf *bytes.Buffer) (*Coord, error) {
// ANSI escape sequence for DSR - Device Status Report
// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences
fmt.Fprint(c.Out, "\x1b[6n")
// There may be input in Stdin prior to CursorLocation so make sure we don't
// drop those bytes.
var loc []int
var match string
for loc == nil {
// Reports the cursor position (CPR) to the application as (as though typed at
// the keyboard) ESC[n;mR, where n is the row and m is the column.
reader := bufio.NewReader(c.In)
text, err := reader.ReadSlice('R')
if err != nil {
return nil, err
}
loc = dsrPattern.FindStringIndex(string(text))
if loc == nil {
// Stdin contains R that doesn't match DSR.
buf.Write(text)
} else {
buf.Write(text[:loc[0]])
match = string(text[loc[0]:loc[1]])
}
}
matches := dsrPattern.FindStringSubmatch(string(match))
if len(matches) != 3 {
return nil, fmt.Errorf("incorrect number of matches: %d", len(matches))
}
col, err := strconv.Atoi(matches[2])
if err != nil {
return nil, err
}
row, err := strconv.Atoi(matches[1])
if err != nil {
return nil, err
}
return &Coord{Short(col), Short(row)}, nil
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"Location",
"(",
"buf",
"*",
"bytes",
".",
"Buffer",
")",
"(",
"*",
"Coord",
",",
"error",
")",
"{",
"// ANSI escape sequence for DSR - Device Status Report",
"// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences",
"fmt",
".",
"Fprint",
"(",
"c",
".",
"Out",
",",
"\"",
"\\x1b",
"\"",
")",
"\n\n",
"// There may be input in Stdin prior to CursorLocation so make sure we don't",
"// drop those bytes.",
"var",
"loc",
"[",
"]",
"int",
"\n",
"var",
"match",
"string",
"\n",
"for",
"loc",
"==",
"nil",
"{",
"// Reports the cursor position (CPR) to the application as (as though typed at",
"// the keyboard) ESC[n;mR, where n is the row and m is the column.",
"reader",
":=",
"bufio",
".",
"NewReader",
"(",
"c",
".",
"In",
")",
"\n",
"text",
",",
"err",
":=",
"reader",
".",
"ReadSlice",
"(",
"'R'",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"loc",
"=",
"dsrPattern",
".",
"FindStringIndex",
"(",
"string",
"(",
"text",
")",
")",
"\n",
"if",
"loc",
"==",
"nil",
"{",
"// Stdin contains R that doesn't match DSR.",
"buf",
".",
"Write",
"(",
"text",
")",
"\n",
"}",
"else",
"{",
"buf",
".",
"Write",
"(",
"text",
"[",
":",
"loc",
"[",
"0",
"]",
"]",
")",
"\n",
"match",
"=",
"string",
"(",
"text",
"[",
"loc",
"[",
"0",
"]",
":",
"loc",
"[",
"1",
"]",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"matches",
":=",
"dsrPattern",
".",
"FindStringSubmatch",
"(",
"string",
"(",
"match",
")",
")",
"\n",
"if",
"len",
"(",
"matches",
")",
"!=",
"3",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"matches",
")",
")",
"\n",
"}",
"\n\n",
"col",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"matches",
"[",
"2",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"row",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"matches",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"Coord",
"{",
"Short",
"(",
"col",
")",
",",
"Short",
"(",
"row",
")",
"}",
",",
"nil",
"\n",
"}"
]
| // Location returns the current location of the cursor in the terminal | [
"Location",
"returns",
"the",
"current",
"location",
"of",
"the",
"cursor",
"in",
"the",
"terminal"
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L92-L136 |
149,680 | AlecAivazis/survey | terminal/cursor.go | Size | func (c *Cursor) Size(buf *bytes.Buffer) (*Coord, error) {
// the general approach here is to move the cursor to the very bottom
// of the terminal, ask for the current location and then move the
// cursor back where we started
// hide the cursor (so it doesn't blink when getting the size of the terminal)
c.Hide()
// save the current location of the cursor
c.Save()
// move the cursor to the very bottom of the terminal
c.Move(999, 999)
// ask for the current location
bottom, err := c.Location(buf)
if err != nil {
return nil, err
}
// move back where we began
c.Restore()
// show the cursor
c.Show()
// sice the bottom was calcuated in the lower right corner, it
// is the dimensions we are looking for
return bottom, nil
} | go | func (c *Cursor) Size(buf *bytes.Buffer) (*Coord, error) {
// the general approach here is to move the cursor to the very bottom
// of the terminal, ask for the current location and then move the
// cursor back where we started
// hide the cursor (so it doesn't blink when getting the size of the terminal)
c.Hide()
// save the current location of the cursor
c.Save()
// move the cursor to the very bottom of the terminal
c.Move(999, 999)
// ask for the current location
bottom, err := c.Location(buf)
if err != nil {
return nil, err
}
// move back where we began
c.Restore()
// show the cursor
c.Show()
// sice the bottom was calcuated in the lower right corner, it
// is the dimensions we are looking for
return bottom, nil
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"Size",
"(",
"buf",
"*",
"bytes",
".",
"Buffer",
")",
"(",
"*",
"Coord",
",",
"error",
")",
"{",
"// the general approach here is to move the cursor to the very bottom",
"// of the terminal, ask for the current location and then move the",
"// cursor back where we started",
"// hide the cursor (so it doesn't blink when getting the size of the terminal)",
"c",
".",
"Hide",
"(",
")",
"\n",
"// save the current location of the cursor",
"c",
".",
"Save",
"(",
")",
"\n\n",
"// move the cursor to the very bottom of the terminal",
"c",
".",
"Move",
"(",
"999",
",",
"999",
")",
"\n\n",
"// ask for the current location",
"bottom",
",",
"err",
":=",
"c",
".",
"Location",
"(",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// move back where we began",
"c",
".",
"Restore",
"(",
")",
"\n\n",
"// show the cursor",
"c",
".",
"Show",
"(",
")",
"\n",
"// sice the bottom was calcuated in the lower right corner, it",
"// is the dimensions we are looking for",
"return",
"bottom",
",",
"nil",
"\n",
"}"
]
| // Size returns the height and width of the terminal. | [
"Size",
"returns",
"the",
"height",
"and",
"width",
"of",
"the",
"terminal",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L147-L174 |
149,681 | AlecAivazis/survey | multiselect.go | Cleanup | func (m *MultiSelect) Cleanup(val interface{}) error {
// execute the output summary template with the answer
return m.Render(
MultiSelectQuestionTemplate,
MultiSelectTemplateData{
MultiSelect: *m,
SelectedIndex: m.selectedIndex,
Checked: m.checked,
Answer: strings.Join(val.([]string), ", "),
ShowAnswer: true,
},
)
} | go | func (m *MultiSelect) Cleanup(val interface{}) error {
// execute the output summary template with the answer
return m.Render(
MultiSelectQuestionTemplate,
MultiSelectTemplateData{
MultiSelect: *m,
SelectedIndex: m.selectedIndex,
Checked: m.checked,
Answer: strings.Join(val.([]string), ", "),
ShowAnswer: true,
},
)
} | [
"func",
"(",
"m",
"*",
"MultiSelect",
")",
"Cleanup",
"(",
"val",
"interface",
"{",
"}",
")",
"error",
"{",
"// execute the output summary template with the answer",
"return",
"m",
".",
"Render",
"(",
"MultiSelectQuestionTemplate",
",",
"MultiSelectTemplateData",
"{",
"MultiSelect",
":",
"*",
"m",
",",
"SelectedIndex",
":",
"m",
".",
"selectedIndex",
",",
"Checked",
":",
"m",
".",
"checked",
",",
"Answer",
":",
"strings",
".",
"Join",
"(",
"val",
".",
"(",
"[",
"]",
"string",
")",
",",
"\"",
"\"",
")",
",",
"ShowAnswer",
":",
"true",
",",
"}",
",",
")",
"\n",
"}"
]
| // Cleanup removes the options section, and renders the ask like a normal question. | [
"Cleanup",
"removes",
"the",
"options",
"section",
"and",
"renders",
"the",
"ask",
"like",
"a",
"normal",
"question",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/multiselect.go#L236-L248 |
149,682 | AlecAivazis/survey | terminal/runereader_posix.go | SetTermMode | func (rr *RuneReader) SetTermMode() error {
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlReadTermios, uintptr(unsafe.Pointer(&rr.state.term)), 0, 0, 0); err != 0 {
return err
}
newState := rr.state.term
newState.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 {
return err
}
return nil
} | go | func (rr *RuneReader) SetTermMode() error {
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlReadTermios, uintptr(unsafe.Pointer(&rr.state.term)), 0, 0, 0); err != 0 {
return err
}
newState := rr.state.term
newState.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 {
return err
}
return nil
} | [
"func",
"(",
"rr",
"*",
"RuneReader",
")",
"SetTermMode",
"(",
")",
"error",
"{",
"if",
"_",
",",
"_",
",",
"err",
":=",
"syscall",
".",
"Syscall6",
"(",
"syscall",
".",
"SYS_IOCTL",
",",
"uintptr",
"(",
"rr",
".",
"stdio",
".",
"In",
".",
"Fd",
"(",
")",
")",
",",
"ioctlReadTermios",
",",
"uintptr",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"rr",
".",
"state",
".",
"term",
")",
")",
",",
"0",
",",
"0",
",",
"0",
")",
";",
"err",
"!=",
"0",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"newState",
":=",
"rr",
".",
"state",
".",
"term",
"\n",
"newState",
".",
"Lflag",
"&^=",
"syscall",
".",
"ECHO",
"|",
"syscall",
".",
"ECHONL",
"|",
"syscall",
".",
"ICANON",
"|",
"syscall",
".",
"ISIG",
"\n\n",
"if",
"_",
",",
"_",
",",
"err",
":=",
"syscall",
".",
"Syscall6",
"(",
"syscall",
".",
"SYS_IOCTL",
",",
"uintptr",
"(",
"rr",
".",
"stdio",
".",
"In",
".",
"Fd",
"(",
")",
")",
",",
"ioctlWriteTermios",
",",
"uintptr",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"newState",
")",
")",
",",
"0",
",",
"0",
",",
"0",
")",
";",
"err",
"!=",
"0",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
]
| // For reading runes we just want to disable echo. | [
"For",
"reading",
"runes",
"we",
"just",
"want",
"to",
"disable",
"echo",
"."
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/runereader_posix.go#L41-L54 |
149,683 | AlecAivazis/survey | confirm.go | Cleanup | func (c *Confirm) Cleanup(val interface{}) error {
// if the value was previously true
ans := yesNo(val.(bool))
// render the template
return c.Render(
ConfirmQuestionTemplate,
ConfirmTemplateData{Confirm: *c, Answer: ans},
)
} | go | func (c *Confirm) Cleanup(val interface{}) error {
// if the value was previously true
ans := yesNo(val.(bool))
// render the template
return c.Render(
ConfirmQuestionTemplate,
ConfirmTemplateData{Confirm: *c, Answer: ans},
)
} | [
"func",
"(",
"c",
"*",
"Confirm",
")",
"Cleanup",
"(",
"val",
"interface",
"{",
"}",
")",
"error",
"{",
"// if the value was previously true",
"ans",
":=",
"yesNo",
"(",
"val",
".",
"(",
"bool",
")",
")",
"\n",
"// render the template",
"return",
"c",
".",
"Render",
"(",
"ConfirmQuestionTemplate",
",",
"ConfirmTemplateData",
"{",
"Confirm",
":",
"*",
"c",
",",
"Answer",
":",
"ans",
"}",
",",
")",
"\n",
"}"
]
| // Cleanup overwrite the line with the finalized formatted version | [
"Cleanup",
"overwrite",
"the",
"line",
"with",
"the",
"finalized",
"formatted",
"version"
]
| a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/confirm.go#L130-L138 |
149,684 | golang/gddo | httputil/respbuf.go | Write | func (rb *ResponseBuffer) Write(p []byte) (int, error) {
return rb.buf.Write(p)
} | go | func (rb *ResponseBuffer) Write(p []byte) (int, error) {
return rb.buf.Write(p)
} | [
"func",
"(",
"rb",
"*",
"ResponseBuffer",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"rb",
".",
"buf",
".",
"Write",
"(",
"p",
")",
"\n",
"}"
]
| // Write implements the http.ResponseWriter interface. | [
"Write",
"implements",
"the",
"http",
".",
"ResponseWriter",
"interface",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/respbuf.go#L24-L26 |
149,685 | golang/gddo | httputil/respbuf.go | Header | func (rb *ResponseBuffer) Header() http.Header {
if rb.header == nil {
rb.header = make(http.Header)
}
return rb.header
} | go | func (rb *ResponseBuffer) Header() http.Header {
if rb.header == nil {
rb.header = make(http.Header)
}
return rb.header
} | [
"func",
"(",
"rb",
"*",
"ResponseBuffer",
")",
"Header",
"(",
")",
"http",
".",
"Header",
"{",
"if",
"rb",
".",
"header",
"==",
"nil",
"{",
"rb",
".",
"header",
"=",
"make",
"(",
"http",
".",
"Header",
")",
"\n",
"}",
"\n",
"return",
"rb",
".",
"header",
"\n",
"}"
]
| // Header implements the http.ResponseWriter interface. | [
"Header",
"implements",
"the",
"http",
".",
"ResponseWriter",
"interface",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/respbuf.go#L34-L39 |
149,686 | golang/gddo | httputil/httputil.go | StripPort | func StripPort(s string) string {
if h, _, err := net.SplitHostPort(s); err == nil {
s = h
}
return s
} | go | func StripPort(s string) string {
if h, _, err := net.SplitHostPort(s); err == nil {
s = h
}
return s
} | [
"func",
"StripPort",
"(",
"s",
"string",
")",
"string",
"{",
"if",
"h",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"s",
")",
";",
"err",
"==",
"nil",
"{",
"s",
"=",
"h",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}"
]
| // StripPort removes the port specification from an address. | [
"StripPort",
"removes",
"the",
"port",
"specification",
"from",
"an",
"address",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/httputil.go#L16-L21 |
149,687 | golang/gddo | doc/builder.go | synopsis | func synopsis(s string) string {
parts := strings.SplitN(s, "\n\n", 2)
s = parts[0]
var buf []byte
const (
other = iota
period
space
)
last := space
Loop:
for i := 0; i < len(s); i++ {
b := s[i]
switch b {
case ' ', '\t', '\r', '\n':
switch last {
case period:
break Loop
case other:
buf = append(buf, ' ')
last = space
}
case '.':
last = period
buf = append(buf, b)
default:
last = other
buf = append(buf, b)
}
}
// Ensure that synopsis fits an App Engine datastore text property.
const m = 400
if len(buf) > m {
buf = buf[:m]
if i := bytes.LastIndex(buf, []byte{' '}); i >= 0 {
buf = buf[:i]
}
buf = append(buf, " ..."...)
}
s = string(buf)
r, n := utf8.DecodeRuneInString(s)
if n < 0 || unicode.IsPunct(r) || unicode.IsSymbol(r) {
// ignore Markdown headings, editor settings, Go build constraints, and * in poorly formatted block comments.
s = ""
} else {
for _, prefix := range badSynopsisPrefixes {
if strings.HasPrefix(s, prefix) {
s = ""
break
}
}
}
return s
} | go | func synopsis(s string) string {
parts := strings.SplitN(s, "\n\n", 2)
s = parts[0]
var buf []byte
const (
other = iota
period
space
)
last := space
Loop:
for i := 0; i < len(s); i++ {
b := s[i]
switch b {
case ' ', '\t', '\r', '\n':
switch last {
case period:
break Loop
case other:
buf = append(buf, ' ')
last = space
}
case '.':
last = period
buf = append(buf, b)
default:
last = other
buf = append(buf, b)
}
}
// Ensure that synopsis fits an App Engine datastore text property.
const m = 400
if len(buf) > m {
buf = buf[:m]
if i := bytes.LastIndex(buf, []byte{' '}); i >= 0 {
buf = buf[:i]
}
buf = append(buf, " ..."...)
}
s = string(buf)
r, n := utf8.DecodeRuneInString(s)
if n < 0 || unicode.IsPunct(r) || unicode.IsSymbol(r) {
// ignore Markdown headings, editor settings, Go build constraints, and * in poorly formatted block comments.
s = ""
} else {
for _, prefix := range badSynopsisPrefixes {
if strings.HasPrefix(s, prefix) {
s = ""
break
}
}
}
return s
} | [
"func",
"synopsis",
"(",
"s",
"string",
")",
"string",
"{",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"s",
",",
"\"",
"\\n",
"\\n",
"\"",
",",
"2",
")",
"\n",
"s",
"=",
"parts",
"[",
"0",
"]",
"\n\n",
"var",
"buf",
"[",
"]",
"byte",
"\n",
"const",
"(",
"other",
"=",
"iota",
"\n",
"period",
"\n",
"space",
"\n",
")",
"\n",
"last",
":=",
"space",
"\n",
"Loop",
":",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"s",
")",
";",
"i",
"++",
"{",
"b",
":=",
"s",
"[",
"i",
"]",
"\n",
"switch",
"b",
"{",
"case",
"' '",
",",
"'\\t'",
",",
"'\\r'",
",",
"'\\n'",
":",
"switch",
"last",
"{",
"case",
"period",
":",
"break",
"Loop",
"\n",
"case",
"other",
":",
"buf",
"=",
"append",
"(",
"buf",
",",
"' '",
")",
"\n",
"last",
"=",
"space",
"\n",
"}",
"\n",
"case",
"'.'",
":",
"last",
"=",
"period",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"b",
")",
"\n",
"default",
":",
"last",
"=",
"other",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"b",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Ensure that synopsis fits an App Engine datastore text property.",
"const",
"m",
"=",
"400",
"\n",
"if",
"len",
"(",
"buf",
")",
">",
"m",
"{",
"buf",
"=",
"buf",
"[",
":",
"m",
"]",
"\n",
"if",
"i",
":=",
"bytes",
".",
"LastIndex",
"(",
"buf",
",",
"[",
"]",
"byte",
"{",
"' '",
"}",
")",
";",
"i",
">=",
"0",
"{",
"buf",
"=",
"buf",
"[",
":",
"i",
"]",
"\n",
"}",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"\"",
"\"",
"...",
")",
"\n",
"}",
"\n\n",
"s",
"=",
"string",
"(",
"buf",
")",
"\n\n",
"r",
",",
"n",
":=",
"utf8",
".",
"DecodeRuneInString",
"(",
"s",
")",
"\n",
"if",
"n",
"<",
"0",
"||",
"unicode",
".",
"IsPunct",
"(",
"r",
")",
"||",
"unicode",
".",
"IsSymbol",
"(",
"r",
")",
"{",
"// ignore Markdown headings, editor settings, Go build constraints, and * in poorly formatted block comments.",
"s",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"for",
"_",
",",
"prefix",
":=",
"range",
"badSynopsisPrefixes",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"s",
",",
"prefix",
")",
"{",
"s",
"=",
"\"",
"\"",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"s",
"\n",
"}"
]
| // synopsis extracts the first sentence from s. All runs of whitespace are
// replaced by a single space. | [
"synopsis",
"extracts",
"the",
"first",
"sentence",
"from",
"s",
".",
"All",
"runs",
"of",
"whitespace",
"are",
"replaced",
"by",
"a",
"single",
"space",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/doc/builder.go#L46-L105 |
149,688 | golang/gddo | doc/builder.go | addReferences | func addReferences(references map[string]bool, s []byte) {
for _, pat := range referencesPats {
for _, m := range pat.FindAllSubmatch(s, -1) {
p := string(m[1])
if gosrc.IsValidRemotePath(p) {
references[p] = true
}
}
}
} | go | func addReferences(references map[string]bool, s []byte) {
for _, pat := range referencesPats {
for _, m := range pat.FindAllSubmatch(s, -1) {
p := string(m[1])
if gosrc.IsValidRemotePath(p) {
references[p] = true
}
}
}
} | [
"func",
"addReferences",
"(",
"references",
"map",
"[",
"string",
"]",
"bool",
",",
"s",
"[",
"]",
"byte",
")",
"{",
"for",
"_",
",",
"pat",
":=",
"range",
"referencesPats",
"{",
"for",
"_",
",",
"m",
":=",
"range",
"pat",
".",
"FindAllSubmatch",
"(",
"s",
",",
"-",
"1",
")",
"{",
"p",
":=",
"string",
"(",
"m",
"[",
"1",
"]",
")",
"\n",
"if",
"gosrc",
".",
"IsValidRemotePath",
"(",
"p",
")",
"{",
"references",
"[",
"p",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
]
| // addReferences adds packages referenced in plain text s. | [
"addReferences",
"adds",
"packages",
"referenced",
"in",
"plain",
"text",
"s",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/doc/builder.go#L121-L130 |
149,689 | golang/gddo | doc/builder.go | SetDefaultGOOS | func SetDefaultGOOS(goos string) {
if goos == "" {
return
}
var i int
for ; i < len(goEnvs); i++ {
if goEnvs[i].GOOS == goos {
break
}
}
switch i {
case 0:
return
case len(goEnvs):
env := goEnvs[0]
env.GOOS = goos
goEnvs = append(goEnvs, env)
}
goEnvs[0], goEnvs[i] = goEnvs[i], goEnvs[0]
} | go | func SetDefaultGOOS(goos string) {
if goos == "" {
return
}
var i int
for ; i < len(goEnvs); i++ {
if goEnvs[i].GOOS == goos {
break
}
}
switch i {
case 0:
return
case len(goEnvs):
env := goEnvs[0]
env.GOOS = goos
goEnvs = append(goEnvs, env)
}
goEnvs[0], goEnvs[i] = goEnvs[i], goEnvs[0]
} | [
"func",
"SetDefaultGOOS",
"(",
"goos",
"string",
")",
"{",
"if",
"goos",
"==",
"\"",
"\"",
"{",
"return",
"\n",
"}",
"\n",
"var",
"i",
"int",
"\n",
"for",
";",
"i",
"<",
"len",
"(",
"goEnvs",
")",
";",
"i",
"++",
"{",
"if",
"goEnvs",
"[",
"i",
"]",
".",
"GOOS",
"==",
"goos",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"switch",
"i",
"{",
"case",
"0",
":",
"return",
"\n",
"case",
"len",
"(",
"goEnvs",
")",
":",
"env",
":=",
"goEnvs",
"[",
"0",
"]",
"\n",
"env",
".",
"GOOS",
"=",
"goos",
"\n",
"goEnvs",
"=",
"append",
"(",
"goEnvs",
",",
"env",
")",
"\n",
"}",
"\n",
"goEnvs",
"[",
"0",
"]",
",",
"goEnvs",
"[",
"i",
"]",
"=",
"goEnvs",
"[",
"i",
"]",
",",
"goEnvs",
"[",
"0",
"]",
"\n",
"}"
]
| // SetDefaultGOOS sets given GOOS value as default one to use when building
// package documents. SetDefaultGOOS has no effect on some windows-only
// packages. | [
"SetDefaultGOOS",
"sets",
"given",
"GOOS",
"value",
"as",
"default",
"one",
"to",
"use",
"when",
"building",
"package",
"documents",
".",
"SetDefaultGOOS",
"has",
"no",
"effect",
"on",
"some",
"windows",
"-",
"only",
"packages",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/doc/builder.go#L475-L494 |
149,690 | golang/gddo | httputil/header/header.go | Copy | func Copy(header http.Header) http.Header {
h := make(http.Header)
for k, vs := range header {
h[k] = vs
}
return h
} | go | func Copy(header http.Header) http.Header {
h := make(http.Header)
for k, vs := range header {
h[k] = vs
}
return h
} | [
"func",
"Copy",
"(",
"header",
"http",
".",
"Header",
")",
"http",
".",
"Header",
"{",
"h",
":=",
"make",
"(",
"http",
".",
"Header",
")",
"\n",
"for",
"k",
",",
"vs",
":=",
"range",
"header",
"{",
"h",
"[",
"k",
"]",
"=",
"vs",
"\n",
"}",
"\n",
"return",
"h",
"\n",
"}"
]
| // Copy returns a shallow copy of the header. | [
"Copy",
"returns",
"a",
"shallow",
"copy",
"of",
"the",
"header",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/header/header.go#L59-L65 |
149,691 | golang/gddo | httputil/header/header.go | ParseTime | func ParseTime(header http.Header, key string) time.Time {
if s := header.Get(key); s != "" {
for _, layout := range timeLayouts {
if t, err := time.Parse(layout, s); err == nil {
return t.UTC()
}
}
}
return time.Time{}
} | go | func ParseTime(header http.Header, key string) time.Time {
if s := header.Get(key); s != "" {
for _, layout := range timeLayouts {
if t, err := time.Parse(layout, s); err == nil {
return t.UTC()
}
}
}
return time.Time{}
} | [
"func",
"ParseTime",
"(",
"header",
"http",
".",
"Header",
",",
"key",
"string",
")",
"time",
".",
"Time",
"{",
"if",
"s",
":=",
"header",
".",
"Get",
"(",
"key",
")",
";",
"s",
"!=",
"\"",
"\"",
"{",
"for",
"_",
",",
"layout",
":=",
"range",
"timeLayouts",
"{",
"if",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"layout",
",",
"s",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"t",
".",
"UTC",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"time",
".",
"Time",
"{",
"}",
"\n",
"}"
]
| // ParseTime parses the header as time. The zero value is returned if the
// header is not present or there is an error parsing the
// header. | [
"ParseTime",
"parses",
"the",
"header",
"as",
"time",
".",
"The",
"zero",
"value",
"is",
"returned",
"if",
"the",
"header",
"is",
"not",
"present",
"or",
"there",
"is",
"an",
"error",
"parsing",
"the",
"header",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/header/header.go#L72-L81 |
149,692 | golang/gddo | httputil/header/header.go | ParseList | func ParseList(header http.Header, key string) []string {
var result []string
for _, s := range header[http.CanonicalHeaderKey(key)] {
begin := 0
end := 0
escape := false
quote := false
for i := 0; i < len(s); i++ {
b := s[i]
switch {
case escape:
escape = false
end = i + 1
case quote:
switch b {
case '\\':
escape = true
case '"':
quote = false
}
end = i + 1
case b == '"':
quote = true
end = i + 1
case octetTypes[b]&isSpace != 0:
if begin == end {
begin = i + 1
end = begin
}
case b == ',':
if begin < end {
result = append(result, s[begin:end])
}
begin = i + 1
end = begin
default:
end = i + 1
}
}
if begin < end {
result = append(result, s[begin:end])
}
}
return result
} | go | func ParseList(header http.Header, key string) []string {
var result []string
for _, s := range header[http.CanonicalHeaderKey(key)] {
begin := 0
end := 0
escape := false
quote := false
for i := 0; i < len(s); i++ {
b := s[i]
switch {
case escape:
escape = false
end = i + 1
case quote:
switch b {
case '\\':
escape = true
case '"':
quote = false
}
end = i + 1
case b == '"':
quote = true
end = i + 1
case octetTypes[b]&isSpace != 0:
if begin == end {
begin = i + 1
end = begin
}
case b == ',':
if begin < end {
result = append(result, s[begin:end])
}
begin = i + 1
end = begin
default:
end = i + 1
}
}
if begin < end {
result = append(result, s[begin:end])
}
}
return result
} | [
"func",
"ParseList",
"(",
"header",
"http",
".",
"Header",
",",
"key",
"string",
")",
"[",
"]",
"string",
"{",
"var",
"result",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"header",
"[",
"http",
".",
"CanonicalHeaderKey",
"(",
"key",
")",
"]",
"{",
"begin",
":=",
"0",
"\n",
"end",
":=",
"0",
"\n",
"escape",
":=",
"false",
"\n",
"quote",
":=",
"false",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"s",
")",
";",
"i",
"++",
"{",
"b",
":=",
"s",
"[",
"i",
"]",
"\n",
"switch",
"{",
"case",
"escape",
":",
"escape",
"=",
"false",
"\n",
"end",
"=",
"i",
"+",
"1",
"\n",
"case",
"quote",
":",
"switch",
"b",
"{",
"case",
"'\\\\'",
":",
"escape",
"=",
"true",
"\n",
"case",
"'\"'",
":",
"quote",
"=",
"false",
"\n",
"}",
"\n",
"end",
"=",
"i",
"+",
"1",
"\n",
"case",
"b",
"==",
"'\"'",
":",
"quote",
"=",
"true",
"\n",
"end",
"=",
"i",
"+",
"1",
"\n",
"case",
"octetTypes",
"[",
"b",
"]",
"&",
"isSpace",
"!=",
"0",
":",
"if",
"begin",
"==",
"end",
"{",
"begin",
"=",
"i",
"+",
"1",
"\n",
"end",
"=",
"begin",
"\n",
"}",
"\n",
"case",
"b",
"==",
"','",
":",
"if",
"begin",
"<",
"end",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"s",
"[",
"begin",
":",
"end",
"]",
")",
"\n",
"}",
"\n",
"begin",
"=",
"i",
"+",
"1",
"\n",
"end",
"=",
"begin",
"\n",
"default",
":",
"end",
"=",
"i",
"+",
"1",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"begin",
"<",
"end",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"s",
"[",
"begin",
":",
"end",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
]
| // ParseList parses a comma separated list of values. Commas are ignored in
// quoted strings. Quoted values are not unescaped or unquoted. Whitespace is
// trimmed. | [
"ParseList",
"parses",
"a",
"comma",
"separated",
"list",
"of",
"values",
".",
"Commas",
"are",
"ignored",
"in",
"quoted",
"strings",
".",
"Quoted",
"values",
"are",
"not",
"unescaped",
"or",
"unquoted",
".",
"Whitespace",
"is",
"trimmed",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/header/header.go#L86-L130 |
149,693 | golang/gddo | httputil/static.go | FileHandler | func (ss *StaticServer) FileHandler(fileName string) http.Handler {
id := fileName
fileName = ss.resolve(fileName)
return &staticHandler{
ss: ss,
id: func(_ string) string { return id },
open: func(_ string) (io.ReadCloser, int64, string, error) { return ss.openFile(fileName) },
}
} | go | func (ss *StaticServer) FileHandler(fileName string) http.Handler {
id := fileName
fileName = ss.resolve(fileName)
return &staticHandler{
ss: ss,
id: func(_ string) string { return id },
open: func(_ string) (io.ReadCloser, int64, string, error) { return ss.openFile(fileName) },
}
} | [
"func",
"(",
"ss",
"*",
"StaticServer",
")",
"FileHandler",
"(",
"fileName",
"string",
")",
"http",
".",
"Handler",
"{",
"id",
":=",
"fileName",
"\n",
"fileName",
"=",
"ss",
".",
"resolve",
"(",
"fileName",
")",
"\n",
"return",
"&",
"staticHandler",
"{",
"ss",
":",
"ss",
",",
"id",
":",
"func",
"(",
"_",
"string",
")",
"string",
"{",
"return",
"id",
"}",
",",
"open",
":",
"func",
"(",
"_",
"string",
")",
"(",
"io",
".",
"ReadCloser",
",",
"int64",
",",
"string",
",",
"error",
")",
"{",
"return",
"ss",
".",
"openFile",
"(",
"fileName",
")",
"}",
",",
"}",
"\n",
"}"
]
| // FileHandler returns a handler that serves a single file. The file is
// specified by a slash separated path relative to the static server's Dir
// field. | [
"FileHandler",
"returns",
"a",
"handler",
"that",
"serves",
"a",
"single",
"file",
".",
"The",
"file",
"is",
"specified",
"by",
"a",
"slash",
"separated",
"path",
"relative",
"to",
"the",
"static",
"server",
"s",
"Dir",
"field",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/static.go#L96-L104 |
149,694 | golang/gddo | httputil/static.go | DirectoryHandler | func (ss *StaticServer) DirectoryHandler(prefix, dirName string) http.Handler {
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
idBase := dirName
dirName = ss.resolve(dirName)
return &staticHandler{
ss: ss,
id: func(p string) string {
if !strings.HasPrefix(p, prefix) {
return "."
}
return path.Join(idBase, p[len(prefix):])
},
open: func(p string) (io.ReadCloser, int64, string, error) {
if !strings.HasPrefix(p, prefix) {
return nil, 0, "", errors.New("request url does not match directory prefix")
}
p = p[len(prefix):]
return ss.openFile(filepath.Join(dirName, filepath.FromSlash(p)))
},
}
} | go | func (ss *StaticServer) DirectoryHandler(prefix, dirName string) http.Handler {
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
idBase := dirName
dirName = ss.resolve(dirName)
return &staticHandler{
ss: ss,
id: func(p string) string {
if !strings.HasPrefix(p, prefix) {
return "."
}
return path.Join(idBase, p[len(prefix):])
},
open: func(p string) (io.ReadCloser, int64, string, error) {
if !strings.HasPrefix(p, prefix) {
return nil, 0, "", errors.New("request url does not match directory prefix")
}
p = p[len(prefix):]
return ss.openFile(filepath.Join(dirName, filepath.FromSlash(p)))
},
}
} | [
"func",
"(",
"ss",
"*",
"StaticServer",
")",
"DirectoryHandler",
"(",
"prefix",
",",
"dirName",
"string",
")",
"http",
".",
"Handler",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"prefix",
",",
"\"",
"\"",
")",
"{",
"prefix",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"idBase",
":=",
"dirName",
"\n",
"dirName",
"=",
"ss",
".",
"resolve",
"(",
"dirName",
")",
"\n",
"return",
"&",
"staticHandler",
"{",
"ss",
":",
"ss",
",",
"id",
":",
"func",
"(",
"p",
"string",
")",
"string",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"p",
",",
"prefix",
")",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"path",
".",
"Join",
"(",
"idBase",
",",
"p",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
")",
"\n",
"}",
",",
"open",
":",
"func",
"(",
"p",
"string",
")",
"(",
"io",
".",
"ReadCloser",
",",
"int64",
",",
"string",
",",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"p",
",",
"prefix",
")",
"{",
"return",
"nil",
",",
"0",
",",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"p",
"=",
"p",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"\n",
"return",
"ss",
".",
"openFile",
"(",
"filepath",
".",
"Join",
"(",
"dirName",
",",
"filepath",
".",
"FromSlash",
"(",
"p",
")",
")",
")",
"\n",
"}",
",",
"}",
"\n",
"}"
]
| // DirectoryHandler returns a handler that serves files from a directory tree.
// The directory is specified by a slash separated path relative to the static
// server's Dir field. | [
"DirectoryHandler",
"returns",
"a",
"handler",
"that",
"serves",
"files",
"from",
"a",
"directory",
"tree",
".",
"The",
"directory",
"is",
"specified",
"by",
"a",
"slash",
"separated",
"path",
"relative",
"to",
"the",
"static",
"server",
"s",
"Dir",
"field",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/static.go#L109-L131 |
149,695 | golang/gddo | httputil/static.go | FilesHandler | func (ss *StaticServer) FilesHandler(fileNames ...string) http.Handler {
// todo: cache concatenated files on disk and serve from there.
mimeType := ss.mimeType(fileNames[0])
var buf []byte
var openErr error
for _, fileName := range fileNames {
p, err := ioutil.ReadFile(ss.resolve(fileName))
if err != nil {
openErr = err
buf = nil
break
}
buf = append(buf, p...)
}
id := strings.Join(fileNames, " ")
return &staticHandler{
ss: ss,
id: func(_ string) string { return id },
open: func(p string) (io.ReadCloser, int64, string, error) {
return ioutil.NopCloser(bytes.NewReader(buf)), int64(len(buf)), mimeType, openErr
},
}
} | go | func (ss *StaticServer) FilesHandler(fileNames ...string) http.Handler {
// todo: cache concatenated files on disk and serve from there.
mimeType := ss.mimeType(fileNames[0])
var buf []byte
var openErr error
for _, fileName := range fileNames {
p, err := ioutil.ReadFile(ss.resolve(fileName))
if err != nil {
openErr = err
buf = nil
break
}
buf = append(buf, p...)
}
id := strings.Join(fileNames, " ")
return &staticHandler{
ss: ss,
id: func(_ string) string { return id },
open: func(p string) (io.ReadCloser, int64, string, error) {
return ioutil.NopCloser(bytes.NewReader(buf)), int64(len(buf)), mimeType, openErr
},
}
} | [
"func",
"(",
"ss",
"*",
"StaticServer",
")",
"FilesHandler",
"(",
"fileNames",
"...",
"string",
")",
"http",
".",
"Handler",
"{",
"// todo: cache concatenated files on disk and serve from there.",
"mimeType",
":=",
"ss",
".",
"mimeType",
"(",
"fileNames",
"[",
"0",
"]",
")",
"\n",
"var",
"buf",
"[",
"]",
"byte",
"\n",
"var",
"openErr",
"error",
"\n\n",
"for",
"_",
",",
"fileName",
":=",
"range",
"fileNames",
"{",
"p",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"ss",
".",
"resolve",
"(",
"fileName",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"openErr",
"=",
"err",
"\n",
"buf",
"=",
"nil",
"\n",
"break",
"\n",
"}",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"p",
"...",
")",
"\n",
"}",
"\n\n",
"id",
":=",
"strings",
".",
"Join",
"(",
"fileNames",
",",
"\"",
"\"",
")",
"\n\n",
"return",
"&",
"staticHandler",
"{",
"ss",
":",
"ss",
",",
"id",
":",
"func",
"(",
"_",
"string",
")",
"string",
"{",
"return",
"id",
"}",
",",
"open",
":",
"func",
"(",
"p",
"string",
")",
"(",
"io",
".",
"ReadCloser",
",",
"int64",
",",
"string",
",",
"error",
")",
"{",
"return",
"ioutil",
".",
"NopCloser",
"(",
"bytes",
".",
"NewReader",
"(",
"buf",
")",
")",
",",
"int64",
"(",
"len",
"(",
"buf",
")",
")",
",",
"mimeType",
",",
"openErr",
"\n",
"}",
",",
"}",
"\n",
"}"
]
| // FilesHandler returns a handler that serves the concatentation of the
// specified files. The files are specified by slash separated paths relative
// to the static server's Dir field. | [
"FilesHandler",
"returns",
"a",
"handler",
"that",
"serves",
"the",
"concatentation",
"of",
"the",
"specified",
"files",
".",
"The",
"files",
"are",
"specified",
"by",
"slash",
"separated",
"paths",
"relative",
"to",
"the",
"static",
"server",
"s",
"Dir",
"field",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/static.go#L136-L163 |
149,696 | golang/gddo | database/database.go | New | func New(serverURI string, idleTimeout time.Duration, logConn bool, gaeEndpoint string) (*Database, error) {
pool := &redis.Pool{
Dial: newDBDialer(serverURI, logConn),
MaxIdle: 10,
IdleTimeout: idleTimeout,
}
var rc *remote_api.Client
if gaeEndpoint != "" {
var err error
if rc, err = newRemoteClient(gaeEndpoint); err != nil {
return nil, err
}
} else {
log.Println("remote_api client not setup to use App Engine search")
}
return &Database{Pool: pool, RemoteClient: rc}, nil
} | go | func New(serverURI string, idleTimeout time.Duration, logConn bool, gaeEndpoint string) (*Database, error) {
pool := &redis.Pool{
Dial: newDBDialer(serverURI, logConn),
MaxIdle: 10,
IdleTimeout: idleTimeout,
}
var rc *remote_api.Client
if gaeEndpoint != "" {
var err error
if rc, err = newRemoteClient(gaeEndpoint); err != nil {
return nil, err
}
} else {
log.Println("remote_api client not setup to use App Engine search")
}
return &Database{Pool: pool, RemoteClient: rc}, nil
} | [
"func",
"New",
"(",
"serverURI",
"string",
",",
"idleTimeout",
"time",
".",
"Duration",
",",
"logConn",
"bool",
",",
"gaeEndpoint",
"string",
")",
"(",
"*",
"Database",
",",
"error",
")",
"{",
"pool",
":=",
"&",
"redis",
".",
"Pool",
"{",
"Dial",
":",
"newDBDialer",
"(",
"serverURI",
",",
"logConn",
")",
",",
"MaxIdle",
":",
"10",
",",
"IdleTimeout",
":",
"idleTimeout",
",",
"}",
"\n\n",
"var",
"rc",
"*",
"remote_api",
".",
"Client",
"\n",
"if",
"gaeEndpoint",
"!=",
"\"",
"\"",
"{",
"var",
"err",
"error",
"\n",
"if",
"rc",
",",
"err",
"=",
"newRemoteClient",
"(",
"gaeEndpoint",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"Database",
"{",
"Pool",
":",
"pool",
",",
"RemoteClient",
":",
"rc",
"}",
",",
"nil",
"\n",
"}"
]
| // New creates a gddo database. serverURI, idleTimeout, and logConn configure
// the use of redis. gaeEndpoint is the target of the App Engine remoteapi
// endpoint. | [
"New",
"creates",
"a",
"gddo",
"database",
".",
"serverURI",
"idleTimeout",
"and",
"logConn",
"configure",
"the",
"use",
"of",
"redis",
".",
"gaeEndpoint",
"is",
"the",
"target",
"of",
"the",
"App",
"Engine",
"remoteapi",
"endpoint",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L140-L158 |
149,697 | golang/gddo | database/database.go | pkgIDAndImportCount | func pkgIDAndImportCount(c redis.Conn, path string) (id string, numImported int, err error) {
numImported, err = redis.Int(c.Do("SCARD", "index:import:"+path))
if err != nil {
return
}
id, err = redis.String(c.Do("HGET", "ids", path))
if err == redis.ErrNil {
return "", 0, nil
} else if err != nil {
return "", 0, err
}
return id, numImported, nil
} | go | func pkgIDAndImportCount(c redis.Conn, path string) (id string, numImported int, err error) {
numImported, err = redis.Int(c.Do("SCARD", "index:import:"+path))
if err != nil {
return
}
id, err = redis.String(c.Do("HGET", "ids", path))
if err == redis.ErrNil {
return "", 0, nil
} else if err != nil {
return "", 0, err
}
return id, numImported, nil
} | [
"func",
"pkgIDAndImportCount",
"(",
"c",
"redis",
".",
"Conn",
",",
"path",
"string",
")",
"(",
"id",
"string",
",",
"numImported",
"int",
",",
"err",
"error",
")",
"{",
"numImported",
",",
"err",
"=",
"redis",
".",
"Int",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"path",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"id",
",",
"err",
"=",
"redis",
".",
"String",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"path",
")",
")",
"\n",
"if",
"err",
"==",
"redis",
".",
"ErrNil",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"nil",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"id",
",",
"numImported",
",",
"nil",
"\n",
"}"
]
| // pkgIDAndImportCount returns the ID and import count of a specified package. | [
"pkgIDAndImportCount",
"returns",
"the",
"ID",
"and",
"import",
"count",
"of",
"a",
"specified",
"package",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L363-L375 |
149,698 | golang/gddo | database/database.go | SetNextCrawl | func (db *Database) SetNextCrawl(path string, t time.Time) error {
c := db.Pool.Get()
defer c.Close()
_, err := setNextCrawlScript.Do(c, path, t.Unix())
return err
} | go | func (db *Database) SetNextCrawl(path string, t time.Time) error {
c := db.Pool.Get()
defer c.Close()
_, err := setNextCrawlScript.Do(c, path, t.Unix())
return err
} | [
"func",
"(",
"db",
"*",
"Database",
")",
"SetNextCrawl",
"(",
"path",
"string",
",",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"c",
":=",
"db",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"setNextCrawlScript",
".",
"Do",
"(",
"c",
",",
"path",
",",
"t",
".",
"Unix",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // SetNextCrawl sets the next crawl time for a package. | [
"SetNextCrawl",
"sets",
"the",
"next",
"crawl",
"time",
"for",
"a",
"package",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L422-L427 |
149,699 | golang/gddo | database/database.go | Get | func (db *Database) Get(ctx context.Context, path string) (*doc.Package, []Package, time.Time, error) {
c := db.Pool.Get()
defer c.Close()
pdoc, nextCrawl, err := db.getDoc(ctx, c, path)
if err != nil {
return nil, nil, time.Time{}, err
}
if pdoc != nil {
// fixup for speclal "-" path.
path = pdoc.ImportPath
}
subdirs, err := db.getSubdirs(c, path, pdoc)
if err != nil {
return nil, nil, time.Time{}, err
}
return pdoc, subdirs, nextCrawl, nil
} | go | func (db *Database) Get(ctx context.Context, path string) (*doc.Package, []Package, time.Time, error) {
c := db.Pool.Get()
defer c.Close()
pdoc, nextCrawl, err := db.getDoc(ctx, c, path)
if err != nil {
return nil, nil, time.Time{}, err
}
if pdoc != nil {
// fixup for speclal "-" path.
path = pdoc.ImportPath
}
subdirs, err := db.getSubdirs(c, path, pdoc)
if err != nil {
return nil, nil, time.Time{}, err
}
return pdoc, subdirs, nextCrawl, nil
} | [
"func",
"(",
"db",
"*",
"Database",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
")",
"(",
"*",
"doc",
".",
"Package",
",",
"[",
"]",
"Package",
",",
"time",
".",
"Time",
",",
"error",
")",
"{",
"c",
":=",
"db",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"pdoc",
",",
"nextCrawl",
",",
"err",
":=",
"db",
".",
"getDoc",
"(",
"ctx",
",",
"c",
",",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"time",
".",
"Time",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"pdoc",
"!=",
"nil",
"{",
"// fixup for speclal \"-\" path.",
"path",
"=",
"pdoc",
".",
"ImportPath",
"\n",
"}",
"\n\n",
"subdirs",
",",
"err",
":=",
"db",
".",
"getSubdirs",
"(",
"c",
",",
"path",
",",
"pdoc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"time",
".",
"Time",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"pdoc",
",",
"subdirs",
",",
"nextCrawl",
",",
"nil",
"\n",
"}"
]
| // Get gets the package documentation and sub-directories for the the given
// import path. | [
"Get",
"gets",
"the",
"package",
"documentation",
"and",
"sub",
"-",
"directories",
"for",
"the",
"the",
"given",
"import",
"path",
"."
]
| af0f2af80721261f4d211b2c9563f7b46b2aab06 | https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L588-L607 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.