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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
btcsuite/btcd | rpcclient/mining.go | Receive | func (r FutureGetMiningInfoResult) Receive() (*btcjson.GetMiningInfoResult, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a getmininginfo result object.
var infoResult btcjson.GetMiningInfoResult
err = json.Unmarshal(res, &infoResult)
if err != nil {
return nil, err
}
return &infoResult, nil
} | go | func (r FutureGetMiningInfoResult) Receive() (*btcjson.GetMiningInfoResult, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a getmininginfo result object.
var infoResult btcjson.GetMiningInfoResult
err = json.Unmarshal(res, &infoResult)
if err != nil {
return nil, err
}
return &infoResult, nil
} | [
"func",
"(",
"r",
"FutureGetMiningInfoResult",
")",
"Receive",
"(",
")",
"(",
"*",
"btcjson",
".",
"GetMiningInfoResult",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal result as a getmininginfo result object.",
"var",
"infoResult",
"btcjson",
".",
"GetMiningInfoResult",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"infoResult",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"infoResult",
",",
"nil",
"\n",
"}"
] | // Receive waits for the response promised by the future and returns the mining
// information. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"the",
"mining",
"information",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L173-L187 | train |
btcsuite/btcd | rpcclient/mining.go | GetMiningInfoAsync | func (c *Client) GetMiningInfoAsync() FutureGetMiningInfoResult {
cmd := btcjson.NewGetMiningInfoCmd()
return c.sendCmd(cmd)
} | go | func (c *Client) GetMiningInfoAsync() FutureGetMiningInfoResult {
cmd := btcjson.NewGetMiningInfoCmd()
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetMiningInfoAsync",
"(",
")",
"FutureGetMiningInfoResult",
"{",
"cmd",
":=",
"btcjson",
".",
"NewGetMiningInfoCmd",
"(",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // GetMiningInfoAsync returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function on
// the returned instance.
//
// See GetMiningInfo for the blocking version and more details. | [
"GetMiningInfoAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"instance",
".",
"See",
"GetMiningInfo",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L194-L197 | train |
btcsuite/btcd | rpcclient/mining.go | Receive | func (r FutureGetNetworkHashPS) Receive() (int64, error) {
res, err := receiveFuture(r)
if err != nil {
return -1, err
}
// Unmarshal result as an int64.
var result int64
err = json.Unmarshal(res, &result)
if err != nil {
return 0, err
}
return result, nil
} | go | func (r FutureGetNetworkHashPS) Receive() (int64, error) {
res, err := receiveFuture(r)
if err != nil {
return -1, err
}
// Unmarshal result as an int64.
var result int64
err = json.Unmarshal(res, &result)
if err != nil {
return 0, err
}
return result, nil
} | [
"func",
"(",
"r",
"FutureGetNetworkHashPS",
")",
"Receive",
"(",
")",
"(",
"int64",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal result as an int64.",
"var",
"result",
"int64",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // Receive waits for the response promised by the future and returns the
// estimated network hashes per second for the block heights provided by the
// parameters. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"the",
"estimated",
"network",
"hashes",
"per",
"second",
"for",
"the",
"block",
"heights",
"provided",
"by",
"the",
"parameters",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L211-L225 | train |
btcsuite/btcd | rpcclient/mining.go | GetNetworkHashPSAsync | func (c *Client) GetNetworkHashPSAsync() FutureGetNetworkHashPS {
cmd := btcjson.NewGetNetworkHashPSCmd(nil, nil)
return c.sendCmd(cmd)
} | go | func (c *Client) GetNetworkHashPSAsync() FutureGetNetworkHashPS {
cmd := btcjson.NewGetNetworkHashPSCmd(nil, nil)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetNetworkHashPSAsync",
"(",
")",
"FutureGetNetworkHashPS",
"{",
"cmd",
":=",
"btcjson",
".",
"NewGetNetworkHashPSCmd",
"(",
"nil",
",",
"nil",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // GetNetworkHashPSAsync returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function on
// the returned instance.
//
// See GetNetworkHashPS for the blocking version and more details. | [
"GetNetworkHashPSAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"instance",
".",
"See",
"GetNetworkHashPS",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L232-L235 | train |
btcsuite/btcd | rpcclient/mining.go | GetNetworkHashPS2Async | func (c *Client) GetNetworkHashPS2Async(blocks int) FutureGetNetworkHashPS {
cmd := btcjson.NewGetNetworkHashPSCmd(&blocks, nil)
return c.sendCmd(cmd)
} | go | func (c *Client) GetNetworkHashPS2Async(blocks int) FutureGetNetworkHashPS {
cmd := btcjson.NewGetNetworkHashPSCmd(&blocks, nil)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetNetworkHashPS2Async",
"(",
"blocks",
"int",
")",
"FutureGetNetworkHashPS",
"{",
"cmd",
":=",
"btcjson",
".",
"NewGetNetworkHashPSCmd",
"(",
"&",
"blocks",
",",
"nil",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // GetNetworkHashPS2Async returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function on
// the returned instance.
//
// See GetNetworkHashPS2 for the blocking version and more details. | [
"GetNetworkHashPS2Async",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"instance",
".",
"See",
"GetNetworkHashPS2",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L251-L254 | train |
btcsuite/btcd | rpcclient/mining.go | GetNetworkHashPS2 | func (c *Client) GetNetworkHashPS2(blocks int) (int64, error) {
return c.GetNetworkHashPS2Async(blocks).Receive()
} | go | func (c *Client) GetNetworkHashPS2(blocks int) (int64, error) {
return c.GetNetworkHashPS2Async(blocks).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetNetworkHashPS2",
"(",
"blocks",
"int",
")",
"(",
"int64",
",",
"error",
")",
"{",
"return",
"c",
".",
"GetNetworkHashPS2Async",
"(",
"blocks",
")",
".",
"Receive",
"(",
")",
"\n",
"}"
] | // GetNetworkHashPS2 returns the estimated network hashes per second for the
// specified previous number of blocks working backwards from the most recent
// block height. The blocks parameter can also be -1 in which case the number
// of blocks since the last difficulty change will be used.
//
// See GetNetworkHashPS to use defaults and GetNetworkHashPS3 to override the
// height at which to calculate the estimate. | [
"GetNetworkHashPS2",
"returns",
"the",
"estimated",
"network",
"hashes",
"per",
"second",
"for",
"the",
"specified",
"previous",
"number",
"of",
"blocks",
"working",
"backwards",
"from",
"the",
"most",
"recent",
"block",
"height",
".",
"The",
"blocks",
"parameter",
"can",
"also",
"be",
"-",
"1",
"in",
"which",
"case",
"the",
"number",
"of",
"blocks",
"since",
"the",
"last",
"difficulty",
"change",
"will",
"be",
"used",
".",
"See",
"GetNetworkHashPS",
"to",
"use",
"defaults",
"and",
"GetNetworkHashPS3",
"to",
"override",
"the",
"height",
"at",
"which",
"to",
"calculate",
"the",
"estimate",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L263-L265 | train |
btcsuite/btcd | rpcclient/mining.go | GetNetworkHashPS3Async | func (c *Client) GetNetworkHashPS3Async(blocks, height int) FutureGetNetworkHashPS {
cmd := btcjson.NewGetNetworkHashPSCmd(&blocks, &height)
return c.sendCmd(cmd)
} | go | func (c *Client) GetNetworkHashPS3Async(blocks, height int) FutureGetNetworkHashPS {
cmd := btcjson.NewGetNetworkHashPSCmd(&blocks, &height)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetNetworkHashPS3Async",
"(",
"blocks",
",",
"height",
"int",
")",
"FutureGetNetworkHashPS",
"{",
"cmd",
":=",
"btcjson",
".",
"NewGetNetworkHashPSCmd",
"(",
"&",
"blocks",
",",
"&",
"height",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // GetNetworkHashPS3Async returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function on
// the returned instance.
//
// See GetNetworkHashPS3 for the blocking version and more details. | [
"GetNetworkHashPS3Async",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"instance",
".",
"See",
"GetNetworkHashPS3",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L272-L275 | train |
btcsuite/btcd | rpcclient/mining.go | GetNetworkHashPS3 | func (c *Client) GetNetworkHashPS3(blocks, height int) (int64, error) {
return c.GetNetworkHashPS3Async(blocks, height).Receive()
} | go | func (c *Client) GetNetworkHashPS3(blocks, height int) (int64, error) {
return c.GetNetworkHashPS3Async(blocks, height).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetNetworkHashPS3",
"(",
"blocks",
",",
"height",
"int",
")",
"(",
"int64",
",",
"error",
")",
"{",
"return",
"c",
".",
"GetNetworkHashPS3Async",
"(",
"blocks",
",",
"height",
")",
".",
"Receive",
"(",
")",
"\n",
"}"
] | // GetNetworkHashPS3 returns the estimated network hashes per second for the
// specified previous number of blocks working backwards from the specified
// block height. The blocks parameter can also be -1 in which case the number
// of blocks since the last difficulty change will be used.
//
// See GetNetworkHashPS and GetNetworkHashPS2 to use defaults. | [
"GetNetworkHashPS3",
"returns",
"the",
"estimated",
"network",
"hashes",
"per",
"second",
"for",
"the",
"specified",
"previous",
"number",
"of",
"blocks",
"working",
"backwards",
"from",
"the",
"specified",
"block",
"height",
".",
"The",
"blocks",
"parameter",
"can",
"also",
"be",
"-",
"1",
"in",
"which",
"case",
"the",
"number",
"of",
"blocks",
"since",
"the",
"last",
"difficulty",
"change",
"will",
"be",
"used",
".",
"See",
"GetNetworkHashPS",
"and",
"GetNetworkHashPS2",
"to",
"use",
"defaults",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L283-L285 | train |
btcsuite/btcd | rpcclient/mining.go | Receive | func (r FutureGetWork) Receive() (*btcjson.GetWorkResult, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a getwork result object.
var result btcjson.GetWorkResult
err = json.Unmarshal(res, &result)
if err != nil {
return nil, err
}
return &result, nil
} | go | func (r FutureGetWork) Receive() (*btcjson.GetWorkResult, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a getwork result object.
var result btcjson.GetWorkResult
err = json.Unmarshal(res, &result)
if err != nil {
return nil, err
}
return &result, nil
} | [
"func",
"(",
"r",
"FutureGetWork",
")",
"Receive",
"(",
")",
"(",
"*",
"btcjson",
".",
"GetWorkResult",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal result as a getwork result object.",
"var",
"result",
"btcjson",
".",
"GetWorkResult",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"result",
",",
"nil",
"\n",
"}"
] | // Receive waits for the response promised by the future and returns the hash
// data to work on. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"the",
"hash",
"data",
"to",
"work",
"on",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L293-L307 | train |
btcsuite/btcd | rpcclient/mining.go | GetWorkAsync | func (c *Client) GetWorkAsync() FutureGetWork {
cmd := btcjson.NewGetWorkCmd(nil)
return c.sendCmd(cmd)
} | go | func (c *Client) GetWorkAsync() FutureGetWork {
cmd := btcjson.NewGetWorkCmd(nil)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetWorkAsync",
"(",
")",
"FutureGetWork",
"{",
"cmd",
":=",
"btcjson",
".",
"NewGetWorkCmd",
"(",
"nil",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // GetWorkAsync returns an instance of a type that can be used to get the result
// of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See GetWork for the blocking version and more details. | [
"GetWorkAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"instance",
".",
"See",
"GetWork",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L314-L317 | train |
btcsuite/btcd | rpcclient/mining.go | Receive | func (r FutureGetWorkSubmit) Receive() (bool, error) {
res, err := receiveFuture(r)
if err != nil {
return false, err
}
// Unmarshal result as a boolean.
var accepted bool
err = json.Unmarshal(res, &accepted)
if err != nil {
return false, err
}
return accepted, nil
} | go | func (r FutureGetWorkSubmit) Receive() (bool, error) {
res, err := receiveFuture(r)
if err != nil {
return false, err
}
// Unmarshal result as a boolean.
var accepted bool
err = json.Unmarshal(res, &accepted)
if err != nil {
return false, err
}
return accepted, nil
} | [
"func",
"(",
"r",
"FutureGetWorkSubmit",
")",
"Receive",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal result as a boolean.",
"var",
"accepted",
"bool",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"accepted",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"accepted",
",",
"nil",
"\n",
"}"
] | // Receive waits for the response promised by the future and returns whether
// or not the submitted block header was accepted. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"whether",
"or",
"not",
"the",
"submitted",
"block",
"header",
"was",
"accepted",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L332-L346 | train |
btcsuite/btcd | rpcclient/mining.go | GetWorkSubmitAsync | func (c *Client) GetWorkSubmitAsync(data string) FutureGetWorkSubmit {
cmd := btcjson.NewGetWorkCmd(&data)
return c.sendCmd(cmd)
} | go | func (c *Client) GetWorkSubmitAsync(data string) FutureGetWorkSubmit {
cmd := btcjson.NewGetWorkCmd(&data)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetWorkSubmitAsync",
"(",
"data",
"string",
")",
"FutureGetWorkSubmit",
"{",
"cmd",
":=",
"btcjson",
".",
"NewGetWorkCmd",
"(",
"&",
"data",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // GetWorkSubmitAsync returns an instance of a type that can be used to get the
// result of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See GetWorkSubmit for the blocking version and more details. | [
"GetWorkSubmitAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"instance",
".",
"See",
"GetWorkSubmit",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L353-L356 | train |
btcsuite/btcd | rpcclient/mining.go | GetWorkSubmit | func (c *Client) GetWorkSubmit(data string) (bool, error) {
return c.GetWorkSubmitAsync(data).Receive()
} | go | func (c *Client) GetWorkSubmit(data string) (bool, error) {
return c.GetWorkSubmitAsync(data).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetWorkSubmit",
"(",
"data",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"c",
".",
"GetWorkSubmitAsync",
"(",
"data",
")",
".",
"Receive",
"(",
")",
"\n",
"}"
] | // GetWorkSubmit submits a block header which is a solution to previously
// requested data and returns whether or not the solution was accepted.
//
// See GetWork to request data to work on. | [
"GetWorkSubmit",
"submits",
"a",
"block",
"header",
"which",
"is",
"a",
"solution",
"to",
"previously",
"requested",
"data",
"and",
"returns",
"whether",
"or",
"not",
"the",
"solution",
"was",
"accepted",
".",
"See",
"GetWork",
"to",
"request",
"data",
"to",
"work",
"on",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L362-L364 | train |
btcsuite/btcd | rpcclient/mining.go | Receive | func (r FutureSubmitBlockResult) Receive() error {
res, err := receiveFuture(r)
if err != nil {
return err
}
if string(res) != "null" {
var result string
err = json.Unmarshal(res, &result)
if err != nil {
return err
}
return errors.New(result)
}
return nil
} | go | func (r FutureSubmitBlockResult) Receive() error {
res, err := receiveFuture(r)
if err != nil {
return err
}
if string(res) != "null" {
var result string
err = json.Unmarshal(res, &result)
if err != nil {
return err
}
return errors.New(result)
}
return nil
} | [
"func",
"(",
"r",
"FutureSubmitBlockResult",
")",
"Receive",
"(",
")",
"error",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"string",
"(",
"res",
")",
"!=",
"\"",
"\"",
"{",
"var",
"result",
"string",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"errors",
".",
"New",
"(",
"result",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n\n",
"}"
] | // Receive waits for the response promised by the future and returns an error if
// any occurred when submitting the block. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"an",
"error",
"if",
"any",
"occurred",
"when",
"submitting",
"the",
"block",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L372-L390 | train |
btcsuite/btcd | rpcclient/mining.go | SubmitBlockAsync | func (c *Client) SubmitBlockAsync(block *btcutil.Block, options *btcjson.SubmitBlockOptions) FutureSubmitBlockResult {
blockHex := ""
if block != nil {
blockBytes, err := block.Bytes()
if err != nil {
return newFutureError(err)
}
blockHex = hex.EncodeToString(blockBytes)
}
cmd := btcjson.NewSubmitBlockCmd(blockHex, options)
return c.sendCmd(cmd)
} | go | func (c *Client) SubmitBlockAsync(block *btcutil.Block, options *btcjson.SubmitBlockOptions) FutureSubmitBlockResult {
blockHex := ""
if block != nil {
blockBytes, err := block.Bytes()
if err != nil {
return newFutureError(err)
}
blockHex = hex.EncodeToString(blockBytes)
}
cmd := btcjson.NewSubmitBlockCmd(blockHex, options)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SubmitBlockAsync",
"(",
"block",
"*",
"btcutil",
".",
"Block",
",",
"options",
"*",
"btcjson",
".",
"SubmitBlockOptions",
")",
"FutureSubmitBlockResult",
"{",
"blockHex",
":=",
"\"",
"\"",
"\n",
"if",
"block",
"!=",
"nil",
"{",
"blockBytes",
",",
"err",
":=",
"block",
".",
"Bytes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"newFutureError",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"blockHex",
"=",
"hex",
".",
"EncodeToString",
"(",
"blockBytes",
")",
"\n",
"}",
"\n\n",
"cmd",
":=",
"btcjson",
".",
"NewSubmitBlockCmd",
"(",
"blockHex",
",",
"options",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // SubmitBlockAsync returns an instance of a type that can be used to get the
// result of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See SubmitBlock for the blocking version and more details. | [
"SubmitBlockAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"instance",
".",
"See",
"SubmitBlock",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L397-L410 | train |
btcsuite/btcd | rpcclient/mining.go | SubmitBlock | func (c *Client) SubmitBlock(block *btcutil.Block, options *btcjson.SubmitBlockOptions) error {
return c.SubmitBlockAsync(block, options).Receive()
} | go | func (c *Client) SubmitBlock(block *btcutil.Block, options *btcjson.SubmitBlockOptions) error {
return c.SubmitBlockAsync(block, options).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SubmitBlock",
"(",
"block",
"*",
"btcutil",
".",
"Block",
",",
"options",
"*",
"btcjson",
".",
"SubmitBlockOptions",
")",
"error",
"{",
"return",
"c",
".",
"SubmitBlockAsync",
"(",
"block",
",",
"options",
")",
".",
"Receive",
"(",
")",
"\n",
"}"
] | // SubmitBlock attempts to submit a new block into the bitcoin network. | [
"SubmitBlock",
"attempts",
"to",
"submit",
"a",
"new",
"block",
"into",
"the",
"bitcoin",
"network",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L413-L415 | train |
silenceper/wechat | miniprogram/decrypt.go | pkcs7Unpad | func pkcs7Unpad(data []byte, blockSize int) ([]byte, error) {
if blockSize <= 0 {
return nil, ErrInvalidBlockSize
}
if len(data)%blockSize != 0 || len(data) == 0 {
return nil, ErrInvalidPKCS7Data
}
c := data[len(data)-1]
n := int(c)
if n == 0 || n > len(data) {
return nil, ErrInvalidPKCS7Padding
}
for i := 0; i < n; i++ {
if data[len(data)-n+i] != c {
return nil, ErrInvalidPKCS7Padding
}
}
return data[:len(data)-n], nil
} | go | func pkcs7Unpad(data []byte, blockSize int) ([]byte, error) {
if blockSize <= 0 {
return nil, ErrInvalidBlockSize
}
if len(data)%blockSize != 0 || len(data) == 0 {
return nil, ErrInvalidPKCS7Data
}
c := data[len(data)-1]
n := int(c)
if n == 0 || n > len(data) {
return nil, ErrInvalidPKCS7Padding
}
for i := 0; i < n; i++ {
if data[len(data)-n+i] != c {
return nil, ErrInvalidPKCS7Padding
}
}
return data[:len(data)-n], nil
} | [
"func",
"pkcs7Unpad",
"(",
"data",
"[",
"]",
"byte",
",",
"blockSize",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"blockSize",
"<=",
"0",
"{",
"return",
"nil",
",",
"ErrInvalidBlockSize",
"\n",
"}",
"\n",
"if",
"len",
"(",
"data",
")",
"%",
"blockSize",
"!=",
"0",
"||",
"len",
"(",
"data",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"ErrInvalidPKCS7Data",
"\n",
"}",
"\n",
"c",
":=",
"data",
"[",
"len",
"(",
"data",
")",
"-",
"1",
"]",
"\n",
"n",
":=",
"int",
"(",
"c",
")",
"\n",
"if",
"n",
"==",
"0",
"||",
"n",
">",
"len",
"(",
"data",
")",
"{",
"return",
"nil",
",",
"ErrInvalidPKCS7Padding",
"\n",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"if",
"data",
"[",
"len",
"(",
"data",
")",
"-",
"n",
"+",
"i",
"]",
"!=",
"c",
"{",
"return",
"nil",
",",
"ErrInvalidPKCS7Padding",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"data",
"[",
":",
"len",
"(",
"data",
")",
"-",
"n",
"]",
",",
"nil",
"\n",
"}"
] | // pkcs7Unpad returns slice of the original data without padding | [
"pkcs7Unpad",
"returns",
"slice",
"of",
"the",
"original",
"data",
"without",
"padding"
] | 42332eca27305295d688bf251d3a279ea2de38fc | https://github.com/silenceper/wechat/blob/42332eca27305295d688bf251d3a279ea2de38fc/miniprogram/decrypt.go#L40-L58 | train |
silenceper/wechat | cache/memcache.go | NewMemcache | func NewMemcache(server ...string) *Memcache {
mc := memcache.New(server...)
return &Memcache{mc}
} | go | func NewMemcache(server ...string) *Memcache {
mc := memcache.New(server...)
return &Memcache{mc}
} | [
"func",
"NewMemcache",
"(",
"server",
"...",
"string",
")",
"*",
"Memcache",
"{",
"mc",
":=",
"memcache",
".",
"New",
"(",
"server",
"...",
")",
"\n",
"return",
"&",
"Memcache",
"{",
"mc",
"}",
"\n",
"}"
] | //NewMemcache create new memcache | [
"NewMemcache",
"create",
"new",
"memcache"
] | 42332eca27305295d688bf251d3a279ea2de38fc | https://github.com/silenceper/wechat/blob/42332eca27305295d688bf251d3a279ea2de38fc/cache/memcache.go#L16-L19 | train |
silenceper/wechat | cache/memcache.go | Delete | func (mem *Memcache) Delete(key string) error {
return mem.conn.Delete(key)
} | go | func (mem *Memcache) Delete(key string) error {
return mem.conn.Delete(key)
} | [
"func",
"(",
"mem",
"*",
"Memcache",
")",
"Delete",
"(",
"key",
"string",
")",
"error",
"{",
"return",
"mem",
".",
"conn",
".",
"Delete",
"(",
"key",
")",
"\n",
"}"
] | //Delete delete value in memcache. | [
"Delete",
"delete",
"value",
"in",
"memcache",
"."
] | 42332eca27305295d688bf251d3a279ea2de38fc | https://github.com/silenceper/wechat/blob/42332eca27305295d688bf251d3a279ea2de38fc/cache/memcache.go#L55-L57 | train |
silenceper/wechat | context/context.go | Query | func (ctx *Context) Query(key string) string {
value, _ := ctx.GetQuery(key)
return value
} | go | func (ctx *Context) Query(key string) string {
value, _ := ctx.GetQuery(key)
return value
} | [
"func",
"(",
"ctx",
"*",
"Context",
")",
"Query",
"(",
"key",
"string",
")",
"string",
"{",
"value",
",",
"_",
":=",
"ctx",
".",
"GetQuery",
"(",
"key",
")",
"\n",
"return",
"value",
"\n",
"}"
] | // Query returns the keyed url query value if it exists | [
"Query",
"returns",
"the",
"keyed",
"url",
"query",
"value",
"if",
"it",
"exists"
] | 42332eca27305295d688bf251d3a279ea2de38fc | https://github.com/silenceper/wechat/blob/42332eca27305295d688bf251d3a279ea2de38fc/context/context.go#L33-L36 | train |
silenceper/wechat | pay/pay.go | NewPay | func NewPay(ctx *context.Context) *Pay {
pay := Pay{Context: ctx}
return &pay
} | go | func NewPay(ctx *context.Context) *Pay {
pay := Pay{Context: ctx}
return &pay
} | [
"func",
"NewPay",
"(",
"ctx",
"*",
"context",
".",
"Context",
")",
"*",
"Pay",
"{",
"pay",
":=",
"Pay",
"{",
"Context",
":",
"ctx",
"}",
"\n",
"return",
"&",
"pay",
"\n",
"}"
] | // NewPay return an instance of Pay package | [
"NewPay",
"return",
"an",
"instance",
"of",
"Pay",
"package"
] | 42332eca27305295d688bf251d3a279ea2de38fc | https://github.com/silenceper/wechat/blob/42332eca27305295d688bf251d3a279ea2de38fc/pay/pay.go#L84-L87 | train |
silenceper/wechat | pay/pay.go | PrePayOrder | func (pcf *Pay) PrePayOrder(p *Params) (payOrder PreOrder, err error) {
nonceStr := util.RandomStr(32)
param := make(map[string]interface{})
param["appid"] = pcf.AppID
param["body"] = p.Body
param["mch_id"] = pcf.PayMchID
param["nonce_str"] =nonceStr
param["notify_url"] =pcf.PayNotifyURL
param["out_trade_no"] =p.OutTradeNo
param["spbill_create_ip"] =p.CreateIP
param["total_fee"] =p.TotalFee
param["trade_type"] =p.TradeType
param["openid"] = p.OpenID
bizKey := "&key="+pcf.PayKey
str := orderParam(param,bizKey)
sign := util.MD5Sum(str)
request := payRequest{
AppID: pcf.AppID,
MchID: pcf.PayMchID,
NonceStr: nonceStr,
Sign: sign,
Body: p.Body,
OutTradeNo: p.OutTradeNo,
TotalFee: p.TotalFee,
SpbillCreateIP: p.CreateIP,
NotifyURL: pcf.PayNotifyURL,
TradeType: p.TradeType,
OpenID: p.OpenID,
}
rawRet, err := util.PostXML(payGateway, request)
if err != nil {
return
}
err = xml.Unmarshal(rawRet, &payOrder)
if err != nil {
return
}
if payOrder.ReturnCode == "SUCCESS" {
//pay success
if payOrder.ResultCode == "SUCCESS" {
err = nil
return
}
err = errors.New(payOrder.ErrCode + payOrder.ErrCodeDes)
return
}
err = errors.New("[msg : xmlUnmarshalError] [rawReturn : " + string(rawRet) + "] [params : " + str + "] [sign : " + sign + "]")
return
} | go | func (pcf *Pay) PrePayOrder(p *Params) (payOrder PreOrder, err error) {
nonceStr := util.RandomStr(32)
param := make(map[string]interface{})
param["appid"] = pcf.AppID
param["body"] = p.Body
param["mch_id"] = pcf.PayMchID
param["nonce_str"] =nonceStr
param["notify_url"] =pcf.PayNotifyURL
param["out_trade_no"] =p.OutTradeNo
param["spbill_create_ip"] =p.CreateIP
param["total_fee"] =p.TotalFee
param["trade_type"] =p.TradeType
param["openid"] = p.OpenID
bizKey := "&key="+pcf.PayKey
str := orderParam(param,bizKey)
sign := util.MD5Sum(str)
request := payRequest{
AppID: pcf.AppID,
MchID: pcf.PayMchID,
NonceStr: nonceStr,
Sign: sign,
Body: p.Body,
OutTradeNo: p.OutTradeNo,
TotalFee: p.TotalFee,
SpbillCreateIP: p.CreateIP,
NotifyURL: pcf.PayNotifyURL,
TradeType: p.TradeType,
OpenID: p.OpenID,
}
rawRet, err := util.PostXML(payGateway, request)
if err != nil {
return
}
err = xml.Unmarshal(rawRet, &payOrder)
if err != nil {
return
}
if payOrder.ReturnCode == "SUCCESS" {
//pay success
if payOrder.ResultCode == "SUCCESS" {
err = nil
return
}
err = errors.New(payOrder.ErrCode + payOrder.ErrCodeDes)
return
}
err = errors.New("[msg : xmlUnmarshalError] [rawReturn : " + string(rawRet) + "] [params : " + str + "] [sign : " + sign + "]")
return
} | [
"func",
"(",
"pcf",
"*",
"Pay",
")",
"PrePayOrder",
"(",
"p",
"*",
"Params",
")",
"(",
"payOrder",
"PreOrder",
",",
"err",
"error",
")",
"{",
"nonceStr",
":=",
"util",
".",
"RandomStr",
"(",
"32",
")",
"\n",
"param",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"param",
"[",
"\"",
"\"",
"]",
"=",
"pcf",
".",
"AppID",
"\n",
"param",
"[",
"\"",
"\"",
"]",
"=",
"p",
".",
"Body",
"\n",
"param",
"[",
"\"",
"\"",
"]",
"=",
"pcf",
".",
"PayMchID",
"\n",
"param",
"[",
"\"",
"\"",
"]",
"=",
"nonceStr",
"\n",
"param",
"[",
"\"",
"\"",
"]",
"=",
"pcf",
".",
"PayNotifyURL",
"\n",
"param",
"[",
"\"",
"\"",
"]",
"=",
"p",
".",
"OutTradeNo",
"\n",
"param",
"[",
"\"",
"\"",
"]",
"=",
"p",
".",
"CreateIP",
"\n",
"param",
"[",
"\"",
"\"",
"]",
"=",
"p",
".",
"TotalFee",
"\n",
"param",
"[",
"\"",
"\"",
"]",
"=",
"p",
".",
"TradeType",
"\n",
"param",
"[",
"\"",
"\"",
"]",
"=",
"p",
".",
"OpenID",
"\n\n",
"bizKey",
":=",
"\"",
"\"",
"+",
"pcf",
".",
"PayKey",
"\n",
"str",
":=",
"orderParam",
"(",
"param",
",",
"bizKey",
")",
"\n",
"sign",
":=",
"util",
".",
"MD5Sum",
"(",
"str",
")",
"\n",
"request",
":=",
"payRequest",
"{",
"AppID",
":",
"pcf",
".",
"AppID",
",",
"MchID",
":",
"pcf",
".",
"PayMchID",
",",
"NonceStr",
":",
"nonceStr",
",",
"Sign",
":",
"sign",
",",
"Body",
":",
"p",
".",
"Body",
",",
"OutTradeNo",
":",
"p",
".",
"OutTradeNo",
",",
"TotalFee",
":",
"p",
".",
"TotalFee",
",",
"SpbillCreateIP",
":",
"p",
".",
"CreateIP",
",",
"NotifyURL",
":",
"pcf",
".",
"PayNotifyURL",
",",
"TradeType",
":",
"p",
".",
"TradeType",
",",
"OpenID",
":",
"p",
".",
"OpenID",
",",
"}",
"\n",
"rawRet",
",",
"err",
":=",
"util",
".",
"PostXML",
"(",
"payGateway",
",",
"request",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"err",
"=",
"xml",
".",
"Unmarshal",
"(",
"rawRet",
",",
"&",
"payOrder",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"payOrder",
".",
"ReturnCode",
"==",
"\"",
"\"",
"{",
"//pay success",
"if",
"payOrder",
".",
"ResultCode",
"==",
"\"",
"\"",
"{",
"err",
"=",
"nil",
"\n",
"return",
"\n",
"}",
"\n",
"err",
"=",
"errors",
".",
"New",
"(",
"payOrder",
".",
"ErrCode",
"+",
"payOrder",
".",
"ErrCodeDes",
")",
"\n",
"return",
"\n",
"}",
"\n",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"string",
"(",
"rawRet",
")",
"+",
"\"",
"\"",
"+",
"str",
"+",
"\"",
"\"",
"+",
"sign",
"+",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}"
] | // PrePayOrder return data for invoke wechat payment | [
"PrePayOrder",
"return",
"data",
"for",
"invoke",
"wechat",
"payment"
] | 42332eca27305295d688bf251d3a279ea2de38fc | https://github.com/silenceper/wechat/blob/42332eca27305295d688bf251d3a279ea2de38fc/pay/pay.go#L90-L139 | train |
silenceper/wechat | pay/pay.go | PrePayID | func (pcf *Pay) PrePayID(p *Params) (prePayID string, err error) {
order, err := pcf.PrePayOrder(p)
if err != nil {
return
}
if order.PrePayID == "" {
err = errors.New("empty prepayid")
}
prePayID = order.PrePayID
return
} | go | func (pcf *Pay) PrePayID(p *Params) (prePayID string, err error) {
order, err := pcf.PrePayOrder(p)
if err != nil {
return
}
if order.PrePayID == "" {
err = errors.New("empty prepayid")
}
prePayID = order.PrePayID
return
} | [
"func",
"(",
"pcf",
"*",
"Pay",
")",
"PrePayID",
"(",
"p",
"*",
"Params",
")",
"(",
"prePayID",
"string",
",",
"err",
"error",
")",
"{",
"order",
",",
"err",
":=",
"pcf",
".",
"PrePayOrder",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"order",
".",
"PrePayID",
"==",
"\"",
"\"",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"prePayID",
"=",
"order",
".",
"PrePayID",
"\n",
"return",
"\n",
"}"
] | // PrePayID will request wechat merchant api and request for a pre payment order id | [
"PrePayID",
"will",
"request",
"wechat",
"merchant",
"api",
"and",
"request",
"for",
"a",
"pre",
"payment",
"order",
"id"
] | 42332eca27305295d688bf251d3a279ea2de38fc | https://github.com/silenceper/wechat/blob/42332eca27305295d688bf251d3a279ea2de38fc/pay/pay.go#L142-L152 | train |
silenceper/wechat | context/render.go | Render | func (ctx *Context) Render(bytes []byte) {
//debug
//fmt.Println("response msg = ", string(bytes))
ctx.Writer.WriteHeader(200)
_, err := ctx.Writer.Write(bytes)
if err != nil {
panic(err)
}
} | go | func (ctx *Context) Render(bytes []byte) {
//debug
//fmt.Println("response msg = ", string(bytes))
ctx.Writer.WriteHeader(200)
_, err := ctx.Writer.Write(bytes)
if err != nil {
panic(err)
}
} | [
"func",
"(",
"ctx",
"*",
"Context",
")",
"Render",
"(",
"bytes",
"[",
"]",
"byte",
")",
"{",
"//debug",
"//fmt.Println(\"response msg = \", string(bytes))",
"ctx",
".",
"Writer",
".",
"WriteHeader",
"(",
"200",
")",
"\n",
"_",
",",
"err",
":=",
"ctx",
".",
"Writer",
".",
"Write",
"(",
"bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] | //Render render from bytes | [
"Render",
"render",
"from",
"bytes"
] | 42332eca27305295d688bf251d3a279ea2de38fc | https://github.com/silenceper/wechat/blob/42332eca27305295d688bf251d3a279ea2de38fc/context/render.go#L12-L20 | train |
silenceper/wechat | context/render.go | String | func (ctx *Context) String(str string) {
writeContextType(ctx.Writer, plainContentType)
ctx.Render([]byte(str))
} | go | func (ctx *Context) String(str string) {
writeContextType(ctx.Writer, plainContentType)
ctx.Render([]byte(str))
} | [
"func",
"(",
"ctx",
"*",
"Context",
")",
"String",
"(",
"str",
"string",
")",
"{",
"writeContextType",
"(",
"ctx",
".",
"Writer",
",",
"plainContentType",
")",
"\n",
"ctx",
".",
"Render",
"(",
"[",
"]",
"byte",
"(",
"str",
")",
")",
"\n",
"}"
] | //String render from string | [
"String",
"render",
"from",
"string"
] | 42332eca27305295d688bf251d3a279ea2de38fc | https://github.com/silenceper/wechat/blob/42332eca27305295d688bf251d3a279ea2de38fc/context/render.go#L23-L26 | train |
silenceper/wechat | context/render.go | XML | func (ctx *Context) XML(obj interface{}) {
writeContextType(ctx.Writer, xmlContentType)
bytes, err := xml.Marshal(obj)
if err != nil {
panic(err)
}
ctx.Render(bytes)
} | go | func (ctx *Context) XML(obj interface{}) {
writeContextType(ctx.Writer, xmlContentType)
bytes, err := xml.Marshal(obj)
if err != nil {
panic(err)
}
ctx.Render(bytes)
} | [
"func",
"(",
"ctx",
"*",
"Context",
")",
"XML",
"(",
"obj",
"interface",
"{",
"}",
")",
"{",
"writeContextType",
"(",
"ctx",
".",
"Writer",
",",
"xmlContentType",
")",
"\n",
"bytes",
",",
"err",
":=",
"xml",
".",
"Marshal",
"(",
"obj",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"ctx",
".",
"Render",
"(",
"bytes",
")",
"\n",
"}"
] | //XML render to xml | [
"XML",
"render",
"to",
"xml"
] | 42332eca27305295d688bf251d3a279ea2de38fc | https://github.com/silenceper/wechat/blob/42332eca27305295d688bf251d3a279ea2de38fc/context/render.go#L29-L36 | train |
elazarl/goproxy | examples/goproxy-httpdump/httpdump.go | Close | func (t *TeeReadCloser) Close() error {
err1 := t.c.Close()
err2 := t.w.Close()
if err1 != nil {
return err1
}
return err2
} | go | func (t *TeeReadCloser) Close() error {
err1 := t.c.Close()
err2 := t.w.Close()
if err1 != nil {
return err1
}
return err2
} | [
"func",
"(",
"t",
"*",
"TeeReadCloser",
")",
"Close",
"(",
")",
"error",
"{",
"err1",
":=",
"t",
".",
"c",
".",
"Close",
"(",
")",
"\n",
"err2",
":=",
"t",
".",
"w",
".",
"Close",
"(",
")",
"\n",
"if",
"err1",
"!=",
"nil",
"{",
"return",
"err1",
"\n",
"}",
"\n",
"return",
"err2",
"\n",
"}"
] | // Close attempts to close the reader and write. It returns an error if both
// failed to Close. | [
"Close",
"attempts",
"to",
"close",
"the",
"reader",
"and",
"write",
".",
"It",
"returns",
"an",
"error",
"if",
"both",
"failed",
"to",
"Close",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/examples/goproxy-httpdump/httpdump.go#L198-L205 | train |
elazarl/goproxy | ext/html/html.go | HandleStringReader | func HandleStringReader(f func(r io.Reader, ctx *goproxy.ProxyCtx) io.Reader) goproxy.RespHandler {
return goproxy.FuncRespHandler(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
if ctx.Error != nil {
return nil
}
charsetName := ctx.Charset()
if charsetName == "" {
charsetName = "utf-8"
}
if strings.ToLower(charsetName) != "utf-8" {
r, err := charset.NewReader(charsetName, resp.Body)
if err != nil {
ctx.Warnf("Cannot convert from %v to utf-8: %v", charsetName, err)
return resp
}
tr, err := charset.TranslatorTo(charsetName)
if err != nil {
ctx.Warnf("Can't translate to %v from utf-8: %v", charsetName, err)
return resp
}
if err != nil {
ctx.Warnf("Cannot translate to %v: %v", charsetName, err)
return resp
}
newr := charset.NewTranslatingReader(f(r, ctx), tr)
resp.Body = &readFirstCloseBoth{ioutil.NopCloser(newr), resp.Body}
} else {
//no translation is needed, already at utf-8
resp.Body = &readFirstCloseBoth{ioutil.NopCloser(f(resp.Body, ctx)), resp.Body}
}
return resp
})
} | go | func HandleStringReader(f func(r io.Reader, ctx *goproxy.ProxyCtx) io.Reader) goproxy.RespHandler {
return goproxy.FuncRespHandler(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
if ctx.Error != nil {
return nil
}
charsetName := ctx.Charset()
if charsetName == "" {
charsetName = "utf-8"
}
if strings.ToLower(charsetName) != "utf-8" {
r, err := charset.NewReader(charsetName, resp.Body)
if err != nil {
ctx.Warnf("Cannot convert from %v to utf-8: %v", charsetName, err)
return resp
}
tr, err := charset.TranslatorTo(charsetName)
if err != nil {
ctx.Warnf("Can't translate to %v from utf-8: %v", charsetName, err)
return resp
}
if err != nil {
ctx.Warnf("Cannot translate to %v: %v", charsetName, err)
return resp
}
newr := charset.NewTranslatingReader(f(r, ctx), tr)
resp.Body = &readFirstCloseBoth{ioutil.NopCloser(newr), resp.Body}
} else {
//no translation is needed, already at utf-8
resp.Body = &readFirstCloseBoth{ioutil.NopCloser(f(resp.Body, ctx)), resp.Body}
}
return resp
})
} | [
"func",
"HandleStringReader",
"(",
"f",
"func",
"(",
"r",
"io",
".",
"Reader",
",",
"ctx",
"*",
"goproxy",
".",
"ProxyCtx",
")",
"io",
".",
"Reader",
")",
"goproxy",
".",
"RespHandler",
"{",
"return",
"goproxy",
".",
"FuncRespHandler",
"(",
"func",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"ctx",
"*",
"goproxy",
".",
"ProxyCtx",
")",
"*",
"http",
".",
"Response",
"{",
"if",
"ctx",
".",
"Error",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"charsetName",
":=",
"ctx",
".",
"Charset",
"(",
")",
"\n",
"if",
"charsetName",
"==",
"\"",
"\"",
"{",
"charsetName",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"strings",
".",
"ToLower",
"(",
"charsetName",
")",
"!=",
"\"",
"\"",
"{",
"r",
",",
"err",
":=",
"charset",
".",
"NewReader",
"(",
"charsetName",
",",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ctx",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"charsetName",
",",
"err",
")",
"\n",
"return",
"resp",
"\n",
"}",
"\n",
"tr",
",",
"err",
":=",
"charset",
".",
"TranslatorTo",
"(",
"charsetName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ctx",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"charsetName",
",",
"err",
")",
"\n",
"return",
"resp",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ctx",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"charsetName",
",",
"err",
")",
"\n",
"return",
"resp",
"\n",
"}",
"\n",
"newr",
":=",
"charset",
".",
"NewTranslatingReader",
"(",
"f",
"(",
"r",
",",
"ctx",
")",
",",
"tr",
")",
"\n",
"resp",
".",
"Body",
"=",
"&",
"readFirstCloseBoth",
"{",
"ioutil",
".",
"NopCloser",
"(",
"newr",
")",
",",
"resp",
".",
"Body",
"}",
"\n",
"}",
"else",
"{",
"//no translation is needed, already at utf-8",
"resp",
".",
"Body",
"=",
"&",
"readFirstCloseBoth",
"{",
"ioutil",
".",
"NopCloser",
"(",
"f",
"(",
"resp",
".",
"Body",
",",
"ctx",
")",
")",
",",
"resp",
".",
"Body",
"}",
"\n",
"}",
"\n",
"return",
"resp",
"\n",
"}",
")",
"\n",
"}"
] | // Will receive an input stream which would convert the response to utf-8
// The given function must close the reader r, in order to close the response body. | [
"Will",
"receive",
"an",
"input",
"stream",
"which",
"would",
"convert",
"the",
"response",
"to",
"utf",
"-",
"8",
"The",
"given",
"function",
"must",
"close",
"the",
"reader",
"r",
"in",
"order",
"to",
"close",
"the",
"response",
"body",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/ext/html/html.go#L51-L84 | train |
elazarl/goproxy | transport/transport.go | RegisterProtocol | func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) {
if scheme == "http" || scheme == "https" {
panic("protocol " + scheme + " already registered")
}
t.lk.Lock()
defer t.lk.Unlock()
if t.altProto == nil {
t.altProto = make(map[string]RoundTripper)
}
if _, exists := t.altProto[scheme]; exists {
panic("protocol " + scheme + " already registered")
}
t.altProto[scheme] = rt
} | go | func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) {
if scheme == "http" || scheme == "https" {
panic("protocol " + scheme + " already registered")
}
t.lk.Lock()
defer t.lk.Unlock()
if t.altProto == nil {
t.altProto = make(map[string]RoundTripper)
}
if _, exists := t.altProto[scheme]; exists {
panic("protocol " + scheme + " already registered")
}
t.altProto[scheme] = rt
} | [
"func",
"(",
"t",
"*",
"Transport",
")",
"RegisterProtocol",
"(",
"scheme",
"string",
",",
"rt",
"RoundTripper",
")",
"{",
"if",
"scheme",
"==",
"\"",
"\"",
"||",
"scheme",
"==",
"\"",
"\"",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"scheme",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"t",
".",
"lk",
".",
"Lock",
"(",
")",
"\n",
"defer",
"t",
".",
"lk",
".",
"Unlock",
"(",
")",
"\n",
"if",
"t",
".",
"altProto",
"==",
"nil",
"{",
"t",
".",
"altProto",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"RoundTripper",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"exists",
":=",
"t",
".",
"altProto",
"[",
"scheme",
"]",
";",
"exists",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"scheme",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"t",
".",
"altProto",
"[",
"scheme",
"]",
"=",
"rt",
"\n",
"}"
] | // RegisterProtocol registers a new protocol with scheme.
// The Transport will pass requests using the given scheme to rt.
// It is rt's responsibility to simulate HTTP request semantics.
//
// RegisterProtocol can be used by other packages to provide
// implementations of protocol schemes like "ftp" or "file". | [
"RegisterProtocol",
"registers",
"a",
"new",
"protocol",
"with",
"scheme",
".",
"The",
"Transport",
"will",
"pass",
"requests",
"using",
"the",
"given",
"scheme",
"to",
"rt",
".",
"It",
"is",
"rt",
"s",
"responsibility",
"to",
"simulate",
"HTTP",
"request",
"semantics",
".",
"RegisterProtocol",
"can",
"be",
"used",
"by",
"other",
"packages",
"to",
"provide",
"implementations",
"of",
"protocol",
"schemes",
"like",
"ftp",
"or",
"file",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/transport/transport.go#L185-L198 | train |
elazarl/goproxy | transport/transport.go | CloseIdleConnections | func (t *Transport) CloseIdleConnections() {
t.lk.Lock()
defer t.lk.Unlock()
if t.idleConn == nil {
return
}
for _, conns := range t.idleConn {
for _, pconn := range conns {
pconn.close()
}
}
t.idleConn = make(map[string][]*persistConn)
} | go | func (t *Transport) CloseIdleConnections() {
t.lk.Lock()
defer t.lk.Unlock()
if t.idleConn == nil {
return
}
for _, conns := range t.idleConn {
for _, pconn := range conns {
pconn.close()
}
}
t.idleConn = make(map[string][]*persistConn)
} | [
"func",
"(",
"t",
"*",
"Transport",
")",
"CloseIdleConnections",
"(",
")",
"{",
"t",
".",
"lk",
".",
"Lock",
"(",
")",
"\n",
"defer",
"t",
".",
"lk",
".",
"Unlock",
"(",
")",
"\n",
"if",
"t",
".",
"idleConn",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"conns",
":=",
"range",
"t",
".",
"idleConn",
"{",
"for",
"_",
",",
"pconn",
":=",
"range",
"conns",
"{",
"pconn",
".",
"close",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"t",
".",
"idleConn",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"persistConn",
")",
"\n",
"}"
] | // CloseIdleConnections closes any connections which were previously
// connected from previous requests but are now sitting idle in
// a "keep-alive" state. It does not interrupt any connections currently
// in use. | [
"CloseIdleConnections",
"closes",
"any",
"connections",
"which",
"were",
"previously",
"connected",
"from",
"previous",
"requests",
"but",
"are",
"now",
"sitting",
"idle",
"in",
"a",
"keep",
"-",
"alive",
"state",
".",
"It",
"does",
"not",
"interrupt",
"any",
"connections",
"currently",
"in",
"use",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/transport/transport.go#L204-L216 | train |
elazarl/goproxy | transport/transport.go | getenvEitherCase | func getenvEitherCase(k string) string {
if v := os.Getenv(strings.ToUpper(k)); v != "" {
return v
}
return os.Getenv(strings.ToLower(k))
} | go | func getenvEitherCase(k string) string {
if v := os.Getenv(strings.ToUpper(k)); v != "" {
return v
}
return os.Getenv(strings.ToLower(k))
} | [
"func",
"getenvEitherCase",
"(",
"k",
"string",
")",
"string",
"{",
"if",
"v",
":=",
"os",
".",
"Getenv",
"(",
"strings",
".",
"ToUpper",
"(",
"k",
")",
")",
";",
"v",
"!=",
"\"",
"\"",
"{",
"return",
"v",
"\n",
"}",
"\n",
"return",
"os",
".",
"Getenv",
"(",
"strings",
".",
"ToLower",
"(",
"k",
")",
")",
"\n",
"}"
] | //
// Private implementation past this point.
// | [
"Private",
"implementation",
"past",
"this",
"point",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/transport/transport.go#L222-L227 | train |
elazarl/goproxy | transport/transport.go | proxyAuth | func (cm *connectMethod) proxyAuth() string {
if cm.proxyURL == nil {
return ""
}
if u := cm.proxyURL.User; u != nil {
return "Basic " + base64.URLEncoding.EncodeToString([]byte(u.String()))
}
return ""
} | go | func (cm *connectMethod) proxyAuth() string {
if cm.proxyURL == nil {
return ""
}
if u := cm.proxyURL.User; u != nil {
return "Basic " + base64.URLEncoding.EncodeToString([]byte(u.String()))
}
return ""
} | [
"func",
"(",
"cm",
"*",
"connectMethod",
")",
"proxyAuth",
"(",
")",
"string",
"{",
"if",
"cm",
".",
"proxyURL",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"u",
":=",
"cm",
".",
"proxyURL",
".",
"User",
";",
"u",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"+",
"base64",
".",
"URLEncoding",
".",
"EncodeToString",
"(",
"[",
"]",
"byte",
"(",
"u",
".",
"String",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // proxyAuth returns the Proxy-Authorization header to set
// on requests, if applicable. | [
"proxyAuth",
"returns",
"the",
"Proxy",
"-",
"Authorization",
"header",
"to",
"set",
"on",
"requests",
"if",
"applicable",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/transport/transport.go#L246-L254 | train |
elazarl/goproxy | transport/transport.go | putIdleConn | func (t *Transport) putIdleConn(pconn *persistConn) bool {
t.lk.Lock()
defer t.lk.Unlock()
if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 {
pconn.close()
return false
}
if pconn.isBroken() {
return false
}
key := pconn.cacheKey
max := t.MaxIdleConnsPerHost
if max == 0 {
max = DefaultMaxIdleConnsPerHost
}
if len(t.idleConn[key]) >= max {
pconn.close()
return false
}
t.idleConn[key] = append(t.idleConn[key], pconn)
return true
} | go | func (t *Transport) putIdleConn(pconn *persistConn) bool {
t.lk.Lock()
defer t.lk.Unlock()
if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 {
pconn.close()
return false
}
if pconn.isBroken() {
return false
}
key := pconn.cacheKey
max := t.MaxIdleConnsPerHost
if max == 0 {
max = DefaultMaxIdleConnsPerHost
}
if len(t.idleConn[key]) >= max {
pconn.close()
return false
}
t.idleConn[key] = append(t.idleConn[key], pconn)
return true
} | [
"func",
"(",
"t",
"*",
"Transport",
")",
"putIdleConn",
"(",
"pconn",
"*",
"persistConn",
")",
"bool",
"{",
"t",
".",
"lk",
".",
"Lock",
"(",
")",
"\n",
"defer",
"t",
".",
"lk",
".",
"Unlock",
"(",
")",
"\n",
"if",
"t",
".",
"DisableKeepAlives",
"||",
"t",
".",
"MaxIdleConnsPerHost",
"<",
"0",
"{",
"pconn",
".",
"close",
"(",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"if",
"pconn",
".",
"isBroken",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"key",
":=",
"pconn",
".",
"cacheKey",
"\n",
"max",
":=",
"t",
".",
"MaxIdleConnsPerHost",
"\n",
"if",
"max",
"==",
"0",
"{",
"max",
"=",
"DefaultMaxIdleConnsPerHost",
"\n",
"}",
"\n",
"if",
"len",
"(",
"t",
".",
"idleConn",
"[",
"key",
"]",
")",
">=",
"max",
"{",
"pconn",
".",
"close",
"(",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"t",
".",
"idleConn",
"[",
"key",
"]",
"=",
"append",
"(",
"t",
".",
"idleConn",
"[",
"key",
"]",
",",
"pconn",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // putIdleConn adds pconn to the list of idle persistent connections awaiting
// a new request.
// If pconn is no longer needed or not in a good state, putIdleConn
// returns false. | [
"putIdleConn",
"adds",
"pconn",
"to",
"the",
"list",
"of",
"idle",
"persistent",
"connections",
"awaiting",
"a",
"new",
"request",
".",
"If",
"pconn",
"is",
"no",
"longer",
"needed",
"or",
"not",
"in",
"a",
"good",
"state",
"putIdleConn",
"returns",
"false",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/transport/transport.go#L260-L281 | train |
elazarl/goproxy | transport/transport.go | useProxy | func useProxy(addr string) bool {
if len(addr) == 0 {
return true
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
return false
}
if host == "localhost" {
return false
}
if ip := net.ParseIP(host); ip != nil {
if ip.IsLoopback() {
return false
}
}
no_proxy := getenvEitherCase("NO_PROXY")
if no_proxy == "*" {
return false
}
addr = strings.ToLower(strings.TrimSpace(addr))
if hasPort(addr) {
addr = addr[:strings.LastIndex(addr, ":")]
}
for _, p := range strings.Split(no_proxy, ",") {
p = strings.ToLower(strings.TrimSpace(p))
if len(p) == 0 {
continue
}
if hasPort(p) {
p = p[:strings.LastIndex(p, ":")]
}
if addr == p || (p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:])) {
return false
}
}
return true
} | go | func useProxy(addr string) bool {
if len(addr) == 0 {
return true
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
return false
}
if host == "localhost" {
return false
}
if ip := net.ParseIP(host); ip != nil {
if ip.IsLoopback() {
return false
}
}
no_proxy := getenvEitherCase("NO_PROXY")
if no_proxy == "*" {
return false
}
addr = strings.ToLower(strings.TrimSpace(addr))
if hasPort(addr) {
addr = addr[:strings.LastIndex(addr, ":")]
}
for _, p := range strings.Split(no_proxy, ",") {
p = strings.ToLower(strings.TrimSpace(p))
if len(p) == 0 {
continue
}
if hasPort(p) {
p = p[:strings.LastIndex(p, ":")]
}
if addr == p || (p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:])) {
return false
}
}
return true
} | [
"func",
"useProxy",
"(",
"addr",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"addr",
")",
"==",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n",
"host",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"host",
"==",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"host",
")",
";",
"ip",
"!=",
"nil",
"{",
"if",
"ip",
".",
"IsLoopback",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n\n",
"no_proxy",
":=",
"getenvEitherCase",
"(",
"\"",
"\"",
")",
"\n",
"if",
"no_proxy",
"==",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"addr",
"=",
"strings",
".",
"ToLower",
"(",
"strings",
".",
"TrimSpace",
"(",
"addr",
")",
")",
"\n",
"if",
"hasPort",
"(",
"addr",
")",
"{",
"addr",
"=",
"addr",
"[",
":",
"strings",
".",
"LastIndex",
"(",
"addr",
",",
"\"",
"\"",
")",
"]",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"p",
":=",
"range",
"strings",
".",
"Split",
"(",
"no_proxy",
",",
"\"",
"\"",
")",
"{",
"p",
"=",
"strings",
".",
"ToLower",
"(",
"strings",
".",
"TrimSpace",
"(",
"p",
")",
")",
"\n",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"hasPort",
"(",
"p",
")",
"{",
"p",
"=",
"p",
"[",
":",
"strings",
".",
"LastIndex",
"(",
"p",
",",
"\"",
"\"",
")",
"]",
"\n",
"}",
"\n",
"if",
"addr",
"==",
"p",
"||",
"(",
"p",
"[",
"0",
"]",
"==",
"'.'",
"&&",
"(",
"strings",
".",
"HasSuffix",
"(",
"addr",
",",
"p",
")",
"||",
"addr",
"==",
"p",
"[",
"1",
":",
"]",
")",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // useProxy returns true if requests to addr should use a proxy,
// according to the NO_PROXY or no_proxy environment variable.
// addr is always a canonicalAddr with a host and port. | [
"useProxy",
"returns",
"true",
"if",
"requests",
"to",
"addr",
"should",
"use",
"a",
"proxy",
"according",
"to",
"the",
"NO_PROXY",
"or",
"no_proxy",
"environment",
"variable",
".",
"addr",
"is",
"always",
"a",
"canonicalAddr",
"with",
"a",
"host",
"and",
"port",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/transport/transport.go#L419-L459 | train |
elazarl/goproxy | transport/transport.go | tlsHost | func (cm *connectMethod) tlsHost() string {
h := cm.targetAddr
if hasPort(h) {
h = h[:strings.LastIndex(h, ":")]
}
return h
} | go | func (cm *connectMethod) tlsHost() string {
h := cm.targetAddr
if hasPort(h) {
h = h[:strings.LastIndex(h, ":")]
}
return h
} | [
"func",
"(",
"cm",
"*",
"connectMethod",
")",
"tlsHost",
"(",
")",
"string",
"{",
"h",
":=",
"cm",
".",
"targetAddr",
"\n",
"if",
"hasPort",
"(",
"h",
")",
"{",
"h",
"=",
"h",
"[",
":",
"strings",
".",
"LastIndex",
"(",
"h",
",",
"\"",
"\"",
")",
"]",
"\n",
"}",
"\n",
"return",
"h",
"\n",
"}"
] | // tlsHost returns the host name to match against the peer's
// TLS certificate. | [
"tlsHost",
"returns",
"the",
"host",
"name",
"to",
"match",
"against",
"the",
"peer",
"s",
"TLS",
"certificate",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/transport/transport.go#L499-L505 | train |
elazarl/goproxy | regretable/regretreader.go | NewRegretableReaderCloserSize | func NewRegretableReaderCloserSize(rc io.ReadCloser, size int) *RegretableReaderCloser {
return &RegretableReaderCloser{*NewRegretableReaderSize(rc, size), rc}
} | go | func NewRegretableReaderCloserSize(rc io.ReadCloser, size int) *RegretableReaderCloser {
return &RegretableReaderCloser{*NewRegretableReaderSize(rc, size), rc}
} | [
"func",
"NewRegretableReaderCloserSize",
"(",
"rc",
"io",
".",
"ReadCloser",
",",
"size",
"int",
")",
"*",
"RegretableReaderCloser",
"{",
"return",
"&",
"RegretableReaderCloser",
"{",
"*",
"NewRegretableReaderSize",
"(",
"rc",
",",
"size",
")",
",",
"rc",
"}",
"\n",
"}"
] | // initialize a RegretableReaderCloser with underlying readCloser rc | [
"initialize",
"a",
"RegretableReaderCloser",
"with",
"underlying",
"readCloser",
"rc"
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/regretable/regretreader.go#L41-L43 | train |
elazarl/goproxy | regretable/regretreader.go | NewRegretableReaderSize | func NewRegretableReaderSize(r io.Reader, size int) *RegretableReader {
return &RegretableReader{reader: r, buf: make([]byte, size)}
} | go | func NewRegretableReaderSize(r io.Reader, size int) *RegretableReader {
return &RegretableReader{reader: r, buf: make([]byte, size)}
} | [
"func",
"NewRegretableReaderSize",
"(",
"r",
"io",
".",
"Reader",
",",
"size",
"int",
")",
"*",
"RegretableReader",
"{",
"return",
"&",
"RegretableReader",
"{",
"reader",
":",
"r",
",",
"buf",
":",
"make",
"(",
"[",
"]",
"byte",
",",
"size",
")",
"}",
"\n",
"}"
] | // initialize a RegretableReader with underlying reader r, whose buffer is size bytes long | [
"initialize",
"a",
"RegretableReader",
"with",
"underlying",
"reader",
"r",
"whose",
"buffer",
"is",
"size",
"bytes",
"long"
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/regretable/regretreader.go#L71-L73 | train |
elazarl/goproxy | regretable/regretreader.go | Read | func (rb *RegretableReader) Read(p []byte) (n int, err error) {
if rb.overflow {
return rb.reader.Read(p)
}
if rb.r < rb.w {
n = copy(p, rb.buf[rb.r:rb.w])
rb.r += n
return
}
n, err = rb.reader.Read(p)
bn := copy(rb.buf[rb.w:], p[:n])
rb.w, rb.r = rb.w+bn, rb.w+n
if bn < n {
rb.overflow = true
}
return
} | go | func (rb *RegretableReader) Read(p []byte) (n int, err error) {
if rb.overflow {
return rb.reader.Read(p)
}
if rb.r < rb.w {
n = copy(p, rb.buf[rb.r:rb.w])
rb.r += n
return
}
n, err = rb.reader.Read(p)
bn := copy(rb.buf[rb.w:], p[:n])
rb.w, rb.r = rb.w+bn, rb.w+n
if bn < n {
rb.overflow = true
}
return
} | [
"func",
"(",
"rb",
"*",
"RegretableReader",
")",
"Read",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"if",
"rb",
".",
"overflow",
"{",
"return",
"rb",
".",
"reader",
".",
"Read",
"(",
"p",
")",
"\n",
"}",
"\n",
"if",
"rb",
".",
"r",
"<",
"rb",
".",
"w",
"{",
"n",
"=",
"copy",
"(",
"p",
",",
"rb",
".",
"buf",
"[",
"rb",
".",
"r",
":",
"rb",
".",
"w",
"]",
")",
"\n",
"rb",
".",
"r",
"+=",
"n",
"\n",
"return",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"rb",
".",
"reader",
".",
"Read",
"(",
"p",
")",
"\n",
"bn",
":=",
"copy",
"(",
"rb",
".",
"buf",
"[",
"rb",
".",
"w",
":",
"]",
",",
"p",
"[",
":",
"n",
"]",
")",
"\n",
"rb",
".",
"w",
",",
"rb",
".",
"r",
"=",
"rb",
".",
"w",
"+",
"bn",
",",
"rb",
".",
"w",
"+",
"n",
"\n",
"if",
"bn",
"<",
"n",
"{",
"rb",
".",
"overflow",
"=",
"true",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // reads from the underlying reader. Will buffer all input until Regret is called. | [
"reads",
"from",
"the",
"underlying",
"reader",
".",
"Will",
"buffer",
"all",
"input",
"until",
"Regret",
"is",
"called",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/regretable/regretreader.go#L81-L97 | train |
elazarl/goproxy | examples/goproxy-jquery-version/main.go | findScriptSrc | func findScriptSrc(html string) []string {
srcs := make([]string, 0)
matches := scriptMatcher.FindAllStringIndex(html, -1)
for _, match := range matches {
// -1 to capture the whitespace at the end of the script tag
srcMatch := srcAttrMatcher.FindStringSubmatch(html[match[1]-1:])
if srcMatch != nil {
srcs = append(srcs, srcMatch[1])
}
}
return srcs
} | go | func findScriptSrc(html string) []string {
srcs := make([]string, 0)
matches := scriptMatcher.FindAllStringIndex(html, -1)
for _, match := range matches {
// -1 to capture the whitespace at the end of the script tag
srcMatch := srcAttrMatcher.FindStringSubmatch(html[match[1]-1:])
if srcMatch != nil {
srcs = append(srcs, srcMatch[1])
}
}
return srcs
} | [
"func",
"findScriptSrc",
"(",
"html",
"string",
")",
"[",
"]",
"string",
"{",
"srcs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"matches",
":=",
"scriptMatcher",
".",
"FindAllStringIndex",
"(",
"html",
",",
"-",
"1",
")",
"\n",
"for",
"_",
",",
"match",
":=",
"range",
"matches",
"{",
"// -1 to capture the whitespace at the end of the script tag",
"srcMatch",
":=",
"srcAttrMatcher",
".",
"FindStringSubmatch",
"(",
"html",
"[",
"match",
"[",
"1",
"]",
"-",
"1",
":",
"]",
")",
"\n",
"if",
"srcMatch",
"!=",
"nil",
"{",
"srcs",
"=",
"append",
"(",
"srcs",
",",
"srcMatch",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"srcs",
"\n",
"}"
] | // findScripts returns all sources of HTML script tags found in input text. | [
"findScripts",
"returns",
"all",
"sources",
"of",
"HTML",
"script",
"tags",
"found",
"in",
"input",
"text",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/examples/goproxy-jquery-version/main.go#L18-L29 | train |
elazarl/goproxy | examples/goproxy-jquery-version/main.go | NewJqueryVersionProxy | func NewJqueryVersionProxy() *goproxy.ProxyHttpServer {
proxy := goproxy.NewProxyHttpServer()
m := make(map[string]string)
jqueryMatcher := regexp.MustCompile(`(?i:jquery\.)`)
proxy.OnResponse(goproxy_html.IsHtml).Do(goproxy_html.HandleString(
func(s string, ctx *goproxy.ProxyCtx) string {
for _, src := range findScriptSrc(s) {
if !jqueryMatcher.MatchString(src) {
continue
}
prev, ok := m[ctx.Req.Host]
if ok {
if prev != src {
ctx.Warnf("In %v, Contradicting jqueries %v %v",
ctx.Req.URL, prev, src)
break
}
} else {
ctx.Warnf("%s uses jquery %s", ctx.Req.Host, src)
m[ctx.Req.Host] = src
}
}
return s
}))
return proxy
} | go | func NewJqueryVersionProxy() *goproxy.ProxyHttpServer {
proxy := goproxy.NewProxyHttpServer()
m := make(map[string]string)
jqueryMatcher := regexp.MustCompile(`(?i:jquery\.)`)
proxy.OnResponse(goproxy_html.IsHtml).Do(goproxy_html.HandleString(
func(s string, ctx *goproxy.ProxyCtx) string {
for _, src := range findScriptSrc(s) {
if !jqueryMatcher.MatchString(src) {
continue
}
prev, ok := m[ctx.Req.Host]
if ok {
if prev != src {
ctx.Warnf("In %v, Contradicting jqueries %v %v",
ctx.Req.URL, prev, src)
break
}
} else {
ctx.Warnf("%s uses jquery %s", ctx.Req.Host, src)
m[ctx.Req.Host] = src
}
}
return s
}))
return proxy
} | [
"func",
"NewJqueryVersionProxy",
"(",
")",
"*",
"goproxy",
".",
"ProxyHttpServer",
"{",
"proxy",
":=",
"goproxy",
".",
"NewProxyHttpServer",
"(",
")",
"\n",
"m",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"jqueryMatcher",
":=",
"regexp",
".",
"MustCompile",
"(",
"`(?i:jquery\\.)`",
")",
"\n",
"proxy",
".",
"OnResponse",
"(",
"goproxy_html",
".",
"IsHtml",
")",
".",
"Do",
"(",
"goproxy_html",
".",
"HandleString",
"(",
"func",
"(",
"s",
"string",
",",
"ctx",
"*",
"goproxy",
".",
"ProxyCtx",
")",
"string",
"{",
"for",
"_",
",",
"src",
":=",
"range",
"findScriptSrc",
"(",
"s",
")",
"{",
"if",
"!",
"jqueryMatcher",
".",
"MatchString",
"(",
"src",
")",
"{",
"continue",
"\n",
"}",
"\n",
"prev",
",",
"ok",
":=",
"m",
"[",
"ctx",
".",
"Req",
".",
"Host",
"]",
"\n",
"if",
"ok",
"{",
"if",
"prev",
"!=",
"src",
"{",
"ctx",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"ctx",
".",
"Req",
".",
"URL",
",",
"prev",
",",
"src",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"else",
"{",
"ctx",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"ctx",
".",
"Req",
".",
"Host",
",",
"src",
")",
"\n",
"m",
"[",
"ctx",
".",
"Req",
".",
"Host",
"]",
"=",
"src",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}",
")",
")",
"\n",
"return",
"proxy",
"\n",
"}"
] | // NewJQueryVersionProxy creates a proxy checking responses HTML content, looks
// for scripts referencing jQuery library and emits warnings if different
// versions of the library are being used for a given host. | [
"NewJQueryVersionProxy",
"creates",
"a",
"proxy",
"checking",
"responses",
"HTML",
"content",
"looks",
"for",
"scripts",
"referencing",
"jQuery",
"library",
"and",
"emits",
"warnings",
"if",
"different",
"versions",
"of",
"the",
"library",
"are",
"being",
"used",
"for",
"a",
"given",
"host",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/examples/goproxy-jquery-version/main.go#L34-L59 | train |
elazarl/goproxy | proxy.go | NewProxyHttpServer | func NewProxyHttpServer() *ProxyHttpServer {
proxy := ProxyHttpServer{
Logger: log.New(os.Stderr, "", log.LstdFlags),
reqHandlers: []ReqHandler{},
respHandlers: []RespHandler{},
httpsHandlers: []HttpsHandler{},
NonproxyHandler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
http.Error(w, "This is a proxy server. Does not respond to non-proxy requests.", 500)
}),
Tr: &http.Transport{TLSClientConfig: tlsClientSkipVerify, Proxy: http.ProxyFromEnvironment},
}
proxy.ConnectDial = dialerFromEnv(&proxy)
return &proxy
} | go | func NewProxyHttpServer() *ProxyHttpServer {
proxy := ProxyHttpServer{
Logger: log.New(os.Stderr, "", log.LstdFlags),
reqHandlers: []ReqHandler{},
respHandlers: []RespHandler{},
httpsHandlers: []HttpsHandler{},
NonproxyHandler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
http.Error(w, "This is a proxy server. Does not respond to non-proxy requests.", 500)
}),
Tr: &http.Transport{TLSClientConfig: tlsClientSkipVerify, Proxy: http.ProxyFromEnvironment},
}
proxy.ConnectDial = dialerFromEnv(&proxy)
return &proxy
} | [
"func",
"NewProxyHttpServer",
"(",
")",
"*",
"ProxyHttpServer",
"{",
"proxy",
":=",
"ProxyHttpServer",
"{",
"Logger",
":",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\"",
",",
"log",
".",
"LstdFlags",
")",
",",
"reqHandlers",
":",
"[",
"]",
"ReqHandler",
"{",
"}",
",",
"respHandlers",
":",
"[",
"]",
"RespHandler",
"{",
"}",
",",
"httpsHandlers",
":",
"[",
"]",
"HttpsHandler",
"{",
"}",
",",
"NonproxyHandler",
":",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"500",
")",
"\n",
"}",
")",
",",
"Tr",
":",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"tlsClientSkipVerify",
",",
"Proxy",
":",
"http",
".",
"ProxyFromEnvironment",
"}",
",",
"}",
"\n",
"proxy",
".",
"ConnectDial",
"=",
"dialerFromEnv",
"(",
"&",
"proxy",
")",
"\n\n",
"return",
"&",
"proxy",
"\n",
"}"
] | // NewProxyHttpServer creates and returns a proxy server, logging to stderr by default | [
"NewProxyHttpServer",
"creates",
"and",
"returns",
"a",
"proxy",
"server",
"logging",
"to",
"stderr",
"by",
"default"
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/proxy.go#L153-L167 | train |
elazarl/goproxy | actions.go | HandleConnect | func (f FuncHttpsHandler) HandleConnect(host string, ctx *ProxyCtx) (*ConnectAction, string) {
return f(host, ctx)
} | go | func (f FuncHttpsHandler) HandleConnect(host string, ctx *ProxyCtx) (*ConnectAction, string) {
return f(host, ctx)
} | [
"func",
"(",
"f",
"FuncHttpsHandler",
")",
"HandleConnect",
"(",
"host",
"string",
",",
"ctx",
"*",
"ProxyCtx",
")",
"(",
"*",
"ConnectAction",
",",
"string",
")",
"{",
"return",
"f",
"(",
"host",
",",
"ctx",
")",
"\n",
"}"
] | // FuncHttpsHandler should implement the RespHandler interface | [
"FuncHttpsHandler",
"should",
"implement",
"the",
"RespHandler",
"interface"
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/actions.go#L55-L57 | train |
elazarl/goproxy | ext/auth/basic.go | ProxyBasic | func ProxyBasic(proxy *goproxy.ProxyHttpServer, realm string, f func(user, passwd string) bool) {
proxy.OnRequest().Do(Basic(realm, f))
proxy.OnRequest().HandleConnect(BasicConnect(realm, f))
} | go | func ProxyBasic(proxy *goproxy.ProxyHttpServer, realm string, f func(user, passwd string) bool) {
proxy.OnRequest().Do(Basic(realm, f))
proxy.OnRequest().HandleConnect(BasicConnect(realm, f))
} | [
"func",
"ProxyBasic",
"(",
"proxy",
"*",
"goproxy",
".",
"ProxyHttpServer",
",",
"realm",
"string",
",",
"f",
"func",
"(",
"user",
",",
"passwd",
"string",
")",
"bool",
")",
"{",
"proxy",
".",
"OnRequest",
"(",
")",
".",
"Do",
"(",
"Basic",
"(",
"realm",
",",
"f",
")",
")",
"\n",
"proxy",
".",
"OnRequest",
"(",
")",
".",
"HandleConnect",
"(",
"BasicConnect",
"(",
"realm",
",",
"f",
")",
")",
"\n",
"}"
] | // ProxyBasic will force HTTP authentication before any request to the proxy is processed | [
"ProxyBasic",
"will",
"force",
"HTTP",
"authentication",
"before",
"any",
"request",
"to",
"the",
"proxy",
"is",
"processed"
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/ext/auth/basic.go#L76-L79 | train |
elazarl/goproxy | dispatcher.go | HandleResp | func (c ReqConditionFunc) HandleResp(resp *http.Response, ctx *ProxyCtx) bool {
return c(ctx.Req, ctx)
} | go | func (c ReqConditionFunc) HandleResp(resp *http.Response, ctx *ProxyCtx) bool {
return c(ctx.Req, ctx)
} | [
"func",
"(",
"c",
"ReqConditionFunc",
")",
"HandleResp",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"ctx",
"*",
"ProxyCtx",
")",
"bool",
"{",
"return",
"c",
"(",
"ctx",
".",
"Req",
",",
"ctx",
")",
"\n",
"}"
] | // ReqConditionFunc cannot test responses. It only satisfies RespCondition interface so that
// to be usable as RespCondition. | [
"ReqConditionFunc",
"cannot",
"test",
"responses",
".",
"It",
"only",
"satisfies",
"RespCondition",
"interface",
"so",
"that",
"to",
"be",
"usable",
"as",
"RespCondition",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/dispatcher.go#L38-L40 | train |
elazarl/goproxy | dispatcher.go | ReqHostMatches | func ReqHostMatches(regexps ...*regexp.Regexp) ReqConditionFunc {
return func(req *http.Request, ctx *ProxyCtx) bool {
for _, re := range regexps {
if re.MatchString(req.Host) {
return true
}
}
return false
}
} | go | func ReqHostMatches(regexps ...*regexp.Regexp) ReqConditionFunc {
return func(req *http.Request, ctx *ProxyCtx) bool {
for _, re := range regexps {
if re.MatchString(req.Host) {
return true
}
}
return false
}
} | [
"func",
"ReqHostMatches",
"(",
"regexps",
"...",
"*",
"regexp",
".",
"Regexp",
")",
"ReqConditionFunc",
"{",
"return",
"func",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"ctx",
"*",
"ProxyCtx",
")",
"bool",
"{",
"for",
"_",
",",
"re",
":=",
"range",
"regexps",
"{",
"if",
"re",
".",
"MatchString",
"(",
"req",
".",
"Host",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"}"
] | // ReqHostMatches returns a ReqCondition, testing whether the host to which the request was directed to matches
// any of the given regular expressions. | [
"ReqHostMatches",
"returns",
"a",
"ReqCondition",
"testing",
"whether",
"the",
"host",
"to",
"which",
"the",
"request",
"was",
"directed",
"to",
"matches",
"any",
"of",
"the",
"given",
"regular",
"expressions",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/dispatcher.go#L76-L85 | train |
elazarl/goproxy | dispatcher.go | ReqHostIs | func ReqHostIs(hosts ...string) ReqConditionFunc {
hostSet := make(map[string]bool)
for _, h := range hosts {
hostSet[h] = true
}
return func(req *http.Request, ctx *ProxyCtx) bool {
_, ok := hostSet[req.URL.Host]
return ok
}
} | go | func ReqHostIs(hosts ...string) ReqConditionFunc {
hostSet := make(map[string]bool)
for _, h := range hosts {
hostSet[h] = true
}
return func(req *http.Request, ctx *ProxyCtx) bool {
_, ok := hostSet[req.URL.Host]
return ok
}
} | [
"func",
"ReqHostIs",
"(",
"hosts",
"...",
"string",
")",
"ReqConditionFunc",
"{",
"hostSet",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"for",
"_",
",",
"h",
":=",
"range",
"hosts",
"{",
"hostSet",
"[",
"h",
"]",
"=",
"true",
"\n",
"}",
"\n",
"return",
"func",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"ctx",
"*",
"ProxyCtx",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"hostSet",
"[",
"req",
".",
"URL",
".",
"Host",
"]",
"\n",
"return",
"ok",
"\n",
"}",
"\n",
"}"
] | // ReqHostIs returns a ReqCondition, testing whether the host to which the request is directed to equal
// to one of the given strings | [
"ReqHostIs",
"returns",
"a",
"ReqCondition",
"testing",
"whether",
"the",
"host",
"to",
"which",
"the",
"request",
"is",
"directed",
"to",
"equal",
"to",
"one",
"of",
"the",
"given",
"strings"
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/dispatcher.go#L89-L98 | train |
elazarl/goproxy | dispatcher.go | UrlMatches | func UrlMatches(re *regexp.Regexp) ReqConditionFunc {
return func(req *http.Request, ctx *ProxyCtx) bool {
return re.MatchString(req.URL.Path) ||
re.MatchString(req.URL.Host+req.URL.Path)
}
} | go | func UrlMatches(re *regexp.Regexp) ReqConditionFunc {
return func(req *http.Request, ctx *ProxyCtx) bool {
return re.MatchString(req.URL.Path) ||
re.MatchString(req.URL.Host+req.URL.Path)
}
} | [
"func",
"UrlMatches",
"(",
"re",
"*",
"regexp",
".",
"Regexp",
")",
"ReqConditionFunc",
"{",
"return",
"func",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"ctx",
"*",
"ProxyCtx",
")",
"bool",
"{",
"return",
"re",
".",
"MatchString",
"(",
"req",
".",
"URL",
".",
"Path",
")",
"||",
"re",
".",
"MatchString",
"(",
"req",
".",
"URL",
".",
"Host",
"+",
"req",
".",
"URL",
".",
"Path",
")",
"\n",
"}",
"\n",
"}"
] | // UrlMatches returns a ReqCondition testing whether the destination URL
// of the request matches the given regexp, with or without prefix | [
"UrlMatches",
"returns",
"a",
"ReqCondition",
"testing",
"whether",
"the",
"destination",
"URL",
"of",
"the",
"request",
"matches",
"the",
"given",
"regexp",
"with",
"or",
"without",
"prefix"
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/dispatcher.go#L113-L118 | train |
elazarl/goproxy | dispatcher.go | DstHostIs | func DstHostIs(host string) ReqConditionFunc {
return func(req *http.Request, ctx *ProxyCtx) bool {
return req.URL.Host == host
}
} | go | func DstHostIs(host string) ReqConditionFunc {
return func(req *http.Request, ctx *ProxyCtx) bool {
return req.URL.Host == host
}
} | [
"func",
"DstHostIs",
"(",
"host",
"string",
")",
"ReqConditionFunc",
"{",
"return",
"func",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"ctx",
"*",
"ProxyCtx",
")",
"bool",
"{",
"return",
"req",
".",
"URL",
".",
"Host",
"==",
"host",
"\n",
"}",
"\n",
"}"
] | // DstHostIs returns a ReqCondition testing wether the host in the request url is the given string | [
"DstHostIs",
"returns",
"a",
"ReqCondition",
"testing",
"wether",
"the",
"host",
"in",
"the",
"request",
"url",
"is",
"the",
"given",
"string"
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/dispatcher.go#L121-L125 | train |
elazarl/goproxy | dispatcher.go | SrcIpIs | func SrcIpIs(ips ...string) ReqCondition {
return ReqConditionFunc(func(req *http.Request, ctx *ProxyCtx) bool {
for _, ip := range ips {
if strings.HasPrefix(req.RemoteAddr, ip+":") {
return true
}
}
return false
})
} | go | func SrcIpIs(ips ...string) ReqCondition {
return ReqConditionFunc(func(req *http.Request, ctx *ProxyCtx) bool {
for _, ip := range ips {
if strings.HasPrefix(req.RemoteAddr, ip+":") {
return true
}
}
return false
})
} | [
"func",
"SrcIpIs",
"(",
"ips",
"...",
"string",
")",
"ReqCondition",
"{",
"return",
"ReqConditionFunc",
"(",
"func",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"ctx",
"*",
"ProxyCtx",
")",
"bool",
"{",
"for",
"_",
",",
"ip",
":=",
"range",
"ips",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"req",
".",
"RemoteAddr",
",",
"ip",
"+",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
")",
"\n",
"}"
] | // SrcIpIs returns a ReqCondition testing whether the source IP of the request is one of the given strings | [
"SrcIpIs",
"returns",
"a",
"ReqCondition",
"testing",
"whether",
"the",
"source",
"IP",
"of",
"the",
"request",
"is",
"one",
"of",
"the",
"given",
"strings"
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/dispatcher.go#L128-L137 | train |
elazarl/goproxy | dispatcher.go | Not | func Not(r ReqCondition) ReqConditionFunc {
return func(req *http.Request, ctx *ProxyCtx) bool {
return !r.HandleReq(req, ctx)
}
} | go | func Not(r ReqCondition) ReqConditionFunc {
return func(req *http.Request, ctx *ProxyCtx) bool {
return !r.HandleReq(req, ctx)
}
} | [
"func",
"Not",
"(",
"r",
"ReqCondition",
")",
"ReqConditionFunc",
"{",
"return",
"func",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"ctx",
"*",
"ProxyCtx",
")",
"bool",
"{",
"return",
"!",
"r",
".",
"HandleReq",
"(",
"req",
",",
"ctx",
")",
"\n",
"}",
"\n",
"}"
] | // Not returns a ReqCondition negating the given ReqCondition | [
"Not",
"returns",
"a",
"ReqCondition",
"negating",
"the",
"given",
"ReqCondition"
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/dispatcher.go#L140-L144 | train |
elazarl/goproxy | dispatcher.go | ContentTypeIs | func ContentTypeIs(typ string, types ...string) RespCondition {
types = append(types, typ)
return RespConditionFunc(func(resp *http.Response, ctx *ProxyCtx) bool {
if resp == nil {
return false
}
contentType := resp.Header.Get("Content-Type")
for _, typ := range types {
if contentType == typ || strings.HasPrefix(contentType, typ+";") {
return true
}
}
return false
})
} | go | func ContentTypeIs(typ string, types ...string) RespCondition {
types = append(types, typ)
return RespConditionFunc(func(resp *http.Response, ctx *ProxyCtx) bool {
if resp == nil {
return false
}
contentType := resp.Header.Get("Content-Type")
for _, typ := range types {
if contentType == typ || strings.HasPrefix(contentType, typ+";") {
return true
}
}
return false
})
} | [
"func",
"ContentTypeIs",
"(",
"typ",
"string",
",",
"types",
"...",
"string",
")",
"RespCondition",
"{",
"types",
"=",
"append",
"(",
"types",
",",
"typ",
")",
"\n",
"return",
"RespConditionFunc",
"(",
"func",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"ctx",
"*",
"ProxyCtx",
")",
"bool",
"{",
"if",
"resp",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"contentType",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"typ",
":=",
"range",
"types",
"{",
"if",
"contentType",
"==",
"typ",
"||",
"strings",
".",
"HasPrefix",
"(",
"contentType",
",",
"typ",
"+",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
")",
"\n",
"}"
] | // ContentTypeIs returns a RespCondition testing whether the HTTP response has Content-Type header equal
// to one of the given strings. | [
"ContentTypeIs",
"returns",
"a",
"RespCondition",
"testing",
"whether",
"the",
"HTTP",
"response",
"has",
"Content",
"-",
"Type",
"header",
"equal",
"to",
"one",
"of",
"the",
"given",
"strings",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/dispatcher.go#L148-L162 | train |
elazarl/goproxy | dispatcher.go | HandleBytes | func HandleBytes(f func(b []byte, ctx *ProxyCtx) []byte) RespHandler {
return FuncRespHandler(func(resp *http.Response, ctx *ProxyCtx) *http.Response {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
ctx.Warnf("Cannot read response %s", err)
return resp
}
resp.Body.Close()
resp.Body = ioutil.NopCloser(bytes.NewBuffer(f(b, ctx)))
return resp
})
} | go | func HandleBytes(f func(b []byte, ctx *ProxyCtx) []byte) RespHandler {
return FuncRespHandler(func(resp *http.Response, ctx *ProxyCtx) *http.Response {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
ctx.Warnf("Cannot read response %s", err)
return resp
}
resp.Body.Close()
resp.Body = ioutil.NopCloser(bytes.NewBuffer(f(b, ctx)))
return resp
})
} | [
"func",
"HandleBytes",
"(",
"f",
"func",
"(",
"b",
"[",
"]",
"byte",
",",
"ctx",
"*",
"ProxyCtx",
")",
"[",
"]",
"byte",
")",
"RespHandler",
"{",
"return",
"FuncRespHandler",
"(",
"func",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"ctx",
"*",
"ProxyCtx",
")",
"*",
"http",
".",
"Response",
"{",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ctx",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"resp",
"\n",
"}",
"\n",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"resp",
".",
"Body",
"=",
"ioutil",
".",
"NopCloser",
"(",
"bytes",
".",
"NewBuffer",
"(",
"f",
"(",
"b",
",",
"ctx",
")",
")",
")",
"\n",
"return",
"resp",
"\n",
"}",
")",
"\n",
"}"
] | // HandleBytes will return a RespHandler that read the entire body of the request
// to a byte array in memory, would run the user supplied f function on the byte arra,
// and will replace the body of the original response with the resulting byte array. | [
"HandleBytes",
"will",
"return",
"a",
"RespHandler",
"that",
"read",
"the",
"entire",
"body",
"of",
"the",
"request",
"to",
"a",
"byte",
"array",
"in",
"memory",
"would",
"run",
"the",
"user",
"supplied",
"f",
"function",
"on",
"the",
"byte",
"arra",
"and",
"will",
"replace",
"the",
"body",
"of",
"the",
"original",
"response",
"with",
"the",
"resulting",
"byte",
"array",
"."
] | 9d40249d3c2f14d1a9d75e070a738362adeb5a83 | https://github.com/elazarl/goproxy/blob/9d40249d3c2f14d1a9d75e070a738362adeb5a83/dispatcher.go#L313-L325 | train |
centrifugal/centrifugo | internal/api/handler.go | NewHandler | func NewHandler(n *centrifuge.Node, c Config) *Handler {
return &Handler{
node: n,
config: c,
api: newAPIExecutor(n, "http"),
}
} | go | func NewHandler(n *centrifuge.Node, c Config) *Handler {
return &Handler{
node: n,
config: c,
api: newAPIExecutor(n, "http"),
}
} | [
"func",
"NewHandler",
"(",
"n",
"*",
"centrifuge",
".",
"Node",
",",
"c",
"Config",
")",
"*",
"Handler",
"{",
"return",
"&",
"Handler",
"{",
"node",
":",
"n",
",",
"config",
":",
"c",
",",
"api",
":",
"newAPIExecutor",
"(",
"n",
",",
"\"",
"\"",
")",
",",
"}",
"\n",
"}"
] | // NewHandler creates new APIHandler. | [
"NewHandler",
"creates",
"new",
"APIHandler",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/handler.go#L24-L30 | train |
centrifugal/centrifugo | internal/api/grpc.go | RegisterGRPCServerAPI | func RegisterGRPCServerAPI(n *centrifuge.Node, server *grpc.Server, config GRPCAPIServiceConfig) error {
RegisterCentrifugoServer(server, newGRPCAPIService(n, config))
return nil
} | go | func RegisterGRPCServerAPI(n *centrifuge.Node, server *grpc.Server, config GRPCAPIServiceConfig) error {
RegisterCentrifugoServer(server, newGRPCAPIService(n, config))
return nil
} | [
"func",
"RegisterGRPCServerAPI",
"(",
"n",
"*",
"centrifuge",
".",
"Node",
",",
"server",
"*",
"grpc",
".",
"Server",
",",
"config",
"GRPCAPIServiceConfig",
")",
"error",
"{",
"RegisterCentrifugoServer",
"(",
"server",
",",
"newGRPCAPIService",
"(",
"n",
",",
"config",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // RegisterGRPCServerAPI registers GRPC API service in provided GRPC server. | [
"RegisterGRPCServerAPI",
"registers",
"GRPC",
"API",
"service",
"in",
"provided",
"GRPC",
"server",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/grpc.go#L14-L17 | train |
centrifugal/centrifugo | internal/api/grpc.go | newGRPCAPIService | func newGRPCAPIService(n *centrifuge.Node, c GRPCAPIServiceConfig) *grpcAPIService {
return &grpcAPIService{
config: c,
api: newAPIExecutor(n, "grpc"),
}
} | go | func newGRPCAPIService(n *centrifuge.Node, c GRPCAPIServiceConfig) *grpcAPIService {
return &grpcAPIService{
config: c,
api: newAPIExecutor(n, "grpc"),
}
} | [
"func",
"newGRPCAPIService",
"(",
"n",
"*",
"centrifuge",
".",
"Node",
",",
"c",
"GRPCAPIServiceConfig",
")",
"*",
"grpcAPIService",
"{",
"return",
"&",
"grpcAPIService",
"{",
"config",
":",
"c",
",",
"api",
":",
"newAPIExecutor",
"(",
"n",
",",
"\"",
"\"",
")",
",",
"}",
"\n",
"}"
] | // newGRPCAPIService creates new Service. | [
"newGRPCAPIService",
"creates",
"new",
"Service",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/grpc.go#L26-L31 | train |
centrifugal/centrifugo | internal/api/grpc.go | Publish | func (s *grpcAPIService) Publish(ctx context.Context, req *PublishRequest) (*PublishResponse, error) {
return s.api.Publish(ctx, req), nil
} | go | func (s *grpcAPIService) Publish(ctx context.Context, req *PublishRequest) (*PublishResponse, error) {
return s.api.Publish(ctx, req), nil
} | [
"func",
"(",
"s",
"*",
"grpcAPIService",
")",
"Publish",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"PublishRequest",
")",
"(",
"*",
"PublishResponse",
",",
"error",
")",
"{",
"return",
"s",
".",
"api",
".",
"Publish",
"(",
"ctx",
",",
"req",
")",
",",
"nil",
"\n",
"}"
] | // Publish into channel. | [
"Publish",
"into",
"channel",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/grpc.go#L34-L36 | train |
centrifugal/centrifugo | internal/api/grpc.go | Broadcast | func (s *grpcAPIService) Broadcast(ctx context.Context, req *BroadcastRequest) (*BroadcastResponse, error) {
return s.api.Broadcast(ctx, req), nil
} | go | func (s *grpcAPIService) Broadcast(ctx context.Context, req *BroadcastRequest) (*BroadcastResponse, error) {
return s.api.Broadcast(ctx, req), nil
} | [
"func",
"(",
"s",
"*",
"grpcAPIService",
")",
"Broadcast",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"BroadcastRequest",
")",
"(",
"*",
"BroadcastResponse",
",",
"error",
")",
"{",
"return",
"s",
".",
"api",
".",
"Broadcast",
"(",
"ctx",
",",
"req",
")",
",",
"nil",
"\n",
"}"
] | // Broadcast into channels. | [
"Broadcast",
"into",
"channels",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/grpc.go#L39-L41 | train |
centrifugal/centrifugo | internal/api/grpc.go | Channels | func (s *grpcAPIService) Channels(ctx context.Context, req *ChannelsRequest) (*ChannelsResponse, error) {
return s.api.Channels(ctx, req), nil
} | go | func (s *grpcAPIService) Channels(ctx context.Context, req *ChannelsRequest) (*ChannelsResponse, error) {
return s.api.Channels(ctx, req), nil
} | [
"func",
"(",
"s",
"*",
"grpcAPIService",
")",
"Channels",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"ChannelsRequest",
")",
"(",
"*",
"ChannelsResponse",
",",
"error",
")",
"{",
"return",
"s",
".",
"api",
".",
"Channels",
"(",
"ctx",
",",
"req",
")",
",",
"nil",
"\n",
"}"
] | // Channels allows to retrieve list of channels. | [
"Channels",
"allows",
"to",
"retrieve",
"list",
"of",
"channels",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/grpc.go#L44-L46 | train |
centrifugal/centrifugo | internal/api/grpc.go | Unsubscribe | func (s *grpcAPIService) Unsubscribe(ctx context.Context, req *UnsubscribeRequest) (*UnsubscribeResponse, error) {
return s.api.Unsubscribe(ctx, req), nil
} | go | func (s *grpcAPIService) Unsubscribe(ctx context.Context, req *UnsubscribeRequest) (*UnsubscribeResponse, error) {
return s.api.Unsubscribe(ctx, req), nil
} | [
"func",
"(",
"s",
"*",
"grpcAPIService",
")",
"Unsubscribe",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"UnsubscribeRequest",
")",
"(",
"*",
"UnsubscribeResponse",
",",
"error",
")",
"{",
"return",
"s",
".",
"api",
".",
"Unsubscribe",
"(",
"ctx",
",",
"req",
")",
",",
"nil",
"\n",
"}"
] | // Unsubscribe user from channel. | [
"Unsubscribe",
"user",
"from",
"channel",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/grpc.go#L49-L51 | train |
centrifugal/centrifugo | internal/api/grpc.go | Disconnect | func (s *grpcAPIService) Disconnect(ctx context.Context, req *DisconnectRequest) (*DisconnectResponse, error) {
return s.api.Disconnect(ctx, req), nil
} | go | func (s *grpcAPIService) Disconnect(ctx context.Context, req *DisconnectRequest) (*DisconnectResponse, error) {
return s.api.Disconnect(ctx, req), nil
} | [
"func",
"(",
"s",
"*",
"grpcAPIService",
")",
"Disconnect",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"DisconnectRequest",
")",
"(",
"*",
"DisconnectResponse",
",",
"error",
")",
"{",
"return",
"s",
".",
"api",
".",
"Disconnect",
"(",
"ctx",
",",
"req",
")",
",",
"nil",
"\n",
"}"
] | // Disconnect user. | [
"Disconnect",
"user",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/grpc.go#L54-L56 | train |
centrifugal/centrifugo | internal/api/grpc.go | History | func (s *grpcAPIService) History(ctx context.Context, req *HistoryRequest) (*HistoryResponse, error) {
return s.api.History(ctx, req), nil
} | go | func (s *grpcAPIService) History(ctx context.Context, req *HistoryRequest) (*HistoryResponse, error) {
return s.api.History(ctx, req), nil
} | [
"func",
"(",
"s",
"*",
"grpcAPIService",
")",
"History",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"HistoryRequest",
")",
"(",
"*",
"HistoryResponse",
",",
"error",
")",
"{",
"return",
"s",
".",
"api",
".",
"History",
"(",
"ctx",
",",
"req",
")",
",",
"nil",
"\n",
"}"
] | // History in channel. | [
"History",
"in",
"channel",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/grpc.go#L59-L61 | train |
centrifugal/centrifugo | internal/api/grpc.go | Presence | func (s *grpcAPIService) Presence(ctx context.Context, req *PresenceRequest) (*PresenceResponse, error) {
return s.api.Presence(ctx, req), nil
} | go | func (s *grpcAPIService) Presence(ctx context.Context, req *PresenceRequest) (*PresenceResponse, error) {
return s.api.Presence(ctx, req), nil
} | [
"func",
"(",
"s",
"*",
"grpcAPIService",
")",
"Presence",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"PresenceRequest",
")",
"(",
"*",
"PresenceResponse",
",",
"error",
")",
"{",
"return",
"s",
".",
"api",
".",
"Presence",
"(",
"ctx",
",",
"req",
")",
",",
"nil",
"\n",
"}"
] | // Presence in channel. | [
"Presence",
"in",
"channel",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/grpc.go#L69-L71 | train |
centrifugal/centrifugo | internal/api/grpc.go | PresenceStats | func (s *grpcAPIService) PresenceStats(ctx context.Context, req *PresenceStatsRequest) (*PresenceStatsResponse, error) {
return s.api.PresenceStats(ctx, req), nil
} | go | func (s *grpcAPIService) PresenceStats(ctx context.Context, req *PresenceStatsRequest) (*PresenceStatsResponse, error) {
return s.api.PresenceStats(ctx, req), nil
} | [
"func",
"(",
"s",
"*",
"grpcAPIService",
")",
"PresenceStats",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"PresenceStatsRequest",
")",
"(",
"*",
"PresenceStatsResponse",
",",
"error",
")",
"{",
"return",
"s",
".",
"api",
".",
"PresenceStats",
"(",
"ctx",
",",
"req",
")",
",",
"nil",
"\n",
"}"
] | // PresenceStats information for channel. | [
"PresenceStats",
"information",
"for",
"channel",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/grpc.go#L74-L76 | train |
centrifugal/centrifugo | internal/api/grpc.go | Info | func (s *grpcAPIService) Info(ctx context.Context, req *InfoRequest) (*InfoResponse, error) {
return s.api.Info(ctx, req), nil
} | go | func (s *grpcAPIService) Info(ctx context.Context, req *InfoRequest) (*InfoResponse, error) {
return s.api.Info(ctx, req), nil
} | [
"func",
"(",
"s",
"*",
"grpcAPIService",
")",
"Info",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"InfoRequest",
")",
"(",
"*",
"InfoResponse",
",",
"error",
")",
"{",
"return",
"s",
".",
"api",
".",
"Info",
"(",
"ctx",
",",
"req",
")",
",",
"nil",
"\n",
"}"
] | // Info returns information about Centrifugo state. | [
"Info",
"returns",
"information",
"about",
"Centrifugo",
"state",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/grpc.go#L79-L81 | train |
centrifugal/centrifugo | internal/middleware/auth.go | APIKeyAuth | func APIKeyAuth(key string, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if key == "" {
log.Error().Msg("API key is empty")
w.WriteHeader(http.StatusUnauthorized)
return
}
authorization := r.Header.Get("Authorization")
parts := strings.Fields(authorization)
if len(parts) != 2 {
w.WriteHeader(http.StatusUnauthorized)
return
}
authMethod := strings.ToLower(parts[0])
if authMethod != "apikey" || parts[1] != key {
w.WriteHeader(http.StatusUnauthorized)
return
}
h.ServeHTTP(w, r)
})
} | go | func APIKeyAuth(key string, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if key == "" {
log.Error().Msg("API key is empty")
w.WriteHeader(http.StatusUnauthorized)
return
}
authorization := r.Header.Get("Authorization")
parts := strings.Fields(authorization)
if len(parts) != 2 {
w.WriteHeader(http.StatusUnauthorized)
return
}
authMethod := strings.ToLower(parts[0])
if authMethod != "apikey" || parts[1] != key {
w.WriteHeader(http.StatusUnauthorized)
return
}
h.ServeHTTP(w, r)
})
} | [
"func",
"APIKeyAuth",
"(",
"key",
"string",
",",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"key",
"==",
"\"",
"\"",
"{",
"log",
".",
"Error",
"(",
")",
".",
"Msg",
"(",
"\"",
"\"",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"return",
"\n",
"}",
"\n",
"authorization",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"parts",
":=",
"strings",
".",
"Fields",
"(",
"authorization",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"2",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"return",
"\n",
"}",
"\n",
"authMethod",
":=",
"strings",
".",
"ToLower",
"(",
"parts",
"[",
"0",
"]",
")",
"\n",
"if",
"authMethod",
"!=",
"\"",
"\"",
"||",
"parts",
"[",
"1",
"]",
"!=",
"key",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"return",
"\n",
"}",
"\n",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] | // APIKeyAuth middleware authorizes request using API key authorization. | [
"APIKeyAuth",
"middleware",
"authorizes",
"request",
"using",
"API",
"key",
"authorization",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/middleware/auth.go#L11-L31 | train |
centrifugal/centrifugo | internal/api/raw.go | Marshal | func (r Raw) Marshal() ([]byte, error) {
if len(r) == 0 {
return nil, nil
}
return []byte(r), nil
} | go | func (r Raw) Marshal() ([]byte, error) {
if len(r) == 0 {
return nil, nil
}
return []byte(r), nil
} | [
"func",
"(",
"r",
"Raw",
")",
"Marshal",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"r",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"[",
"]",
"byte",
"(",
"r",
")",
",",
"nil",
"\n",
"}"
] | // Marshal encodes Raw to slice of bytes. Exists to fit gogoprotobuf custom
// type interface. | [
"Marshal",
"encodes",
"Raw",
"to",
"slice",
"of",
"bytes",
".",
"Exists",
"to",
"fit",
"gogoprotobuf",
"custom",
"type",
"interface",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/raw.go#L16-L21 | train |
centrifugal/centrifugo | internal/api/raw.go | MarshalTo | func (r Raw) MarshalTo(data []byte) (n int, err error) {
if len(r) == 0 {
return 0, nil
}
copy(data, r)
return len(r), nil
} | go | func (r Raw) MarshalTo(data []byte) (n int, err error) {
if len(r) == 0 {
return 0, nil
}
copy(data, r)
return len(r), nil
} | [
"func",
"(",
"r",
"Raw",
")",
"MarshalTo",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"r",
")",
"==",
"0",
"{",
"return",
"0",
",",
"nil",
"\n",
"}",
"\n",
"copy",
"(",
"data",
",",
"r",
")",
"\n",
"return",
"len",
"(",
"r",
")",
",",
"nil",
"\n",
"}"
] | // MarshalTo exists to fit gogoprotobuf custom type interface. | [
"MarshalTo",
"exists",
"to",
"fit",
"gogoprotobuf",
"custom",
"type",
"interface",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/raw.go#L24-L30 | train |
centrifugal/centrifugo | internal/api/raw.go | Unmarshal | func (r *Raw) Unmarshal(data []byte) error {
if len(data) == 0 {
r = nil
return nil
}
id := Raw(make([]byte, len(data)))
copy(id, data)
*r = id
return nil
} | go | func (r *Raw) Unmarshal(data []byte) error {
if len(data) == 0 {
r = nil
return nil
}
id := Raw(make([]byte, len(data)))
copy(id, data)
*r = id
return nil
} | [
"func",
"(",
"r",
"*",
"Raw",
")",
"Unmarshal",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"len",
"(",
"data",
")",
"==",
"0",
"{",
"r",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"id",
":=",
"Raw",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"data",
")",
")",
")",
"\n",
"copy",
"(",
"id",
",",
"data",
")",
"\n",
"*",
"r",
"=",
"id",
"\n",
"return",
"nil",
"\n",
"}"
] | // Unmarshal exists to fit gogoprotobuf custom type interface. | [
"Unmarshal",
"exists",
"to",
"fit",
"gogoprotobuf",
"custom",
"type",
"interface",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/raw.go#L33-L42 | train |
centrifugal/centrifugo | internal/api/raw.go | Equal | func (r Raw) Equal(other Raw) bool {
return bytes.Equal(r[0:], other[0:])
} | go | func (r Raw) Equal(other Raw) bool {
return bytes.Equal(r[0:], other[0:])
} | [
"func",
"(",
"r",
"Raw",
")",
"Equal",
"(",
"other",
"Raw",
")",
"bool",
"{",
"return",
"bytes",
".",
"Equal",
"(",
"r",
"[",
"0",
":",
"]",
",",
"other",
"[",
"0",
":",
"]",
")",
"\n",
"}"
] | // Equal exists to fit gogoprotobuf custom type interface. | [
"Equal",
"exists",
"to",
"fit",
"gogoprotobuf",
"custom",
"type",
"interface",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/raw.go#L70-L72 | train |
centrifugal/centrifugo | internal/api/raw.go | Compare | func (r Raw) Compare(other Raw) int {
return bytes.Compare(r[0:], other[0:])
} | go | func (r Raw) Compare(other Raw) int {
return bytes.Compare(r[0:], other[0:])
} | [
"func",
"(",
"r",
"Raw",
")",
"Compare",
"(",
"other",
"Raw",
")",
"int",
"{",
"return",
"bytes",
".",
"Compare",
"(",
"r",
"[",
"0",
":",
"]",
",",
"other",
"[",
"0",
":",
"]",
")",
"\n",
"}"
] | // Compare exists to fit gogoprotobuf custom type interface. | [
"Compare",
"exists",
"to",
"fit",
"gogoprotobuf",
"custom",
"type",
"interface",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/raw.go#L75-L77 | train |
centrifugal/centrifugo | internal/api/raw.go | NewPopulatedRaw | func NewPopulatedRaw(r intn) *Raw {
v1 := r.Intn(100)
data := make([]byte, v1)
for i := 0; i < v1; i++ {
data[i] = byte('a')
}
d := `{"key":"` + string(data) + `"}`
raw := Raw([]byte(d))
return &raw
} | go | func NewPopulatedRaw(r intn) *Raw {
v1 := r.Intn(100)
data := make([]byte, v1)
for i := 0; i < v1; i++ {
data[i] = byte('a')
}
d := `{"key":"` + string(data) + `"}`
raw := Raw([]byte(d))
return &raw
} | [
"func",
"NewPopulatedRaw",
"(",
"r",
"intn",
")",
"*",
"Raw",
"{",
"v1",
":=",
"r",
".",
"Intn",
"(",
"100",
")",
"\n",
"data",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"v1",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"v1",
";",
"i",
"++",
"{",
"data",
"[",
"i",
"]",
"=",
"byte",
"(",
"'a'",
")",
"\n",
"}",
"\n",
"d",
":=",
"`{\"key\":\"`",
"+",
"string",
"(",
"data",
")",
"+",
"`\"}`",
"\n",
"raw",
":=",
"Raw",
"(",
"[",
"]",
"byte",
"(",
"d",
")",
")",
"\n",
"return",
"&",
"raw",
"\n",
"}"
] | // NewPopulatedRaw required for gogoprotobuf custom type. | [
"NewPopulatedRaw",
"required",
"for",
"gogoprotobuf",
"custom",
"type",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/raw.go#L84-L93 | train |
centrifugal/centrifugo | internal/api/unmarshal.go | UnmarshalJSON | func (m *MethodType) UnmarshalJSON(data []byte) error {
val, err := strconv.Atoi(string(data))
if err != nil {
method := strings.Trim(strings.ToUpper(string(data)), `"`)
if v, ok := MethodType_value[method]; ok {
*m = MethodType(v)
return nil
}
return err
}
*m = MethodType(val)
return nil
} | go | func (m *MethodType) UnmarshalJSON(data []byte) error {
val, err := strconv.Atoi(string(data))
if err != nil {
method := strings.Trim(strings.ToUpper(string(data)), `"`)
if v, ok := MethodType_value[method]; ok {
*m = MethodType(v)
return nil
}
return err
}
*m = MethodType(val)
return nil
} | [
"func",
"(",
"m",
"*",
"MethodType",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"val",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"string",
"(",
"data",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"method",
":=",
"strings",
".",
"Trim",
"(",
"strings",
".",
"ToUpper",
"(",
"string",
"(",
"data",
")",
")",
",",
"`\"`",
")",
"\n",
"if",
"v",
",",
"ok",
":=",
"MethodType_value",
"[",
"method",
"]",
";",
"ok",
"{",
"*",
"m",
"=",
"MethodType",
"(",
"v",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"*",
"m",
"=",
"MethodType",
"(",
"val",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalJSON helps to unmarshal command method when set as string. | [
"UnmarshalJSON",
"helps",
"to",
"unmarshal",
"command",
"method",
"when",
"set",
"as",
"string",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/unmarshal.go#L13-L25 | train |
centrifugal/centrifugo | internal/middleware/log.go | LogRequest | func LogRequest(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var start time.Time
if zerolog.GlobalLevel() <= zerolog.DebugLevel {
start = time.Now()
}
h.ServeHTTP(w, r)
if zerolog.GlobalLevel() <= zerolog.DebugLevel {
addr := r.Header.Get("X-Real-IP")
if addr == "" {
addr = r.Header.Get("X-Forwarded-For")
if addr == "" {
addr = r.RemoteAddr
}
}
log.Debug().Str("method", r.Method).Str("path", r.URL.Path).Str("addr", addr).Dur("duration", time.Since(start)).Msgf("http request")
}
return
})
} | go | func LogRequest(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var start time.Time
if zerolog.GlobalLevel() <= zerolog.DebugLevel {
start = time.Now()
}
h.ServeHTTP(w, r)
if zerolog.GlobalLevel() <= zerolog.DebugLevel {
addr := r.Header.Get("X-Real-IP")
if addr == "" {
addr = r.Header.Get("X-Forwarded-For")
if addr == "" {
addr = r.RemoteAddr
}
}
log.Debug().Str("method", r.Method).Str("path", r.URL.Path).Str("addr", addr).Dur("duration", time.Since(start)).Msgf("http request")
}
return
})
} | [
"func",
"LogRequest",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"var",
"start",
"time",
".",
"Time",
"\n",
"if",
"zerolog",
".",
"GlobalLevel",
"(",
")",
"<=",
"zerolog",
".",
"DebugLevel",
"{",
"start",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}",
"\n",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"if",
"zerolog",
".",
"GlobalLevel",
"(",
")",
"<=",
"zerolog",
".",
"DebugLevel",
"{",
"addr",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"addr",
"=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"addr",
"=",
"r",
".",
"RemoteAddr",
"\n",
"}",
"\n",
"}",
"\n",
"log",
".",
"Debug",
"(",
")",
".",
"Str",
"(",
"\"",
"\"",
",",
"r",
".",
"Method",
")",
".",
"Str",
"(",
"\"",
"\"",
",",
"r",
".",
"URL",
".",
"Path",
")",
".",
"Str",
"(",
"\"",
"\"",
",",
"addr",
")",
".",
"Dur",
"(",
"\"",
"\"",
",",
"time",
".",
"Since",
"(",
"start",
")",
")",
".",
"Msgf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
")",
"\n",
"}"
] | // LogRequest middleware logs details of request. | [
"LogRequest",
"middleware",
"logs",
"details",
"of",
"request",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/middleware/log.go#L12-L31 | train |
centrifugal/centrifugo | internal/admin/handlers.go | authHandler | func (s *Handler) authHandler(w http.ResponseWriter, r *http.Request) {
formPassword := r.FormValue("password")
insecure := s.config.Insecure
password := s.config.Password
secret := s.config.Secret
if insecure {
w.Header().Set("Content-Type", "application/json")
resp := struct {
Token string `json:"token"`
}{
Token: "insecure",
}
json.NewEncoder(w).Encode(resp)
return
}
if password == "" || secret == "" {
log.Error().Msg("admin_password and admin_secret must be set in configuration")
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
if formPassword == password {
w.Header().Set("Content-Type", "application/json")
token, err := generateSecureAdminToken(secret)
if err != nil {
log.Error().Msgf("error generating admin token: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
resp := map[string]string{
"token": token,
}
json.NewEncoder(w).Encode(resp)
return
}
http.Error(w, "Bad Request", http.StatusBadRequest)
} | go | func (s *Handler) authHandler(w http.ResponseWriter, r *http.Request) {
formPassword := r.FormValue("password")
insecure := s.config.Insecure
password := s.config.Password
secret := s.config.Secret
if insecure {
w.Header().Set("Content-Type", "application/json")
resp := struct {
Token string `json:"token"`
}{
Token: "insecure",
}
json.NewEncoder(w).Encode(resp)
return
}
if password == "" || secret == "" {
log.Error().Msg("admin_password and admin_secret must be set in configuration")
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
if formPassword == password {
w.Header().Set("Content-Type", "application/json")
token, err := generateSecureAdminToken(secret)
if err != nil {
log.Error().Msgf("error generating admin token: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
resp := map[string]string{
"token": token,
}
json.NewEncoder(w).Encode(resp)
return
}
http.Error(w, "Bad Request", http.StatusBadRequest)
} | [
"func",
"(",
"s",
"*",
"Handler",
")",
"authHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"formPassword",
":=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n\n",
"insecure",
":=",
"s",
".",
"config",
".",
"Insecure",
"\n",
"password",
":=",
"s",
".",
"config",
".",
"Password",
"\n",
"secret",
":=",
"s",
".",
"config",
".",
"Secret",
"\n\n",
"if",
"insecure",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"resp",
":=",
"struct",
"{",
"Token",
"string",
"`json:\"token\"`",
"\n",
"}",
"{",
"Token",
":",
"\"",
"\"",
",",
"}",
"\n",
"json",
".",
"NewEncoder",
"(",
"w",
")",
".",
"Encode",
"(",
"resp",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"password",
"==",
"\"",
"\"",
"||",
"secret",
"==",
"\"",
"\"",
"{",
"log",
".",
"Error",
"(",
")",
".",
"Msg",
"(",
"\"",
"\"",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"formPassword",
"==",
"password",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"token",
",",
"err",
":=",
"generateSecureAdminToken",
"(",
"secret",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Error",
"(",
")",
".",
"Msgf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"resp",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"token",
",",
"}",
"\n",
"json",
".",
"NewEncoder",
"(",
"w",
")",
".",
"Encode",
"(",
"resp",
")",
"\n",
"return",
"\n",
"}",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}"
] | // authHandler allows to get admin web interface token. | [
"authHandler",
"allows",
"to",
"get",
"admin",
"web",
"interface",
"token",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/admin/handlers.go#L102-L141 | train |
centrifugal/centrifugo | internal/admin/handlers.go | generateSecureAdminToken | func generateSecureAdminToken(secret string) (string, error) {
s := securecookie.New([]byte(secret), nil)
return s.Encode(secureAdminTokenKey, secureAdminTokenValue)
} | go | func generateSecureAdminToken(secret string) (string, error) {
s := securecookie.New([]byte(secret), nil)
return s.Encode(secureAdminTokenKey, secureAdminTokenValue)
} | [
"func",
"generateSecureAdminToken",
"(",
"secret",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"s",
":=",
"securecookie",
".",
"New",
"(",
"[",
"]",
"byte",
"(",
"secret",
")",
",",
"nil",
")",
"\n",
"return",
"s",
".",
"Encode",
"(",
"secureAdminTokenKey",
",",
"secureAdminTokenValue",
")",
"\n",
"}"
] | // generateSecureAdminToken generates admin authentication token. | [
"generateSecureAdminToken",
"generates",
"admin",
"authentication",
"token",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/admin/handlers.go#L151-L154 | train |
centrifugal/centrifugo | internal/admin/handlers.go | checkSecureAdminToken | func checkSecureAdminToken(secret string, token string) bool {
s := securecookie.New([]byte(secret), nil)
var val string
err := s.Decode(secureAdminTokenKey, token, &val)
if err != nil {
return false
}
if val != secureAdminTokenValue {
return false
}
return true
} | go | func checkSecureAdminToken(secret string, token string) bool {
s := securecookie.New([]byte(secret), nil)
var val string
err := s.Decode(secureAdminTokenKey, token, &val)
if err != nil {
return false
}
if val != secureAdminTokenValue {
return false
}
return true
} | [
"func",
"checkSecureAdminToken",
"(",
"secret",
"string",
",",
"token",
"string",
")",
"bool",
"{",
"s",
":=",
"securecookie",
".",
"New",
"(",
"[",
"]",
"byte",
"(",
"secret",
")",
",",
"nil",
")",
"\n",
"var",
"val",
"string",
"\n",
"err",
":=",
"s",
".",
"Decode",
"(",
"secureAdminTokenKey",
",",
"token",
",",
"&",
"val",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"val",
"!=",
"secureAdminTokenValue",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // checkSecureAdminToken checks admin connection token which Centrifugo returns after admin login. | [
"checkSecureAdminToken",
"checks",
"admin",
"connection",
"token",
"which",
"Centrifugo",
"returns",
"after",
"admin",
"login",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/admin/handlers.go#L157-L168 | train |
centrifugal/centrifugo | internal/api/api.go | Publish | func (h *apiExecutor) Publish(ctx context.Context, cmd *PublishRequest) *PublishResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "publish").Observe(time.Since(started).Seconds())
}(time.Now())
ch := cmd.Channel
data := cmd.Data
resp := &PublishResponse{}
if ch == "" {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "channel required for publish", nil))
resp.Error = ErrorBadRequest
return resp
}
if len(data) == 0 {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "data required for publish", nil))
resp.Error = ErrorBadRequest
return resp
}
_, ok := h.node.ChannelOpts(ch)
if !ok {
resp.Error = ErrorNamespaceNotFound
return resp
}
err := h.node.Publish(cmd.Channel, cmd.Data)
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error publishing message in engine", map[string]interface{}{"error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
return resp
} | go | func (h *apiExecutor) Publish(ctx context.Context, cmd *PublishRequest) *PublishResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "publish").Observe(time.Since(started).Seconds())
}(time.Now())
ch := cmd.Channel
data := cmd.Data
resp := &PublishResponse{}
if ch == "" {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "channel required for publish", nil))
resp.Error = ErrorBadRequest
return resp
}
if len(data) == 0 {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "data required for publish", nil))
resp.Error = ErrorBadRequest
return resp
}
_, ok := h.node.ChannelOpts(ch)
if !ok {
resp.Error = ErrorNamespaceNotFound
return resp
}
err := h.node.Publish(cmd.Channel, cmd.Data)
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error publishing message in engine", map[string]interface{}{"error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
return resp
} | [
"func",
"(",
"h",
"*",
"apiExecutor",
")",
"Publish",
"(",
"ctx",
"context",
".",
"Context",
",",
"cmd",
"*",
"PublishRequest",
")",
"*",
"PublishResponse",
"{",
"defer",
"func",
"(",
"started",
"time",
".",
"Time",
")",
"{",
"apiCommandDurationSummary",
".",
"WithLabelValues",
"(",
"h",
".",
"protocol",
",",
"\"",
"\"",
")",
".",
"Observe",
"(",
"time",
".",
"Since",
"(",
"started",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"ch",
":=",
"cmd",
".",
"Channel",
"\n",
"data",
":=",
"cmd",
".",
"Data",
"\n\n",
"resp",
":=",
"&",
"PublishResponse",
"{",
"}",
"\n\n",
"if",
"ch",
"==",
"\"",
"\"",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"nil",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorBadRequest",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"data",
")",
"==",
"0",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"nil",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorBadRequest",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"_",
",",
"ok",
":=",
"h",
".",
"node",
".",
"ChannelOpts",
"(",
"ch",
")",
"\n",
"if",
"!",
"ok",
"{",
"resp",
".",
"Error",
"=",
"ErrorNamespaceNotFound",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"err",
":=",
"h",
".",
"node",
".",
"Publish",
"(",
"cmd",
".",
"Channel",
",",
"cmd",
".",
"Data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"err",
".",
"Error",
"(",
")",
"}",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorInternal",
"\n",
"return",
"resp",
"\n",
"}",
"\n",
"return",
"resp",
"\n",
"}"
] | // Publish publishes data into channel. | [
"Publish",
"publishes",
"data",
"into",
"channel",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/api.go#L25-L60 | train |
centrifugal/centrifugo | internal/api/api.go | Broadcast | func (h *apiExecutor) Broadcast(ctx context.Context, cmd *BroadcastRequest) *BroadcastResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "broadcast").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &BroadcastResponse{}
channels := cmd.Channels
data := cmd.Data
if len(channels) == 0 {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "channels required for broadcast", nil))
resp.Error = ErrorBadRequest
return resp
}
if len(data) == 0 {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "data required for broadcast", nil))
resp.Error = ErrorBadRequest
return resp
}
errs := make([]error, len(channels))
var wg sync.WaitGroup
for i, ch := range channels {
if ch == "" {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "channel can not be blank in broadcast", nil))
resp.Error = ErrorBadRequest
return resp
}
_, ok := h.node.ChannelOpts(ch)
if !ok {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "can't find namespace for channel", map[string]interface{}{"channel": ch}))
resp.Error = ErrorNamespaceNotFound
return resp
}
wg.Add(1)
go func(i int, ch string) {
errs[i] = h.node.Publish(ch, data)
wg.Done()
}(i, ch)
}
wg.Wait()
var firstErr error
for i := range errs {
err := errs[i]
if err != nil {
if firstErr == nil {
firstErr = err
}
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error publishing into channel", map[string]interface{}{"channel": channels[i], "error": err.Error()}))
}
}
if firstErr != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error broadcasting data", map[string]interface{}{"error": firstErr.Error()}))
resp.Error = ErrorInternal
return resp
}
return resp
} | go | func (h *apiExecutor) Broadcast(ctx context.Context, cmd *BroadcastRequest) *BroadcastResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "broadcast").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &BroadcastResponse{}
channels := cmd.Channels
data := cmd.Data
if len(channels) == 0 {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "channels required for broadcast", nil))
resp.Error = ErrorBadRequest
return resp
}
if len(data) == 0 {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "data required for broadcast", nil))
resp.Error = ErrorBadRequest
return resp
}
errs := make([]error, len(channels))
var wg sync.WaitGroup
for i, ch := range channels {
if ch == "" {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "channel can not be blank in broadcast", nil))
resp.Error = ErrorBadRequest
return resp
}
_, ok := h.node.ChannelOpts(ch)
if !ok {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "can't find namespace for channel", map[string]interface{}{"channel": ch}))
resp.Error = ErrorNamespaceNotFound
return resp
}
wg.Add(1)
go func(i int, ch string) {
errs[i] = h.node.Publish(ch, data)
wg.Done()
}(i, ch)
}
wg.Wait()
var firstErr error
for i := range errs {
err := errs[i]
if err != nil {
if firstErr == nil {
firstErr = err
}
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error publishing into channel", map[string]interface{}{"channel": channels[i], "error": err.Error()}))
}
}
if firstErr != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error broadcasting data", map[string]interface{}{"error": firstErr.Error()}))
resp.Error = ErrorInternal
return resp
}
return resp
} | [
"func",
"(",
"h",
"*",
"apiExecutor",
")",
"Broadcast",
"(",
"ctx",
"context",
".",
"Context",
",",
"cmd",
"*",
"BroadcastRequest",
")",
"*",
"BroadcastResponse",
"{",
"defer",
"func",
"(",
"started",
"time",
".",
"Time",
")",
"{",
"apiCommandDurationSummary",
".",
"WithLabelValues",
"(",
"h",
".",
"protocol",
",",
"\"",
"\"",
")",
".",
"Observe",
"(",
"time",
".",
"Since",
"(",
"started",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"resp",
":=",
"&",
"BroadcastResponse",
"{",
"}",
"\n\n",
"channels",
":=",
"cmd",
".",
"Channels",
"\n",
"data",
":=",
"cmd",
".",
"Data",
"\n\n",
"if",
"len",
"(",
"channels",
")",
"==",
"0",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"nil",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorBadRequest",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"data",
")",
"==",
"0",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"nil",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorBadRequest",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"errs",
":=",
"make",
"(",
"[",
"]",
"error",
",",
"len",
"(",
"channels",
")",
")",
"\n\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n\n",
"for",
"i",
",",
"ch",
":=",
"range",
"channels",
"{",
"if",
"ch",
"==",
"\"",
"\"",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"nil",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorBadRequest",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"_",
",",
"ok",
":=",
"h",
".",
"node",
".",
"ChannelOpts",
"(",
"ch",
")",
"\n",
"if",
"!",
"ok",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"ch",
"}",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorNamespaceNotFound",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"i",
"int",
",",
"ch",
"string",
")",
"{",
"errs",
"[",
"i",
"]",
"=",
"h",
".",
"node",
".",
"Publish",
"(",
"ch",
",",
"data",
")",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
"i",
",",
"ch",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n\n",
"var",
"firstErr",
"error",
"\n",
"for",
"i",
":=",
"range",
"errs",
"{",
"err",
":=",
"errs",
"[",
"i",
"]",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"firstErr",
"==",
"nil",
"{",
"firstErr",
"=",
"err",
"\n",
"}",
"\n",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"channels",
"[",
"i",
"]",
",",
"\"",
"\"",
":",
"err",
".",
"Error",
"(",
")",
"}",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"firstErr",
"!=",
"nil",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"firstErr",
".",
"Error",
"(",
")",
"}",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorInternal",
"\n",
"return",
"resp",
"\n",
"}",
"\n",
"return",
"resp",
"\n",
"}"
] | // Broadcast publishes the same data into many channels. | [
"Broadcast",
"publishes",
"the",
"same",
"data",
"into",
"many",
"channels",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/api.go#L63-L128 | train |
centrifugal/centrifugo | internal/api/api.go | Unsubscribe | func (h *apiExecutor) Unsubscribe(ctx context.Context, cmd *UnsubscribeRequest) *UnsubscribeResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "unsubscribe").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &UnsubscribeResponse{}
user := cmd.User
channel := cmd.Channel
if user == "" {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "user required for unsubscribe", map[string]interface{}{"channel": channel, "user": user}))
resp.Error = ErrorBadRequest
return resp
}
if channel != "" {
_, ok := h.node.ChannelOpts(channel)
if !ok {
resp.Error = ErrorNamespaceNotFound
return resp
}
}
err := h.node.Unsubscribe(user, channel)
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error unsubscribing user from channel", map[string]interface{}{"channel": channel, "user": user, "error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
return resp
} | go | func (h *apiExecutor) Unsubscribe(ctx context.Context, cmd *UnsubscribeRequest) *UnsubscribeResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "unsubscribe").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &UnsubscribeResponse{}
user := cmd.User
channel := cmd.Channel
if user == "" {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "user required for unsubscribe", map[string]interface{}{"channel": channel, "user": user}))
resp.Error = ErrorBadRequest
return resp
}
if channel != "" {
_, ok := h.node.ChannelOpts(channel)
if !ok {
resp.Error = ErrorNamespaceNotFound
return resp
}
}
err := h.node.Unsubscribe(user, channel)
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error unsubscribing user from channel", map[string]interface{}{"channel": channel, "user": user, "error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
return resp
} | [
"func",
"(",
"h",
"*",
"apiExecutor",
")",
"Unsubscribe",
"(",
"ctx",
"context",
".",
"Context",
",",
"cmd",
"*",
"UnsubscribeRequest",
")",
"*",
"UnsubscribeResponse",
"{",
"defer",
"func",
"(",
"started",
"time",
".",
"Time",
")",
"{",
"apiCommandDurationSummary",
".",
"WithLabelValues",
"(",
"h",
".",
"protocol",
",",
"\"",
"\"",
")",
".",
"Observe",
"(",
"time",
".",
"Since",
"(",
"started",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"resp",
":=",
"&",
"UnsubscribeResponse",
"{",
"}",
"\n\n",
"user",
":=",
"cmd",
".",
"User",
"\n",
"channel",
":=",
"cmd",
".",
"Channel",
"\n\n",
"if",
"user",
"==",
"\"",
"\"",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"channel",
",",
"\"",
"\"",
":",
"user",
"}",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorBadRequest",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"if",
"channel",
"!=",
"\"",
"\"",
"{",
"_",
",",
"ok",
":=",
"h",
".",
"node",
".",
"ChannelOpts",
"(",
"channel",
")",
"\n",
"if",
"!",
"ok",
"{",
"resp",
".",
"Error",
"=",
"ErrorNamespaceNotFound",
"\n",
"return",
"resp",
"\n",
"}",
"\n",
"}",
"\n\n",
"err",
":=",
"h",
".",
"node",
".",
"Unsubscribe",
"(",
"user",
",",
"channel",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"channel",
",",
"\"",
"\"",
":",
"user",
",",
"\"",
"\"",
":",
"err",
".",
"Error",
"(",
")",
"}",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorInternal",
"\n",
"return",
"resp",
"\n",
"}",
"\n",
"return",
"resp",
"\n",
"}"
] | // Unsubscribe unsubscribes user from channel and sends unsubscribe
// control message to other nodes so they could also unsubscribe user. | [
"Unsubscribe",
"unsubscribes",
"user",
"from",
"channel",
"and",
"sends",
"unsubscribe",
"control",
"message",
"to",
"other",
"nodes",
"so",
"they",
"could",
"also",
"unsubscribe",
"user",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/api.go#L132-L163 | train |
centrifugal/centrifugo | internal/api/api.go | Disconnect | func (h *apiExecutor) Disconnect(ctx context.Context, cmd *DisconnectRequest) *DisconnectResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "disconnect").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &DisconnectResponse{}
user := cmd.User
if user == "" {
// h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "user required for disconnect", map[string]interface{}{}))
resp.Error = ErrorBadRequest
return resp
}
err := h.node.Disconnect(user, false)
if err != nil {
// h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error disconnecting user", map[string]interface{}{"user": cmd.User, "error": errError()}))
resp.Error = ErrorInternal
return resp
}
return resp
} | go | func (h *apiExecutor) Disconnect(ctx context.Context, cmd *DisconnectRequest) *DisconnectResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "disconnect").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &DisconnectResponse{}
user := cmd.User
if user == "" {
// h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "user required for disconnect", map[string]interface{}{}))
resp.Error = ErrorBadRequest
return resp
}
err := h.node.Disconnect(user, false)
if err != nil {
// h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error disconnecting user", map[string]interface{}{"user": cmd.User, "error": errError()}))
resp.Error = ErrorInternal
return resp
}
return resp
} | [
"func",
"(",
"h",
"*",
"apiExecutor",
")",
"Disconnect",
"(",
"ctx",
"context",
".",
"Context",
",",
"cmd",
"*",
"DisconnectRequest",
")",
"*",
"DisconnectResponse",
"{",
"defer",
"func",
"(",
"started",
"time",
".",
"Time",
")",
"{",
"apiCommandDurationSummary",
".",
"WithLabelValues",
"(",
"h",
".",
"protocol",
",",
"\"",
"\"",
")",
".",
"Observe",
"(",
"time",
".",
"Since",
"(",
"started",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"resp",
":=",
"&",
"DisconnectResponse",
"{",
"}",
"\n\n",
"user",
":=",
"cmd",
".",
"User",
"\n",
"if",
"user",
"==",
"\"",
"\"",
"{",
"// h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, \"user required for disconnect\", map[string]interface{}{}))",
"resp",
".",
"Error",
"=",
"ErrorBadRequest",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"err",
":=",
"h",
".",
"node",
".",
"Disconnect",
"(",
"user",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, \"error disconnecting user\", map[string]interface{}{\"user\": cmd.User, \"error\": errError()}))",
"resp",
".",
"Error",
"=",
"ErrorInternal",
"\n",
"return",
"resp",
"\n",
"}",
"\n",
"return",
"resp",
"\n",
"}"
] | // Disconnect disconnects user by its ID and sends disconnect
// control message to other nodes so they could also disconnect user. | [
"Disconnect",
"disconnects",
"user",
"by",
"its",
"ID",
"and",
"sends",
"disconnect",
"control",
"message",
"to",
"other",
"nodes",
"so",
"they",
"could",
"also",
"disconnect",
"user",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/api.go#L167-L188 | train |
centrifugal/centrifugo | internal/api/api.go | Presence | func (h *apiExecutor) Presence(ctx context.Context, cmd *PresenceRequest) *PresenceResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "presence").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &PresenceResponse{}
ch := cmd.Channel
if ch == "" {
resp.Error = ErrorBadRequest
return resp
}
chOpts, ok := h.node.ChannelOpts(ch)
if !ok {
resp.Error = ErrorNamespaceNotFound
return resp
}
if !chOpts.Presence {
resp.Error = ErrorNotAvailable
return resp
}
presence, err := h.node.Presence(ch)
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error calling presence", map[string]interface{}{"error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
apiPresence := make(map[string]*ClientInfo, len(presence))
for k, v := range presence {
apiPresence[k] = &ClientInfo{
User: v.User,
Client: v.Client,
ConnInfo: Raw(v.ConnInfo),
ChanInfo: Raw(v.ChanInfo),
}
}
resp.Result = &PresenceResult{
Presence: apiPresence,
}
return resp
} | go | func (h *apiExecutor) Presence(ctx context.Context, cmd *PresenceRequest) *PresenceResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "presence").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &PresenceResponse{}
ch := cmd.Channel
if ch == "" {
resp.Error = ErrorBadRequest
return resp
}
chOpts, ok := h.node.ChannelOpts(ch)
if !ok {
resp.Error = ErrorNamespaceNotFound
return resp
}
if !chOpts.Presence {
resp.Error = ErrorNotAvailable
return resp
}
presence, err := h.node.Presence(ch)
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error calling presence", map[string]interface{}{"error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
apiPresence := make(map[string]*ClientInfo, len(presence))
for k, v := range presence {
apiPresence[k] = &ClientInfo{
User: v.User,
Client: v.Client,
ConnInfo: Raw(v.ConnInfo),
ChanInfo: Raw(v.ChanInfo),
}
}
resp.Result = &PresenceResult{
Presence: apiPresence,
}
return resp
} | [
"func",
"(",
"h",
"*",
"apiExecutor",
")",
"Presence",
"(",
"ctx",
"context",
".",
"Context",
",",
"cmd",
"*",
"PresenceRequest",
")",
"*",
"PresenceResponse",
"{",
"defer",
"func",
"(",
"started",
"time",
".",
"Time",
")",
"{",
"apiCommandDurationSummary",
".",
"WithLabelValues",
"(",
"h",
".",
"protocol",
",",
"\"",
"\"",
")",
".",
"Observe",
"(",
"time",
".",
"Since",
"(",
"started",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"resp",
":=",
"&",
"PresenceResponse",
"{",
"}",
"\n\n",
"ch",
":=",
"cmd",
".",
"Channel",
"\n\n",
"if",
"ch",
"==",
"\"",
"\"",
"{",
"resp",
".",
"Error",
"=",
"ErrorBadRequest",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"chOpts",
",",
"ok",
":=",
"h",
".",
"node",
".",
"ChannelOpts",
"(",
"ch",
")",
"\n",
"if",
"!",
"ok",
"{",
"resp",
".",
"Error",
"=",
"ErrorNamespaceNotFound",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"if",
"!",
"chOpts",
".",
"Presence",
"{",
"resp",
".",
"Error",
"=",
"ErrorNotAvailable",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"presence",
",",
"err",
":=",
"h",
".",
"node",
".",
"Presence",
"(",
"ch",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"err",
".",
"Error",
"(",
")",
"}",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorInternal",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"apiPresence",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"ClientInfo",
",",
"len",
"(",
"presence",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"presence",
"{",
"apiPresence",
"[",
"k",
"]",
"=",
"&",
"ClientInfo",
"{",
"User",
":",
"v",
".",
"User",
",",
"Client",
":",
"v",
".",
"Client",
",",
"ConnInfo",
":",
"Raw",
"(",
"v",
".",
"ConnInfo",
")",
",",
"ChanInfo",
":",
"Raw",
"(",
"v",
".",
"ChanInfo",
")",
",",
"}",
"\n",
"}",
"\n\n",
"resp",
".",
"Result",
"=",
"&",
"PresenceResult",
"{",
"Presence",
":",
"apiPresence",
",",
"}",
"\n",
"return",
"resp",
"\n",
"}"
] | // Presence returns response with presence information for channel. | [
"Presence",
"returns",
"response",
"with",
"presence",
"information",
"for",
"channel",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/api.go#L191-L237 | train |
centrifugal/centrifugo | internal/api/api.go | PresenceStats | func (h *apiExecutor) PresenceStats(ctx context.Context, cmd *PresenceStatsRequest) *PresenceStatsResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "presence_stats").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &PresenceStatsResponse{}
ch := cmd.Channel
if ch == "" {
resp.Error = ErrorBadRequest
return resp
}
chOpts, ok := h.node.ChannelOpts(ch)
if !ok {
resp.Error = ErrorNamespaceNotFound
return resp
}
if !chOpts.Presence {
resp.Error = ErrorNotAvailable
return resp
}
stats, err := h.node.PresenceStats(cmd.Channel)
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error calling presence stats", map[string]interface{}{"error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
resp.Result = &PresenceStatsResult{
NumClients: uint32(stats.NumClients),
NumUsers: uint32(stats.NumUsers),
}
return resp
} | go | func (h *apiExecutor) PresenceStats(ctx context.Context, cmd *PresenceStatsRequest) *PresenceStatsResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "presence_stats").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &PresenceStatsResponse{}
ch := cmd.Channel
if ch == "" {
resp.Error = ErrorBadRequest
return resp
}
chOpts, ok := h.node.ChannelOpts(ch)
if !ok {
resp.Error = ErrorNamespaceNotFound
return resp
}
if !chOpts.Presence {
resp.Error = ErrorNotAvailable
return resp
}
stats, err := h.node.PresenceStats(cmd.Channel)
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error calling presence stats", map[string]interface{}{"error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
resp.Result = &PresenceStatsResult{
NumClients: uint32(stats.NumClients),
NumUsers: uint32(stats.NumUsers),
}
return resp
} | [
"func",
"(",
"h",
"*",
"apiExecutor",
")",
"PresenceStats",
"(",
"ctx",
"context",
".",
"Context",
",",
"cmd",
"*",
"PresenceStatsRequest",
")",
"*",
"PresenceStatsResponse",
"{",
"defer",
"func",
"(",
"started",
"time",
".",
"Time",
")",
"{",
"apiCommandDurationSummary",
".",
"WithLabelValues",
"(",
"h",
".",
"protocol",
",",
"\"",
"\"",
")",
".",
"Observe",
"(",
"time",
".",
"Since",
"(",
"started",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"resp",
":=",
"&",
"PresenceStatsResponse",
"{",
"}",
"\n\n",
"ch",
":=",
"cmd",
".",
"Channel",
"\n\n",
"if",
"ch",
"==",
"\"",
"\"",
"{",
"resp",
".",
"Error",
"=",
"ErrorBadRequest",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"chOpts",
",",
"ok",
":=",
"h",
".",
"node",
".",
"ChannelOpts",
"(",
"ch",
")",
"\n",
"if",
"!",
"ok",
"{",
"resp",
".",
"Error",
"=",
"ErrorNamespaceNotFound",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"if",
"!",
"chOpts",
".",
"Presence",
"{",
"resp",
".",
"Error",
"=",
"ErrorNotAvailable",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"stats",
",",
"err",
":=",
"h",
".",
"node",
".",
"PresenceStats",
"(",
"cmd",
".",
"Channel",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"err",
".",
"Error",
"(",
")",
"}",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorInternal",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"resp",
".",
"Result",
"=",
"&",
"PresenceStatsResult",
"{",
"NumClients",
":",
"uint32",
"(",
"stats",
".",
"NumClients",
")",
",",
"NumUsers",
":",
"uint32",
"(",
"stats",
".",
"NumUsers",
")",
",",
"}",
"\n\n",
"return",
"resp",
"\n",
"}"
] | // PresenceStats returns response with presence stats information for channel. | [
"PresenceStats",
"returns",
"response",
"with",
"presence",
"stats",
"information",
"for",
"channel",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/api.go#L240-L278 | train |
centrifugal/centrifugo | internal/api/api.go | History | func (h *apiExecutor) History(ctx context.Context, cmd *HistoryRequest) *HistoryResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "history").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &HistoryResponse{}
ch := cmd.Channel
if ch == "" {
resp.Error = ErrorBadRequest
return resp
}
chOpts, ok := h.node.ChannelOpts(ch)
if !ok {
resp.Error = ErrorNamespaceNotFound
return resp
}
if chOpts.HistorySize <= 0 || chOpts.HistoryLifetime <= 0 {
resp.Error = ErrorNotAvailable
return resp
}
history, err := h.node.History(ch)
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error calling history", map[string]interface{}{"error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
apiPubs := make([]*Publication, len(history))
for i, pub := range history {
apiPub := &Publication{
UID: pub.UID,
Data: Raw(pub.Data),
}
if pub.Info != nil {
apiPub.Info = &ClientInfo{
User: pub.Info.User,
Client: pub.Info.Client,
ConnInfo: Raw(pub.Info.ConnInfo),
ChanInfo: Raw(pub.Info.ChanInfo),
}
}
apiPubs[i] = apiPub
}
resp.Result = &HistoryResult{
Publications: apiPubs,
}
return resp
} | go | func (h *apiExecutor) History(ctx context.Context, cmd *HistoryRequest) *HistoryResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "history").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &HistoryResponse{}
ch := cmd.Channel
if ch == "" {
resp.Error = ErrorBadRequest
return resp
}
chOpts, ok := h.node.ChannelOpts(ch)
if !ok {
resp.Error = ErrorNamespaceNotFound
return resp
}
if chOpts.HistorySize <= 0 || chOpts.HistoryLifetime <= 0 {
resp.Error = ErrorNotAvailable
return resp
}
history, err := h.node.History(ch)
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error calling history", map[string]interface{}{"error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
apiPubs := make([]*Publication, len(history))
for i, pub := range history {
apiPub := &Publication{
UID: pub.UID,
Data: Raw(pub.Data),
}
if pub.Info != nil {
apiPub.Info = &ClientInfo{
User: pub.Info.User,
Client: pub.Info.Client,
ConnInfo: Raw(pub.Info.ConnInfo),
ChanInfo: Raw(pub.Info.ChanInfo),
}
}
apiPubs[i] = apiPub
}
resp.Result = &HistoryResult{
Publications: apiPubs,
}
return resp
} | [
"func",
"(",
"h",
"*",
"apiExecutor",
")",
"History",
"(",
"ctx",
"context",
".",
"Context",
",",
"cmd",
"*",
"HistoryRequest",
")",
"*",
"HistoryResponse",
"{",
"defer",
"func",
"(",
"started",
"time",
".",
"Time",
")",
"{",
"apiCommandDurationSummary",
".",
"WithLabelValues",
"(",
"h",
".",
"protocol",
",",
"\"",
"\"",
")",
".",
"Observe",
"(",
"time",
".",
"Since",
"(",
"started",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"resp",
":=",
"&",
"HistoryResponse",
"{",
"}",
"\n\n",
"ch",
":=",
"cmd",
".",
"Channel",
"\n\n",
"if",
"ch",
"==",
"\"",
"\"",
"{",
"resp",
".",
"Error",
"=",
"ErrorBadRequest",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"chOpts",
",",
"ok",
":=",
"h",
".",
"node",
".",
"ChannelOpts",
"(",
"ch",
")",
"\n",
"if",
"!",
"ok",
"{",
"resp",
".",
"Error",
"=",
"ErrorNamespaceNotFound",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"if",
"chOpts",
".",
"HistorySize",
"<=",
"0",
"||",
"chOpts",
".",
"HistoryLifetime",
"<=",
"0",
"{",
"resp",
".",
"Error",
"=",
"ErrorNotAvailable",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"history",
",",
"err",
":=",
"h",
".",
"node",
".",
"History",
"(",
"ch",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"err",
".",
"Error",
"(",
")",
"}",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorInternal",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"apiPubs",
":=",
"make",
"(",
"[",
"]",
"*",
"Publication",
",",
"len",
"(",
"history",
")",
")",
"\n\n",
"for",
"i",
",",
"pub",
":=",
"range",
"history",
"{",
"apiPub",
":=",
"&",
"Publication",
"{",
"UID",
":",
"pub",
".",
"UID",
",",
"Data",
":",
"Raw",
"(",
"pub",
".",
"Data",
")",
",",
"}",
"\n",
"if",
"pub",
".",
"Info",
"!=",
"nil",
"{",
"apiPub",
".",
"Info",
"=",
"&",
"ClientInfo",
"{",
"User",
":",
"pub",
".",
"Info",
".",
"User",
",",
"Client",
":",
"pub",
".",
"Info",
".",
"Client",
",",
"ConnInfo",
":",
"Raw",
"(",
"pub",
".",
"Info",
".",
"ConnInfo",
")",
",",
"ChanInfo",
":",
"Raw",
"(",
"pub",
".",
"Info",
".",
"ChanInfo",
")",
",",
"}",
"\n",
"}",
"\n",
"apiPubs",
"[",
"i",
"]",
"=",
"apiPub",
"\n",
"}",
"\n\n",
"resp",
".",
"Result",
"=",
"&",
"HistoryResult",
"{",
"Publications",
":",
"apiPubs",
",",
"}",
"\n",
"return",
"resp",
"\n",
"}"
] | // History returns response with history information for channel. | [
"History",
"returns",
"response",
"with",
"history",
"information",
"for",
"channel",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/api.go#L281-L335 | train |
centrifugal/centrifugo | internal/api/api.go | Channels | func (h *apiExecutor) Channels(ctx context.Context, cmd *ChannelsRequest) *ChannelsResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "channels").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &ChannelsResponse{}
channels, err := h.node.Channels()
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error calling channels", map[string]interface{}{"error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
resp.Result = &ChannelsResult{
Channels: channels,
}
return resp
} | go | func (h *apiExecutor) Channels(ctx context.Context, cmd *ChannelsRequest) *ChannelsResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "channels").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &ChannelsResponse{}
channels, err := h.node.Channels()
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error calling channels", map[string]interface{}{"error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
resp.Result = &ChannelsResult{
Channels: channels,
}
return resp
} | [
"func",
"(",
"h",
"*",
"apiExecutor",
")",
"Channels",
"(",
"ctx",
"context",
".",
"Context",
",",
"cmd",
"*",
"ChannelsRequest",
")",
"*",
"ChannelsResponse",
"{",
"defer",
"func",
"(",
"started",
"time",
".",
"Time",
")",
"{",
"apiCommandDurationSummary",
".",
"WithLabelValues",
"(",
"h",
".",
"protocol",
",",
"\"",
"\"",
")",
".",
"Observe",
"(",
"time",
".",
"Since",
"(",
"started",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"resp",
":=",
"&",
"ChannelsResponse",
"{",
"}",
"\n\n",
"channels",
",",
"err",
":=",
"h",
".",
"node",
".",
"Channels",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"err",
".",
"Error",
"(",
")",
"}",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorInternal",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"resp",
".",
"Result",
"=",
"&",
"ChannelsResult",
"{",
"Channels",
":",
"channels",
",",
"}",
"\n",
"return",
"resp",
"\n",
"}"
] | // Channels returns active channels. | [
"Channels",
"returns",
"active",
"channels",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/api.go#L374-L392 | train |
centrifugal/centrifugo | internal/api/api.go | Info | func (h *apiExecutor) Info(ctx context.Context, cmd *InfoRequest) *InfoResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "info").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &InfoResponse{}
info, err := h.node.Info()
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error calling info", map[string]interface{}{"error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
nodes := make([]*NodeResult, len(info.Nodes))
for i, nd := range info.Nodes {
res := &NodeResult{
UID: nd.UID,
Version: nd.Version,
Name: nd.Name,
NumClients: nd.NumClients,
NumUsers: nd.NumUsers,
NumChannels: nd.NumChannels,
Uptime: nd.Uptime,
}
if nd.Metrics != nil {
res.Metrics = &Metrics{
Interval: nd.Metrics.Interval,
Items: nd.Metrics.Items,
}
}
nodes[i] = res
}
resp.Result = &InfoResult{
Nodes: nodes,
}
return resp
} | go | func (h *apiExecutor) Info(ctx context.Context, cmd *InfoRequest) *InfoResponse {
defer func(started time.Time) {
apiCommandDurationSummary.WithLabelValues(h.protocol, "info").Observe(time.Since(started).Seconds())
}(time.Now())
resp := &InfoResponse{}
info, err := h.node.Info()
if err != nil {
h.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error calling info", map[string]interface{}{"error": err.Error()}))
resp.Error = ErrorInternal
return resp
}
nodes := make([]*NodeResult, len(info.Nodes))
for i, nd := range info.Nodes {
res := &NodeResult{
UID: nd.UID,
Version: nd.Version,
Name: nd.Name,
NumClients: nd.NumClients,
NumUsers: nd.NumUsers,
NumChannels: nd.NumChannels,
Uptime: nd.Uptime,
}
if nd.Metrics != nil {
res.Metrics = &Metrics{
Interval: nd.Metrics.Interval,
Items: nd.Metrics.Items,
}
}
nodes[i] = res
}
resp.Result = &InfoResult{
Nodes: nodes,
}
return resp
} | [
"func",
"(",
"h",
"*",
"apiExecutor",
")",
"Info",
"(",
"ctx",
"context",
".",
"Context",
",",
"cmd",
"*",
"InfoRequest",
")",
"*",
"InfoResponse",
"{",
"defer",
"func",
"(",
"started",
"time",
".",
"Time",
")",
"{",
"apiCommandDurationSummary",
".",
"WithLabelValues",
"(",
"h",
".",
"protocol",
",",
"\"",
"\"",
")",
".",
"Observe",
"(",
"time",
".",
"Since",
"(",
"started",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"resp",
":=",
"&",
"InfoResponse",
"{",
"}",
"\n\n",
"info",
",",
"err",
":=",
"h",
".",
"node",
".",
"Info",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"node",
".",
"Log",
"(",
"centrifuge",
".",
"NewLogEntry",
"(",
"centrifuge",
".",
"LogLevelError",
",",
"\"",
"\"",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"err",
".",
"Error",
"(",
")",
"}",
")",
")",
"\n",
"resp",
".",
"Error",
"=",
"ErrorInternal",
"\n",
"return",
"resp",
"\n",
"}",
"\n\n",
"nodes",
":=",
"make",
"(",
"[",
"]",
"*",
"NodeResult",
",",
"len",
"(",
"info",
".",
"Nodes",
")",
")",
"\n",
"for",
"i",
",",
"nd",
":=",
"range",
"info",
".",
"Nodes",
"{",
"res",
":=",
"&",
"NodeResult",
"{",
"UID",
":",
"nd",
".",
"UID",
",",
"Version",
":",
"nd",
".",
"Version",
",",
"Name",
":",
"nd",
".",
"Name",
",",
"NumClients",
":",
"nd",
".",
"NumClients",
",",
"NumUsers",
":",
"nd",
".",
"NumUsers",
",",
"NumChannels",
":",
"nd",
".",
"NumChannels",
",",
"Uptime",
":",
"nd",
".",
"Uptime",
",",
"}",
"\n",
"if",
"nd",
".",
"Metrics",
"!=",
"nil",
"{",
"res",
".",
"Metrics",
"=",
"&",
"Metrics",
"{",
"Interval",
":",
"nd",
".",
"Metrics",
".",
"Interval",
",",
"Items",
":",
"nd",
".",
"Metrics",
".",
"Items",
",",
"}",
"\n",
"}",
"\n",
"nodes",
"[",
"i",
"]",
"=",
"res",
"\n",
"}",
"\n",
"resp",
".",
"Result",
"=",
"&",
"InfoResult",
"{",
"Nodes",
":",
"nodes",
",",
"}",
"\n",
"return",
"resp",
"\n",
"}"
] | // Info returns information about running nodes. | [
"Info",
"returns",
"information",
"about",
"running",
"nodes",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/api/api.go#L395-L432 | train |
centrifugal/centrifugo | main.go | generateConfig | func generateConfig(f string) error {
exists, err := pathExists(f)
if err != nil {
return err
}
if exists {
return errors.New("output config file already exists: " + f)
}
ext := filepath.Ext(f)
if len(ext) > 1 {
ext = ext[1:]
}
supportedExts := []string{"json", "toml", "yaml", "yml"}
if !stringInSlice(ext, supportedExts) {
return errors.New("output config file must have one of supported extensions: " + strings.Join(supportedExts, ", "))
}
var t *template.Template
switch ext {
case "json":
t, err = template.New("config").Parse(jsonConfigTemplate)
case "toml":
t, err = template.New("config").Parse(tomlConfigTemplate)
case "yaml", "yml":
t, err = template.New("config").Parse(yamlConfigTemplate)
}
if err != nil {
return err
}
var output bytes.Buffer
t.Execute(&output, struct {
Secret string
AdminPassword string
AdminSecret string
APIKey string
}{
uuid.NewV4().String(),
uuid.NewV4().String(),
uuid.NewV4().String(),
uuid.NewV4().String(),
})
err = ioutil.WriteFile(f, output.Bytes(), 0644)
if err != nil {
return err
}
err = validateConfig(f)
if err != nil {
_ = os.Remove(f)
return err
}
return nil
} | go | func generateConfig(f string) error {
exists, err := pathExists(f)
if err != nil {
return err
}
if exists {
return errors.New("output config file already exists: " + f)
}
ext := filepath.Ext(f)
if len(ext) > 1 {
ext = ext[1:]
}
supportedExts := []string{"json", "toml", "yaml", "yml"}
if !stringInSlice(ext, supportedExts) {
return errors.New("output config file must have one of supported extensions: " + strings.Join(supportedExts, ", "))
}
var t *template.Template
switch ext {
case "json":
t, err = template.New("config").Parse(jsonConfigTemplate)
case "toml":
t, err = template.New("config").Parse(tomlConfigTemplate)
case "yaml", "yml":
t, err = template.New("config").Parse(yamlConfigTemplate)
}
if err != nil {
return err
}
var output bytes.Buffer
t.Execute(&output, struct {
Secret string
AdminPassword string
AdminSecret string
APIKey string
}{
uuid.NewV4().String(),
uuid.NewV4().String(),
uuid.NewV4().String(),
uuid.NewV4().String(),
})
err = ioutil.WriteFile(f, output.Bytes(), 0644)
if err != nil {
return err
}
err = validateConfig(f)
if err != nil {
_ = os.Remove(f)
return err
}
return nil
} | [
"func",
"generateConfig",
"(",
"f",
"string",
")",
"error",
"{",
"exists",
",",
"err",
":=",
"pathExists",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"exists",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"f",
")",
"\n",
"}",
"\n",
"ext",
":=",
"filepath",
".",
"Ext",
"(",
"f",
")",
"\n\n",
"if",
"len",
"(",
"ext",
")",
">",
"1",
"{",
"ext",
"=",
"ext",
"[",
"1",
":",
"]",
"\n",
"}",
"\n\n",
"supportedExts",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n\n",
"if",
"!",
"stringInSlice",
"(",
"ext",
",",
"supportedExts",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"strings",
".",
"Join",
"(",
"supportedExts",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"var",
"t",
"*",
"template",
".",
"Template",
"\n\n",
"switch",
"ext",
"{",
"case",
"\"",
"\"",
":",
"t",
",",
"err",
"=",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Parse",
"(",
"jsonConfigTemplate",
")",
"\n",
"case",
"\"",
"\"",
":",
"t",
",",
"err",
"=",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Parse",
"(",
"tomlConfigTemplate",
")",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"t",
",",
"err",
"=",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Parse",
"(",
"yamlConfigTemplate",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"output",
"bytes",
".",
"Buffer",
"\n",
"t",
".",
"Execute",
"(",
"&",
"output",
",",
"struct",
"{",
"Secret",
"string",
"\n",
"AdminPassword",
"string",
"\n",
"AdminSecret",
"string",
"\n",
"APIKey",
"string",
"\n",
"}",
"{",
"uuid",
".",
"NewV4",
"(",
")",
".",
"String",
"(",
")",
",",
"uuid",
".",
"NewV4",
"(",
")",
".",
"String",
"(",
")",
",",
"uuid",
".",
"NewV4",
"(",
")",
".",
"String",
"(",
")",
",",
"uuid",
".",
"NewV4",
"(",
")",
".",
"String",
"(",
")",
",",
"}",
")",
"\n\n",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"f",
",",
"output",
".",
"Bytes",
"(",
")",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"validateConfig",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"_",
"=",
"os",
".",
"Remove",
"(",
"f",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // generateConfig generates configuration file at provided path. | [
"generateConfig",
"generates",
"configuration",
"file",
"at",
"provided",
"path",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/main.go#L712-L771 | train |
centrifugal/centrifugo | main.go | validateConfig | func validateConfig(f string) error {
viper.SetConfigFile(f)
err := viper.ReadInConfig()
if err != nil {
switch err.(type) {
case viper.ConfigParseError:
return err
default:
return errors.New("unable to locate config file, use \"centrifugo genconfig -c " + f + "\" command to generate one")
}
}
c := nodeConfig()
return c.Validate()
} | go | func validateConfig(f string) error {
viper.SetConfigFile(f)
err := viper.ReadInConfig()
if err != nil {
switch err.(type) {
case viper.ConfigParseError:
return err
default:
return errors.New("unable to locate config file, use \"centrifugo genconfig -c " + f + "\" command to generate one")
}
}
c := nodeConfig()
return c.Validate()
} | [
"func",
"validateConfig",
"(",
"f",
"string",
")",
"error",
"{",
"viper",
".",
"SetConfigFile",
"(",
"f",
")",
"\n",
"err",
":=",
"viper",
".",
"ReadInConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"viper",
".",
"ConfigParseError",
":",
"return",
"err",
"\n",
"default",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\\\"",
"\"",
"+",
"f",
"+",
"\"",
"\\\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"c",
":=",
"nodeConfig",
"(",
")",
"\n",
"return",
"c",
".",
"Validate",
"(",
")",
"\n",
"}"
] | // validateConfig validates config file located at provided path. | [
"validateConfig",
"validates",
"config",
"file",
"located",
"at",
"provided",
"path",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/main.go#L774-L787 | train |
centrifugal/centrifugo | main.go | applicationName | func applicationName() string {
v := viper.GetViper()
name := v.GetString("name")
if name != "" {
return name
}
port := v.GetString("port")
var hostname string
hostname, err := os.Hostname()
if err != nil {
hostname = "?"
}
return hostname + "_" + port
} | go | func applicationName() string {
v := viper.GetViper()
name := v.GetString("name")
if name != "" {
return name
}
port := v.GetString("port")
var hostname string
hostname, err := os.Hostname()
if err != nil {
hostname = "?"
}
return hostname + "_" + port
} | [
"func",
"applicationName",
"(",
")",
"string",
"{",
"v",
":=",
"viper",
".",
"GetViper",
"(",
")",
"\n\n",
"name",
":=",
"v",
".",
"GetString",
"(",
"\"",
"\"",
")",
"\n",
"if",
"name",
"!=",
"\"",
"\"",
"{",
"return",
"name",
"\n",
"}",
"\n",
"port",
":=",
"v",
".",
"GetString",
"(",
"\"",
"\"",
")",
"\n",
"var",
"hostname",
"string",
"\n",
"hostname",
",",
"err",
":=",
"os",
".",
"Hostname",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"hostname",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"hostname",
"+",
"\"",
"\"",
"+",
"port",
"\n",
"}"
] | // applicationName returns a name for this centrifuge. If no name provided
// in configuration then it constructs node name based on hostname and port | [
"applicationName",
"returns",
"a",
"name",
"for",
"this",
"centrifuge",
".",
"If",
"no",
"name",
"provided",
"in",
"configuration",
"then",
"it",
"constructs",
"node",
"name",
"based",
"on",
"hostname",
"and",
"port"
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/main.go#L851-L865 | train |
centrifugal/centrifugo | main.go | namespacesFromConfig | func namespacesFromConfig(v *viper.Viper) []centrifuge.ChannelNamespace {
ns := []centrifuge.ChannelNamespace{}
if !v.IsSet("namespaces") {
return ns
}
v.UnmarshalKey("namespaces", &ns)
return ns
} | go | func namespacesFromConfig(v *viper.Viper) []centrifuge.ChannelNamespace {
ns := []centrifuge.ChannelNamespace{}
if !v.IsSet("namespaces") {
return ns
}
v.UnmarshalKey("namespaces", &ns)
return ns
} | [
"func",
"namespacesFromConfig",
"(",
"v",
"*",
"viper",
".",
"Viper",
")",
"[",
"]",
"centrifuge",
".",
"ChannelNamespace",
"{",
"ns",
":=",
"[",
"]",
"centrifuge",
".",
"ChannelNamespace",
"{",
"}",
"\n",
"if",
"!",
"v",
".",
"IsSet",
"(",
"\"",
"\"",
")",
"{",
"return",
"ns",
"\n",
"}",
"\n",
"v",
".",
"UnmarshalKey",
"(",
"\"",
"\"",
",",
"&",
"ns",
")",
"\n",
"return",
"ns",
"\n",
"}"
] | // namespacesFromConfig allows to unmarshal channel namespaces. | [
"namespacesFromConfig",
"allows",
"to",
"unmarshal",
"channel",
"namespaces",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/main.go#L868-L875 | train |
centrifugal/centrifugo | main.go | Mux | func Mux(n *centrifuge.Node, flags HandlerFlag) *http.ServeMux {
mux := http.NewServeMux()
if flags&HandlerDebug != 0 {
mux.Handle("/debug/pprof/", middleware.LogRequest(http.HandlerFunc(pprof.Index)))
mux.Handle("/debug/pprof/cmdline", middleware.LogRequest(http.HandlerFunc(pprof.Cmdline)))
mux.Handle("/debug/pprof/profile", middleware.LogRequest(http.HandlerFunc(pprof.Profile)))
mux.Handle("/debug/pprof/symbol", middleware.LogRequest(http.HandlerFunc(pprof.Symbol)))
mux.Handle("/debug/pprof/trace", middleware.LogRequest(http.HandlerFunc(pprof.Trace)))
}
if flags&HandlerWebsocket != 0 {
// register Websocket connection endpoint.
mux.Handle("/connection/websocket", middleware.LogRequest(centrifuge.NewWebsocketHandler(n, websocketHandlerConfig())))
}
if flags&HandlerSockJS != 0 {
// register SockJS connection endpoints.
sockjsConfig := sockjsHandlerConfig()
sockjsConfig.HandlerPrefix = "/connection/sockjs"
mux.Handle(sockjsConfig.HandlerPrefix+"/", middleware.LogRequest(centrifuge.NewSockjsHandler(n, sockjsConfig)))
}
if flags&HandlerAPI != 0 {
// register HTTP API endpoint.
apiHandler := api.NewHandler(n, api.Config{})
if viper.GetBool("api_insecure") {
mux.Handle("/api", middleware.LogRequest(apiHandler))
} else {
mux.Handle("/api", middleware.LogRequest(middleware.APIKeyAuth(viper.GetString("api_key"), apiHandler)))
}
}
if flags&HandlerPrometheus != 0 {
// register Prometheus metrics export endpoint.
mux.Handle("/metrics", middleware.LogRequest(promhttp.Handler()))
}
if flags&HandlerAdmin != 0 {
// register admin web interface API endpoints.
mux.Handle("/", middleware.LogRequest(admin.NewHandler(n, adminHandlerConfig())))
} else {
mux.Handle("/", middleware.LogRequest(http.HandlerFunc(notFoundHandler)))
}
if flags&HandlerHealth != 0 {
mux.Handle("/health", middleware.LogRequest(health.NewHandler(n, health.Config{})))
}
return mux
} | go | func Mux(n *centrifuge.Node, flags HandlerFlag) *http.ServeMux {
mux := http.NewServeMux()
if flags&HandlerDebug != 0 {
mux.Handle("/debug/pprof/", middleware.LogRequest(http.HandlerFunc(pprof.Index)))
mux.Handle("/debug/pprof/cmdline", middleware.LogRequest(http.HandlerFunc(pprof.Cmdline)))
mux.Handle("/debug/pprof/profile", middleware.LogRequest(http.HandlerFunc(pprof.Profile)))
mux.Handle("/debug/pprof/symbol", middleware.LogRequest(http.HandlerFunc(pprof.Symbol)))
mux.Handle("/debug/pprof/trace", middleware.LogRequest(http.HandlerFunc(pprof.Trace)))
}
if flags&HandlerWebsocket != 0 {
// register Websocket connection endpoint.
mux.Handle("/connection/websocket", middleware.LogRequest(centrifuge.NewWebsocketHandler(n, websocketHandlerConfig())))
}
if flags&HandlerSockJS != 0 {
// register SockJS connection endpoints.
sockjsConfig := sockjsHandlerConfig()
sockjsConfig.HandlerPrefix = "/connection/sockjs"
mux.Handle(sockjsConfig.HandlerPrefix+"/", middleware.LogRequest(centrifuge.NewSockjsHandler(n, sockjsConfig)))
}
if flags&HandlerAPI != 0 {
// register HTTP API endpoint.
apiHandler := api.NewHandler(n, api.Config{})
if viper.GetBool("api_insecure") {
mux.Handle("/api", middleware.LogRequest(apiHandler))
} else {
mux.Handle("/api", middleware.LogRequest(middleware.APIKeyAuth(viper.GetString("api_key"), apiHandler)))
}
}
if flags&HandlerPrometheus != 0 {
// register Prometheus metrics export endpoint.
mux.Handle("/metrics", middleware.LogRequest(promhttp.Handler()))
}
if flags&HandlerAdmin != 0 {
// register admin web interface API endpoints.
mux.Handle("/", middleware.LogRequest(admin.NewHandler(n, adminHandlerConfig())))
} else {
mux.Handle("/", middleware.LogRequest(http.HandlerFunc(notFoundHandler)))
}
if flags&HandlerHealth != 0 {
mux.Handle("/health", middleware.LogRequest(health.NewHandler(n, health.Config{})))
}
return mux
} | [
"func",
"Mux",
"(",
"n",
"*",
"centrifuge",
".",
"Node",
",",
"flags",
"HandlerFlag",
")",
"*",
"http",
".",
"ServeMux",
"{",
"mux",
":=",
"http",
".",
"NewServeMux",
"(",
")",
"\n\n",
"if",
"flags",
"&",
"HandlerDebug",
"!=",
"0",
"{",
"mux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"http",
".",
"HandlerFunc",
"(",
"pprof",
".",
"Index",
")",
")",
")",
"\n",
"mux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"http",
".",
"HandlerFunc",
"(",
"pprof",
".",
"Cmdline",
")",
")",
")",
"\n",
"mux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"http",
".",
"HandlerFunc",
"(",
"pprof",
".",
"Profile",
")",
")",
")",
"\n",
"mux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"http",
".",
"HandlerFunc",
"(",
"pprof",
".",
"Symbol",
")",
")",
")",
"\n",
"mux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"http",
".",
"HandlerFunc",
"(",
"pprof",
".",
"Trace",
")",
")",
")",
"\n",
"}",
"\n\n",
"if",
"flags",
"&",
"HandlerWebsocket",
"!=",
"0",
"{",
"// register Websocket connection endpoint.",
"mux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"centrifuge",
".",
"NewWebsocketHandler",
"(",
"n",
",",
"websocketHandlerConfig",
"(",
")",
")",
")",
")",
"\n",
"}",
"\n\n",
"if",
"flags",
"&",
"HandlerSockJS",
"!=",
"0",
"{",
"// register SockJS connection endpoints.",
"sockjsConfig",
":=",
"sockjsHandlerConfig",
"(",
")",
"\n",
"sockjsConfig",
".",
"HandlerPrefix",
"=",
"\"",
"\"",
"\n",
"mux",
".",
"Handle",
"(",
"sockjsConfig",
".",
"HandlerPrefix",
"+",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"centrifuge",
".",
"NewSockjsHandler",
"(",
"n",
",",
"sockjsConfig",
")",
")",
")",
"\n",
"}",
"\n\n",
"if",
"flags",
"&",
"HandlerAPI",
"!=",
"0",
"{",
"// register HTTP API endpoint.",
"apiHandler",
":=",
"api",
".",
"NewHandler",
"(",
"n",
",",
"api",
".",
"Config",
"{",
"}",
")",
"\n",
"if",
"viper",
".",
"GetBool",
"(",
"\"",
"\"",
")",
"{",
"mux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"apiHandler",
")",
")",
"\n",
"}",
"else",
"{",
"mux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"middleware",
".",
"APIKeyAuth",
"(",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"apiHandler",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"flags",
"&",
"HandlerPrometheus",
"!=",
"0",
"{",
"// register Prometheus metrics export endpoint.",
"mux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"promhttp",
".",
"Handler",
"(",
")",
")",
")",
"\n",
"}",
"\n\n",
"if",
"flags",
"&",
"HandlerAdmin",
"!=",
"0",
"{",
"// register admin web interface API endpoints.",
"mux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"admin",
".",
"NewHandler",
"(",
"n",
",",
"adminHandlerConfig",
"(",
")",
")",
")",
")",
"\n",
"}",
"else",
"{",
"mux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"http",
".",
"HandlerFunc",
"(",
"notFoundHandler",
")",
")",
")",
"\n",
"}",
"\n\n",
"if",
"flags",
"&",
"HandlerHealth",
"!=",
"0",
"{",
"mux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"middleware",
".",
"LogRequest",
"(",
"health",
".",
"NewHandler",
"(",
"n",
",",
"health",
".",
"Config",
"{",
"}",
")",
")",
")",
"\n",
"}",
"\n\n",
"return",
"mux",
"\n",
"}"
] | // Mux returns a mux including set of default handlers for Centrifugo server. | [
"Mux",
"returns",
"a",
"mux",
"including",
"set",
"of",
"default",
"handlers",
"for",
"Centrifugo",
"server",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/main.go#L1199-L1250 | train |
centrifugal/centrifugo | internal/metrics/graphite/graphite.go | PreparePathComponent | func PreparePathComponent(s string) string {
s = re.ReplaceAllLiteralString(s, "_")
return strings.Replace(s, ".", "_", -1)
} | go | func PreparePathComponent(s string) string {
s = re.ReplaceAllLiteralString(s, "_")
return strings.Replace(s, ".", "_", -1)
} | [
"func",
"PreparePathComponent",
"(",
"s",
"string",
")",
"string",
"{",
"s",
"=",
"re",
".",
"ReplaceAllLiteralString",
"(",
"s",
",",
"\"",
"\"",
")",
"\n",
"return",
"strings",
".",
"Replace",
"(",
"s",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"}"
] | // PreparePathComponent cleans string to be used as Graphite metric path. | [
"PreparePathComponent",
"cleans",
"string",
"to",
"be",
"used",
"as",
"Graphite",
"metric",
"path",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/metrics/graphite/graphite.go#L19-L22 | train |
centrifugal/centrifugo | internal/metrics/graphite/graphite.go | New | func New(c Config) *Exporter {
exporter := &Exporter{
prefix: c.Prefix,
address: c.Address,
timeout: time.Second,
tags: c.Tags,
closeCh: make(chan struct{}),
sink: make(chan eagle.Metrics),
}
exporter.eagle = eagle.New(eagle.Config{
Gatherer: c.Gatherer,
Interval: c.Interval,
Sink: exporter.sink,
})
go exporter.run()
return exporter
} | go | func New(c Config) *Exporter {
exporter := &Exporter{
prefix: c.Prefix,
address: c.Address,
timeout: time.Second,
tags: c.Tags,
closeCh: make(chan struct{}),
sink: make(chan eagle.Metrics),
}
exporter.eagle = eagle.New(eagle.Config{
Gatherer: c.Gatherer,
Interval: c.Interval,
Sink: exporter.sink,
})
go exporter.run()
return exporter
} | [
"func",
"New",
"(",
"c",
"Config",
")",
"*",
"Exporter",
"{",
"exporter",
":=",
"&",
"Exporter",
"{",
"prefix",
":",
"c",
".",
"Prefix",
",",
"address",
":",
"c",
".",
"Address",
",",
"timeout",
":",
"time",
".",
"Second",
",",
"tags",
":",
"c",
".",
"Tags",
",",
"closeCh",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"sink",
":",
"make",
"(",
"chan",
"eagle",
".",
"Metrics",
")",
",",
"}",
"\n",
"exporter",
".",
"eagle",
"=",
"eagle",
".",
"New",
"(",
"eagle",
".",
"Config",
"{",
"Gatherer",
":",
"c",
".",
"Gatherer",
",",
"Interval",
":",
"c",
".",
"Interval",
",",
"Sink",
":",
"exporter",
".",
"sink",
",",
"}",
")",
"\n",
"go",
"exporter",
".",
"run",
"(",
")",
"\n",
"return",
"exporter",
"\n",
"}"
] | // New creates new Graphite Exporter. | [
"New",
"creates",
"new",
"Graphite",
"Exporter",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/metrics/graphite/graphite.go#L46-L62 | train |
centrifugal/centrifugo | internal/metrics/graphite/graphite.go | Close | func (e *Exporter) Close() error {
e.closeOnce.Do(func() {
close(e.closeCh)
e.eagle.Close()
})
return nil
} | go | func (e *Exporter) Close() error {
e.closeOnce.Do(func() {
close(e.closeCh)
e.eagle.Close()
})
return nil
} | [
"func",
"(",
"e",
"*",
"Exporter",
")",
"Close",
"(",
")",
"error",
"{",
"e",
".",
"closeOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"close",
"(",
"e",
".",
"closeCh",
")",
"\n",
"e",
".",
"eagle",
".",
"Close",
"(",
")",
"\n",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close stops exporter. | [
"Close",
"stops",
"exporter",
"."
] | a1ffa9a106edbebbe0ed238e155d1b7f30677cb7 | https://github.com/centrifugal/centrifugo/blob/a1ffa9a106edbebbe0ed238e155d1b7f30677cb7/internal/metrics/graphite/graphite.go#L76-L82 | train |
rivo/tview | demos/primitive/main.go | NewRadioButtons | func NewRadioButtons(options []string) *RadioButtons {
return &RadioButtons{
Box: tview.NewBox(),
options: options,
}
} | go | func NewRadioButtons(options []string) *RadioButtons {
return &RadioButtons{
Box: tview.NewBox(),
options: options,
}
} | [
"func",
"NewRadioButtons",
"(",
"options",
"[",
"]",
"string",
")",
"*",
"RadioButtons",
"{",
"return",
"&",
"RadioButtons",
"{",
"Box",
":",
"tview",
".",
"NewBox",
"(",
")",
",",
"options",
":",
"options",
",",
"}",
"\n",
"}"
] | // NewRadioButtons returns a new radio button primitive. | [
"NewRadioButtons",
"returns",
"a",
"new",
"radio",
"button",
"primitive",
"."
] | 90b4da1bd64ceee13d2e7d782b315b819190f7bf | https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/demos/primitive/main.go#L19-L24 | train |
rivo/tview | box.go | NewBox | func NewBox() *Box {
b := &Box{
width: 15,
height: 10,
innerX: -1, // Mark as uninitialized.
backgroundColor: Styles.PrimitiveBackgroundColor,
borderColor: Styles.BorderColor,
titleColor: Styles.TitleColor,
titleAlign: AlignCenter,
}
b.focus = b
return b
} | go | func NewBox() *Box {
b := &Box{
width: 15,
height: 10,
innerX: -1, // Mark as uninitialized.
backgroundColor: Styles.PrimitiveBackgroundColor,
borderColor: Styles.BorderColor,
titleColor: Styles.TitleColor,
titleAlign: AlignCenter,
}
b.focus = b
return b
} | [
"func",
"NewBox",
"(",
")",
"*",
"Box",
"{",
"b",
":=",
"&",
"Box",
"{",
"width",
":",
"15",
",",
"height",
":",
"10",
",",
"innerX",
":",
"-",
"1",
",",
"// Mark as uninitialized.",
"backgroundColor",
":",
"Styles",
".",
"PrimitiveBackgroundColor",
",",
"borderColor",
":",
"Styles",
".",
"BorderColor",
",",
"titleColor",
":",
"Styles",
".",
"TitleColor",
",",
"titleAlign",
":",
"AlignCenter",
",",
"}",
"\n",
"b",
".",
"focus",
"=",
"b",
"\n",
"return",
"b",
"\n",
"}"
] | // NewBox returns a Box without a border. | [
"NewBox",
"returns",
"a",
"Box",
"without",
"a",
"border",
"."
] | 90b4da1bd64ceee13d2e7d782b315b819190f7bf | https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/box.go#L64-L76 | train |
rivo/tview | box.go | SetBorderPadding | func (b *Box) SetBorderPadding(top, bottom, left, right int) *Box {
b.paddingTop, b.paddingBottom, b.paddingLeft, b.paddingRight = top, bottom, left, right
return b
} | go | func (b *Box) SetBorderPadding(top, bottom, left, right int) *Box {
b.paddingTop, b.paddingBottom, b.paddingLeft, b.paddingRight = top, bottom, left, right
return b
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"SetBorderPadding",
"(",
"top",
",",
"bottom",
",",
"left",
",",
"right",
"int",
")",
"*",
"Box",
"{",
"b",
".",
"paddingTop",
",",
"b",
".",
"paddingBottom",
",",
"b",
".",
"paddingLeft",
",",
"b",
".",
"paddingRight",
"=",
"top",
",",
"bottom",
",",
"left",
",",
"right",
"\n",
"return",
"b",
"\n",
"}"
] | // SetBorderPadding sets the size of the borders around the box content. | [
"SetBorderPadding",
"sets",
"the",
"size",
"of",
"the",
"borders",
"around",
"the",
"box",
"content",
"."
] | 90b4da1bd64ceee13d2e7d782b315b819190f7bf | https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/box.go#L79-L82 | train |
rivo/tview | box.go | GetRect | func (b *Box) GetRect() (int, int, int, int) {
return b.x, b.y, b.width, b.height
} | go | func (b *Box) GetRect() (int, int, int, int) {
return b.x, b.y, b.width, b.height
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"GetRect",
"(",
")",
"(",
"int",
",",
"int",
",",
"int",
",",
"int",
")",
"{",
"return",
"b",
".",
"x",
",",
"b",
".",
"y",
",",
"b",
".",
"width",
",",
"b",
".",
"height",
"\n",
"}"
] | // GetRect returns the current position of the rectangle, x, y, width, and
// height. | [
"GetRect",
"returns",
"the",
"current",
"position",
"of",
"the",
"rectangle",
"x",
"y",
"width",
"and",
"height",
"."
] | 90b4da1bd64ceee13d2e7d782b315b819190f7bf | https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/box.go#L86-L88 | train |
rivo/tview | box.go | InputHandler | func (b *Box) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive)) {
return b.WrapInputHandler(nil)
} | go | func (b *Box) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive)) {
return b.WrapInputHandler(nil)
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"InputHandler",
"(",
")",
"func",
"(",
"event",
"*",
"tcell",
".",
"EventKey",
",",
"setFocus",
"func",
"(",
"p",
"Primitive",
")",
")",
"{",
"return",
"b",
".",
"WrapInputHandler",
"(",
"nil",
")",
"\n",
"}"
] | // InputHandler returns nil. | [
"InputHandler",
"returns",
"nil",
"."
] | 90b4da1bd64ceee13d2e7d782b315b819190f7bf | https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/box.go#L158-L160 | train |
rivo/tview | box.go | SetBackgroundColor | func (b *Box) SetBackgroundColor(color tcell.Color) *Box {
b.backgroundColor = color
return b
} | go | func (b *Box) SetBackgroundColor(color tcell.Color) *Box {
b.backgroundColor = color
return b
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"SetBackgroundColor",
"(",
"color",
"tcell",
".",
"Color",
")",
"*",
"Box",
"{",
"b",
".",
"backgroundColor",
"=",
"color",
"\n",
"return",
"b",
"\n",
"}"
] | // SetBackgroundColor sets the box's background color. | [
"SetBackgroundColor",
"sets",
"the",
"box",
"s",
"background",
"color",
"."
] | 90b4da1bd64ceee13d2e7d782b315b819190f7bf | https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/box.go#L188-L191 | train |
rivo/tview | box.go | SetBorder | func (b *Box) SetBorder(show bool) *Box {
b.border = show
return b
} | go | func (b *Box) SetBorder(show bool) *Box {
b.border = show
return b
} | [
"func",
"(",
"b",
"*",
"Box",
")",
"SetBorder",
"(",
"show",
"bool",
")",
"*",
"Box",
"{",
"b",
".",
"border",
"=",
"show",
"\n",
"return",
"b",
"\n",
"}"
] | // SetBorder sets the flag indicating whether or not the box should have a
// border. | [
"SetBorder",
"sets",
"the",
"flag",
"indicating",
"whether",
"or",
"not",
"the",
"box",
"should",
"have",
"a",
"border",
"."
] | 90b4da1bd64ceee13d2e7d782b315b819190f7bf | https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/box.go#L195-L198 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.