id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
|---|---|---|---|---|---|---|---|---|---|---|---|
13,500
|
moovweb/gokogiri
|
xml/node.go
|
Namespace
|
func (xmlNode *XmlNode) Namespace() (href string) {
if xmlNode.Ptr.ns != nil {
p := unsafe.Pointer(xmlNode.Ptr.ns.href)
href = C.GoString((*C.char)(p))
}
return
}
|
go
|
func (xmlNode *XmlNode) Namespace() (href string) {
if xmlNode.Ptr.ns != nil {
p := unsafe.Pointer(xmlNode.Ptr.ns.href)
href = C.GoString((*C.char)(p))
}
return
}
|
[
"func",
"(",
"xmlNode",
"*",
"XmlNode",
")",
"Namespace",
"(",
")",
"(",
"href",
"string",
")",
"{",
"if",
"xmlNode",
".",
"Ptr",
".",
"ns",
"!=",
"nil",
"{",
"p",
":=",
"unsafe",
".",
"Pointer",
"(",
"xmlNode",
".",
"Ptr",
".",
"ns",
".",
"href",
")",
"\n",
"href",
"=",
"C",
".",
"GoString",
"(",
"(",
"*",
"C",
".",
"char",
")",
"(",
"p",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// The namespace of the node. This is the empty string if there
// no associated namespace.
|
[
"The",
"namespace",
"of",
"the",
"node",
".",
"This",
"is",
"the",
"empty",
"string",
"if",
"there",
"no",
"associated",
"namespace",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/node.go#L727-L733
|
13,501
|
moovweb/gokogiri
|
xml/node.go
|
ToXml
|
func (xmlNode *XmlNode) ToXml(encoding, outputBuffer []byte) ([]byte, int) {
return xmlNode.serialize(XML_SAVE_AS_XML|XML_SAVE_FORMAT, encoding, outputBuffer)
}
|
go
|
func (xmlNode *XmlNode) ToXml(encoding, outputBuffer []byte) ([]byte, int) {
return xmlNode.serialize(XML_SAVE_AS_XML|XML_SAVE_FORMAT, encoding, outputBuffer)
}
|
[
"func",
"(",
"xmlNode",
"*",
"XmlNode",
")",
"ToXml",
"(",
"encoding",
",",
"outputBuffer",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"int",
")",
"{",
"return",
"xmlNode",
".",
"serialize",
"(",
"XML_SAVE_AS_XML",
"|",
"XML_SAVE_FORMAT",
",",
"encoding",
",",
"outputBuffer",
")",
"\n",
"}"
] |
// ToXml generates an indented XML document with an XML declaration.
// It is not guaranteed to be well formed unless xmlNode is an element node,
// or a document node with only one element child.
// If you need finer control over the formatting, call SerializeWithFormat.
// If encoding is nil, the document's output encoding is used - this defaults to UTF-8.
// If outputBuffer is nil, one will be created for you.
|
[
"ToXml",
"generates",
"an",
"indented",
"XML",
"document",
"with",
"an",
"XML",
"declaration",
".",
"It",
"is",
"not",
"guaranteed",
"to",
"be",
"well",
"formed",
"unless",
"xmlNode",
"is",
"an",
"element",
"node",
"or",
"a",
"document",
"node",
"with",
"only",
"one",
"element",
"child",
".",
"If",
"you",
"need",
"finer",
"control",
"over",
"the",
"formatting",
"call",
"SerializeWithFormat",
".",
"If",
"encoding",
"is",
"nil",
"the",
"document",
"s",
"output",
"encoding",
"is",
"used",
"-",
"this",
"defaults",
"to",
"UTF",
"-",
"8",
".",
"If",
"outputBuffer",
"is",
"nil",
"one",
"will",
"be",
"created",
"for",
"you",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/node.go#L800-L802
|
13,502
|
moovweb/gokogiri
|
xml/node.go
|
ToUnformattedXml
|
func (xmlNode *XmlNode) ToUnformattedXml() string {
var b []byte
var size int
b, size = xmlNode.serialize(XML_SAVE_AS_XML|XML_SAVE_NO_DECL, nil, nil)
if b == nil {
return ""
}
return string(b[:size])
}
|
go
|
func (xmlNode *XmlNode) ToUnformattedXml() string {
var b []byte
var size int
b, size = xmlNode.serialize(XML_SAVE_AS_XML|XML_SAVE_NO_DECL, nil, nil)
if b == nil {
return ""
}
return string(b[:size])
}
|
[
"func",
"(",
"xmlNode",
"*",
"XmlNode",
")",
"ToUnformattedXml",
"(",
")",
"string",
"{",
"var",
"b",
"[",
"]",
"byte",
"\n",
"var",
"size",
"int",
"\n",
"b",
",",
"size",
"=",
"xmlNode",
".",
"serialize",
"(",
"XML_SAVE_AS_XML",
"|",
"XML_SAVE_NO_DECL",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"b",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"string",
"(",
"b",
"[",
":",
"size",
"]",
")",
"\n",
"}"
] |
// ToUnformattedXml generates an unformatted XML document without an XML declaration.
// This is useful for conforming to various standards and for unit testing, although
// the output is not guaranteed to be well formed unless xmlNode is an element node.
|
[
"ToUnformattedXml",
"generates",
"an",
"unformatted",
"XML",
"document",
"without",
"an",
"XML",
"declaration",
".",
"This",
"is",
"useful",
"for",
"conforming",
"to",
"various",
"standards",
"and",
"for",
"unit",
"testing",
"although",
"the",
"output",
"is",
"not",
"guaranteed",
"to",
"be",
"well",
"formed",
"unless",
"xmlNode",
"is",
"an",
"element",
"node",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/node.go#L807-L815
|
13,503
|
moovweb/gokogiri
|
xml/node.go
|
ToHtml
|
func (xmlNode *XmlNode) ToHtml(encoding, outputBuffer []byte) ([]byte, int) {
return xmlNode.serialize(XML_SAVE_AS_HTML|XML_SAVE_FORMAT, encoding, outputBuffer)
}
|
go
|
func (xmlNode *XmlNode) ToHtml(encoding, outputBuffer []byte) ([]byte, int) {
return xmlNode.serialize(XML_SAVE_AS_HTML|XML_SAVE_FORMAT, encoding, outputBuffer)
}
|
[
"func",
"(",
"xmlNode",
"*",
"XmlNode",
")",
"ToHtml",
"(",
"encoding",
",",
"outputBuffer",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"int",
")",
"{",
"return",
"xmlNode",
".",
"serialize",
"(",
"XML_SAVE_AS_HTML",
"|",
"XML_SAVE_FORMAT",
",",
"encoding",
",",
"outputBuffer",
")",
"\n",
"}"
] |
// ToHtml generates an indented XML document that conforms to HTML 4.0 rules; meaning
// that some elements may be unclosed or forced to use end tags even when empty.
// If you want to output XHTML, call SerializeWithFormat and enable the XML_SAVE_XHTML
// flag as part of the format.
// If encoding is nil, the document's output encoding is used - this defaults to UTF-8.
// If outputBuffer is nil, one will be created for you.
|
[
"ToHtml",
"generates",
"an",
"indented",
"XML",
"document",
"that",
"conforms",
"to",
"HTML",
"4",
".",
"0",
"rules",
";",
"meaning",
"that",
"some",
"elements",
"may",
"be",
"unclosed",
"or",
"forced",
"to",
"use",
"end",
"tags",
"even",
"when",
"empty",
".",
"If",
"you",
"want",
"to",
"output",
"XHTML",
"call",
"SerializeWithFormat",
"and",
"enable",
"the",
"XML_SAVE_XHTML",
"flag",
"as",
"part",
"of",
"the",
"format",
".",
"If",
"encoding",
"is",
"nil",
"the",
"document",
"s",
"output",
"encoding",
"is",
"used",
"-",
"this",
"defaults",
"to",
"UTF",
"-",
"8",
".",
"If",
"outputBuffer",
"is",
"nil",
"one",
"will",
"be",
"created",
"for",
"you",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/node.go#L825-L827
|
13,504
|
moovweb/gokogiri
|
xml/node.go
|
DeclareNamespace
|
func (xmlNode *XmlNode) DeclareNamespace(prefix, href string) {
//can only declare namespaces on elements
if xmlNode.NodeType() != XML_ELEMENT_NODE {
return
}
hrefBytes := GetCString([]byte(href))
hrefPtr := unsafe.Pointer(&hrefBytes[0])
//if the namespace is already declared using this prefix, just return
_ns := C.xmlSearchNsByHref((*C.xmlDoc)(xmlNode.Document.DocPtr()), xmlNode.Ptr, (*C.xmlChar)(hrefPtr))
if _ns != nil {
_prefixPtr := unsafe.Pointer(_ns.prefix)
_prefix := C.GoString((*C.char)(_prefixPtr))
if prefix == _prefix {
return
}
}
prefixBytes := GetCString([]byte(prefix))
prefixPtr := unsafe.Pointer(&prefixBytes[0])
if prefix == "" {
prefixPtr = nil
}
//this adds the namespace declaration to the node
_ = C.xmlNewNs(xmlNode.Ptr, (*C.xmlChar)(hrefPtr), (*C.xmlChar)(prefixPtr))
}
|
go
|
func (xmlNode *XmlNode) DeclareNamespace(prefix, href string) {
//can only declare namespaces on elements
if xmlNode.NodeType() != XML_ELEMENT_NODE {
return
}
hrefBytes := GetCString([]byte(href))
hrefPtr := unsafe.Pointer(&hrefBytes[0])
//if the namespace is already declared using this prefix, just return
_ns := C.xmlSearchNsByHref((*C.xmlDoc)(xmlNode.Document.DocPtr()), xmlNode.Ptr, (*C.xmlChar)(hrefPtr))
if _ns != nil {
_prefixPtr := unsafe.Pointer(_ns.prefix)
_prefix := C.GoString((*C.char)(_prefixPtr))
if prefix == _prefix {
return
}
}
prefixBytes := GetCString([]byte(prefix))
prefixPtr := unsafe.Pointer(&prefixBytes[0])
if prefix == "" {
prefixPtr = nil
}
//this adds the namespace declaration to the node
_ = C.xmlNewNs(xmlNode.Ptr, (*C.xmlChar)(hrefPtr), (*C.xmlChar)(prefixPtr))
}
|
[
"func",
"(",
"xmlNode",
"*",
"XmlNode",
")",
"DeclareNamespace",
"(",
"prefix",
",",
"href",
"string",
")",
"{",
"//can only declare namespaces on elements",
"if",
"xmlNode",
".",
"NodeType",
"(",
")",
"!=",
"XML_ELEMENT_NODE",
"{",
"return",
"\n",
"}",
"\n",
"hrefBytes",
":=",
"GetCString",
"(",
"[",
"]",
"byte",
"(",
"href",
")",
")",
"\n",
"hrefPtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"&",
"hrefBytes",
"[",
"0",
"]",
")",
"\n\n",
"//if the namespace is already declared using this prefix, just return",
"_ns",
":=",
"C",
".",
"xmlSearchNsByHref",
"(",
"(",
"*",
"C",
".",
"xmlDoc",
")",
"(",
"xmlNode",
".",
"Document",
".",
"DocPtr",
"(",
")",
")",
",",
"xmlNode",
".",
"Ptr",
",",
"(",
"*",
"C",
".",
"xmlChar",
")",
"(",
"hrefPtr",
")",
")",
"\n",
"if",
"_ns",
"!=",
"nil",
"{",
"_prefixPtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"_ns",
".",
"prefix",
")",
"\n",
"_prefix",
":=",
"C",
".",
"GoString",
"(",
"(",
"*",
"C",
".",
"char",
")",
"(",
"_prefixPtr",
")",
")",
"\n",
"if",
"prefix",
"==",
"_prefix",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"prefixBytes",
":=",
"GetCString",
"(",
"[",
"]",
"byte",
"(",
"prefix",
")",
")",
"\n",
"prefixPtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"&",
"prefixBytes",
"[",
"0",
"]",
")",
"\n",
"if",
"prefix",
"==",
"\"",
"\"",
"{",
"prefixPtr",
"=",
"nil",
"\n",
"}",
"\n\n",
"//this adds the namespace declaration to the node",
"_",
"=",
"C",
".",
"xmlNewNs",
"(",
"xmlNode",
".",
"Ptr",
",",
"(",
"*",
"C",
".",
"xmlChar",
")",
"(",
"hrefPtr",
")",
",",
"(",
"*",
"C",
".",
"xmlChar",
")",
"(",
"prefixPtr",
")",
")",
"\n",
"}"
] |
// Add a namespace declaration to an element.
// This is typically done on the root element or node high up in the tree
// to avoid duplication. The declaration is not created if the namespace
// is already declared in this scope with the same prefix.
|
[
"Add",
"a",
"namespace",
"declaration",
"to",
"an",
"element",
".",
"This",
"is",
"typically",
"done",
"on",
"the",
"root",
"element",
"or",
"node",
"high",
"up",
"in",
"the",
"tree",
"to",
"avoid",
"duplication",
".",
"The",
"declaration",
"is",
"not",
"created",
"if",
"the",
"namespace",
"is",
"already",
"declared",
"in",
"this",
"scope",
"with",
"the",
"same",
"prefix",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/node.go#L1089-L1115
|
13,505
|
moovweb/gokogiri
|
xml/document.go
|
ReadFile
|
func ReadFile(filename string, options ParseOption) (doc *XmlDocument, err error) {
// verify the file exists and can be read before we invoke C API
_, err = os.Stat(filename)
if err != nil {
return
}
dataBytes := GetCString([]byte(filename))
dataPtr := unsafe.Pointer(&dataBytes[0])
var docPtr *C.xmlDoc
docPtr = C.xmlReadFile((*C.char)(dataPtr), nil, C.int(options))
if docPtr == nil {
err = ERR_FAILED_TO_PARSE_XML
} else {
var encoding []byte
// capture the detected input encoding
p := docPtr.encoding
if p != nil {
encoding = []byte(C.GoString((*C.char)(unsafe.Pointer(p))))
}
doc = NewDocument(unsafe.Pointer(docPtr), 0, encoding, DefaultEncodingBytes)
}
return
}
|
go
|
func ReadFile(filename string, options ParseOption) (doc *XmlDocument, err error) {
// verify the file exists and can be read before we invoke C API
_, err = os.Stat(filename)
if err != nil {
return
}
dataBytes := GetCString([]byte(filename))
dataPtr := unsafe.Pointer(&dataBytes[0])
var docPtr *C.xmlDoc
docPtr = C.xmlReadFile((*C.char)(dataPtr), nil, C.int(options))
if docPtr == nil {
err = ERR_FAILED_TO_PARSE_XML
} else {
var encoding []byte
// capture the detected input encoding
p := docPtr.encoding
if p != nil {
encoding = []byte(C.GoString((*C.char)(unsafe.Pointer(p))))
}
doc = NewDocument(unsafe.Pointer(docPtr), 0, encoding, DefaultEncodingBytes)
}
return
}
|
[
"func",
"ReadFile",
"(",
"filename",
"string",
",",
"options",
"ParseOption",
")",
"(",
"doc",
"*",
"XmlDocument",
",",
"err",
"error",
")",
"{",
"// verify the file exists and can be read before we invoke C API",
"_",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"dataBytes",
":=",
"GetCString",
"(",
"[",
"]",
"byte",
"(",
"filename",
")",
")",
"\n",
"dataPtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"&",
"dataBytes",
"[",
"0",
"]",
")",
"\n",
"var",
"docPtr",
"*",
"C",
".",
"xmlDoc",
"\n",
"docPtr",
"=",
"C",
".",
"xmlReadFile",
"(",
"(",
"*",
"C",
".",
"char",
")",
"(",
"dataPtr",
")",
",",
"nil",
",",
"C",
".",
"int",
"(",
"options",
")",
")",
"\n",
"if",
"docPtr",
"==",
"nil",
"{",
"err",
"=",
"ERR_FAILED_TO_PARSE_XML",
"\n",
"}",
"else",
"{",
"var",
"encoding",
"[",
"]",
"byte",
"\n",
"// capture the detected input encoding",
"p",
":=",
"docPtr",
".",
"encoding",
"\n",
"if",
"p",
"!=",
"nil",
"{",
"encoding",
"=",
"[",
"]",
"byte",
"(",
"C",
".",
"GoString",
"(",
"(",
"*",
"C",
".",
"char",
")",
"(",
"unsafe",
".",
"Pointer",
"(",
"p",
")",
")",
")",
")",
"\n",
"}",
"\n",
"doc",
"=",
"NewDocument",
"(",
"unsafe",
".",
"Pointer",
"(",
"docPtr",
")",
",",
"0",
",",
"encoding",
",",
"DefaultEncodingBytes",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// ReadFile loads an XmlDocument from a filename. The encoding declared in the document will be
// used as the input encoding. If no encoding is declared, the library will use the alogrithm
// in the XML standard to determine if the document is encoded with UTF-8 or UTF-16.
|
[
"ReadFile",
"loads",
"an",
"XmlDocument",
"from",
"a",
"filename",
".",
"The",
"encoding",
"declared",
"in",
"the",
"document",
"will",
"be",
"used",
"as",
"the",
"input",
"encoding",
".",
"If",
"no",
"encoding",
"is",
"declared",
"the",
"library",
"will",
"use",
"the",
"alogrithm",
"in",
"the",
"XML",
"standard",
"to",
"determine",
"if",
"the",
"document",
"is",
"encoded",
"with",
"UTF",
"-",
"8",
"or",
"UTF",
"-",
"16",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/document.go#L181-L204
|
13,506
|
moovweb/gokogiri
|
xml/document.go
|
DocPtr
|
func (document *XmlDocument) DocPtr() (ptr unsafe.Pointer) {
ptr = unsafe.Pointer(document.Ptr)
return
}
|
go
|
func (document *XmlDocument) DocPtr() (ptr unsafe.Pointer) {
ptr = unsafe.Pointer(document.Ptr)
return
}
|
[
"func",
"(",
"document",
"*",
"XmlDocument",
")",
"DocPtr",
"(",
")",
"(",
"ptr",
"unsafe",
".",
"Pointer",
")",
"{",
"ptr",
"=",
"unsafe",
".",
"Pointer",
"(",
"document",
".",
"Ptr",
")",
"\n",
"return",
"\n",
"}"
] |
// DocPtr provides access to the libxml2 structure underlying the document.
|
[
"DocPtr",
"provides",
"access",
"to",
"the",
"libxml2",
"structure",
"underlying",
"the",
"document",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/document.go#L217-L220
|
13,507
|
moovweb/gokogiri
|
xml/document.go
|
Root
|
func (document *XmlDocument) Root() (element *ElementNode) {
nodePtr := C.xmlDocGetRootElement(document.Ptr)
if nodePtr != nil {
element = NewNode(unsafe.Pointer(nodePtr), document).(*ElementNode)
}
return
}
|
go
|
func (document *XmlDocument) Root() (element *ElementNode) {
nodePtr := C.xmlDocGetRootElement(document.Ptr)
if nodePtr != nil {
element = NewNode(unsafe.Pointer(nodePtr), document).(*ElementNode)
}
return
}
|
[
"func",
"(",
"document",
"*",
"XmlDocument",
")",
"Root",
"(",
")",
"(",
"element",
"*",
"ElementNode",
")",
"{",
"nodePtr",
":=",
"C",
".",
"xmlDocGetRootElement",
"(",
"document",
".",
"Ptr",
")",
"\n",
"if",
"nodePtr",
"!=",
"nil",
"{",
"element",
"=",
"NewNode",
"(",
"unsafe",
".",
"Pointer",
"(",
"nodePtr",
")",
",",
"document",
")",
".",
"(",
"*",
"ElementNode",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Root returns the root node of the document. Newly created documents do not
// have a root node until an element node is added a child of the document.
//
// Documents that have multiple root nodes are invalid adn the behaviour is
// not well defined.
|
[
"Root",
"returns",
"the",
"root",
"node",
"of",
"the",
"document",
".",
"Newly",
"created",
"documents",
"do",
"not",
"have",
"a",
"root",
"node",
"until",
"an",
"element",
"node",
"is",
"added",
"a",
"child",
"of",
"the",
"document",
".",
"Documents",
"that",
"have",
"multiple",
"root",
"nodes",
"are",
"invalid",
"adn",
"the",
"behaviour",
"is",
"not",
"well",
"defined",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/document.go#L282-L288
|
13,508
|
moovweb/gokogiri
|
xml/document.go
|
NodeById
|
func (document *XmlDocument) NodeById(id string) (element *ElementNode) {
dataBytes := GetCString([]byte(id))
dataPtr := unsafe.Pointer(&dataBytes[0])
nodePtr := C.xmlGetID(document.Ptr, (*C.xmlChar)(dataPtr))
if nodePtr != nil {
idattr := NewNode(unsafe.Pointer(nodePtr), document).(*AttributeNode)
element = idattr.Parent().(*ElementNode)
}
return
}
|
go
|
func (document *XmlDocument) NodeById(id string) (element *ElementNode) {
dataBytes := GetCString([]byte(id))
dataPtr := unsafe.Pointer(&dataBytes[0])
nodePtr := C.xmlGetID(document.Ptr, (*C.xmlChar)(dataPtr))
if nodePtr != nil {
idattr := NewNode(unsafe.Pointer(nodePtr), document).(*AttributeNode)
element = idattr.Parent().(*ElementNode)
}
return
}
|
[
"func",
"(",
"document",
"*",
"XmlDocument",
")",
"NodeById",
"(",
"id",
"string",
")",
"(",
"element",
"*",
"ElementNode",
")",
"{",
"dataBytes",
":=",
"GetCString",
"(",
"[",
"]",
"byte",
"(",
"id",
")",
")",
"\n",
"dataPtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"&",
"dataBytes",
"[",
"0",
"]",
")",
"\n",
"nodePtr",
":=",
"C",
".",
"xmlGetID",
"(",
"document",
".",
"Ptr",
",",
"(",
"*",
"C",
".",
"xmlChar",
")",
"(",
"dataPtr",
")",
")",
"\n",
"if",
"nodePtr",
"!=",
"nil",
"{",
"idattr",
":=",
"NewNode",
"(",
"unsafe",
".",
"Pointer",
"(",
"nodePtr",
")",
",",
"document",
")",
".",
"(",
"*",
"AttributeNode",
")",
"\n",
"element",
"=",
"idattr",
".",
"Parent",
"(",
")",
".",
"(",
"*",
"ElementNode",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Get an element node by the value of its ID attribute. By convention this attribute
// is named id, but the actual name of the attribute is set by the document's DTD or schema.
//
// The value for an ID attribute is guaranteed to be unique within a valid document.
|
[
"Get",
"an",
"element",
"node",
"by",
"the",
"value",
"of",
"its",
"ID",
"attribute",
".",
"By",
"convention",
"this",
"attribute",
"is",
"named",
"id",
"but",
"the",
"actual",
"name",
"of",
"the",
"attribute",
"is",
"set",
"by",
"the",
"document",
"s",
"DTD",
"or",
"schema",
".",
"The",
"value",
"for",
"an",
"ID",
"attribute",
"is",
"guaranteed",
"to",
"be",
"unique",
"within",
"a",
"valid",
"document",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/document.go#L294-L303
|
13,509
|
moovweb/gokogiri
|
xml/document.go
|
CreateTextNode
|
func (document *XmlDocument) CreateTextNode(data string) (text *TextNode) {
dataBytes := GetCString([]byte(data))
dataPtr := unsafe.Pointer(&dataBytes[0])
nodePtr := C.xmlNewText((*C.xmlChar)(dataPtr))
if nodePtr != nil {
nodePtr.doc = (*_Ctype_struct__xmlDoc)(document.DocPtr())
text = NewNode(unsafe.Pointer(nodePtr), document).(*TextNode)
}
return
}
|
go
|
func (document *XmlDocument) CreateTextNode(data string) (text *TextNode) {
dataBytes := GetCString([]byte(data))
dataPtr := unsafe.Pointer(&dataBytes[0])
nodePtr := C.xmlNewText((*C.xmlChar)(dataPtr))
if nodePtr != nil {
nodePtr.doc = (*_Ctype_struct__xmlDoc)(document.DocPtr())
text = NewNode(unsafe.Pointer(nodePtr), document).(*TextNode)
}
return
}
|
[
"func",
"(",
"document",
"*",
"XmlDocument",
")",
"CreateTextNode",
"(",
"data",
"string",
")",
"(",
"text",
"*",
"TextNode",
")",
"{",
"dataBytes",
":=",
"GetCString",
"(",
"[",
"]",
"byte",
"(",
"data",
")",
")",
"\n",
"dataPtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"&",
"dataBytes",
"[",
"0",
"]",
")",
"\n",
"nodePtr",
":=",
"C",
".",
"xmlNewText",
"(",
"(",
"*",
"C",
".",
"xmlChar",
")",
"(",
"dataPtr",
")",
")",
"\n",
"if",
"nodePtr",
"!=",
"nil",
"{",
"nodePtr",
".",
"doc",
"=",
"(",
"*",
"_Ctype_struct__xmlDoc",
")",
"(",
"document",
".",
"DocPtr",
"(",
")",
")",
"\n",
"text",
"=",
"NewNode",
"(",
"unsafe",
".",
"Pointer",
"(",
"nodePtr",
")",
",",
"document",
")",
".",
"(",
"*",
"TextNode",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
//CreateTextNode creates a text node. It can be added as a child of an element.
//
// The data argument is XML-escaped and used as the content of the node.
|
[
"CreateTextNode",
"creates",
"a",
"text",
"node",
".",
"It",
"can",
"be",
"added",
"as",
"a",
"child",
"of",
"an",
"element",
".",
"The",
"data",
"argument",
"is",
"XML",
"-",
"escaped",
"and",
"used",
"as",
"the",
"content",
"of",
"the",
"node",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/document.go#L325-L334
|
13,510
|
moovweb/gokogiri
|
xml/document.go
|
CreateCDataNode
|
func (document *XmlDocument) CreateCDataNode(data string) (cdata *CDataNode) {
dataLen := len(data)
dataBytes := GetCString([]byte(data))
dataPtr := unsafe.Pointer(&dataBytes[0])
nodePtr := C.xmlNewCDataBlock(document.Ptr, (*C.xmlChar)(dataPtr), C.int(dataLen))
if nodePtr != nil {
cdata = NewNode(unsafe.Pointer(nodePtr), document).(*CDataNode)
}
return
}
|
go
|
func (document *XmlDocument) CreateCDataNode(data string) (cdata *CDataNode) {
dataLen := len(data)
dataBytes := GetCString([]byte(data))
dataPtr := unsafe.Pointer(&dataBytes[0])
nodePtr := C.xmlNewCDataBlock(document.Ptr, (*C.xmlChar)(dataPtr), C.int(dataLen))
if nodePtr != nil {
cdata = NewNode(unsafe.Pointer(nodePtr), document).(*CDataNode)
}
return
}
|
[
"func",
"(",
"document",
"*",
"XmlDocument",
")",
"CreateCDataNode",
"(",
"data",
"string",
")",
"(",
"cdata",
"*",
"CDataNode",
")",
"{",
"dataLen",
":=",
"len",
"(",
"data",
")",
"\n",
"dataBytes",
":=",
"GetCString",
"(",
"[",
"]",
"byte",
"(",
"data",
")",
")",
"\n",
"dataPtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"&",
"dataBytes",
"[",
"0",
"]",
")",
"\n",
"nodePtr",
":=",
"C",
".",
"xmlNewCDataBlock",
"(",
"document",
".",
"Ptr",
",",
"(",
"*",
"C",
".",
"xmlChar",
")",
"(",
"dataPtr",
")",
",",
"C",
".",
"int",
"(",
"dataLen",
")",
")",
"\n",
"if",
"nodePtr",
"!=",
"nil",
"{",
"cdata",
"=",
"NewNode",
"(",
"unsafe",
".",
"Pointer",
"(",
"nodePtr",
")",
",",
"document",
")",
".",
"(",
"*",
"CDataNode",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
//CreateCDataNode creates a CDATA node. CDATA nodes can
// only be children of an element.
//
// The data argument will become the content of the newly created node.
|
[
"CreateCDataNode",
"creates",
"a",
"CDATA",
"node",
".",
"CDATA",
"nodes",
"can",
"only",
"be",
"children",
"of",
"an",
"element",
".",
"The",
"data",
"argument",
"will",
"become",
"the",
"content",
"of",
"the",
"newly",
"created",
"node",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/document.go#L340-L349
|
13,511
|
moovweb/gokogiri
|
xml/document.go
|
CreateCommentNode
|
func (document *XmlDocument) CreateCommentNode(data string) (comment *CommentNode) {
dataBytes := GetCString([]byte(data))
dataPtr := unsafe.Pointer(&dataBytes[0])
nodePtr := C.xmlNewComment((*C.xmlChar)(dataPtr))
if nodePtr != nil {
comment = NewNode(unsafe.Pointer(nodePtr), document).(*CommentNode)
}
return
}
|
go
|
func (document *XmlDocument) CreateCommentNode(data string) (comment *CommentNode) {
dataBytes := GetCString([]byte(data))
dataPtr := unsafe.Pointer(&dataBytes[0])
nodePtr := C.xmlNewComment((*C.xmlChar)(dataPtr))
if nodePtr != nil {
comment = NewNode(unsafe.Pointer(nodePtr), document).(*CommentNode)
}
return
}
|
[
"func",
"(",
"document",
"*",
"XmlDocument",
")",
"CreateCommentNode",
"(",
"data",
"string",
")",
"(",
"comment",
"*",
"CommentNode",
")",
"{",
"dataBytes",
":=",
"GetCString",
"(",
"[",
"]",
"byte",
"(",
"data",
")",
")",
"\n",
"dataPtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"&",
"dataBytes",
"[",
"0",
"]",
")",
"\n",
"nodePtr",
":=",
"C",
".",
"xmlNewComment",
"(",
"(",
"*",
"C",
".",
"xmlChar",
")",
"(",
"dataPtr",
")",
")",
"\n",
"if",
"nodePtr",
"!=",
"nil",
"{",
"comment",
"=",
"NewNode",
"(",
"unsafe",
".",
"Pointer",
"(",
"nodePtr",
")",
",",
"document",
")",
".",
"(",
"*",
"CommentNode",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
//CreateCommentNode creates a comment node. Comment nodes can
// be children of an element or of the document itself.
//
// The data argument will become the content of the comment.
|
[
"CreateCommentNode",
"creates",
"a",
"comment",
"node",
".",
"Comment",
"nodes",
"can",
"be",
"children",
"of",
"an",
"element",
"or",
"of",
"the",
"document",
"itself",
".",
"The",
"data",
"argument",
"will",
"become",
"the",
"content",
"of",
"the",
"comment",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/document.go#L355-L363
|
13,512
|
moovweb/gokogiri
|
xml/document.go
|
CreatePINode
|
func (document *XmlDocument) CreatePINode(name, data string) (pi *ProcessingInstructionNode) {
nameBytes := GetCString([]byte(name))
namePtr := unsafe.Pointer(&nameBytes[0])
dataBytes := GetCString([]byte(data))
dataPtr := unsafe.Pointer(&dataBytes[0])
nodePtr := C.xmlNewDocPI(document.Ptr, (*C.xmlChar)(namePtr), (*C.xmlChar)(dataPtr))
if nodePtr != nil {
pi = NewNode(unsafe.Pointer(nodePtr), document).(*ProcessingInstructionNode)
}
return
}
|
go
|
func (document *XmlDocument) CreatePINode(name, data string) (pi *ProcessingInstructionNode) {
nameBytes := GetCString([]byte(name))
namePtr := unsafe.Pointer(&nameBytes[0])
dataBytes := GetCString([]byte(data))
dataPtr := unsafe.Pointer(&dataBytes[0])
nodePtr := C.xmlNewDocPI(document.Ptr, (*C.xmlChar)(namePtr), (*C.xmlChar)(dataPtr))
if nodePtr != nil {
pi = NewNode(unsafe.Pointer(nodePtr), document).(*ProcessingInstructionNode)
}
return
}
|
[
"func",
"(",
"document",
"*",
"XmlDocument",
")",
"CreatePINode",
"(",
"name",
",",
"data",
"string",
")",
"(",
"pi",
"*",
"ProcessingInstructionNode",
")",
"{",
"nameBytes",
":=",
"GetCString",
"(",
"[",
"]",
"byte",
"(",
"name",
")",
")",
"\n",
"namePtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"&",
"nameBytes",
"[",
"0",
"]",
")",
"\n",
"dataBytes",
":=",
"GetCString",
"(",
"[",
"]",
"byte",
"(",
"data",
")",
")",
"\n",
"dataPtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"&",
"dataBytes",
"[",
"0",
"]",
")",
"\n",
"nodePtr",
":=",
"C",
".",
"xmlNewDocPI",
"(",
"document",
".",
"Ptr",
",",
"(",
"*",
"C",
".",
"xmlChar",
")",
"(",
"namePtr",
")",
",",
"(",
"*",
"C",
".",
"xmlChar",
")",
"(",
"dataPtr",
")",
")",
"\n",
"if",
"nodePtr",
"!=",
"nil",
"{",
"pi",
"=",
"NewNode",
"(",
"unsafe",
".",
"Pointer",
"(",
"nodePtr",
")",
",",
"document",
")",
".",
"(",
"*",
"ProcessingInstructionNode",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
//CreatePINode creates a processing instruction node with the specified name and data.
// Processing instruction nodes can be children of an element or of the document itself.
//
// While it's common to use an attribute-like syntax for processing instructions, the data
// is actually an arbitrary string that you will need to generate or parse yourself.
|
[
"CreatePINode",
"creates",
"a",
"processing",
"instruction",
"node",
"with",
"the",
"specified",
"name",
"and",
"data",
".",
"Processing",
"instruction",
"nodes",
"can",
"be",
"children",
"of",
"an",
"element",
"or",
"of",
"the",
"document",
"itself",
".",
"While",
"it",
"s",
"common",
"to",
"use",
"an",
"attribute",
"-",
"like",
"syntax",
"for",
"processing",
"instructions",
"the",
"data",
"is",
"actually",
"an",
"arbitrary",
"string",
"that",
"you",
"will",
"need",
"to",
"generate",
"or",
"parse",
"yourself",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/document.go#L370-L380
|
13,513
|
moovweb/gokogiri
|
xml/document.go
|
UnparsedEntityURI
|
func (document *XmlDocument) UnparsedEntityURI(name string) (val string) {
if name == "" {
return
}
nameBytes := GetCString([]byte(name))
namePtr := unsafe.Pointer(&nameBytes[0])
entity := C.xmlGetDocEntity(document.Ptr, (*C.xmlChar)(namePtr))
if entity == nil {
return
}
// unlike entity.content (which returns the raw, unprocessed string value of the entity),
// it looks like entity.URI includes any escaping needed to treat the value as a URI.
valPtr := unsafe.Pointer(entity.URI)
if valPtr == nil {
return
}
val = C.GoString((*C.char)(valPtr))
return
}
|
go
|
func (document *XmlDocument) UnparsedEntityURI(name string) (val string) {
if name == "" {
return
}
nameBytes := GetCString([]byte(name))
namePtr := unsafe.Pointer(&nameBytes[0])
entity := C.xmlGetDocEntity(document.Ptr, (*C.xmlChar)(namePtr))
if entity == nil {
return
}
// unlike entity.content (which returns the raw, unprocessed string value of the entity),
// it looks like entity.URI includes any escaping needed to treat the value as a URI.
valPtr := unsafe.Pointer(entity.URI)
if valPtr == nil {
return
}
val = C.GoString((*C.char)(valPtr))
return
}
|
[
"func",
"(",
"document",
"*",
"XmlDocument",
")",
"UnparsedEntityURI",
"(",
"name",
"string",
")",
"(",
"val",
"string",
")",
"{",
"if",
"name",
"==",
"\"",
"\"",
"{",
"return",
"\n",
"}",
"\n\n",
"nameBytes",
":=",
"GetCString",
"(",
"[",
"]",
"byte",
"(",
"name",
")",
")",
"\n",
"namePtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"&",
"nameBytes",
"[",
"0",
"]",
")",
"\n",
"entity",
":=",
"C",
".",
"xmlGetDocEntity",
"(",
"document",
".",
"Ptr",
",",
"(",
"*",
"C",
".",
"xmlChar",
")",
"(",
"namePtr",
")",
")",
"\n",
"if",
"entity",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// unlike entity.content (which returns the raw, unprocessed string value of the entity),",
"// it looks like entity.URI includes any escaping needed to treat the value as a URI.",
"valPtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"entity",
".",
"URI",
")",
"\n",
"if",
"valPtr",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"val",
"=",
"C",
".",
"GoString",
"(",
"(",
"*",
"C",
".",
"char",
")",
"(",
"valPtr",
")",
")",
"\n",
"return",
"\n",
"}"
] |
// Return the value of an NDATA entity declared in the DTD. If there is no such entity or
// the value cannot be encoded as a valid URI, an empty string is returned.
//
// Note that this library assumes you already know the name of entity and does not
// expose any way of getting the list of entities.
|
[
"Return",
"the",
"value",
"of",
"an",
"NDATA",
"entity",
"declared",
"in",
"the",
"DTD",
".",
"If",
"there",
"is",
"no",
"such",
"entity",
"or",
"the",
"value",
"cannot",
"be",
"encoded",
"as",
"a",
"valid",
"URI",
"an",
"empty",
"string",
"is",
"returned",
".",
"Note",
"that",
"this",
"library",
"assumes",
"you",
"already",
"know",
"the",
"name",
"of",
"entity",
"and",
"does",
"not",
"expose",
"any",
"way",
"of",
"getting",
"the",
"list",
"of",
"entities",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/document.go#L397-L418
|
13,514
|
moovweb/gokogiri
|
xml/document.go
|
Free
|
func (document *XmlDocument) Free() {
//must free the xpath context before freeing the fragments or unlinked nodes
//otherwise, it causes memory leaks and crashes when dealing with very large documents (a few MB)
if document.XPathCtx != nil {
document.XPathCtx.Free()
document.XPathCtx = nil
}
//must clear the fragments first
//because the nodes are put in the unlinked list
if document.fragments != nil {
for _, fragment := range document.fragments {
fragment.Remove()
}
}
document.fragments = nil
var p *C.xmlNode
if document.UnlinkedNodes != nil {
for p, _ = range document.UnlinkedNodes {
C.xmlFreeNode(p)
}
}
document.UnlinkedNodes = nil
if document.Ptr != nil {
C.xmlFreeDoc(document.Ptr)
document.Ptr = nil
}
}
|
go
|
func (document *XmlDocument) Free() {
//must free the xpath context before freeing the fragments or unlinked nodes
//otherwise, it causes memory leaks and crashes when dealing with very large documents (a few MB)
if document.XPathCtx != nil {
document.XPathCtx.Free()
document.XPathCtx = nil
}
//must clear the fragments first
//because the nodes are put in the unlinked list
if document.fragments != nil {
for _, fragment := range document.fragments {
fragment.Remove()
}
}
document.fragments = nil
var p *C.xmlNode
if document.UnlinkedNodes != nil {
for p, _ = range document.UnlinkedNodes {
C.xmlFreeNode(p)
}
}
document.UnlinkedNodes = nil
if document.Ptr != nil {
C.xmlFreeDoc(document.Ptr)
document.Ptr = nil
}
}
|
[
"func",
"(",
"document",
"*",
"XmlDocument",
")",
"Free",
"(",
")",
"{",
"//must free the xpath context before freeing the fragments or unlinked nodes",
"//otherwise, it causes memory leaks and crashes when dealing with very large documents (a few MB)",
"if",
"document",
".",
"XPathCtx",
"!=",
"nil",
"{",
"document",
".",
"XPathCtx",
".",
"Free",
"(",
")",
"\n",
"document",
".",
"XPathCtx",
"=",
"nil",
"\n",
"}",
"\n",
"//must clear the fragments first",
"//because the nodes are put in the unlinked list",
"if",
"document",
".",
"fragments",
"!=",
"nil",
"{",
"for",
"_",
",",
"fragment",
":=",
"range",
"document",
".",
"fragments",
"{",
"fragment",
".",
"Remove",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"document",
".",
"fragments",
"=",
"nil",
"\n",
"var",
"p",
"*",
"C",
".",
"xmlNode",
"\n",
"if",
"document",
".",
"UnlinkedNodes",
"!=",
"nil",
"{",
"for",
"p",
",",
"_",
"=",
"range",
"document",
".",
"UnlinkedNodes",
"{",
"C",
".",
"xmlFreeNode",
"(",
"p",
")",
"\n",
"}",
"\n",
"}",
"\n",
"document",
".",
"UnlinkedNodes",
"=",
"nil",
"\n",
"if",
"document",
".",
"Ptr",
"!=",
"nil",
"{",
"C",
".",
"xmlFreeDoc",
"(",
"document",
".",
"Ptr",
")",
"\n",
"document",
".",
"Ptr",
"=",
"nil",
"\n",
"}",
"\n",
"}"
] |
// Free the C structures associated with this document.
|
[
"Free",
"the",
"C",
"structures",
"associated",
"with",
"this",
"document",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/document.go#L421-L447
|
13,515
|
moovweb/gokogiri
|
xml/nodeset.go
|
ToPointers
|
func (n Nodeset) ToPointers() (pointers []unsafe.Pointer) {
for _, node := range n {
pointers = append(pointers, node.NodePtr())
}
return
}
|
go
|
func (n Nodeset) ToPointers() (pointers []unsafe.Pointer) {
for _, node := range n {
pointers = append(pointers, node.NodePtr())
}
return
}
|
[
"func",
"(",
"n",
"Nodeset",
")",
"ToPointers",
"(",
")",
"(",
"pointers",
"[",
"]",
"unsafe",
".",
"Pointer",
")",
"{",
"for",
"_",
",",
"node",
":=",
"range",
"n",
"{",
"pointers",
"=",
"append",
"(",
"pointers",
",",
"node",
".",
"NodePtr",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Produce a slice of unsafe.Pointer objects, suitable for passing to a C function
|
[
"Produce",
"a",
"slice",
"of",
"unsafe",
".",
"Pointer",
"objects",
"suitable",
"for",
"passing",
"to",
"a",
"C",
"function"
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/nodeset.go#L17-L22
|
13,516
|
moovweb/gokogiri
|
xml/nodeset.go
|
ToXPathNodeset
|
func (n Nodeset) ToXPathNodeset() (ret C.xmlXPathObjectPtr) {
ret = C.xmlXPathNewNodeSet(nil)
for _, node := range n {
C.xmlXPathNodeSetAdd(ret.nodesetval, (*C.xmlNode)(node.NodePtr()))
}
return
}
|
go
|
func (n Nodeset) ToXPathNodeset() (ret C.xmlXPathObjectPtr) {
ret = C.xmlXPathNewNodeSet(nil)
for _, node := range n {
C.xmlXPathNodeSetAdd(ret.nodesetval, (*C.xmlNode)(node.NodePtr()))
}
return
}
|
[
"func",
"(",
"n",
"Nodeset",
")",
"ToXPathNodeset",
"(",
")",
"(",
"ret",
"C",
".",
"xmlXPathObjectPtr",
")",
"{",
"ret",
"=",
"C",
".",
"xmlXPathNewNodeSet",
"(",
"nil",
")",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"n",
"{",
"C",
".",
"xmlXPathNodeSetAdd",
"(",
"ret",
".",
"nodesetval",
",",
"(",
"*",
"C",
".",
"xmlNode",
")",
"(",
"node",
".",
"NodePtr",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Produce a C.xmlXPathObjectPtr suitable for passing to libxml2
|
[
"Produce",
"a",
"C",
".",
"xmlXPathObjectPtr",
"suitable",
"for",
"passing",
"to",
"libxml2"
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/nodeset.go#L25-L31
|
13,517
|
moovweb/gokogiri
|
xml/nodeset.go
|
ToXPathValueTree
|
func (n Nodeset) ToXPathValueTree() (ret C.xmlXPathObjectPtr) {
if len(n) == 0 {
ret = C.xmlXPathNewValueTree(nil)
return
}
ret = C.xmlXPathNewValueTree(nil)
for _, node := range n {
C.xmlXPathNodeSetAdd(ret.nodesetval, (*C.xmlNode)(node.NodePtr()))
}
//this hack-ish looking line tells libxml2 not to free the RVT
//if we don't do this we get horrible double-free crashes everywhere
ret.boolval = 0
return
}
|
go
|
func (n Nodeset) ToXPathValueTree() (ret C.xmlXPathObjectPtr) {
if len(n) == 0 {
ret = C.xmlXPathNewValueTree(nil)
return
}
ret = C.xmlXPathNewValueTree(nil)
for _, node := range n {
C.xmlXPathNodeSetAdd(ret.nodesetval, (*C.xmlNode)(node.NodePtr()))
}
//this hack-ish looking line tells libxml2 not to free the RVT
//if we don't do this we get horrible double-free crashes everywhere
ret.boolval = 0
return
}
|
[
"func",
"(",
"n",
"Nodeset",
")",
"ToXPathValueTree",
"(",
")",
"(",
"ret",
"C",
".",
"xmlXPathObjectPtr",
")",
"{",
"if",
"len",
"(",
"n",
")",
"==",
"0",
"{",
"ret",
"=",
"C",
".",
"xmlXPathNewValueTree",
"(",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"ret",
"=",
"C",
".",
"xmlXPathNewValueTree",
"(",
"nil",
")",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"n",
"{",
"C",
".",
"xmlXPathNodeSetAdd",
"(",
"ret",
".",
"nodesetval",
",",
"(",
"*",
"C",
".",
"xmlNode",
")",
"(",
"node",
".",
"NodePtr",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"//this hack-ish looking line tells libxml2 not to free the RVT",
"//if we don't do this we get horrible double-free crashes everywhere",
"ret",
".",
"boolval",
"=",
"0",
"\n",
"return",
"\n",
"}"
] |
// Produce a C.xmlXPathObjectPtr marked as a ResultValueTree, suitable for passing to libxml2
|
[
"Produce",
"a",
"C",
".",
"xmlXPathObjectPtr",
"marked",
"as",
"a",
"ResultValueTree",
"suitable",
"for",
"passing",
"to",
"libxml2"
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/nodeset.go#L34-L48
|
13,518
|
moovweb/gokogiri
|
xpath/util.go
|
ValueToXPathObject
|
func ValueToXPathObject(val interface{}) (ret C.xmlXPathObjectPtr) {
if val == nil {
//return the empty node set
ret = C.xmlXPathNewNodeSet(nil)
return
}
switch v := val.(type) {
case unsafe.Pointer:
return (C.xmlXPathObjectPtr)(v)
case []unsafe.Pointer:
ptrs := v
if len(ptrs) > 0 {
//default - return a node set
ret = C.xmlXPathNewNodeSet(nil)
for _, p := range ptrs {
C.xmlXPathNodeSetAdd(ret.nodesetval, (*C.xmlNode)(p))
}
} else {
ret = C.xmlXPathNewNodeSet(nil)
return
}
case float64:
ret = C.xmlXPathNewFloat(C.double(v))
case string:
xpathBytes := GetCString([]byte(v))
xpathPtr := unsafe.Pointer(&xpathBytes[0])
ret = C.xmlXPathNewString((*C.xmlChar)(xpathPtr))
default:
typ := reflect.TypeOf(val)
// if a pointer to a struct is passed, get the type of the dereferenced object
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
//log the unknown type, return an empty node set
//fmt.Println("go-resolve wrong-type", typ.Kind())
ret = C.xmlXPathNewNodeSet(nil)
}
return
}
|
go
|
func ValueToXPathObject(val interface{}) (ret C.xmlXPathObjectPtr) {
if val == nil {
//return the empty node set
ret = C.xmlXPathNewNodeSet(nil)
return
}
switch v := val.(type) {
case unsafe.Pointer:
return (C.xmlXPathObjectPtr)(v)
case []unsafe.Pointer:
ptrs := v
if len(ptrs) > 0 {
//default - return a node set
ret = C.xmlXPathNewNodeSet(nil)
for _, p := range ptrs {
C.xmlXPathNodeSetAdd(ret.nodesetval, (*C.xmlNode)(p))
}
} else {
ret = C.xmlXPathNewNodeSet(nil)
return
}
case float64:
ret = C.xmlXPathNewFloat(C.double(v))
case string:
xpathBytes := GetCString([]byte(v))
xpathPtr := unsafe.Pointer(&xpathBytes[0])
ret = C.xmlXPathNewString((*C.xmlChar)(xpathPtr))
default:
typ := reflect.TypeOf(val)
// if a pointer to a struct is passed, get the type of the dereferenced object
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
//log the unknown type, return an empty node set
//fmt.Println("go-resolve wrong-type", typ.Kind())
ret = C.xmlXPathNewNodeSet(nil)
}
return
}
|
[
"func",
"ValueToXPathObject",
"(",
"val",
"interface",
"{",
"}",
")",
"(",
"ret",
"C",
".",
"xmlXPathObjectPtr",
")",
"{",
"if",
"val",
"==",
"nil",
"{",
"//return the empty node set",
"ret",
"=",
"C",
".",
"xmlXPathNewNodeSet",
"(",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"switch",
"v",
":=",
"val",
".",
"(",
"type",
")",
"{",
"case",
"unsafe",
".",
"Pointer",
":",
"return",
"(",
"C",
".",
"xmlXPathObjectPtr",
")",
"(",
"v",
")",
"\n",
"case",
"[",
"]",
"unsafe",
".",
"Pointer",
":",
"ptrs",
":=",
"v",
"\n",
"if",
"len",
"(",
"ptrs",
")",
">",
"0",
"{",
"//default - return a node set",
"ret",
"=",
"C",
".",
"xmlXPathNewNodeSet",
"(",
"nil",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"ptrs",
"{",
"C",
".",
"xmlXPathNodeSetAdd",
"(",
"ret",
".",
"nodesetval",
",",
"(",
"*",
"C",
".",
"xmlNode",
")",
"(",
"p",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"ret",
"=",
"C",
".",
"xmlXPathNewNodeSet",
"(",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n",
"case",
"float64",
":",
"ret",
"=",
"C",
".",
"xmlXPathNewFloat",
"(",
"C",
".",
"double",
"(",
"v",
")",
")",
"\n",
"case",
"string",
":",
"xpathBytes",
":=",
"GetCString",
"(",
"[",
"]",
"byte",
"(",
"v",
")",
")",
"\n",
"xpathPtr",
":=",
"unsafe",
".",
"Pointer",
"(",
"&",
"xpathBytes",
"[",
"0",
"]",
")",
"\n",
"ret",
"=",
"C",
".",
"xmlXPathNewString",
"(",
"(",
"*",
"C",
".",
"xmlChar",
")",
"(",
"xpathPtr",
")",
")",
"\n",
"default",
":",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"val",
")",
"\n",
"// if a pointer to a struct is passed, get the type of the dereferenced object",
"if",
"typ",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"typ",
"=",
"typ",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"//log the unknown type, return an empty node set",
"//fmt.Println(\"go-resolve wrong-type\", typ.Kind())",
"ret",
"=",
"C",
".",
"xmlXPathNewNodeSet",
"(",
"nil",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Convert an arbitrary value into a C.xmlXPathObjectPtr
// Unrecognised and nil values are converted to empty node sets.
|
[
"Convert",
"an",
"arbitrary",
"value",
"into",
"a",
"C",
".",
"xmlXPathObjectPtr",
"Unrecognised",
"and",
"nil",
"values",
"are",
"converted",
"to",
"empty",
"node",
"sets",
"."
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xpath/util.go#L34-L72
|
13,519
|
moovweb/gokogiri
|
html/document.go
|
NewDocument
|
func NewDocument(p unsafe.Pointer, contentLen int, inEncoding, outEncoding []byte) (doc *HtmlDocument) {
doc = &HtmlDocument{}
doc.XmlDocument = xml.NewDocument(p, contentLen, inEncoding, outEncoding)
doc.Me = doc
node := doc.Node.(*xml.XmlNode)
node.Document = doc
//runtime.SetFinalizer(doc, (*HtmlDocument).Free)
return
}
|
go
|
func NewDocument(p unsafe.Pointer, contentLen int, inEncoding, outEncoding []byte) (doc *HtmlDocument) {
doc = &HtmlDocument{}
doc.XmlDocument = xml.NewDocument(p, contentLen, inEncoding, outEncoding)
doc.Me = doc
node := doc.Node.(*xml.XmlNode)
node.Document = doc
//runtime.SetFinalizer(doc, (*HtmlDocument).Free)
return
}
|
[
"func",
"NewDocument",
"(",
"p",
"unsafe",
".",
"Pointer",
",",
"contentLen",
"int",
",",
"inEncoding",
",",
"outEncoding",
"[",
"]",
"byte",
")",
"(",
"doc",
"*",
"HtmlDocument",
")",
"{",
"doc",
"=",
"&",
"HtmlDocument",
"{",
"}",
"\n",
"doc",
".",
"XmlDocument",
"=",
"xml",
".",
"NewDocument",
"(",
"p",
",",
"contentLen",
",",
"inEncoding",
",",
"outEncoding",
")",
"\n",
"doc",
".",
"Me",
"=",
"doc",
"\n",
"node",
":=",
"doc",
".",
"Node",
".",
"(",
"*",
"xml",
".",
"XmlNode",
")",
"\n",
"node",
".",
"Document",
"=",
"doc",
"\n",
"//runtime.SetFinalizer(doc, (*HtmlDocument).Free)",
"return",
"\n",
"}"
] |
//create a document
|
[
"create",
"a",
"document"
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/html/document.go#L55-L63
|
13,520
|
moovweb/gokogiri
|
html/document.go
|
Parse
|
func Parse(content, inEncoding, url []byte, options xml.ParseOption, outEncoding []byte) (doc *HtmlDocument, err error) {
inEncoding = AppendCStringTerminator(inEncoding)
outEncoding = AppendCStringTerminator(outEncoding)
var docPtr *C.xmlDoc
contentLen := len(content)
if contentLen > 0 {
var contentPtr, urlPtr, encodingPtr unsafe.Pointer
contentPtr = unsafe.Pointer(&content[0])
if len(url) > 0 {
url = AppendCStringTerminator(url)
urlPtr = unsafe.Pointer(&url[0])
}
if len(inEncoding) > 0 {
encodingPtr = unsafe.Pointer(&inEncoding[0])
}
docPtr = C.htmlParse(contentPtr, C.int(contentLen), urlPtr, encodingPtr, C.int(options), nil, 0)
if docPtr == nil {
err = ERR_FAILED_TO_PARSE_HTML
} else {
doc = NewDocument(unsafe.Pointer(docPtr), contentLen, inEncoding, outEncoding)
}
}
if docPtr == nil {
doc = CreateEmptyDocument(inEncoding, outEncoding)
}
return
}
|
go
|
func Parse(content, inEncoding, url []byte, options xml.ParseOption, outEncoding []byte) (doc *HtmlDocument, err error) {
inEncoding = AppendCStringTerminator(inEncoding)
outEncoding = AppendCStringTerminator(outEncoding)
var docPtr *C.xmlDoc
contentLen := len(content)
if contentLen > 0 {
var contentPtr, urlPtr, encodingPtr unsafe.Pointer
contentPtr = unsafe.Pointer(&content[0])
if len(url) > 0 {
url = AppendCStringTerminator(url)
urlPtr = unsafe.Pointer(&url[0])
}
if len(inEncoding) > 0 {
encodingPtr = unsafe.Pointer(&inEncoding[0])
}
docPtr = C.htmlParse(contentPtr, C.int(contentLen), urlPtr, encodingPtr, C.int(options), nil, 0)
if docPtr == nil {
err = ERR_FAILED_TO_PARSE_HTML
} else {
doc = NewDocument(unsafe.Pointer(docPtr), contentLen, inEncoding, outEncoding)
}
}
if docPtr == nil {
doc = CreateEmptyDocument(inEncoding, outEncoding)
}
return
}
|
[
"func",
"Parse",
"(",
"content",
",",
"inEncoding",
",",
"url",
"[",
"]",
"byte",
",",
"options",
"xml",
".",
"ParseOption",
",",
"outEncoding",
"[",
"]",
"byte",
")",
"(",
"doc",
"*",
"HtmlDocument",
",",
"err",
"error",
")",
"{",
"inEncoding",
"=",
"AppendCStringTerminator",
"(",
"inEncoding",
")",
"\n",
"outEncoding",
"=",
"AppendCStringTerminator",
"(",
"outEncoding",
")",
"\n\n",
"var",
"docPtr",
"*",
"C",
".",
"xmlDoc",
"\n",
"contentLen",
":=",
"len",
"(",
"content",
")",
"\n\n",
"if",
"contentLen",
">",
"0",
"{",
"var",
"contentPtr",
",",
"urlPtr",
",",
"encodingPtr",
"unsafe",
".",
"Pointer",
"\n\n",
"contentPtr",
"=",
"unsafe",
".",
"Pointer",
"(",
"&",
"content",
"[",
"0",
"]",
")",
"\n",
"if",
"len",
"(",
"url",
")",
">",
"0",
"{",
"url",
"=",
"AppendCStringTerminator",
"(",
"url",
")",
"\n",
"urlPtr",
"=",
"unsafe",
".",
"Pointer",
"(",
"&",
"url",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"inEncoding",
")",
">",
"0",
"{",
"encodingPtr",
"=",
"unsafe",
".",
"Pointer",
"(",
"&",
"inEncoding",
"[",
"0",
"]",
")",
"\n",
"}",
"\n\n",
"docPtr",
"=",
"C",
".",
"htmlParse",
"(",
"contentPtr",
",",
"C",
".",
"int",
"(",
"contentLen",
")",
",",
"urlPtr",
",",
"encodingPtr",
",",
"C",
".",
"int",
"(",
"options",
")",
",",
"nil",
",",
"0",
")",
"\n\n",
"if",
"docPtr",
"==",
"nil",
"{",
"err",
"=",
"ERR_FAILED_TO_PARSE_HTML",
"\n",
"}",
"else",
"{",
"doc",
"=",
"NewDocument",
"(",
"unsafe",
".",
"Pointer",
"(",
"docPtr",
")",
",",
"contentLen",
",",
"inEncoding",
",",
"outEncoding",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"docPtr",
"==",
"nil",
"{",
"doc",
"=",
"CreateEmptyDocument",
"(",
"inEncoding",
",",
"outEncoding",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
//parse a string to document
|
[
"parse",
"a",
"string",
"to",
"document"
] |
a1a828153468a7518b184e698f6265904108d957
|
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/html/document.go#L66-L97
|
13,521
|
tcnksm/ghr
|
local.go
|
LocalAssets
|
func LocalAssets(path string) ([]string, error) {
path, err := filepath.Abs(path)
if err != nil {
return nil, errors.Wrap(err, "failed to get abs path")
}
fi, err := os.Stat(path)
if err != nil {
return nil, errors.Wrap(err, "failed to get file stat")
}
if !fi.IsDir() {
return []string{path}, nil
}
// Glob all files in the given path
files, err := filepath.Glob(filepath.Join(path, "*"))
if err != nil {
return nil, errors.Wrap(err, "failed to glob files")
}
if len(files) == 0 {
return nil, errors.New("no local assets are found")
}
assets := make([]string, 0, len(files))
for _, f := range files {
// Exclude directory.
if fi, _ := os.Stat(f); fi.IsDir() {
continue
}
assets = append(assets, f)
}
return assets, nil
}
|
go
|
func LocalAssets(path string) ([]string, error) {
path, err := filepath.Abs(path)
if err != nil {
return nil, errors.Wrap(err, "failed to get abs path")
}
fi, err := os.Stat(path)
if err != nil {
return nil, errors.Wrap(err, "failed to get file stat")
}
if !fi.IsDir() {
return []string{path}, nil
}
// Glob all files in the given path
files, err := filepath.Glob(filepath.Join(path, "*"))
if err != nil {
return nil, errors.Wrap(err, "failed to glob files")
}
if len(files) == 0 {
return nil, errors.New("no local assets are found")
}
assets := make([]string, 0, len(files))
for _, f := range files {
// Exclude directory.
if fi, _ := os.Stat(f); fi.IsDir() {
continue
}
assets = append(assets, f)
}
return assets, nil
}
|
[
"func",
"LocalAssets",
"(",
"path",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"path",
",",
"err",
":=",
"filepath",
".",
"Abs",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"fi",
".",
"IsDir",
"(",
")",
"{",
"return",
"[",
"]",
"string",
"{",
"path",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"// Glob all files in the given path",
"files",
",",
"err",
":=",
"filepath",
".",
"Glob",
"(",
"filepath",
".",
"Join",
"(",
"path",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"files",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"assets",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"files",
")",
")",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"// Exclude directory.",
"if",
"fi",
",",
"_",
":=",
"os",
".",
"Stat",
"(",
"f",
")",
";",
"fi",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"assets",
"=",
"append",
"(",
"assets",
",",
"f",
")",
"\n",
"}",
"\n\n",
"return",
"assets",
",",
"nil",
"\n",
"}"
] |
// LocalAssets contains the local objects to be uploaded
|
[
"LocalAssets",
"contains",
"the",
"local",
"objects",
"to",
"be",
"uploaded"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/local.go#L11-L48
|
13,522
|
tcnksm/ghr
|
cli.go
|
Debugf
|
func Debugf(format string, args ...interface{}) {
if env := os.Getenv(EnvDebug); len(env) != 0 {
log.Printf("[DEBUG] "+format+"\n", args...)
}
}
|
go
|
func Debugf(format string, args ...interface{}) {
if env := os.Getenv(EnvDebug); len(env) != 0 {
log.Printf("[DEBUG] "+format+"\n", args...)
}
}
|
[
"func",
"Debugf",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"env",
":=",
"os",
".",
"Getenv",
"(",
"EnvDebug",
")",
";",
"len",
"(",
"env",
")",
"!=",
"0",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
"+",
"format",
"+",
"\"",
"\\n",
"\"",
",",
"args",
"...",
")",
"\n",
"}",
"\n",
"}"
] |
// Debugf prints debug output when EnvDebug is set
|
[
"Debugf",
"prints",
"debug",
"output",
"when",
"EnvDebug",
"is",
"set"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/cli.go#L55-L59
|
13,523
|
tcnksm/ghr
|
cli.go
|
PrintRedf
|
func PrintRedf(w io.Writer, format string, args ...interface{}) {
format = fmt.Sprintf("[red]%s[reset]", format)
fmt.Fprint(w,
colorstring.Color(fmt.Sprintf(format, args...)))
}
|
go
|
func PrintRedf(w io.Writer, format string, args ...interface{}) {
format = fmt.Sprintf("[red]%s[reset]", format)
fmt.Fprint(w,
colorstring.Color(fmt.Sprintf(format, args...)))
}
|
[
"func",
"PrintRedf",
"(",
"w",
"io",
".",
"Writer",
",",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"format",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"format",
")",
"\n",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"colorstring",
".",
"Color",
"(",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
")",
")",
"\n",
"}"
] |
// PrintRedf prints red error message to console.
|
[
"PrintRedf",
"prints",
"red",
"error",
"message",
"to",
"console",
"."
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/cli.go#L62-L66
|
13,524
|
tcnksm/ghr
|
github.go
|
NewGitHubClient
|
func NewGitHubClient(owner, repo, token, urlStr string) (GitHub, error) {
if len(owner) == 0 {
return nil, errors.New("missing GitHub repository owner")
}
if len(repo) == 0 {
return nil, errors.New("missing GitHub repository name")
}
if len(token) == 0 {
return nil, errors.New("missing GitHub API token")
}
if len(urlStr) == 0 {
return nil, errors.New("missing GitHub API URL")
}
baseURL, err := url.ParseRequestURI(urlStr)
if err != nil {
return nil, errors.Wrap(err, "failed to parse Github API URL")
}
ts := oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: token,
})
tc := oauth2.NewClient(context.TODO(), ts)
client := github.NewClient(tc)
client.BaseURL = baseURL
return &GitHubClient{
Owner: owner,
Repo: repo,
Client: client,
}, nil
}
|
go
|
func NewGitHubClient(owner, repo, token, urlStr string) (GitHub, error) {
if len(owner) == 0 {
return nil, errors.New("missing GitHub repository owner")
}
if len(repo) == 0 {
return nil, errors.New("missing GitHub repository name")
}
if len(token) == 0 {
return nil, errors.New("missing GitHub API token")
}
if len(urlStr) == 0 {
return nil, errors.New("missing GitHub API URL")
}
baseURL, err := url.ParseRequestURI(urlStr)
if err != nil {
return nil, errors.Wrap(err, "failed to parse Github API URL")
}
ts := oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: token,
})
tc := oauth2.NewClient(context.TODO(), ts)
client := github.NewClient(tc)
client.BaseURL = baseURL
return &GitHubClient{
Owner: owner,
Repo: repo,
Client: client,
}, nil
}
|
[
"func",
"NewGitHubClient",
"(",
"owner",
",",
"repo",
",",
"token",
",",
"urlStr",
"string",
")",
"(",
"GitHub",
",",
"error",
")",
"{",
"if",
"len",
"(",
"owner",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"repo",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"token",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"urlStr",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"baseURL",
",",
"err",
":=",
"url",
".",
"ParseRequestURI",
"(",
"urlStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"ts",
":=",
"oauth2",
".",
"StaticTokenSource",
"(",
"&",
"oauth2",
".",
"Token",
"{",
"AccessToken",
":",
"token",
",",
"}",
")",
"\n",
"tc",
":=",
"oauth2",
".",
"NewClient",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"ts",
")",
"\n\n",
"client",
":=",
"github",
".",
"NewClient",
"(",
"tc",
")",
"\n",
"client",
".",
"BaseURL",
"=",
"baseURL",
"\n\n",
"return",
"&",
"GitHubClient",
"{",
"Owner",
":",
"owner",
",",
"Repo",
":",
"repo",
",",
"Client",
":",
"client",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewGitHubClient creates and initializes a new GitHubClient
|
[
"NewGitHubClient",
"creates",
"and",
"initializes",
"a",
"new",
"GitHubClient"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/github.go#L47-L82
|
13,525
|
tcnksm/ghr
|
github.go
|
SetUploadURL
|
func (c *GitHubClient) SetUploadURL(urlStr string) error {
i := strings.Index(urlStr, "repos/")
parsedURL, err := url.ParseRequestURI(urlStr[:i])
if err != nil {
return errors.Wrap(err, "failed to parse upload URL")
}
c.UploadURL = parsedURL
return nil
}
|
go
|
func (c *GitHubClient) SetUploadURL(urlStr string) error {
i := strings.Index(urlStr, "repos/")
parsedURL, err := url.ParseRequestURI(urlStr[:i])
if err != nil {
return errors.Wrap(err, "failed to parse upload URL")
}
c.UploadURL = parsedURL
return nil
}
|
[
"func",
"(",
"c",
"*",
"GitHubClient",
")",
"SetUploadURL",
"(",
"urlStr",
"string",
")",
"error",
"{",
"i",
":=",
"strings",
".",
"Index",
"(",
"urlStr",
",",
"\"",
"\"",
")",
"\n",
"parsedURL",
",",
"err",
":=",
"url",
".",
"ParseRequestURI",
"(",
"urlStr",
"[",
":",
"i",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"c",
".",
"UploadURL",
"=",
"parsedURL",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SetUploadURL constructs the upload URL for a release
|
[
"SetUploadURL",
"constructs",
"the",
"upload",
"URL",
"for",
"a",
"release"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/github.go#L85-L94
|
13,526
|
tcnksm/ghr
|
github.go
|
CreateRelease
|
func (c *GitHubClient) CreateRelease(ctx context.Context, req *github.RepositoryRelease) (*github.RepositoryRelease, error) {
release, res, err := c.Repositories.CreateRelease(context.TODO(), c.Owner, c.Repo, req)
if err != nil {
return nil, errors.Wrap(err, "failed to create a release")
}
if res.StatusCode != http.StatusCreated {
return nil, errors.Errorf("create release: invalid status: %s", res.Status)
}
return release, nil
}
|
go
|
func (c *GitHubClient) CreateRelease(ctx context.Context, req *github.RepositoryRelease) (*github.RepositoryRelease, error) {
release, res, err := c.Repositories.CreateRelease(context.TODO(), c.Owner, c.Repo, req)
if err != nil {
return nil, errors.Wrap(err, "failed to create a release")
}
if res.StatusCode != http.StatusCreated {
return nil, errors.Errorf("create release: invalid status: %s", res.Status)
}
return release, nil
}
|
[
"func",
"(",
"c",
"*",
"GitHubClient",
")",
"CreateRelease",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"github",
".",
"RepositoryRelease",
")",
"(",
"*",
"github",
".",
"RepositoryRelease",
",",
"error",
")",
"{",
"release",
",",
"res",
",",
"err",
":=",
"c",
".",
"Repositories",
".",
"CreateRelease",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"c",
".",
"Owner",
",",
"c",
".",
"Repo",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"res",
".",
"StatusCode",
"!=",
"http",
".",
"StatusCreated",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"res",
".",
"Status",
")",
"\n",
"}",
"\n\n",
"return",
"release",
",",
"nil",
"\n",
"}"
] |
// CreateRelease creates a new release object in the GitHub API
|
[
"CreateRelease",
"creates",
"a",
"new",
"release",
"object",
"in",
"the",
"GitHub",
"API"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/github.go#L97-L109
|
13,527
|
tcnksm/ghr
|
github.go
|
GetRelease
|
func (c *GitHubClient) GetRelease(ctx context.Context, tag string) (*github.RepositoryRelease, error) {
// Check Release whether already exists or not
release, res, err := c.Repositories.GetReleaseByTag(context.TODO(), c.Owner, c.Repo, tag)
if err != nil {
if res == nil {
return nil, errors.Wrapf(err, "failed to get release tag: %s", tag)
}
// TODO(tcnksm): Handle invalid token
if res.StatusCode != http.StatusNotFound {
return nil, errors.Wrapf(err,
"get release tag: invalid status: %s", res.Status)
}
return nil, ErrReleaseNotFound
}
return release, nil
}
|
go
|
func (c *GitHubClient) GetRelease(ctx context.Context, tag string) (*github.RepositoryRelease, error) {
// Check Release whether already exists or not
release, res, err := c.Repositories.GetReleaseByTag(context.TODO(), c.Owner, c.Repo, tag)
if err != nil {
if res == nil {
return nil, errors.Wrapf(err, "failed to get release tag: %s", tag)
}
// TODO(tcnksm): Handle invalid token
if res.StatusCode != http.StatusNotFound {
return nil, errors.Wrapf(err,
"get release tag: invalid status: %s", res.Status)
}
return nil, ErrReleaseNotFound
}
return release, nil
}
|
[
"func",
"(",
"c",
"*",
"GitHubClient",
")",
"GetRelease",
"(",
"ctx",
"context",
".",
"Context",
",",
"tag",
"string",
")",
"(",
"*",
"github",
".",
"RepositoryRelease",
",",
"error",
")",
"{",
"// Check Release whether already exists or not",
"release",
",",
"res",
",",
"err",
":=",
"c",
".",
"Repositories",
".",
"GetReleaseByTag",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"c",
".",
"Owner",
",",
"c",
".",
"Repo",
",",
"tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"res",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"tag",
")",
"\n",
"}",
"\n\n",
"// TODO(tcnksm): Handle invalid token",
"if",
"res",
".",
"StatusCode",
"!=",
"http",
".",
"StatusNotFound",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"res",
".",
"Status",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"ErrReleaseNotFound",
"\n",
"}",
"\n\n",
"return",
"release",
",",
"nil",
"\n",
"}"
] |
// GetRelease queries the GitHub API for a specified release object
|
[
"GetRelease",
"queries",
"the",
"GitHub",
"API",
"for",
"a",
"specified",
"release",
"object"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/github.go#L112-L130
|
13,528
|
tcnksm/ghr
|
github.go
|
EditRelease
|
func (c *GitHubClient) EditRelease(ctx context.Context, releaseID int64, req *github.RepositoryRelease) (*github.RepositoryRelease, error) {
var release *github.RepositoryRelease
err := retry.Retry(3, 3*time.Second, func() error {
var (
res *github.Response
err error
)
release, res, err = c.Repositories.EditRelease(context.TODO(), c.Owner, c.Repo, releaseID, req)
if err != nil {
return errors.Wrapf(err, "failed to edit release: %d", releaseID)
}
if res.StatusCode != http.StatusOK {
return errors.Errorf("edit release: invalid status: %s", res.Status)
}
return nil
})
return release, err
}
|
go
|
func (c *GitHubClient) EditRelease(ctx context.Context, releaseID int64, req *github.RepositoryRelease) (*github.RepositoryRelease, error) {
var release *github.RepositoryRelease
err := retry.Retry(3, 3*time.Second, func() error {
var (
res *github.Response
err error
)
release, res, err = c.Repositories.EditRelease(context.TODO(), c.Owner, c.Repo, releaseID, req)
if err != nil {
return errors.Wrapf(err, "failed to edit release: %d", releaseID)
}
if res.StatusCode != http.StatusOK {
return errors.Errorf("edit release: invalid status: %s", res.Status)
}
return nil
})
return release, err
}
|
[
"func",
"(",
"c",
"*",
"GitHubClient",
")",
"EditRelease",
"(",
"ctx",
"context",
".",
"Context",
",",
"releaseID",
"int64",
",",
"req",
"*",
"github",
".",
"RepositoryRelease",
")",
"(",
"*",
"github",
".",
"RepositoryRelease",
",",
"error",
")",
"{",
"var",
"release",
"*",
"github",
".",
"RepositoryRelease",
"\n\n",
"err",
":=",
"retry",
".",
"Retry",
"(",
"3",
",",
"3",
"*",
"time",
".",
"Second",
",",
"func",
"(",
")",
"error",
"{",
"var",
"(",
"res",
"*",
"github",
".",
"Response",
"\n",
"err",
"error",
"\n",
")",
"\n",
"release",
",",
"res",
",",
"err",
"=",
"c",
".",
"Repositories",
".",
"EditRelease",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"c",
".",
"Owner",
",",
"c",
".",
"Repo",
",",
"releaseID",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"releaseID",
")",
"\n",
"}",
"\n\n",
"if",
"res",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"res",
".",
"Status",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"release",
",",
"err",
"\n",
"}"
] |
// EditRelease edit a release object within the GitHub API
|
[
"EditRelease",
"edit",
"a",
"release",
"object",
"within",
"the",
"GitHub",
"API"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/github.go#L133-L152
|
13,529
|
tcnksm/ghr
|
github.go
|
DeleteRelease
|
func (c *GitHubClient) DeleteRelease(ctx context.Context, releaseID int64) error {
res, err := c.Repositories.DeleteRelease(context.TODO(), c.Owner, c.Repo, releaseID)
if err != nil {
return errors.Wrap(err, "failed to delete release")
}
if res.StatusCode != http.StatusNoContent {
return errors.Errorf("delete release: invalid status: %s", res.Status)
}
return nil
}
|
go
|
func (c *GitHubClient) DeleteRelease(ctx context.Context, releaseID int64) error {
res, err := c.Repositories.DeleteRelease(context.TODO(), c.Owner, c.Repo, releaseID)
if err != nil {
return errors.Wrap(err, "failed to delete release")
}
if res.StatusCode != http.StatusNoContent {
return errors.Errorf("delete release: invalid status: %s", res.Status)
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"GitHubClient",
")",
"DeleteRelease",
"(",
"ctx",
"context",
".",
"Context",
",",
"releaseID",
"int64",
")",
"error",
"{",
"res",
",",
"err",
":=",
"c",
".",
"Repositories",
".",
"DeleteRelease",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"c",
".",
"Owner",
",",
"c",
".",
"Repo",
",",
"releaseID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"res",
".",
"StatusCode",
"!=",
"http",
".",
"StatusNoContent",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"res",
".",
"Status",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteRelease deletes a release object within the GitHub API
|
[
"DeleteRelease",
"deletes",
"a",
"release",
"object",
"within",
"the",
"GitHub",
"API"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/github.go#L155-L166
|
13,530
|
tcnksm/ghr
|
github.go
|
DeleteTag
|
func (c *GitHubClient) DeleteTag(ctx context.Context, tag string) error {
ref := fmt.Sprintf("tags/%s", tag)
res, err := c.Git.DeleteRef(context.TODO(), c.Owner, c.Repo, ref)
if err != nil {
return errors.Wrapf(err, "failed to delete tag: %s", ref)
}
if res.StatusCode != http.StatusNoContent {
return errors.Errorf("delete tag: invalid status: %s", res.Status)
}
return nil
}
|
go
|
func (c *GitHubClient) DeleteTag(ctx context.Context, tag string) error {
ref := fmt.Sprintf("tags/%s", tag)
res, err := c.Git.DeleteRef(context.TODO(), c.Owner, c.Repo, ref)
if err != nil {
return errors.Wrapf(err, "failed to delete tag: %s", ref)
}
if res.StatusCode != http.StatusNoContent {
return errors.Errorf("delete tag: invalid status: %s", res.Status)
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"GitHubClient",
")",
"DeleteTag",
"(",
"ctx",
"context",
".",
"Context",
",",
"tag",
"string",
")",
"error",
"{",
"ref",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"tag",
")",
"\n",
"res",
",",
"err",
":=",
"c",
".",
"Git",
".",
"DeleteRef",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"c",
".",
"Owner",
",",
"c",
".",
"Repo",
",",
"ref",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"ref",
")",
"\n",
"}",
"\n\n",
"if",
"res",
".",
"StatusCode",
"!=",
"http",
".",
"StatusNoContent",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"res",
".",
"Status",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteTag deletes a tag from the GitHub API
|
[
"DeleteTag",
"deletes",
"a",
"tag",
"from",
"the",
"GitHub",
"API"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/github.go#L169-L181
|
13,531
|
tcnksm/ghr
|
github.go
|
UploadAsset
|
func (c *GitHubClient) UploadAsset(ctx context.Context, releaseID int64, filename string) (*github.ReleaseAsset, error) {
filename, err := filepath.Abs(filename)
if err != nil {
return nil, errors.Wrap(err, "failed to get abs path")
}
opts := &github.UploadOptions{
// Use base name by default
Name: filepath.Base(filename),
}
var asset *github.ReleaseAsset
err = retry.Retry(3, 3*time.Second, func() error {
var (
res *github.Response
err error
)
f, err := os.Open(filename)
if err != nil {
return errors.Wrap(err, "failed to open file")
}
defer f.Close()
asset, res, err = c.Repositories.UploadReleaseAsset(context.TODO(), c.Owner, c.Repo, releaseID, opts, f)
if err != nil {
return errors.Wrapf(err, "failed to upload release asset: %s", filename)
}
switch res.StatusCode {
case http.StatusCreated:
return nil
case 422:
return errors.Errorf(
"upload release asset: invalid status code: %s",
"422 (this is probably because the asset already uploaded)")
default:
return errors.Errorf(
"upload release asset: invalid status code: %s", res.Status)
}
})
return asset, err
}
|
go
|
func (c *GitHubClient) UploadAsset(ctx context.Context, releaseID int64, filename string) (*github.ReleaseAsset, error) {
filename, err := filepath.Abs(filename)
if err != nil {
return nil, errors.Wrap(err, "failed to get abs path")
}
opts := &github.UploadOptions{
// Use base name by default
Name: filepath.Base(filename),
}
var asset *github.ReleaseAsset
err = retry.Retry(3, 3*time.Second, func() error {
var (
res *github.Response
err error
)
f, err := os.Open(filename)
if err != nil {
return errors.Wrap(err, "failed to open file")
}
defer f.Close()
asset, res, err = c.Repositories.UploadReleaseAsset(context.TODO(), c.Owner, c.Repo, releaseID, opts, f)
if err != nil {
return errors.Wrapf(err, "failed to upload release asset: %s", filename)
}
switch res.StatusCode {
case http.StatusCreated:
return nil
case 422:
return errors.Errorf(
"upload release asset: invalid status code: %s",
"422 (this is probably because the asset already uploaded)")
default:
return errors.Errorf(
"upload release asset: invalid status code: %s", res.Status)
}
})
return asset, err
}
|
[
"func",
"(",
"c",
"*",
"GitHubClient",
")",
"UploadAsset",
"(",
"ctx",
"context",
".",
"Context",
",",
"releaseID",
"int64",
",",
"filename",
"string",
")",
"(",
"*",
"github",
".",
"ReleaseAsset",
",",
"error",
")",
"{",
"filename",
",",
"err",
":=",
"filepath",
".",
"Abs",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"opts",
":=",
"&",
"github",
".",
"UploadOptions",
"{",
"// Use base name by default",
"Name",
":",
"filepath",
".",
"Base",
"(",
"filename",
")",
",",
"}",
"\n\n",
"var",
"asset",
"*",
"github",
".",
"ReleaseAsset",
"\n",
"err",
"=",
"retry",
".",
"Retry",
"(",
"3",
",",
"3",
"*",
"time",
".",
"Second",
",",
"func",
"(",
")",
"error",
"{",
"var",
"(",
"res",
"*",
"github",
".",
"Response",
"\n",
"err",
"error",
"\n",
")",
"\n\n",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"asset",
",",
"res",
",",
"err",
"=",
"c",
".",
"Repositories",
".",
"UploadReleaseAsset",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"c",
".",
"Owner",
",",
"c",
".",
"Repo",
",",
"releaseID",
",",
"opts",
",",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"filename",
")",
"\n",
"}",
"\n\n",
"switch",
"res",
".",
"StatusCode",
"{",
"case",
"http",
".",
"StatusCreated",
":",
"return",
"nil",
"\n",
"case",
"422",
":",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"default",
":",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"res",
".",
"Status",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"asset",
",",
"err",
"\n",
"}"
] |
// UploadAsset uploads specified assets to a given release object
|
[
"UploadAsset",
"uploads",
"specified",
"assets",
"to",
"a",
"given",
"release",
"object"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/github.go#L184-L227
|
13,532
|
tcnksm/ghr
|
github.go
|
ListAssets
|
func (c *GitHubClient) ListAssets(ctx context.Context, releaseID int64) ([]*github.ReleaseAsset, error) {
result := []*github.ReleaseAsset{}
page := 1
for {
assets, res, err := c.Repositories.ListReleaseAssets(context.TODO(), c.Owner, c.Repo, releaseID, &github.ListOptions{Page: page})
if err != nil {
return nil, errors.Wrap(err, "failed to list assets")
}
if res.StatusCode != http.StatusOK {
return nil, errors.Errorf("list release assets: invalid status code: %s", res.Status)
}
result = append(result, assets...)
if res.NextPage <= page {
break
}
page = res.NextPage
}
return result, nil
}
|
go
|
func (c *GitHubClient) ListAssets(ctx context.Context, releaseID int64) ([]*github.ReleaseAsset, error) {
result := []*github.ReleaseAsset{}
page := 1
for {
assets, res, err := c.Repositories.ListReleaseAssets(context.TODO(), c.Owner, c.Repo, releaseID, &github.ListOptions{Page: page})
if err != nil {
return nil, errors.Wrap(err, "failed to list assets")
}
if res.StatusCode != http.StatusOK {
return nil, errors.Errorf("list release assets: invalid status code: %s", res.Status)
}
result = append(result, assets...)
if res.NextPage <= page {
break
}
page = res.NextPage
}
return result, nil
}
|
[
"func",
"(",
"c",
"*",
"GitHubClient",
")",
"ListAssets",
"(",
"ctx",
"context",
".",
"Context",
",",
"releaseID",
"int64",
")",
"(",
"[",
"]",
"*",
"github",
".",
"ReleaseAsset",
",",
"error",
")",
"{",
"result",
":=",
"[",
"]",
"*",
"github",
".",
"ReleaseAsset",
"{",
"}",
"\n",
"page",
":=",
"1",
"\n\n",
"for",
"{",
"assets",
",",
"res",
",",
"err",
":=",
"c",
".",
"Repositories",
".",
"ListReleaseAssets",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"c",
".",
"Owner",
",",
"c",
".",
"Repo",
",",
"releaseID",
",",
"&",
"github",
".",
"ListOptions",
"{",
"Page",
":",
"page",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"res",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"res",
".",
"Status",
")",
"\n",
"}",
"\n\n",
"result",
"=",
"append",
"(",
"result",
",",
"assets",
"...",
")",
"\n\n",
"if",
"res",
".",
"NextPage",
"<=",
"page",
"{",
"break",
"\n",
"}",
"\n\n",
"page",
"=",
"res",
".",
"NextPage",
"\n",
"}",
"\n\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// ListAssets lists assets associated with a given release
|
[
"ListAssets",
"lists",
"assets",
"associated",
"with",
"a",
"given",
"release"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/github.go#L244-L268
|
13,533
|
tcnksm/ghr
|
version.go
|
OutputVersion
|
func OutputVersion() string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "%s version v%s", Name, Version)
if len(GitCommit) != 0 {
fmt.Fprintf(&buf, " (%s)", GitCommit)
}
fmt.Fprintf(&buf, "\n")
// Check latest version is release or not.
verCheckCh := make(chan *latest.CheckResponse)
go func() {
githubTag := &latest.GithubTag{
Owner: "tcnksm",
Repository: "ghr",
}
res, err := latest.Check(githubTag, Version)
if err != nil {
// Don't return error
Debugf("[ERROR] Check latest version is failed: %s", err)
return
}
verCheckCh <- res
}()
select {
case <-time.After(defaultCheckTimeout):
case res := <-verCheckCh:
if res.Outdated {
fmt.Fprintf(&buf,
"Latest version of ghr is v%s, please upgrade!\n",
res.Current)
}
}
return buf.String()
}
|
go
|
func OutputVersion() string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "%s version v%s", Name, Version)
if len(GitCommit) != 0 {
fmt.Fprintf(&buf, " (%s)", GitCommit)
}
fmt.Fprintf(&buf, "\n")
// Check latest version is release or not.
verCheckCh := make(chan *latest.CheckResponse)
go func() {
githubTag := &latest.GithubTag{
Owner: "tcnksm",
Repository: "ghr",
}
res, err := latest.Check(githubTag, Version)
if err != nil {
// Don't return error
Debugf("[ERROR] Check latest version is failed: %s", err)
return
}
verCheckCh <- res
}()
select {
case <-time.After(defaultCheckTimeout):
case res := <-verCheckCh:
if res.Outdated {
fmt.Fprintf(&buf,
"Latest version of ghr is v%s, please upgrade!\n",
res.Current)
}
}
return buf.String()
}
|
[
"func",
"OutputVersion",
"(",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"fmt",
".",
"Fprintf",
"(",
"&",
"buf",
",",
"\"",
"\"",
",",
"Name",
",",
"Version",
")",
"\n",
"if",
"len",
"(",
"GitCommit",
")",
"!=",
"0",
"{",
"fmt",
".",
"Fprintf",
"(",
"&",
"buf",
",",
"\"",
"\"",
",",
"GitCommit",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"&",
"buf",
",",
"\"",
"\\n",
"\"",
")",
"\n\n",
"// Check latest version is release or not.",
"verCheckCh",
":=",
"make",
"(",
"chan",
"*",
"latest",
".",
"CheckResponse",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"githubTag",
":=",
"&",
"latest",
".",
"GithubTag",
"{",
"Owner",
":",
"\"",
"\"",
",",
"Repository",
":",
"\"",
"\"",
",",
"}",
"\n\n",
"res",
",",
"err",
":=",
"latest",
".",
"Check",
"(",
"githubTag",
",",
"Version",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Don't return error",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"verCheckCh",
"<-",
"res",
"\n",
"}",
"(",
")",
"\n\n",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"defaultCheckTimeout",
")",
":",
"case",
"res",
":=",
"<-",
"verCheckCh",
":",
"if",
"res",
".",
"Outdated",
"{",
"fmt",
".",
"Fprintf",
"(",
"&",
"buf",
",",
"\"",
"\\n",
"\"",
",",
"res",
".",
"Current",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] |
// OutputVersion checks the current version and compares it against releases
// available on GitHub. If there is a newer version available, it prints an
// update warning.
|
[
"OutputVersion",
"checks",
"the",
"current",
"version",
"and",
"compares",
"it",
"against",
"releases",
"available",
"on",
"GitHub",
".",
"If",
"there",
"is",
"a",
"newer",
"version",
"available",
"it",
"prints",
"an",
"update",
"warning",
"."
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/version.go#L24-L60
|
13,534
|
tcnksm/ghr
|
ghr.go
|
DeleteRelease
|
func (g *GHR) DeleteRelease(ctx context.Context, ID int64, tag string) error {
err := g.GitHub.DeleteRelease(ctx, ID)
if err != nil {
return err
}
err = g.GitHub.DeleteTag(ctx, tag)
if err != nil {
return err
}
// This is because sometimes the process of creating a release on GitHub
// is faster than deleting a tag.
time.Sleep(5 * time.Second)
return nil
}
|
go
|
func (g *GHR) DeleteRelease(ctx context.Context, ID int64, tag string) error {
err := g.GitHub.DeleteRelease(ctx, ID)
if err != nil {
return err
}
err = g.GitHub.DeleteTag(ctx, tag)
if err != nil {
return err
}
// This is because sometimes the process of creating a release on GitHub
// is faster than deleting a tag.
time.Sleep(5 * time.Second)
return nil
}
|
[
"func",
"(",
"g",
"*",
"GHR",
")",
"DeleteRelease",
"(",
"ctx",
"context",
".",
"Context",
",",
"ID",
"int64",
",",
"tag",
"string",
")",
"error",
"{",
"err",
":=",
"g",
".",
"GitHub",
".",
"DeleteRelease",
"(",
"ctx",
",",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"g",
".",
"GitHub",
".",
"DeleteTag",
"(",
"ctx",
",",
"tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// This is because sometimes the process of creating a release on GitHub",
"// is faster than deleting a tag.",
"time",
".",
"Sleep",
"(",
"5",
"*",
"time",
".",
"Second",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteRelease removes an existing release, if it exists. If it does not exist,
// DeleteRelease returns an error
|
[
"DeleteRelease",
"removes",
"an",
"existing",
"release",
"if",
"it",
"exists",
".",
"If",
"it",
"does",
"not",
"exist",
"DeleteRelease",
"returns",
"an",
"error"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/ghr.go#L79-L96
|
13,535
|
tcnksm/ghr
|
ghr.go
|
DeleteAssets
|
func (g *GHR) DeleteAssets(ctx context.Context, releaseID int64, localAssets []string, parallel int) error {
start := time.Now()
defer func() {
Debugf("DeleteAssets: time: %d ms", int(time.Since(start).Seconds()*1000))
}()
eg, ctx := errgroup.WithContext(ctx)
assets, err := g.GitHub.ListAssets(ctx, releaseID)
if err != nil {
return errors.Wrap(err, "failed to list assets")
}
semaphore := make(chan struct{}, parallel)
for _, localAsset := range localAssets {
for _, asset := range assets {
// https://golang.org/doc/faq#closures_and_goroutines
localAsset, asset := localAsset, asset
// Uploaded asset name is same as basename of local file
if *asset.Name == filepath.Base(localAsset) {
eg.Go(func() error {
semaphore <- struct{}{}
defer func() {
<-semaphore
}()
fmt.Fprintf(g.outStream, "--> Deleting: %15s\n", *asset.Name)
if err := g.GitHub.DeleteAsset(ctx, *asset.ID); err != nil {
return errors.Wrapf(err,
"failed to delete asset: %s", *asset.Name)
}
return nil
})
}
}
}
if err := eg.Wait(); err != nil {
return errors.Wrap(err, "one of the goroutines failed")
}
return nil
}
|
go
|
func (g *GHR) DeleteAssets(ctx context.Context, releaseID int64, localAssets []string, parallel int) error {
start := time.Now()
defer func() {
Debugf("DeleteAssets: time: %d ms", int(time.Since(start).Seconds()*1000))
}()
eg, ctx := errgroup.WithContext(ctx)
assets, err := g.GitHub.ListAssets(ctx, releaseID)
if err != nil {
return errors.Wrap(err, "failed to list assets")
}
semaphore := make(chan struct{}, parallel)
for _, localAsset := range localAssets {
for _, asset := range assets {
// https://golang.org/doc/faq#closures_and_goroutines
localAsset, asset := localAsset, asset
// Uploaded asset name is same as basename of local file
if *asset.Name == filepath.Base(localAsset) {
eg.Go(func() error {
semaphore <- struct{}{}
defer func() {
<-semaphore
}()
fmt.Fprintf(g.outStream, "--> Deleting: %15s\n", *asset.Name)
if err := g.GitHub.DeleteAsset(ctx, *asset.ID); err != nil {
return errors.Wrapf(err,
"failed to delete asset: %s", *asset.Name)
}
return nil
})
}
}
}
if err := eg.Wait(); err != nil {
return errors.Wrap(err, "one of the goroutines failed")
}
return nil
}
|
[
"func",
"(",
"g",
"*",
"GHR",
")",
"DeleteAssets",
"(",
"ctx",
"context",
".",
"Context",
",",
"releaseID",
"int64",
",",
"localAssets",
"[",
"]",
"string",
",",
"parallel",
"int",
")",
"error",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"Debugf",
"(",
"\"",
"\"",
",",
"int",
"(",
"time",
".",
"Since",
"(",
"start",
")",
".",
"Seconds",
"(",
")",
"*",
"1000",
")",
")",
"\n",
"}",
"(",
")",
"\n\n",
"eg",
",",
"ctx",
":=",
"errgroup",
".",
"WithContext",
"(",
"ctx",
")",
"\n\n",
"assets",
",",
"err",
":=",
"g",
".",
"GitHub",
".",
"ListAssets",
"(",
"ctx",
",",
"releaseID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"semaphore",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"parallel",
")",
"\n",
"for",
"_",
",",
"localAsset",
":=",
"range",
"localAssets",
"{",
"for",
"_",
",",
"asset",
":=",
"range",
"assets",
"{",
"// https://golang.org/doc/faq#closures_and_goroutines",
"localAsset",
",",
"asset",
":=",
"localAsset",
",",
"asset",
"\n\n",
"// Uploaded asset name is same as basename of local file",
"if",
"*",
"asset",
".",
"Name",
"==",
"filepath",
".",
"Base",
"(",
"localAsset",
")",
"{",
"eg",
".",
"Go",
"(",
"func",
"(",
")",
"error",
"{",
"semaphore",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"<-",
"semaphore",
"\n",
"}",
"(",
")",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"g",
".",
"outStream",
",",
"\"",
"\\n",
"\"",
",",
"*",
"asset",
".",
"Name",
")",
"\n",
"if",
"err",
":=",
"g",
".",
"GitHub",
".",
"DeleteAsset",
"(",
"ctx",
",",
"*",
"asset",
".",
"ID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"*",
"asset",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"eg",
".",
"Wait",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteAssets removes uploaded assets for a given release
|
[
"DeleteAssets",
"removes",
"uploaded",
"assets",
"for",
"a",
"given",
"release"
] |
87433aff999f09ee6d397c810df5eccb765d969b
|
https://github.com/tcnksm/ghr/blob/87433aff999f09ee6d397c810df5eccb765d969b/ghr.go#L133-L176
|
13,536
|
hokaccha/go-prettyjson
|
prettyjson.go
|
NewFormatter
|
func NewFormatter() *Formatter {
return &Formatter{
KeyColor: color.New(color.FgBlue, color.Bold),
StringColor: color.New(color.FgGreen, color.Bold),
BoolColor: color.New(color.FgYellow, color.Bold),
NumberColor: color.New(color.FgCyan, color.Bold),
NullColor: color.New(color.FgBlack, color.Bold),
StringMaxLength: 0,
DisabledColor: false,
Indent: 2,
Newline: "\n",
}
}
|
go
|
func NewFormatter() *Formatter {
return &Formatter{
KeyColor: color.New(color.FgBlue, color.Bold),
StringColor: color.New(color.FgGreen, color.Bold),
BoolColor: color.New(color.FgYellow, color.Bold),
NumberColor: color.New(color.FgCyan, color.Bold),
NullColor: color.New(color.FgBlack, color.Bold),
StringMaxLength: 0,
DisabledColor: false,
Indent: 2,
Newline: "\n",
}
}
|
[
"func",
"NewFormatter",
"(",
")",
"*",
"Formatter",
"{",
"return",
"&",
"Formatter",
"{",
"KeyColor",
":",
"color",
".",
"New",
"(",
"color",
".",
"FgBlue",
",",
"color",
".",
"Bold",
")",
",",
"StringColor",
":",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
",",
"color",
".",
"Bold",
")",
",",
"BoolColor",
":",
"color",
".",
"New",
"(",
"color",
".",
"FgYellow",
",",
"color",
".",
"Bold",
")",
",",
"NumberColor",
":",
"color",
".",
"New",
"(",
"color",
".",
"FgCyan",
",",
"color",
".",
"Bold",
")",
",",
"NullColor",
":",
"color",
".",
"New",
"(",
"color",
".",
"FgBlack",
",",
"color",
".",
"Bold",
")",
",",
"StringMaxLength",
":",
"0",
",",
"DisabledColor",
":",
"false",
",",
"Indent",
":",
"2",
",",
"Newline",
":",
"\"",
"\\n",
"\"",
",",
"}",
"\n",
"}"
] |
// NewFormatter returns a new formatter with following default values.
|
[
"NewFormatter",
"returns",
"a",
"new",
"formatter",
"with",
"following",
"default",
"values",
"."
] |
f579f869bbfea48a61fbea09207cadd1aaeceb83
|
https://github.com/hokaccha/go-prettyjson/blob/f579f869bbfea48a61fbea09207cadd1aaeceb83/prettyjson.go#L47-L59
|
13,537
|
hokaccha/go-prettyjson
|
prettyjson.go
|
Marshal
|
func (f *Formatter) Marshal(v interface{}) ([]byte, error) {
data, err := json.Marshal(v)
if err != nil {
return nil, err
}
return f.Format(data)
}
|
go
|
func (f *Formatter) Marshal(v interface{}) ([]byte, error) {
data, err := json.Marshal(v)
if err != nil {
return nil, err
}
return f.Format(data)
}
|
[
"func",
"(",
"f",
"*",
"Formatter",
")",
"Marshal",
"(",
"v",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"f",
".",
"Format",
"(",
"data",
")",
"\n",
"}"
] |
// Marshal marshals and formats JSON data.
|
[
"Marshal",
"marshals",
"and",
"formats",
"JSON",
"data",
"."
] |
f579f869bbfea48a61fbea09207cadd1aaeceb83
|
https://github.com/hokaccha/go-prettyjson/blob/f579f869bbfea48a61fbea09207cadd1aaeceb83/prettyjson.go#L62-L69
|
13,538
|
hokaccha/go-prettyjson
|
prettyjson.go
|
Format
|
func (f *Formatter) Format(data []byte) ([]byte, error) {
var v interface{}
if err := json.Unmarshal(data, &v); err != nil {
return nil, err
}
return []byte(f.pretty(v, 1)), nil
}
|
go
|
func (f *Formatter) Format(data []byte) ([]byte, error) {
var v interface{}
if err := json.Unmarshal(data, &v); err != nil {
return nil, err
}
return []byte(f.pretty(v, 1)), nil
}
|
[
"func",
"(",
"f",
"*",
"Formatter",
")",
"Format",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"v",
"interface",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"[",
"]",
"byte",
"(",
"f",
".",
"pretty",
"(",
"v",
",",
"1",
")",
")",
",",
"nil",
"\n",
"}"
] |
// Format formats JSON string.
|
[
"Format",
"formats",
"JSON",
"string",
"."
] |
f579f869bbfea48a61fbea09207cadd1aaeceb83
|
https://github.com/hokaccha/go-prettyjson/blob/f579f869bbfea48a61fbea09207cadd1aaeceb83/prettyjson.go#L72-L79
|
13,539
|
beldur/kraken-go-api-client
|
types.go
|
GetPairTickerInfo
|
func (v *TickerResponse) GetPairTickerInfo(pair string) PairTickerInfo {
r := reflect.ValueOf(v)
f := reflect.Indirect(r).FieldByName(pair)
return f.Interface().(PairTickerInfo)
}
|
go
|
func (v *TickerResponse) GetPairTickerInfo(pair string) PairTickerInfo {
r := reflect.ValueOf(v)
f := reflect.Indirect(r).FieldByName(pair)
return f.Interface().(PairTickerInfo)
}
|
[
"func",
"(",
"v",
"*",
"TickerResponse",
")",
"GetPairTickerInfo",
"(",
"pair",
"string",
")",
"PairTickerInfo",
"{",
"r",
":=",
"reflect",
".",
"ValueOf",
"(",
"v",
")",
"\n",
"f",
":=",
"reflect",
".",
"Indirect",
"(",
"r",
")",
".",
"FieldByName",
"(",
"pair",
")",
"\n\n",
"return",
"f",
".",
"Interface",
"(",
")",
".",
"(",
"PairTickerInfo",
")",
"\n",
"}"
] |
// GetPairTickerInfo is a helper method that returns given `pair`'s `PairTickerInfo`
|
[
"GetPairTickerInfo",
"is",
"a",
"helper",
"method",
"that",
"returns",
"given",
"pair",
"s",
"PairTickerInfo"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/types.go#L403-L408
|
13,540
|
beldur/kraken-go-api-client
|
types.go
|
UnmarshalJSON
|
func (o *OrderBookItem) UnmarshalJSON(data []byte) error {
tmp_struct := struct {
price string
amount string
ts int64
}{}
tmp_arr := []interface{}{&tmp_struct.price, &tmp_struct.amount, &tmp_struct.ts}
err := json.Unmarshal(data, &tmp_arr)
if err != nil {
return err
}
o.Price, err = strconv.ParseFloat(tmp_struct.price, 64)
if err != nil {
return err
}
o.Amount, err = strconv.ParseFloat(tmp_struct.amount, 64)
if err != nil {
return err
}
o.Ts = tmp_struct.ts
return nil
}
|
go
|
func (o *OrderBookItem) UnmarshalJSON(data []byte) error {
tmp_struct := struct {
price string
amount string
ts int64
}{}
tmp_arr := []interface{}{&tmp_struct.price, &tmp_struct.amount, &tmp_struct.ts}
err := json.Unmarshal(data, &tmp_arr)
if err != nil {
return err
}
o.Price, err = strconv.ParseFloat(tmp_struct.price, 64)
if err != nil {
return err
}
o.Amount, err = strconv.ParseFloat(tmp_struct.amount, 64)
if err != nil {
return err
}
o.Ts = tmp_struct.ts
return nil
}
|
[
"func",
"(",
"o",
"*",
"OrderBookItem",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"tmp_struct",
":=",
"struct",
"{",
"price",
"string",
"\n",
"amount",
"string",
"\n",
"ts",
"int64",
"\n",
"}",
"{",
"}",
"\n",
"tmp_arr",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"tmp_struct",
".",
"price",
",",
"&",
"tmp_struct",
".",
"amount",
",",
"&",
"tmp_struct",
".",
"ts",
"}",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"tmp_arr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"o",
".",
"Price",
",",
"err",
"=",
"strconv",
".",
"ParseFloat",
"(",
"tmp_struct",
".",
"price",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"o",
".",
"Amount",
",",
"err",
"=",
"strconv",
".",
"ParseFloat",
"(",
"tmp_struct",
".",
"amount",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"o",
".",
"Ts",
"=",
"tmp_struct",
".",
"ts",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalJSON takes a json array from kraken and converts it into an OrderBookItem.
|
[
"UnmarshalJSON",
"takes",
"a",
"json",
"array",
"from",
"kraken",
"and",
"converts",
"it",
"into",
"an",
"OrderBookItem",
"."
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/types.go#L554-L576
|
13,541
|
beldur/kraken-go-api-client
|
krakenapi.go
|
New
|
func New(key, secret string) *KrakenApi {
return NewWithClient(key, secret, http.DefaultClient)
}
|
go
|
func New(key, secret string) *KrakenApi {
return NewWithClient(key, secret, http.DefaultClient)
}
|
[
"func",
"New",
"(",
"key",
",",
"secret",
"string",
")",
"*",
"KrakenApi",
"{",
"return",
"NewWithClient",
"(",
"key",
",",
"secret",
",",
"http",
".",
"DefaultClient",
")",
"\n",
"}"
] |
// New creates a new Kraken API client
|
[
"New",
"creates",
"a",
"new",
"Kraken",
"API",
"client"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L96-L98
|
13,542
|
beldur/kraken-go-api-client
|
krakenapi.go
|
Time
|
func (api *KrakenApi) Time() (*TimeResponse, error) {
resp, err := api.queryPublic("Time", nil, &TimeResponse{})
if err != nil {
return nil, err
}
return resp.(*TimeResponse), nil
}
|
go
|
func (api *KrakenApi) Time() (*TimeResponse, error) {
resp, err := api.queryPublic("Time", nil, &TimeResponse{})
if err != nil {
return nil, err
}
return resp.(*TimeResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"Time",
"(",
")",
"(",
"*",
"TimeResponse",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"api",
".",
"queryPublic",
"(",
"\"",
"\"",
",",
"nil",
",",
"&",
"TimeResponse",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"(",
"*",
"TimeResponse",
")",
",",
"nil",
"\n",
"}"
] |
// Time returns the server's time
|
[
"Time",
"returns",
"the",
"server",
"s",
"time"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L105-L112
|
13,543
|
beldur/kraken-go-api-client
|
krakenapi.go
|
Assets
|
func (api *KrakenApi) Assets() (*AssetsResponse, error) {
resp, err := api.queryPublic("Assets", nil, &AssetsResponse{})
if err != nil {
return nil, err
}
return resp.(*AssetsResponse), nil
}
|
go
|
func (api *KrakenApi) Assets() (*AssetsResponse, error) {
resp, err := api.queryPublic("Assets", nil, &AssetsResponse{})
if err != nil {
return nil, err
}
return resp.(*AssetsResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"Assets",
"(",
")",
"(",
"*",
"AssetsResponse",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"api",
".",
"queryPublic",
"(",
"\"",
"\"",
",",
"nil",
",",
"&",
"AssetsResponse",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"(",
"*",
"AssetsResponse",
")",
",",
"nil",
"\n",
"}"
] |
// Assets returns the servers available assets
|
[
"Assets",
"returns",
"the",
"servers",
"available",
"assets"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L115-L122
|
13,544
|
beldur/kraken-go-api-client
|
krakenapi.go
|
AssetPairs
|
func (api *KrakenApi) AssetPairs() (*AssetPairsResponse, error) {
resp, err := api.queryPublic("AssetPairs", nil, &AssetPairsResponse{})
if err != nil {
return nil, err
}
return resp.(*AssetPairsResponse), nil
}
|
go
|
func (api *KrakenApi) AssetPairs() (*AssetPairsResponse, error) {
resp, err := api.queryPublic("AssetPairs", nil, &AssetPairsResponse{})
if err != nil {
return nil, err
}
return resp.(*AssetPairsResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"AssetPairs",
"(",
")",
"(",
"*",
"AssetPairsResponse",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"api",
".",
"queryPublic",
"(",
"\"",
"\"",
",",
"nil",
",",
"&",
"AssetPairsResponse",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"(",
"*",
"AssetPairsResponse",
")",
",",
"nil",
"\n",
"}"
] |
// AssetPairs returns the servers available asset pairs
|
[
"AssetPairs",
"returns",
"the",
"servers",
"available",
"asset",
"pairs"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L125-L132
|
13,545
|
beldur/kraken-go-api-client
|
krakenapi.go
|
Ticker
|
func (api *KrakenApi) Ticker(pairs ...string) (*TickerResponse, error) {
resp, err := api.queryPublic("Ticker", url.Values{
"pair": {strings.Join(pairs, ",")},
}, &TickerResponse{})
if err != nil {
return nil, err
}
return resp.(*TickerResponse), nil
}
|
go
|
func (api *KrakenApi) Ticker(pairs ...string) (*TickerResponse, error) {
resp, err := api.queryPublic("Ticker", url.Values{
"pair": {strings.Join(pairs, ",")},
}, &TickerResponse{})
if err != nil {
return nil, err
}
return resp.(*TickerResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"Ticker",
"(",
"pairs",
"...",
"string",
")",
"(",
"*",
"TickerResponse",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"api",
".",
"queryPublic",
"(",
"\"",
"\"",
",",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"strings",
".",
"Join",
"(",
"pairs",
",",
"\"",
"\"",
")",
"}",
",",
"}",
",",
"&",
"TickerResponse",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"(",
"*",
"TickerResponse",
")",
",",
"nil",
"\n",
"}"
] |
// Ticker returns the ticker for given comma separated pairs
|
[
"Ticker",
"returns",
"the",
"ticker",
"for",
"given",
"comma",
"separated",
"pairs"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L135-L144
|
13,546
|
beldur/kraken-go-api-client
|
krakenapi.go
|
Trades
|
func (api *KrakenApi) Trades(pair string, since int64) (*TradesResponse, error) {
values := url.Values{"pair": {pair}}
if since > 0 {
values.Set("since", strconv.FormatInt(since, 10))
}
resp, err := api.queryPublic("Trades", values, nil)
if err != nil {
return nil, err
}
v := resp.(map[string]interface{})
last, err := strconv.ParseInt(v["last"].(string), 10, 64)
if err != nil {
return nil, err
}
result := &TradesResponse{
Last: last,
Trades: make([]TradeInfo, 0),
}
trades := v[pair].([]interface{})
for _, v := range trades {
trade := v.([]interface{})
priceString := trade[0].(string)
price, _ := strconv.ParseFloat(priceString, 64)
volumeString := trade[1].(string)
volume, _ := strconv.ParseFloat(trade[1].(string), 64)
tradeInfo := TradeInfo{
Price: priceString,
PriceFloat: price,
Volume: volumeString,
VolumeFloat: volume,
Time: int64(trade[2].(float64)),
Buy: trade[3].(string) == BUY,
Sell: trade[3].(string) == SELL,
Market: trade[4].(string) == MARKET,
Limit: trade[4].(string) == LIMIT,
Miscellaneous: trade[5].(string),
}
result.Trades = append(result.Trades, tradeInfo)
}
return result, nil
}
|
go
|
func (api *KrakenApi) Trades(pair string, since int64) (*TradesResponse, error) {
values := url.Values{"pair": {pair}}
if since > 0 {
values.Set("since", strconv.FormatInt(since, 10))
}
resp, err := api.queryPublic("Trades", values, nil)
if err != nil {
return nil, err
}
v := resp.(map[string]interface{})
last, err := strconv.ParseInt(v["last"].(string), 10, 64)
if err != nil {
return nil, err
}
result := &TradesResponse{
Last: last,
Trades: make([]TradeInfo, 0),
}
trades := v[pair].([]interface{})
for _, v := range trades {
trade := v.([]interface{})
priceString := trade[0].(string)
price, _ := strconv.ParseFloat(priceString, 64)
volumeString := trade[1].(string)
volume, _ := strconv.ParseFloat(trade[1].(string), 64)
tradeInfo := TradeInfo{
Price: priceString,
PriceFloat: price,
Volume: volumeString,
VolumeFloat: volume,
Time: int64(trade[2].(float64)),
Buy: trade[3].(string) == BUY,
Sell: trade[3].(string) == SELL,
Market: trade[4].(string) == MARKET,
Limit: trade[4].(string) == LIMIT,
Miscellaneous: trade[5].(string),
}
result.Trades = append(result.Trades, tradeInfo)
}
return result, nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"Trades",
"(",
"pair",
"string",
",",
"since",
"int64",
")",
"(",
"*",
"TradesResponse",
",",
"error",
")",
"{",
"values",
":=",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"pair",
"}",
"}",
"\n",
"if",
"since",
">",
"0",
"{",
"values",
".",
"Set",
"(",
"\"",
"\"",
",",
"strconv",
".",
"FormatInt",
"(",
"since",
",",
"10",
")",
")",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"api",
".",
"queryPublic",
"(",
"\"",
"\"",
",",
"values",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"v",
":=",
"resp",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n\n",
"last",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"v",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"result",
":=",
"&",
"TradesResponse",
"{",
"Last",
":",
"last",
",",
"Trades",
":",
"make",
"(",
"[",
"]",
"TradeInfo",
",",
"0",
")",
",",
"}",
"\n\n",
"trades",
":=",
"v",
"[",
"pair",
"]",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"trades",
"{",
"trade",
":=",
"v",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"\n\n",
"priceString",
":=",
"trade",
"[",
"0",
"]",
".",
"(",
"string",
")",
"\n",
"price",
",",
"_",
":=",
"strconv",
".",
"ParseFloat",
"(",
"priceString",
",",
"64",
")",
"\n\n",
"volumeString",
":=",
"trade",
"[",
"1",
"]",
".",
"(",
"string",
")",
"\n",
"volume",
",",
"_",
":=",
"strconv",
".",
"ParseFloat",
"(",
"trade",
"[",
"1",
"]",
".",
"(",
"string",
")",
",",
"64",
")",
"\n\n",
"tradeInfo",
":=",
"TradeInfo",
"{",
"Price",
":",
"priceString",
",",
"PriceFloat",
":",
"price",
",",
"Volume",
":",
"volumeString",
",",
"VolumeFloat",
":",
"volume",
",",
"Time",
":",
"int64",
"(",
"trade",
"[",
"2",
"]",
".",
"(",
"float64",
")",
")",
",",
"Buy",
":",
"trade",
"[",
"3",
"]",
".",
"(",
"string",
")",
"==",
"BUY",
",",
"Sell",
":",
"trade",
"[",
"3",
"]",
".",
"(",
"string",
")",
"==",
"SELL",
",",
"Market",
":",
"trade",
"[",
"4",
"]",
".",
"(",
"string",
")",
"==",
"MARKET",
",",
"Limit",
":",
"trade",
"[",
"4",
"]",
".",
"(",
"string",
")",
"==",
"LIMIT",
",",
"Miscellaneous",
":",
"trade",
"[",
"5",
"]",
".",
"(",
"string",
")",
",",
"}",
"\n\n",
"result",
".",
"Trades",
"=",
"append",
"(",
"result",
".",
"Trades",
",",
"tradeInfo",
")",
"\n",
"}",
"\n\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// Trades returns the recent trades for given pair
|
[
"Trades",
"returns",
"the",
"recent",
"trades",
"for",
"given",
"pair"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L174-L223
|
13,547
|
beldur/kraken-go-api-client
|
krakenapi.go
|
Balance
|
func (api *KrakenApi) Balance() (*BalanceResponse, error) {
resp, err := api.queryPrivate("Balance", url.Values{}, &BalanceResponse{})
if err != nil {
return nil, err
}
return resp.(*BalanceResponse), nil
}
|
go
|
func (api *KrakenApi) Balance() (*BalanceResponse, error) {
resp, err := api.queryPrivate("Balance", url.Values{}, &BalanceResponse{})
if err != nil {
return nil, err
}
return resp.(*BalanceResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"Balance",
"(",
")",
"(",
"*",
"BalanceResponse",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"api",
".",
"queryPrivate",
"(",
"\"",
"\"",
",",
"url",
".",
"Values",
"{",
"}",
",",
"&",
"BalanceResponse",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"(",
"*",
"BalanceResponse",
")",
",",
"nil",
"\n",
"}"
] |
// Balance returns all account asset balances
|
[
"Balance",
"returns",
"all",
"account",
"asset",
"balances"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L226-L233
|
13,548
|
beldur/kraken-go-api-client
|
krakenapi.go
|
TradeBalance
|
func (api *KrakenApi) TradeBalance(args map[string]string) (*TradeBalanceResponse, error) {
params := url.Values{}
if value, ok := args["aclass"]; ok {
params.Add("aclass", value)
}
if value, ok := args["asset"]; ok {
params.Add("asset", value)
}
resp, err := api.queryPrivate("TradeBalance", params, &TradeBalanceResponse{})
if err != nil {
return nil, err
}
return resp.(*TradeBalanceResponse), nil
}
|
go
|
func (api *KrakenApi) TradeBalance(args map[string]string) (*TradeBalanceResponse, error) {
params := url.Values{}
if value, ok := args["aclass"]; ok {
params.Add("aclass", value)
}
if value, ok := args["asset"]; ok {
params.Add("asset", value)
}
resp, err := api.queryPrivate("TradeBalance", params, &TradeBalanceResponse{})
if err != nil {
return nil, err
}
return resp.(*TradeBalanceResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"TradeBalance",
"(",
"args",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"*",
"TradeBalanceResponse",
",",
"error",
")",
"{",
"params",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"api",
".",
"queryPrivate",
"(",
"\"",
"\"",
",",
"params",
",",
"&",
"TradeBalanceResponse",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"(",
"*",
"TradeBalanceResponse",
")",
",",
"nil",
"\n",
"}"
] |
// TradeBalance returns trade balance info
|
[
"TradeBalance",
"returns",
"trade",
"balance",
"info"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L236-L250
|
13,549
|
beldur/kraken-go-api-client
|
krakenapi.go
|
OpenOrders
|
func (api *KrakenApi) OpenOrders(args map[string]string) (*OpenOrdersResponse, error) {
params := url.Values{}
if value, ok := args["trades"]; ok {
params.Add("trades", value)
}
if value, ok := args["userref"]; ok {
params.Add("userref", value)
}
resp, err := api.queryPrivate("OpenOrders", params, &OpenOrdersResponse{})
if err != nil {
return nil, err
}
return resp.(*OpenOrdersResponse), nil
}
|
go
|
func (api *KrakenApi) OpenOrders(args map[string]string) (*OpenOrdersResponse, error) {
params := url.Values{}
if value, ok := args["trades"]; ok {
params.Add("trades", value)
}
if value, ok := args["userref"]; ok {
params.Add("userref", value)
}
resp, err := api.queryPrivate("OpenOrders", params, &OpenOrdersResponse{})
if err != nil {
return nil, err
}
return resp.(*OpenOrdersResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"OpenOrders",
"(",
"args",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"*",
"OpenOrdersResponse",
",",
"error",
")",
"{",
"params",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"api",
".",
"queryPrivate",
"(",
"\"",
"\"",
",",
"params",
",",
"&",
"OpenOrdersResponse",
"{",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"(",
"*",
"OpenOrdersResponse",
")",
",",
"nil",
"\n",
"}"
] |
// OpenOrders returns all open orders
|
[
"OpenOrders",
"returns",
"all",
"open",
"orders"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L253-L269
|
13,550
|
beldur/kraken-go-api-client
|
krakenapi.go
|
ClosedOrders
|
func (api *KrakenApi) ClosedOrders(args map[string]string) (*ClosedOrdersResponse, error) {
params := url.Values{}
if value, ok := args["trades"]; ok {
params.Add("trades", value)
}
if value, ok := args["userref"]; ok {
params.Add("userref", value)
}
if value, ok := args["start"]; ok {
params.Add("start", value)
}
if value, ok := args["end"]; ok {
params.Add("end", value)
}
if value, ok := args["ofs"]; ok {
params.Add("ofs", value)
}
if value, ok := args["closetime"]; ok {
params.Add("closetime", value)
}
resp, err := api.queryPrivate("ClosedOrders", params, &ClosedOrdersResponse{})
if err != nil {
return nil, err
}
return resp.(*ClosedOrdersResponse), nil
}
|
go
|
func (api *KrakenApi) ClosedOrders(args map[string]string) (*ClosedOrdersResponse, error) {
params := url.Values{}
if value, ok := args["trades"]; ok {
params.Add("trades", value)
}
if value, ok := args["userref"]; ok {
params.Add("userref", value)
}
if value, ok := args["start"]; ok {
params.Add("start", value)
}
if value, ok := args["end"]; ok {
params.Add("end", value)
}
if value, ok := args["ofs"]; ok {
params.Add("ofs", value)
}
if value, ok := args["closetime"]; ok {
params.Add("closetime", value)
}
resp, err := api.queryPrivate("ClosedOrders", params, &ClosedOrdersResponse{})
if err != nil {
return nil, err
}
return resp.(*ClosedOrdersResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"ClosedOrders",
"(",
"args",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"*",
"ClosedOrdersResponse",
",",
"error",
")",
"{",
"params",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"api",
".",
"queryPrivate",
"(",
"\"",
"\"",
",",
"params",
",",
"&",
"ClosedOrdersResponse",
"{",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"(",
"*",
"ClosedOrdersResponse",
")",
",",
"nil",
"\n",
"}"
] |
// ClosedOrders returns all closed orders
|
[
"ClosedOrders",
"returns",
"all",
"closed",
"orders"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L272-L299
|
13,551
|
beldur/kraken-go-api-client
|
krakenapi.go
|
Depth
|
func (api *KrakenApi) Depth(pair string, count int) (*OrderBook, error) {
dr := DepthResponse{}
_, err := api.queryPublic("Depth", url.Values{
"pair": {pair}, "count": {strconv.Itoa(count)},
}, &dr)
if err != nil {
return nil, err
}
if book, found := dr[pair]; found {
return &book, nil
}
return nil, errors.New("invalid response")
}
|
go
|
func (api *KrakenApi) Depth(pair string, count int) (*OrderBook, error) {
dr := DepthResponse{}
_, err := api.queryPublic("Depth", url.Values{
"pair": {pair}, "count": {strconv.Itoa(count)},
}, &dr)
if err != nil {
return nil, err
}
if book, found := dr[pair]; found {
return &book, nil
}
return nil, errors.New("invalid response")
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"Depth",
"(",
"pair",
"string",
",",
"count",
"int",
")",
"(",
"*",
"OrderBook",
",",
"error",
")",
"{",
"dr",
":=",
"DepthResponse",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"api",
".",
"queryPublic",
"(",
"\"",
"\"",
",",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"pair",
"}",
",",
"\"",
"\"",
":",
"{",
"strconv",
".",
"Itoa",
"(",
"count",
")",
"}",
",",
"}",
",",
"&",
"dr",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"book",
",",
"found",
":=",
"dr",
"[",
"pair",
"]",
";",
"found",
"{",
"return",
"&",
"book",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// Depth returns the order book for given pair and orders count.
|
[
"Depth",
"returns",
"the",
"order",
"book",
"for",
"given",
"pair",
"and",
"orders",
"count",
"."
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L302-L317
|
13,552
|
beldur/kraken-go-api-client
|
krakenapi.go
|
CancelOrder
|
func (api *KrakenApi) CancelOrder(txid string) (*CancelOrderResponse, error) {
params := url.Values{}
params.Add("txid", txid)
resp, err := api.queryPrivate("CancelOrder", params, &CancelOrderResponse{})
if err != nil {
return nil, err
}
return resp.(*CancelOrderResponse), nil
}
|
go
|
func (api *KrakenApi) CancelOrder(txid string) (*CancelOrderResponse, error) {
params := url.Values{}
params.Add("txid", txid)
resp, err := api.queryPrivate("CancelOrder", params, &CancelOrderResponse{})
if err != nil {
return nil, err
}
return resp.(*CancelOrderResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"CancelOrder",
"(",
"txid",
"string",
")",
"(",
"*",
"CancelOrderResponse",
",",
"error",
")",
"{",
"params",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"txid",
")",
"\n",
"resp",
",",
"err",
":=",
"api",
".",
"queryPrivate",
"(",
"\"",
"\"",
",",
"params",
",",
"&",
"CancelOrderResponse",
"{",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"(",
"*",
"CancelOrderResponse",
")",
",",
"nil",
"\n",
"}"
] |
// CancelOrder cancels order
|
[
"CancelOrder",
"cancels",
"order"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L320-L330
|
13,553
|
beldur/kraken-go-api-client
|
krakenapi.go
|
QueryOrders
|
func (api *KrakenApi) QueryOrders(txids string, args map[string]string) (*QueryOrdersResponse, error) {
params := url.Values{"txid": {txids}}
if value, ok := args["trades"]; ok {
params.Add("trades", value)
}
if value, ok := args["userref"]; ok {
params.Add("userref", value)
}
resp, err := api.queryPrivate("QueryOrders", params, &QueryOrdersResponse{})
if err != nil {
return nil, err
}
return resp.(*QueryOrdersResponse), nil
}
|
go
|
func (api *KrakenApi) QueryOrders(txids string, args map[string]string) (*QueryOrdersResponse, error) {
params := url.Values{"txid": {txids}}
if value, ok := args["trades"]; ok {
params.Add("trades", value)
}
if value, ok := args["userref"]; ok {
params.Add("userref", value)
}
resp, err := api.queryPrivate("QueryOrders", params, &QueryOrdersResponse{})
if err != nil {
return nil, err
}
return resp.(*QueryOrdersResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"QueryOrders",
"(",
"txids",
"string",
",",
"args",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"*",
"QueryOrdersResponse",
",",
"error",
")",
"{",
"params",
":=",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"txids",
"}",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"api",
".",
"queryPrivate",
"(",
"\"",
"\"",
",",
"params",
",",
"&",
"QueryOrdersResponse",
"{",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"(",
"*",
"QueryOrdersResponse",
")",
",",
"nil",
"\n",
"}"
] |
// QueryOrders shows order
|
[
"QueryOrders",
"shows",
"order"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L333-L348
|
13,554
|
beldur/kraken-go-api-client
|
krakenapi.go
|
AddOrder
|
func (api *KrakenApi) AddOrder(pair string, direction string, orderType string, volume string, args map[string]string) (*AddOrderResponse, error) {
params := url.Values{
"pair": {pair},
"type": {direction},
"ordertype": {orderType},
"volume": {volume},
}
if value, ok := args["price"]; ok {
params.Add("price", value)
}
if value, ok := args["price2"]; ok {
params.Add("price2", value)
}
if value, ok := args["leverage"]; ok {
params.Add("leverage", value)
}
if value, ok := args["oflags"]; ok {
params.Add("oflags", value)
}
if value, ok := args["starttm"]; ok {
params.Add("starttm", value)
}
if value, ok := args["expiretm"]; ok {
params.Add("expiretm", value)
}
if value, ok := args["validate"]; ok {
params.Add("validate", value)
}
if value, ok := args["close_order_type"]; ok {
params.Add("close[ordertype]", value)
}
if value, ok := args["close_price"]; ok {
params.Add("close[price]", value)
}
if value, ok := args["close_price2"]; ok {
params.Add("close[price2]", value)
}
if value, ok := args["trading_agreement"]; ok {
params.Add("trading_agreement", value)
}
if value, ok := args["userref"]; ok {
params.Add("userref", value)
}
resp, err := api.queryPrivate("AddOrder", params, &AddOrderResponse{})
if err != nil {
return nil, err
}
return resp.(*AddOrderResponse), nil
}
|
go
|
func (api *KrakenApi) AddOrder(pair string, direction string, orderType string, volume string, args map[string]string) (*AddOrderResponse, error) {
params := url.Values{
"pair": {pair},
"type": {direction},
"ordertype": {orderType},
"volume": {volume},
}
if value, ok := args["price"]; ok {
params.Add("price", value)
}
if value, ok := args["price2"]; ok {
params.Add("price2", value)
}
if value, ok := args["leverage"]; ok {
params.Add("leverage", value)
}
if value, ok := args["oflags"]; ok {
params.Add("oflags", value)
}
if value, ok := args["starttm"]; ok {
params.Add("starttm", value)
}
if value, ok := args["expiretm"]; ok {
params.Add("expiretm", value)
}
if value, ok := args["validate"]; ok {
params.Add("validate", value)
}
if value, ok := args["close_order_type"]; ok {
params.Add("close[ordertype]", value)
}
if value, ok := args["close_price"]; ok {
params.Add("close[price]", value)
}
if value, ok := args["close_price2"]; ok {
params.Add("close[price2]", value)
}
if value, ok := args["trading_agreement"]; ok {
params.Add("trading_agreement", value)
}
if value, ok := args["userref"]; ok {
params.Add("userref", value)
}
resp, err := api.queryPrivate("AddOrder", params, &AddOrderResponse{})
if err != nil {
return nil, err
}
return resp.(*AddOrderResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"AddOrder",
"(",
"pair",
"string",
",",
"direction",
"string",
",",
"orderType",
"string",
",",
"volume",
"string",
",",
"args",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"*",
"AddOrderResponse",
",",
"error",
")",
"{",
"params",
":=",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"pair",
"}",
",",
"\"",
"\"",
":",
"{",
"direction",
"}",
",",
"\"",
"\"",
":",
"{",
"orderType",
"}",
",",
"\"",
"\"",
":",
"{",
"volume",
"}",
",",
"}",
"\n\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"api",
".",
"queryPrivate",
"(",
"\"",
"\"",
",",
"params",
",",
"&",
"AddOrderResponse",
"{",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"(",
"*",
"AddOrderResponse",
")",
",",
"nil",
"\n",
"}"
] |
// AddOrder adds new order
|
[
"AddOrder",
"adds",
"new",
"order"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L351-L402
|
13,555
|
beldur/kraken-go-api-client
|
krakenapi.go
|
Ledgers
|
func (api *KrakenApi) Ledgers(args map[string]string) (*LedgersResponse, error) {
params := url.Values{}
if value, ok := args["aclass"]; ok {
params.Add("aclass", value)
}
if value, ok := args["asset"]; ok {
params.Add("asset", value)
}
if value, ok := args["type"]; ok {
params.Add("type", value)
}
if value, ok := args["start"]; ok {
params.Add("start", value)
}
if value, ok := args["end"]; ok {
params.Add("end", value)
}
if value, ok := args["ofs"]; ok {
params.Add("ofs", value)
}
resp, err := api.queryPrivate("Ledgers", params, &LedgersResponse{})
if err != nil {
return nil, err
}
return resp.(*LedgersResponse), nil
}
|
go
|
func (api *KrakenApi) Ledgers(args map[string]string) (*LedgersResponse, error) {
params := url.Values{}
if value, ok := args["aclass"]; ok {
params.Add("aclass", value)
}
if value, ok := args["asset"]; ok {
params.Add("asset", value)
}
if value, ok := args["type"]; ok {
params.Add("type", value)
}
if value, ok := args["start"]; ok {
params.Add("start", value)
}
if value, ok := args["end"]; ok {
params.Add("end", value)
}
if value, ok := args["ofs"]; ok {
params.Add("ofs", value)
}
resp, err := api.queryPrivate("Ledgers", params, &LedgersResponse{})
if err != nil {
return nil, err
}
return resp.(*LedgersResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"Ledgers",
"(",
"args",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"*",
"LedgersResponse",
",",
"error",
")",
"{",
"params",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"if",
"value",
",",
"ok",
":=",
"args",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"api",
".",
"queryPrivate",
"(",
"\"",
"\"",
",",
"params",
",",
"&",
"LedgersResponse",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"(",
"*",
"LedgersResponse",
")",
",",
"nil",
"\n",
"}"
] |
// Ledgers returns ledgers informations
|
[
"Ledgers",
"returns",
"ledgers",
"informations"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L405-L431
|
13,556
|
beldur/kraken-go-api-client
|
krakenapi.go
|
DepositAddresses
|
func (api *KrakenApi) DepositAddresses(asset string, method string) (*DepositAddressesResponse, error) {
resp, err := api.queryPrivate("DepositAddresses", url.Values{
"asset": {asset},
"method": {method},
}, &DepositAddressesResponse{})
if err != nil {
return nil, err
}
return resp.(*DepositAddressesResponse), nil
}
|
go
|
func (api *KrakenApi) DepositAddresses(asset string, method string) (*DepositAddressesResponse, error) {
resp, err := api.queryPrivate("DepositAddresses", url.Values{
"asset": {asset},
"method": {method},
}, &DepositAddressesResponse{})
if err != nil {
return nil, err
}
return resp.(*DepositAddressesResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"DepositAddresses",
"(",
"asset",
"string",
",",
"method",
"string",
")",
"(",
"*",
"DepositAddressesResponse",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"api",
".",
"queryPrivate",
"(",
"\"",
"\"",
",",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"asset",
"}",
",",
"\"",
"\"",
":",
"{",
"method",
"}",
",",
"}",
",",
"&",
"DepositAddressesResponse",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"resp",
".",
"(",
"*",
"DepositAddressesResponse",
")",
",",
"nil",
"\n",
"}"
] |
// DepositAddresses returns deposit addresses
|
[
"DepositAddresses",
"returns",
"deposit",
"addresses"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L434-L443
|
13,557
|
beldur/kraken-go-api-client
|
krakenapi.go
|
Withdraw
|
func (api *KrakenApi) Withdraw(asset string, key string, amount *big.Float) (*WithdrawResponse, error) {
resp, err := api.queryPrivate("Withdraw", url.Values{
"asset": {asset},
"key": {key},
"amount": {amount.String()},
}, &WithdrawResponse{})
if err != nil {
return nil, err
}
return resp.(*WithdrawResponse), nil
}
|
go
|
func (api *KrakenApi) Withdraw(asset string, key string, amount *big.Float) (*WithdrawResponse, error) {
resp, err := api.queryPrivate("Withdraw", url.Values{
"asset": {asset},
"key": {key},
"amount": {amount.String()},
}, &WithdrawResponse{})
if err != nil {
return nil, err
}
return resp.(*WithdrawResponse), nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"Withdraw",
"(",
"asset",
"string",
",",
"key",
"string",
",",
"amount",
"*",
"big",
".",
"Float",
")",
"(",
"*",
"WithdrawResponse",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"api",
".",
"queryPrivate",
"(",
"\"",
"\"",
",",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"asset",
"}",
",",
"\"",
"\"",
":",
"{",
"key",
"}",
",",
"\"",
"\"",
":",
"{",
"amount",
".",
"String",
"(",
")",
"}",
",",
"}",
",",
"&",
"WithdrawResponse",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"resp",
".",
"(",
"*",
"WithdrawResponse",
")",
",",
"nil",
"\n",
"}"
] |
// Withdraw executes a withdrawal, returning a reference ID
|
[
"Withdraw",
"executes",
"a",
"withdrawal",
"returning",
"a",
"reference",
"ID"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L446-L456
|
13,558
|
beldur/kraken-go-api-client
|
krakenapi.go
|
Query
|
func (api *KrakenApi) Query(method string, data map[string]string) (interface{}, error) {
values := url.Values{}
for key, value := range data {
values.Set(key, value)
}
// Check if method is public or private
if isStringInSlice(method, publicMethods) {
return api.queryPublic(method, values, nil)
} else if isStringInSlice(method, privateMethods) {
return api.queryPrivate(method, values, nil)
}
return nil, fmt.Errorf("Method '%s' is not valid", method)
}
|
go
|
func (api *KrakenApi) Query(method string, data map[string]string) (interface{}, error) {
values := url.Values{}
for key, value := range data {
values.Set(key, value)
}
// Check if method is public or private
if isStringInSlice(method, publicMethods) {
return api.queryPublic(method, values, nil)
} else if isStringInSlice(method, privateMethods) {
return api.queryPrivate(method, values, nil)
}
return nil, fmt.Errorf("Method '%s' is not valid", method)
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"Query",
"(",
"method",
"string",
",",
"data",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"values",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"data",
"{",
"values",
".",
"Set",
"(",
"key",
",",
"value",
")",
"\n",
"}",
"\n\n",
"// Check if method is public or private",
"if",
"isStringInSlice",
"(",
"method",
",",
"publicMethods",
")",
"{",
"return",
"api",
".",
"queryPublic",
"(",
"method",
",",
"values",
",",
"nil",
")",
"\n",
"}",
"else",
"if",
"isStringInSlice",
"(",
"method",
",",
"privateMethods",
")",
"{",
"return",
"api",
".",
"queryPrivate",
"(",
"method",
",",
"values",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"method",
")",
"\n",
"}"
] |
// Query sends a query to Kraken api for given method and parameters
|
[
"Query",
"sends",
"a",
"query",
"to",
"Kraken",
"api",
"for",
"given",
"method",
"and",
"parameters"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L472-L486
|
13,559
|
beldur/kraken-go-api-client
|
krakenapi.go
|
queryPublic
|
func (api *KrakenApi) queryPublic(method string, values url.Values, typ interface{}) (interface{}, error) {
url := fmt.Sprintf("%s/%s/public/%s", APIURL, APIVersion, method)
resp, err := api.doRequest(url, values, nil, typ)
return resp, err
}
|
go
|
func (api *KrakenApi) queryPublic(method string, values url.Values, typ interface{}) (interface{}, error) {
url := fmt.Sprintf("%s/%s/public/%s", APIURL, APIVersion, method)
resp, err := api.doRequest(url, values, nil, typ)
return resp, err
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"queryPublic",
"(",
"method",
"string",
",",
"values",
"url",
".",
"Values",
",",
"typ",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"APIURL",
",",
"APIVersion",
",",
"method",
")",
"\n",
"resp",
",",
"err",
":=",
"api",
".",
"doRequest",
"(",
"url",
",",
"values",
",",
"nil",
",",
"typ",
")",
"\n\n",
"return",
"resp",
",",
"err",
"\n",
"}"
] |
// Execute a public method query
|
[
"Execute",
"a",
"public",
"method",
"query"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L489-L494
|
13,560
|
beldur/kraken-go-api-client
|
krakenapi.go
|
queryPrivate
|
func (api *KrakenApi) queryPrivate(method string, values url.Values, typ interface{}) (interface{}, error) {
urlPath := fmt.Sprintf("/%s/private/%s", APIVersion, method)
reqURL := fmt.Sprintf("%s%s", APIURL, urlPath)
secret, _ := base64.StdEncoding.DecodeString(api.secret)
values.Set("nonce", fmt.Sprintf("%d", time.Now().UnixNano()))
// Create signature
signature := createSignature(urlPath, values, secret)
// Add Key and signature to request headers
headers := map[string]string{
"API-Key": api.key,
"API-Sign": signature,
}
resp, err := api.doRequest(reqURL, values, headers, typ)
return resp, err
}
|
go
|
func (api *KrakenApi) queryPrivate(method string, values url.Values, typ interface{}) (interface{}, error) {
urlPath := fmt.Sprintf("/%s/private/%s", APIVersion, method)
reqURL := fmt.Sprintf("%s%s", APIURL, urlPath)
secret, _ := base64.StdEncoding.DecodeString(api.secret)
values.Set("nonce", fmt.Sprintf("%d", time.Now().UnixNano()))
// Create signature
signature := createSignature(urlPath, values, secret)
// Add Key and signature to request headers
headers := map[string]string{
"API-Key": api.key,
"API-Sign": signature,
}
resp, err := api.doRequest(reqURL, values, headers, typ)
return resp, err
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"queryPrivate",
"(",
"method",
"string",
",",
"values",
"url",
".",
"Values",
",",
"typ",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"urlPath",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"APIVersion",
",",
"method",
")",
"\n",
"reqURL",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"APIURL",
",",
"urlPath",
")",
"\n",
"secret",
",",
"_",
":=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"api",
".",
"secret",
")",
"\n",
"values",
".",
"Set",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
")",
"\n\n",
"// Create signature",
"signature",
":=",
"createSignature",
"(",
"urlPath",
",",
"values",
",",
"secret",
")",
"\n\n",
"// Add Key and signature to request headers",
"headers",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"api",
".",
"key",
",",
"\"",
"\"",
":",
"signature",
",",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"api",
".",
"doRequest",
"(",
"reqURL",
",",
"values",
",",
"headers",
",",
"typ",
")",
"\n\n",
"return",
"resp",
",",
"err",
"\n",
"}"
] |
// queryPrivate executes a private method query
|
[
"queryPrivate",
"executes",
"a",
"private",
"method",
"query"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L497-L515
|
13,561
|
beldur/kraken-go-api-client
|
krakenapi.go
|
doRequest
|
func (api *KrakenApi) doRequest(reqURL string, values url.Values, headers map[string]string, typ interface{}) (interface{}, error) {
// Create request
req, err := http.NewRequest("POST", reqURL, strings.NewReader(values.Encode()))
if err != nil {
return nil, fmt.Errorf("Could not execute request! #1 (%s)", err.Error())
}
req.Header.Add("User-Agent", APIUserAgent)
for key, value := range headers {
req.Header.Add(key, value)
}
// Execute request
resp, err := api.client.Do(req)
if err != nil {
return nil, fmt.Errorf("Could not execute request! #2 (%s)", err.Error())
}
defer resp.Body.Close()
// Read request
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Could not execute request! #3 (%s)", err.Error())
}
// Check mime type of response
mimeType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return nil, fmt.Errorf("Could not execute request #4! (%s)", err.Error())
}
if mimeType != "application/json" {
return nil, fmt.Errorf("Could not execute request #5! (%s)", fmt.Sprintf("Response Content-Type is '%s', but should be 'application/json'.", mimeType))
}
// Parse request
var jsonData KrakenResponse
// Set the KrakenResponse.Result to typ so `json.Unmarshal` will
// unmarshal it into given type, instead of `interface{}`.
if typ != nil {
jsonData.Result = typ
}
err = json.Unmarshal(body, &jsonData)
if err != nil {
return nil, fmt.Errorf("Could not execute request! #6 (%s)", err.Error())
}
// Check for Kraken API error
if len(jsonData.Error) > 0 {
return nil, fmt.Errorf("Could not execute request! #7 (%s)", jsonData.Error)
}
return jsonData.Result, nil
}
|
go
|
func (api *KrakenApi) doRequest(reqURL string, values url.Values, headers map[string]string, typ interface{}) (interface{}, error) {
// Create request
req, err := http.NewRequest("POST", reqURL, strings.NewReader(values.Encode()))
if err != nil {
return nil, fmt.Errorf("Could not execute request! #1 (%s)", err.Error())
}
req.Header.Add("User-Agent", APIUserAgent)
for key, value := range headers {
req.Header.Add(key, value)
}
// Execute request
resp, err := api.client.Do(req)
if err != nil {
return nil, fmt.Errorf("Could not execute request! #2 (%s)", err.Error())
}
defer resp.Body.Close()
// Read request
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Could not execute request! #3 (%s)", err.Error())
}
// Check mime type of response
mimeType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return nil, fmt.Errorf("Could not execute request #4! (%s)", err.Error())
}
if mimeType != "application/json" {
return nil, fmt.Errorf("Could not execute request #5! (%s)", fmt.Sprintf("Response Content-Type is '%s', but should be 'application/json'.", mimeType))
}
// Parse request
var jsonData KrakenResponse
// Set the KrakenResponse.Result to typ so `json.Unmarshal` will
// unmarshal it into given type, instead of `interface{}`.
if typ != nil {
jsonData.Result = typ
}
err = json.Unmarshal(body, &jsonData)
if err != nil {
return nil, fmt.Errorf("Could not execute request! #6 (%s)", err.Error())
}
// Check for Kraken API error
if len(jsonData.Error) > 0 {
return nil, fmt.Errorf("Could not execute request! #7 (%s)", jsonData.Error)
}
return jsonData.Result, nil
}
|
[
"func",
"(",
"api",
"*",
"KrakenApi",
")",
"doRequest",
"(",
"reqURL",
"string",
",",
"values",
"url",
".",
"Values",
",",
"headers",
"map",
"[",
"string",
"]",
"string",
",",
"typ",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"// Create request",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"reqURL",
",",
"strings",
".",
"NewReader",
"(",
"values",
".",
"Encode",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"req",
".",
"Header",
".",
"Add",
"(",
"\"",
"\"",
",",
"APIUserAgent",
")",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"headers",
"{",
"req",
".",
"Header",
".",
"Add",
"(",
"key",
",",
"value",
")",
"\n",
"}",
"\n\n",
"// Execute request",
"resp",
",",
"err",
":=",
"api",
".",
"client",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"// Read request",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// Check mime type of response",
"mimeType",
",",
"_",
",",
"err",
":=",
"mime",
".",
"ParseMediaType",
"(",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"mimeType",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"mimeType",
")",
")",
"\n",
"}",
"\n\n",
"// Parse request",
"var",
"jsonData",
"KrakenResponse",
"\n\n",
"// Set the KrakenResponse.Result to typ so `json.Unmarshal` will",
"// unmarshal it into given type, instead of `interface{}`.",
"if",
"typ",
"!=",
"nil",
"{",
"jsonData",
".",
"Result",
"=",
"typ",
"\n",
"}",
"\n\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"&",
"jsonData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// Check for Kraken API error",
"if",
"len",
"(",
"jsonData",
".",
"Error",
")",
">",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"jsonData",
".",
"Error",
")",
"\n",
"}",
"\n\n",
"return",
"jsonData",
".",
"Result",
",",
"nil",
"\n",
"}"
] |
// doRequest executes a HTTP Request to the Kraken API and returns the result
|
[
"doRequest",
"executes",
"a",
"HTTP",
"Request",
"to",
"the",
"Kraken",
"API",
"and",
"returns",
"the",
"result"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L518-L573
|
13,562
|
beldur/kraken-go-api-client
|
krakenapi.go
|
isStringInSlice
|
func isStringInSlice(term string, list []string) bool {
for _, found := range list {
if term == found {
return true
}
}
return false
}
|
go
|
func isStringInSlice(term string, list []string) bool {
for _, found := range list {
if term == found {
return true
}
}
return false
}
|
[
"func",
"isStringInSlice",
"(",
"term",
"string",
",",
"list",
"[",
"]",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"found",
":=",
"range",
"list",
"{",
"if",
"term",
"==",
"found",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// isStringInSlice is a helper function to test if given term is in a list of strings
|
[
"isStringInSlice",
"is",
"a",
"helper",
"function",
"to",
"test",
"if",
"given",
"term",
"is",
"in",
"a",
"list",
"of",
"strings"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L576-L583
|
13,563
|
beldur/kraken-go-api-client
|
krakenapi.go
|
getHMacSha512
|
func getHMacSha512(message, secret []byte) []byte {
mac := hmac.New(sha512.New, secret)
mac.Write(message)
return mac.Sum(nil)
}
|
go
|
func getHMacSha512(message, secret []byte) []byte {
mac := hmac.New(sha512.New, secret)
mac.Write(message)
return mac.Sum(nil)
}
|
[
"func",
"getHMacSha512",
"(",
"message",
",",
"secret",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"mac",
":=",
"hmac",
".",
"New",
"(",
"sha512",
".",
"New",
",",
"secret",
")",
"\n",
"mac",
".",
"Write",
"(",
"message",
")",
"\n",
"return",
"mac",
".",
"Sum",
"(",
"nil",
")",
"\n",
"}"
] |
// getHMacSha512 creates a hmac hash with sha512
|
[
"getHMacSha512",
"creates",
"a",
"hmac",
"hash",
"with",
"sha512"
] |
1bcd7922cada85d8580b909eaf38189d016f818d
|
https://github.com/beldur/kraken-go-api-client/blob/1bcd7922cada85d8580b909eaf38189d016f818d/krakenapi.go#L593-L597
|
13,564
|
dghubble/oauth1
|
signer.go
|
Sign
|
func (s *HMACSigner) Sign(tokenSecret, message string) (string, error) {
signingKey := strings.Join([]string{s.ConsumerSecret, tokenSecret}, "&")
mac := hmac.New(sha1.New, []byte(signingKey))
mac.Write([]byte(message))
signatureBytes := mac.Sum(nil)
return base64.StdEncoding.EncodeToString(signatureBytes), nil
}
|
go
|
func (s *HMACSigner) Sign(tokenSecret, message string) (string, error) {
signingKey := strings.Join([]string{s.ConsumerSecret, tokenSecret}, "&")
mac := hmac.New(sha1.New, []byte(signingKey))
mac.Write([]byte(message))
signatureBytes := mac.Sum(nil)
return base64.StdEncoding.EncodeToString(signatureBytes), nil
}
|
[
"func",
"(",
"s",
"*",
"HMACSigner",
")",
"Sign",
"(",
"tokenSecret",
",",
"message",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"signingKey",
":=",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"s",
".",
"ConsumerSecret",
",",
"tokenSecret",
"}",
",",
"\"",
"\"",
")",
"\n",
"mac",
":=",
"hmac",
".",
"New",
"(",
"sha1",
".",
"New",
",",
"[",
"]",
"byte",
"(",
"signingKey",
")",
")",
"\n",
"mac",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"message",
")",
")",
"\n",
"signatureBytes",
":=",
"mac",
".",
"Sum",
"(",
"nil",
")",
"\n",
"return",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"signatureBytes",
")",
",",
"nil",
"\n",
"}"
] |
// Sign creates a concatenated consumer and token secret key and calculates
// the HMAC digest of the message. Returns the base64 encoded digest bytes.
|
[
"Sign",
"creates",
"a",
"concatenated",
"consumer",
"and",
"token",
"secret",
"key",
"and",
"calculates",
"the",
"HMAC",
"digest",
"of",
"the",
"message",
".",
"Returns",
"the",
"base64",
"encoded",
"digest",
"bytes",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/signer.go#L34-L40
|
13,565
|
dghubble/oauth1
|
signer.go
|
Sign
|
func (s *RSASigner) Sign(tokenSecret, message string) (string, error) {
digest := sha1.Sum([]byte(message))
signature, err := rsa.SignPKCS1v15(rand.Reader, s.PrivateKey, crypto.SHA1, digest[:])
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(signature), nil
}
|
go
|
func (s *RSASigner) Sign(tokenSecret, message string) (string, error) {
digest := sha1.Sum([]byte(message))
signature, err := rsa.SignPKCS1v15(rand.Reader, s.PrivateKey, crypto.SHA1, digest[:])
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(signature), nil
}
|
[
"func",
"(",
"s",
"*",
"RSASigner",
")",
"Sign",
"(",
"tokenSecret",
",",
"message",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"digest",
":=",
"sha1",
".",
"Sum",
"(",
"[",
"]",
"byte",
"(",
"message",
")",
")",
"\n",
"signature",
",",
"err",
":=",
"rsa",
".",
"SignPKCS1v15",
"(",
"rand",
".",
"Reader",
",",
"s",
".",
"PrivateKey",
",",
"crypto",
".",
"SHA1",
",",
"digest",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"signature",
")",
",",
"nil",
"\n",
"}"
] |
// Sign uses RSA PKCS1-v1_5 to sign a SHA1 digest of the given message. The
// tokenSecret is not used with this signing scheme.
|
[
"Sign",
"uses",
"RSA",
"PKCS1",
"-",
"v1_5",
"to",
"sign",
"a",
"SHA1",
"digest",
"of",
"the",
"given",
"message",
".",
"The",
"tokenSecret",
"is",
"not",
"used",
"with",
"this",
"signing",
"scheme",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/signer.go#L55-L62
|
13,566
|
dghubble/oauth1
|
token.go
|
NewToken
|
func NewToken(token, tokenSecret string) *Token {
return &Token{
Token: token,
TokenSecret: tokenSecret,
}
}
|
go
|
func NewToken(token, tokenSecret string) *Token {
return &Token{
Token: token,
TokenSecret: tokenSecret,
}
}
|
[
"func",
"NewToken",
"(",
"token",
",",
"tokenSecret",
"string",
")",
"*",
"Token",
"{",
"return",
"&",
"Token",
"{",
"Token",
":",
"token",
",",
"TokenSecret",
":",
"tokenSecret",
",",
"}",
"\n",
"}"
] |
// NewToken returns a new Token with the given token and token secret.
|
[
"NewToken",
"returns",
"a",
"new",
"Token",
"with",
"the",
"given",
"token",
"and",
"token",
"secret",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/token.go#L20-L25
|
13,567
|
dghubble/oauth1
|
encode.go
|
PercentEncode
|
func PercentEncode(input string) string {
var buf bytes.Buffer
for _, b := range []byte(input) {
// if in unreserved set
if shouldEscape(b) {
buf.Write([]byte(fmt.Sprintf("%%%02X", b)))
} else {
// do not escape, write byte as-is
buf.WriteByte(b)
}
}
return buf.String()
}
|
go
|
func PercentEncode(input string) string {
var buf bytes.Buffer
for _, b := range []byte(input) {
// if in unreserved set
if shouldEscape(b) {
buf.Write([]byte(fmt.Sprintf("%%%02X", b)))
} else {
// do not escape, write byte as-is
buf.WriteByte(b)
}
}
return buf.String()
}
|
[
"func",
"PercentEncode",
"(",
"input",
"string",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"[",
"]",
"byte",
"(",
"input",
")",
"{",
"// if in unreserved set",
"if",
"shouldEscape",
"(",
"b",
")",
"{",
"buf",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
")",
")",
")",
"\n",
"}",
"else",
"{",
"// do not escape, write byte as-is",
"buf",
".",
"WriteByte",
"(",
"b",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] |
// PercentEncode percent encodes a string according to RFC 3986 2.1.
|
[
"PercentEncode",
"percent",
"encodes",
"a",
"string",
"according",
"to",
"RFC",
"3986",
"2",
".",
"1",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/encode.go#L9-L21
|
13,568
|
dghubble/oauth1
|
encode.go
|
shouldEscape
|
func shouldEscape(c byte) bool {
// RFC3986 2.3 unreserved characters
if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' {
return false
}
switch c {
case '-', '.', '_', '~':
return false
}
// all other bytes must be escaped
return true
}
|
go
|
func shouldEscape(c byte) bool {
// RFC3986 2.3 unreserved characters
if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' {
return false
}
switch c {
case '-', '.', '_', '~':
return false
}
// all other bytes must be escaped
return true
}
|
[
"func",
"shouldEscape",
"(",
"c",
"byte",
")",
"bool",
"{",
"// RFC3986 2.3 unreserved characters",
"if",
"'A'",
"<=",
"c",
"&&",
"c",
"<=",
"'Z'",
"||",
"'a'",
"<=",
"c",
"&&",
"c",
"<=",
"'z'",
"||",
"'0'",
"<=",
"c",
"&&",
"c",
"<=",
"'9'",
"{",
"return",
"false",
"\n",
"}",
"\n",
"switch",
"c",
"{",
"case",
"'-'",
",",
"'.'",
",",
"'_'",
",",
"'~'",
":",
"return",
"false",
"\n",
"}",
"\n",
"// all other bytes must be escaped",
"return",
"true",
"\n",
"}"
] |
// shouldEscape returns false if the byte is an unreserved character that
// should not be escaped and true otherwise, according to RFC 3986 2.1.
|
[
"shouldEscape",
"returns",
"false",
"if",
"the",
"byte",
"is",
"an",
"unreserved",
"character",
"that",
"should",
"not",
"be",
"escaped",
"and",
"true",
"otherwise",
"according",
"to",
"RFC",
"3986",
"2",
".",
"1",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/encode.go#L25-L36
|
13,569
|
dghubble/oauth1
|
transport.go
|
RoundTrip
|
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
if t.source == nil {
return nil, fmt.Errorf("oauth1: Transport's source is nil")
}
accessToken, err := t.source.Token()
if err != nil {
return nil, err
}
if t.auther == nil {
return nil, fmt.Errorf("oauth1: Transport's auther is nil")
}
// RoundTripper should not modify the given request, clone it
req2 := cloneRequest(req)
err = t.auther.setRequestAuthHeader(req2, accessToken)
if err != nil {
return nil, err
}
return t.base().RoundTrip(req2)
}
|
go
|
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
if t.source == nil {
return nil, fmt.Errorf("oauth1: Transport's source is nil")
}
accessToken, err := t.source.Token()
if err != nil {
return nil, err
}
if t.auther == nil {
return nil, fmt.Errorf("oauth1: Transport's auther is nil")
}
// RoundTripper should not modify the given request, clone it
req2 := cloneRequest(req)
err = t.auther.setRequestAuthHeader(req2, accessToken)
if err != nil {
return nil, err
}
return t.base().RoundTrip(req2)
}
|
[
"func",
"(",
"t",
"*",
"Transport",
")",
"RoundTrip",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"t",
".",
"source",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"accessToken",
",",
"err",
":=",
"t",
".",
"source",
".",
"Token",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"t",
".",
"auther",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// RoundTripper should not modify the given request, clone it",
"req2",
":=",
"cloneRequest",
"(",
"req",
")",
"\n",
"err",
"=",
"t",
".",
"auther",
".",
"setRequestAuthHeader",
"(",
"req2",
",",
"accessToken",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"t",
".",
"base",
"(",
")",
".",
"RoundTrip",
"(",
"req2",
")",
"\n",
"}"
] |
// RoundTrip authorizes the request with a signed OAuth1 Authorization header
// using the auther and TokenSource.
|
[
"RoundTrip",
"authorizes",
"the",
"request",
"with",
"a",
"signed",
"OAuth1",
"Authorization",
"header",
"using",
"the",
"auther",
"and",
"TokenSource",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/transport.go#L26-L44
|
13,570
|
dghubble/oauth1
|
context.go
|
contextTransport
|
func contextTransport(ctx context.Context) http.RoundTripper {
if client, ok := ctx.Value(HTTPClient).(*http.Client); ok {
return client.Transport
}
return nil
}
|
go
|
func contextTransport(ctx context.Context) http.RoundTripper {
if client, ok := ctx.Value(HTTPClient).(*http.Client); ok {
return client.Transport
}
return nil
}
|
[
"func",
"contextTransport",
"(",
"ctx",
"context",
".",
"Context",
")",
"http",
".",
"RoundTripper",
"{",
"if",
"client",
",",
"ok",
":=",
"ctx",
".",
"Value",
"(",
"HTTPClient",
")",
".",
"(",
"*",
"http",
".",
"Client",
")",
";",
"ok",
"{",
"return",
"client",
".",
"Transport",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// contextTransport gets the Transport from the context client or nil.
|
[
"contextTransport",
"gets",
"the",
"Transport",
"from",
"the",
"context",
"client",
"or",
"nil",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/context.go#L18-L23
|
13,571
|
dghubble/oauth1
|
config.go
|
NewConfig
|
func NewConfig(consumerKey, consumerSecret string) *Config {
return &Config{
ConsumerKey: consumerKey,
ConsumerSecret: consumerSecret,
}
}
|
go
|
func NewConfig(consumerKey, consumerSecret string) *Config {
return &Config{
ConsumerKey: consumerKey,
ConsumerSecret: consumerSecret,
}
}
|
[
"func",
"NewConfig",
"(",
"consumerKey",
",",
"consumerSecret",
"string",
")",
"*",
"Config",
"{",
"return",
"&",
"Config",
"{",
"ConsumerKey",
":",
"consumerKey",
",",
"ConsumerSecret",
":",
"consumerSecret",
",",
"}",
"\n",
"}"
] |
// NewConfig returns a new Config with the given consumer key and secret.
|
[
"NewConfig",
"returns",
"a",
"new",
"Config",
"with",
"the",
"given",
"consumer",
"key",
"and",
"secret",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/config.go#L35-L40
|
13,572
|
dghubble/oauth1
|
config.go
|
Client
|
func (c *Config) Client(ctx context.Context, t *Token) *http.Client {
return NewClient(ctx, c, t)
}
|
go
|
func (c *Config) Client(ctx context.Context, t *Token) *http.Client {
return NewClient(ctx, c, t)
}
|
[
"func",
"(",
"c",
"*",
"Config",
")",
"Client",
"(",
"ctx",
"context",
".",
"Context",
",",
"t",
"*",
"Token",
")",
"*",
"http",
".",
"Client",
"{",
"return",
"NewClient",
"(",
"ctx",
",",
"c",
",",
"t",
")",
"\n",
"}"
] |
// Client returns an HTTP client which uses the provided ctx and access Token.
|
[
"Client",
"returns",
"an",
"HTTP",
"client",
"which",
"uses",
"the",
"provided",
"ctx",
"and",
"access",
"Token",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/config.go#L43-L45
|
13,573
|
dghubble/oauth1
|
config.go
|
NewClient
|
func NewClient(ctx context.Context, config *Config, token *Token) *http.Client {
transport := &Transport{
Base: contextTransport(ctx),
source: StaticTokenSource(token),
auther: newAuther(config),
}
return &http.Client{Transport: transport}
}
|
go
|
func NewClient(ctx context.Context, config *Config, token *Token) *http.Client {
transport := &Transport{
Base: contextTransport(ctx),
source: StaticTokenSource(token),
auther: newAuther(config),
}
return &http.Client{Transport: transport}
}
|
[
"func",
"NewClient",
"(",
"ctx",
"context",
".",
"Context",
",",
"config",
"*",
"Config",
",",
"token",
"*",
"Token",
")",
"*",
"http",
".",
"Client",
"{",
"transport",
":=",
"&",
"Transport",
"{",
"Base",
":",
"contextTransport",
"(",
"ctx",
")",
",",
"source",
":",
"StaticTokenSource",
"(",
"token",
")",
",",
"auther",
":",
"newAuther",
"(",
"config",
")",
",",
"}",
"\n",
"return",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"transport",
"}",
"\n",
"}"
] |
// NewClient returns a new http Client which signs requests via OAuth1.
|
[
"NewClient",
"returns",
"a",
"new",
"http",
"Client",
"which",
"signs",
"requests",
"via",
"OAuth1",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/config.go#L48-L55
|
13,574
|
dghubble/oauth1
|
config.go
|
ParseAuthorizationCallback
|
func ParseAuthorizationCallback(req *http.Request) (requestToken, verifier string, err error) {
// parse the raw query from the URL into req.Form
err = req.ParseForm()
if err != nil {
return "", "", err
}
requestToken = req.Form.Get(oauthTokenParam)
verifier = req.Form.Get(oauthVerifierParam)
if requestToken == "" || verifier == "" {
return "", "", errors.New("oauth1: Request missing oauth_token or oauth_verifier")
}
return requestToken, verifier, nil
}
|
go
|
func ParseAuthorizationCallback(req *http.Request) (requestToken, verifier string, err error) {
// parse the raw query from the URL into req.Form
err = req.ParseForm()
if err != nil {
return "", "", err
}
requestToken = req.Form.Get(oauthTokenParam)
verifier = req.Form.Get(oauthVerifierParam)
if requestToken == "" || verifier == "" {
return "", "", errors.New("oauth1: Request missing oauth_token or oauth_verifier")
}
return requestToken, verifier, nil
}
|
[
"func",
"ParseAuthorizationCallback",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"requestToken",
",",
"verifier",
"string",
",",
"err",
"error",
")",
"{",
"// parse the raw query from the URL into req.Form",
"err",
"=",
"req",
".",
"ParseForm",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"requestToken",
"=",
"req",
".",
"Form",
".",
"Get",
"(",
"oauthTokenParam",
")",
"\n",
"verifier",
"=",
"req",
".",
"Form",
".",
"Get",
"(",
"oauthVerifierParam",
")",
"\n",
"if",
"requestToken",
"==",
"\"",
"\"",
"||",
"verifier",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"requestToken",
",",
"verifier",
",",
"nil",
"\n",
"}"
] |
// ParseAuthorizationCallback parses an OAuth1 authorization callback request
// from a provider server. The oauth_token and oauth_verifier parameters are
// parsed to return the request token from earlier in the flow and the
// verifier string.
// See RFC 5849 2.2 Resource Owner Authorization.
|
[
"ParseAuthorizationCallback",
"parses",
"an",
"OAuth1",
"authorization",
"callback",
"request",
"from",
"a",
"provider",
"server",
".",
"The",
"oauth_token",
"and",
"oauth_verifier",
"parameters",
"are",
"parsed",
"to",
"return",
"the",
"request",
"token",
"from",
"earlier",
"in",
"the",
"flow",
"and",
"the",
"verifier",
"string",
".",
"See",
"RFC",
"5849",
"2",
".",
"2",
"Resource",
"Owner",
"Authorization",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/config.go#L121-L133
|
13,575
|
dghubble/oauth1
|
auther.go
|
commonOAuthParams
|
func (a *auther) commonOAuthParams() map[string]string {
params := map[string]string{
oauthConsumerKeyParam: a.config.ConsumerKey,
oauthSignatureMethodParam: a.signer().Name(),
oauthTimestampParam: strconv.FormatInt(a.epoch(), 10),
oauthNonceParam: a.nonce(),
oauthVersionParam: defaultOauthVersion,
}
if a.config.Realm != "" {
params[realmParam] = a.config.Realm
}
return params
}
|
go
|
func (a *auther) commonOAuthParams() map[string]string {
params := map[string]string{
oauthConsumerKeyParam: a.config.ConsumerKey,
oauthSignatureMethodParam: a.signer().Name(),
oauthTimestampParam: strconv.FormatInt(a.epoch(), 10),
oauthNonceParam: a.nonce(),
oauthVersionParam: defaultOauthVersion,
}
if a.config.Realm != "" {
params[realmParam] = a.config.Realm
}
return params
}
|
[
"func",
"(",
"a",
"*",
"auther",
")",
"commonOAuthParams",
"(",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"params",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"oauthConsumerKeyParam",
":",
"a",
".",
"config",
".",
"ConsumerKey",
",",
"oauthSignatureMethodParam",
":",
"a",
".",
"signer",
"(",
")",
".",
"Name",
"(",
")",
",",
"oauthTimestampParam",
":",
"strconv",
".",
"FormatInt",
"(",
"a",
".",
"epoch",
"(",
")",
",",
"10",
")",
",",
"oauthNonceParam",
":",
"a",
".",
"nonce",
"(",
")",
",",
"oauthVersionParam",
":",
"defaultOauthVersion",
",",
"}",
"\n",
"if",
"a",
".",
"config",
".",
"Realm",
"!=",
"\"",
"\"",
"{",
"params",
"[",
"realmParam",
"]",
"=",
"a",
".",
"config",
".",
"Realm",
"\n",
"}",
"\n",
"return",
"params",
"\n",
"}"
] |
// commonOAuthParams returns a map of the common OAuth1 protocol parameters,
// excluding the oauth_signature parameter. This includes the realm parameter
// if it was set in the config. The realm parameter will not be included in
// the signature base string as specified in RFC 5849 3.4.1.3.1.
|
[
"commonOAuthParams",
"returns",
"a",
"map",
"of",
"the",
"common",
"OAuth1",
"protocol",
"parameters",
"excluding",
"the",
"oauth_signature",
"parameter",
".",
"This",
"includes",
"the",
"realm",
"parameter",
"if",
"it",
"was",
"set",
"in",
"the",
"config",
".",
"The",
"realm",
"parameter",
"will",
"not",
"be",
"included",
"in",
"the",
"signature",
"base",
"string",
"as",
"specified",
"in",
"RFC",
"5849",
"3",
".",
"4",
".",
"1",
".",
"3",
".",
"1",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/auther.go#L124-L136
|
13,576
|
dghubble/oauth1
|
auther.go
|
epoch
|
func (a *auther) epoch() int64 {
if a.clock != nil {
return a.clock.Now().Unix()
}
return time.Now().Unix()
}
|
go
|
func (a *auther) epoch() int64 {
if a.clock != nil {
return a.clock.Now().Unix()
}
return time.Now().Unix()
}
|
[
"func",
"(",
"a",
"*",
"auther",
")",
"epoch",
"(",
")",
"int64",
"{",
"if",
"a",
".",
"clock",
"!=",
"nil",
"{",
"return",
"a",
".",
"clock",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
"\n",
"}",
"\n",
"return",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
"\n",
"}"
] |
// Returns the Unix epoch seconds.
|
[
"Returns",
"the",
"Unix",
"epoch",
"seconds",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/auther.go#L149-L154
|
13,577
|
dghubble/oauth1
|
auther.go
|
signer
|
func (a *auther) signer() Signer {
if a.config.Signer != nil {
return a.config.Signer
}
return &HMACSigner{ConsumerSecret: a.config.ConsumerSecret}
}
|
go
|
func (a *auther) signer() Signer {
if a.config.Signer != nil {
return a.config.Signer
}
return &HMACSigner{ConsumerSecret: a.config.ConsumerSecret}
}
|
[
"func",
"(",
"a",
"*",
"auther",
")",
"signer",
"(",
")",
"Signer",
"{",
"if",
"a",
".",
"config",
".",
"Signer",
"!=",
"nil",
"{",
"return",
"a",
".",
"config",
".",
"Signer",
"\n",
"}",
"\n",
"return",
"&",
"HMACSigner",
"{",
"ConsumerSecret",
":",
"a",
".",
"config",
".",
"ConsumerSecret",
"}",
"\n",
"}"
] |
// Returns the Config's Signer or the default Signer.
|
[
"Returns",
"the",
"Config",
"s",
"Signer",
"or",
"the",
"default",
"Signer",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/auther.go#L157-L162
|
13,578
|
dghubble/oauth1
|
auther.go
|
encodeParameters
|
func encodeParameters(params map[string]string) map[string]string {
encoded := map[string]string{}
for key, value := range params {
encoded[PercentEncode(key)] = PercentEncode(value)
}
return encoded
}
|
go
|
func encodeParameters(params map[string]string) map[string]string {
encoded := map[string]string{}
for key, value := range params {
encoded[PercentEncode(key)] = PercentEncode(value)
}
return encoded
}
|
[
"func",
"encodeParameters",
"(",
"params",
"map",
"[",
"string",
"]",
"string",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"encoded",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"params",
"{",
"encoded",
"[",
"PercentEncode",
"(",
"key",
")",
"]",
"=",
"PercentEncode",
"(",
"value",
")",
"\n",
"}",
"\n",
"return",
"encoded",
"\n",
"}"
] |
// encodeParameters percent encodes parameter keys and values according to
// RFC5849 3.6 and RFC3986 2.1 and returns a new map.
|
[
"encodeParameters",
"percent",
"encodes",
"parameter",
"keys",
"and",
"values",
"according",
"to",
"RFC5849",
"3",
".",
"6",
"and",
"RFC3986",
"2",
".",
"1",
"and",
"returns",
"a",
"new",
"map",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/auther.go#L176-L182
|
13,579
|
dghubble/oauth1
|
auther.go
|
signatureBase
|
func signatureBase(req *http.Request, params map[string]string) string {
method := strings.ToUpper(req.Method)
baseURL := baseURI(req)
parameterString := normalizedParameterString(params)
// signature base string constructed accoding to 3.4.1.1
baseParts := []string{method, PercentEncode(baseURL), PercentEncode(parameterString)}
return strings.Join(baseParts, "&")
}
|
go
|
func signatureBase(req *http.Request, params map[string]string) string {
method := strings.ToUpper(req.Method)
baseURL := baseURI(req)
parameterString := normalizedParameterString(params)
// signature base string constructed accoding to 3.4.1.1
baseParts := []string{method, PercentEncode(baseURL), PercentEncode(parameterString)}
return strings.Join(baseParts, "&")
}
|
[
"func",
"signatureBase",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"map",
"[",
"string",
"]",
"string",
")",
"string",
"{",
"method",
":=",
"strings",
".",
"ToUpper",
"(",
"req",
".",
"Method",
")",
"\n",
"baseURL",
":=",
"baseURI",
"(",
"req",
")",
"\n",
"parameterString",
":=",
"normalizedParameterString",
"(",
"params",
")",
"\n",
"// signature base string constructed accoding to 3.4.1.1",
"baseParts",
":=",
"[",
"]",
"string",
"{",
"method",
",",
"PercentEncode",
"(",
"baseURL",
")",
",",
"PercentEncode",
"(",
"parameterString",
")",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"baseParts",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// signatureBase combines the uppercase request method, percent encoded base
// string URI, and normalizes the request parameters int a parameter string.
// Returns the OAuth1 signature base string according to RFC5849 3.4.1.
|
[
"signatureBase",
"combines",
"the",
"uppercase",
"request",
"method",
"percent",
"encoded",
"base",
"string",
"URI",
"and",
"normalizes",
"the",
"request",
"parameters",
"int",
"a",
"parameter",
"string",
".",
"Returns",
"the",
"OAuth1",
"signature",
"base",
"string",
"according",
"to",
"RFC5849",
"3",
".",
"4",
".",
"1",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/auther.go#L244-L251
|
13,580
|
dghubble/oauth1
|
auther.go
|
baseURI
|
func baseURI(req *http.Request) string {
scheme := strings.ToLower(req.URL.Scheme)
host := strings.ToLower(req.URL.Host)
if hostPort := strings.Split(host, ":"); len(hostPort) == 2 && (hostPort[1] == "80" || hostPort[1] == "443") {
host = hostPort[0]
}
// TODO: use req.URL.EscapedPath() once Go 1.5 is more generally adopted
// For now, hacky workaround accomplishes the same internal escaping mode
// escape(u.Path, encodePath) for proper compliance with the OAuth1 spec.
path := req.URL.Path
if path != "" {
path = strings.Split(req.URL.RequestURI(), "?")[0]
}
return fmt.Sprintf("%v://%v%v", scheme, host, path)
}
|
go
|
func baseURI(req *http.Request) string {
scheme := strings.ToLower(req.URL.Scheme)
host := strings.ToLower(req.URL.Host)
if hostPort := strings.Split(host, ":"); len(hostPort) == 2 && (hostPort[1] == "80" || hostPort[1] == "443") {
host = hostPort[0]
}
// TODO: use req.URL.EscapedPath() once Go 1.5 is more generally adopted
// For now, hacky workaround accomplishes the same internal escaping mode
// escape(u.Path, encodePath) for proper compliance with the OAuth1 spec.
path := req.URL.Path
if path != "" {
path = strings.Split(req.URL.RequestURI(), "?")[0]
}
return fmt.Sprintf("%v://%v%v", scheme, host, path)
}
|
[
"func",
"baseURI",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"scheme",
":=",
"strings",
".",
"ToLower",
"(",
"req",
".",
"URL",
".",
"Scheme",
")",
"\n",
"host",
":=",
"strings",
".",
"ToLower",
"(",
"req",
".",
"URL",
".",
"Host",
")",
"\n",
"if",
"hostPort",
":=",
"strings",
".",
"Split",
"(",
"host",
",",
"\"",
"\"",
")",
";",
"len",
"(",
"hostPort",
")",
"==",
"2",
"&&",
"(",
"hostPort",
"[",
"1",
"]",
"==",
"\"",
"\"",
"||",
"hostPort",
"[",
"1",
"]",
"==",
"\"",
"\"",
")",
"{",
"host",
"=",
"hostPort",
"[",
"0",
"]",
"\n",
"}",
"\n",
"// TODO: use req.URL.EscapedPath() once Go 1.5 is more generally adopted",
"// For now, hacky workaround accomplishes the same internal escaping mode",
"// escape(u.Path, encodePath) for proper compliance with the OAuth1 spec.",
"path",
":=",
"req",
".",
"URL",
".",
"Path",
"\n",
"if",
"path",
"!=",
"\"",
"\"",
"{",
"path",
"=",
"strings",
".",
"Split",
"(",
"req",
".",
"URL",
".",
"RequestURI",
"(",
")",
",",
"\"",
"\"",
")",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"scheme",
",",
"host",
",",
"path",
")",
"\n",
"}"
] |
// baseURI returns the base string URI of a request according to RFC 5849
// 3.4.1.2. The scheme and host are lowercased, the port is dropped if it
// is 80 or 443, and the path minus query parameters is included.
|
[
"baseURI",
"returns",
"the",
"base",
"string",
"URI",
"of",
"a",
"request",
"according",
"to",
"RFC",
"5849",
"3",
".",
"4",
".",
"1",
".",
"2",
".",
"The",
"scheme",
"and",
"host",
"are",
"lowercased",
"the",
"port",
"is",
"dropped",
"if",
"it",
"is",
"80",
"or",
"443",
"and",
"the",
"path",
"minus",
"query",
"parameters",
"is",
"included",
"."
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/auther.go#L256-L270
|
13,581
|
dghubble/oauth1
|
examples/twitter-login.go
|
main
|
func main() {
// read credentials from environment variables
consumerKey := os.Getenv("TWITTER_CONSUMER_KEY")
consumerSecret := os.Getenv("TWITTER_CONSUMER_SECRET")
if consumerKey == "" || consumerSecret == "" {
log.Fatal("Required environment variable missing.")
}
config = oauth1.Config{
ConsumerKey: consumerKey,
ConsumerSecret: consumerSecret,
CallbackURL: outOfBand,
Endpoint: twauth.AuthorizeEndpoint,
}
requestToken, err := login()
if err != nil {
log.Fatalf("Request Token Phase: %s", err.Error())
}
accessToken, err := receivePIN(requestToken)
if err != nil {
log.Fatalf("Access Token Phase: %s", err.Error())
}
fmt.Println("Consumer was granted an access token to act on behalf of a user.")
fmt.Printf("token: %s\nsecret: %s\n", accessToken.Token, accessToken.TokenSecret)
}
|
go
|
func main() {
// read credentials from environment variables
consumerKey := os.Getenv("TWITTER_CONSUMER_KEY")
consumerSecret := os.Getenv("TWITTER_CONSUMER_SECRET")
if consumerKey == "" || consumerSecret == "" {
log.Fatal("Required environment variable missing.")
}
config = oauth1.Config{
ConsumerKey: consumerKey,
ConsumerSecret: consumerSecret,
CallbackURL: outOfBand,
Endpoint: twauth.AuthorizeEndpoint,
}
requestToken, err := login()
if err != nil {
log.Fatalf("Request Token Phase: %s", err.Error())
}
accessToken, err := receivePIN(requestToken)
if err != nil {
log.Fatalf("Access Token Phase: %s", err.Error())
}
fmt.Println("Consumer was granted an access token to act on behalf of a user.")
fmt.Printf("token: %s\nsecret: %s\n", accessToken.Token, accessToken.TokenSecret)
}
|
[
"func",
"main",
"(",
")",
"{",
"// read credentials from environment variables",
"consumerKey",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"consumerSecret",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"consumerKey",
"==",
"\"",
"\"",
"||",
"consumerSecret",
"==",
"\"",
"\"",
"{",
"log",
".",
"Fatal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"config",
"=",
"oauth1",
".",
"Config",
"{",
"ConsumerKey",
":",
"consumerKey",
",",
"ConsumerSecret",
":",
"consumerSecret",
",",
"CallbackURL",
":",
"outOfBand",
",",
"Endpoint",
":",
"twauth",
".",
"AuthorizeEndpoint",
",",
"}",
"\n\n",
"requestToken",
",",
"err",
":=",
"login",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"accessToken",
",",
"err",
":=",
"receivePIN",
"(",
"requestToken",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\\n",
"\"",
",",
"accessToken",
".",
"Token",
",",
"accessToken",
".",
"TokenSecret",
")",
"\n",
"}"
] |
// main performs Twitter PIN-based 3-legged OAuth 1 from the command line
|
[
"main",
"performs",
"Twitter",
"PIN",
"-",
"based",
"3",
"-",
"legged",
"OAuth",
"1",
"from",
"the",
"command",
"line"
] |
f9f59e0181d588c47e6af9dd5c277dcaaa9e786a
|
https://github.com/dghubble/oauth1/blob/f9f59e0181d588c47e6af9dd5c277dcaaa9e786a/examples/twitter-login.go#L17-L43
|
13,582
|
ikeikeikeike/go-sitemap-generator
|
stm/adapter_buffer.go
|
Bytes
|
func (adp *BufferAdapter) Bytes() [][]byte {
bufs := make([][]byte, len(adp.bufs))
for i, buf := range adp.bufs {
bufs[i] = buf.Bytes()
}
return bufs
}
|
go
|
func (adp *BufferAdapter) Bytes() [][]byte {
bufs := make([][]byte, len(adp.bufs))
for i, buf := range adp.bufs {
bufs[i] = buf.Bytes()
}
return bufs
}
|
[
"func",
"(",
"adp",
"*",
"BufferAdapter",
")",
"Bytes",
"(",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"bufs",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"len",
"(",
"adp",
".",
"bufs",
")",
")",
"\n\n",
"for",
"i",
",",
"buf",
":=",
"range",
"adp",
".",
"bufs",
"{",
"bufs",
"[",
"i",
"]",
"=",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"}",
"\n",
"return",
"bufs",
"\n",
"}"
] |
// Bytes gets written content.
|
[
"Bytes",
"gets",
"written",
"content",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/adapter_buffer.go#L17-L24
|
13,583
|
ikeikeikeike/go-sitemap-generator
|
stm/ping.go
|
PingSearchEngines
|
func PingSearchEngines(opts *Options, urls ...string) {
urls = append(urls, []string{
"http://www.google.com/webmasters/tools/ping?sitemap=%s",
"http://www.bing.com/webmaster/ping.aspx?siteMap=%s",
}...)
sitemapURL := opts.IndexLocation().URL()
bufs := len(urls)
does := make(chan string, bufs)
client := http.Client{Timeout: time.Duration(5 * time.Second)}
for _, url := range urls {
go func(baseurl string) {
url := fmt.Sprintf(baseurl, sitemapURL)
println("Ping now:", url)
resp, err := client.Get(url)
if err != nil {
does <- fmt.Sprintf("[E] Ping failed: %s (URL:%s)",
err, url)
return
}
defer resp.Body.Close()
does <- fmt.Sprintf("Successful ping of `%s`", url)
}(url)
}
for i := 0; i < bufs; i++ {
println(<-does)
}
}
|
go
|
func PingSearchEngines(opts *Options, urls ...string) {
urls = append(urls, []string{
"http://www.google.com/webmasters/tools/ping?sitemap=%s",
"http://www.bing.com/webmaster/ping.aspx?siteMap=%s",
}...)
sitemapURL := opts.IndexLocation().URL()
bufs := len(urls)
does := make(chan string, bufs)
client := http.Client{Timeout: time.Duration(5 * time.Second)}
for _, url := range urls {
go func(baseurl string) {
url := fmt.Sprintf(baseurl, sitemapURL)
println("Ping now:", url)
resp, err := client.Get(url)
if err != nil {
does <- fmt.Sprintf("[E] Ping failed: %s (URL:%s)",
err, url)
return
}
defer resp.Body.Close()
does <- fmt.Sprintf("Successful ping of `%s`", url)
}(url)
}
for i := 0; i < bufs; i++ {
println(<-does)
}
}
|
[
"func",
"PingSearchEngines",
"(",
"opts",
"*",
"Options",
",",
"urls",
"...",
"string",
")",
"{",
"urls",
"=",
"append",
"(",
"urls",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"}",
"...",
")",
"\n",
"sitemapURL",
":=",
"opts",
".",
"IndexLocation",
"(",
")",
".",
"URL",
"(",
")",
"\n\n",
"bufs",
":=",
"len",
"(",
"urls",
")",
"\n",
"does",
":=",
"make",
"(",
"chan",
"string",
",",
"bufs",
")",
"\n",
"client",
":=",
"http",
".",
"Client",
"{",
"Timeout",
":",
"time",
".",
"Duration",
"(",
"5",
"*",
"time",
".",
"Second",
")",
"}",
"\n\n",
"for",
"_",
",",
"url",
":=",
"range",
"urls",
"{",
"go",
"func",
"(",
"baseurl",
"string",
")",
"{",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"baseurl",
",",
"sitemapURL",
")",
"\n",
"println",
"(",
"\"",
"\"",
",",
"url",
")",
"\n\n",
"resp",
",",
"err",
":=",
"client",
".",
"Get",
"(",
"url",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"does",
"<-",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
",",
"url",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"does",
"<-",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"url",
")",
"\n",
"}",
"(",
"url",
")",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"bufs",
";",
"i",
"++",
"{",
"println",
"(",
"<-",
"does",
")",
"\n",
"}",
"\n",
"}"
] |
// PingSearchEngines requests some ping server from it calls Sitemap.PingSearchEngines.
|
[
"PingSearchEngines",
"requests",
"some",
"ping",
"server",
"from",
"it",
"calls",
"Sitemap",
".",
"PingSearchEngines",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/ping.go#L10-L41
|
13,584
|
ikeikeikeike/go-sitemap-generator
|
stm/builder_url.go
|
NewSitemapURL
|
func NewSitemapURL(opts *Options, url URL) (SitemapURL, error) {
smu := &sitemapURL{opts: opts, data: url}
err := smu.validate()
return smu, err
}
|
go
|
func NewSitemapURL(opts *Options, url URL) (SitemapURL, error) {
smu := &sitemapURL{opts: opts, data: url}
err := smu.validate()
return smu, err
}
|
[
"func",
"NewSitemapURL",
"(",
"opts",
"*",
"Options",
",",
"url",
"URL",
")",
"(",
"SitemapURL",
",",
"error",
")",
"{",
"smu",
":=",
"&",
"sitemapURL",
"{",
"opts",
":",
"opts",
",",
"data",
":",
"url",
"}",
"\n",
"err",
":=",
"smu",
".",
"validate",
"(",
")",
"\n",
"return",
"smu",
",",
"err",
"\n",
"}"
] |
// NewSitemapURL returns the created the SitemapURL's pointer
// and it validates URL types error.
|
[
"NewSitemapURL",
"returns",
"the",
"created",
"the",
"SitemapURL",
"s",
"pointer",
"and",
"it",
"validates",
"URL",
"types",
"error",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_url.go#L39-L43
|
13,585
|
ikeikeikeike/go-sitemap-generator
|
stm/builder_url.go
|
XML
|
func (su *sitemapURL) XML() []byte {
doc := etree.NewDocument()
url := doc.CreateElement("url")
SetBuilderElementValue(url, su.data.URLJoinBy("loc", "host", "loc"), "loc")
if _, ok := SetBuilderElementValue(url, su.data, "lastmod"); !ok {
lastmod := url.CreateElement("lastmod")
lastmod.SetText(time.Now().Format(time.RFC3339))
}
if _, ok := SetBuilderElementValue(url, su.data, "changefreq"); !ok {
changefreq := url.CreateElement("changefreq")
changefreq.SetText("weekly")
}
if _, ok := SetBuilderElementValue(url, su.data, "priority"); !ok {
priority := url.CreateElement("priority")
priority.SetText("0.5")
}
SetBuilderElementValue(url, su.data, "expires")
SetBuilderElementValue(url, su.data, "mobile")
SetBuilderElementValue(url, su.data, "news")
SetBuilderElementValue(url, su.data, "video")
SetBuilderElementValue(url, su.data, "image")
SetBuilderElementValue(url, su.data, "geo")
if su.opts.pretty {
doc.Indent(2)
}
buf := poolBuffer.Get()
doc.WriteTo(buf)
bytes := buf.Bytes()
poolBuffer.Put(buf)
return bytes
}
|
go
|
func (su *sitemapURL) XML() []byte {
doc := etree.NewDocument()
url := doc.CreateElement("url")
SetBuilderElementValue(url, su.data.URLJoinBy("loc", "host", "loc"), "loc")
if _, ok := SetBuilderElementValue(url, su.data, "lastmod"); !ok {
lastmod := url.CreateElement("lastmod")
lastmod.SetText(time.Now().Format(time.RFC3339))
}
if _, ok := SetBuilderElementValue(url, su.data, "changefreq"); !ok {
changefreq := url.CreateElement("changefreq")
changefreq.SetText("weekly")
}
if _, ok := SetBuilderElementValue(url, su.data, "priority"); !ok {
priority := url.CreateElement("priority")
priority.SetText("0.5")
}
SetBuilderElementValue(url, su.data, "expires")
SetBuilderElementValue(url, su.data, "mobile")
SetBuilderElementValue(url, su.data, "news")
SetBuilderElementValue(url, su.data, "video")
SetBuilderElementValue(url, su.data, "image")
SetBuilderElementValue(url, su.data, "geo")
if su.opts.pretty {
doc.Indent(2)
}
buf := poolBuffer.Get()
doc.WriteTo(buf)
bytes := buf.Bytes()
poolBuffer.Put(buf)
return bytes
}
|
[
"func",
"(",
"su",
"*",
"sitemapURL",
")",
"XML",
"(",
")",
"[",
"]",
"byte",
"{",
"doc",
":=",
"etree",
".",
"NewDocument",
"(",
")",
"\n",
"url",
":=",
"doc",
".",
"CreateElement",
"(",
"\"",
"\"",
")",
"\n\n",
"SetBuilderElementValue",
"(",
"url",
",",
"su",
".",
"data",
".",
"URLJoinBy",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"SetBuilderElementValue",
"(",
"url",
",",
"su",
".",
"data",
",",
"\"",
"\"",
")",
";",
"!",
"ok",
"{",
"lastmod",
":=",
"url",
".",
"CreateElement",
"(",
"\"",
"\"",
")",
"\n",
"lastmod",
".",
"SetText",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Format",
"(",
"time",
".",
"RFC3339",
")",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"SetBuilderElementValue",
"(",
"url",
",",
"su",
".",
"data",
",",
"\"",
"\"",
")",
";",
"!",
"ok",
"{",
"changefreq",
":=",
"url",
".",
"CreateElement",
"(",
"\"",
"\"",
")",
"\n",
"changefreq",
".",
"SetText",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"SetBuilderElementValue",
"(",
"url",
",",
"su",
".",
"data",
",",
"\"",
"\"",
")",
";",
"!",
"ok",
"{",
"priority",
":=",
"url",
".",
"CreateElement",
"(",
"\"",
"\"",
")",
"\n",
"priority",
".",
"SetText",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"SetBuilderElementValue",
"(",
"url",
",",
"su",
".",
"data",
",",
"\"",
"\"",
")",
"\n",
"SetBuilderElementValue",
"(",
"url",
",",
"su",
".",
"data",
",",
"\"",
"\"",
")",
"\n",
"SetBuilderElementValue",
"(",
"url",
",",
"su",
".",
"data",
",",
"\"",
"\"",
")",
"\n",
"SetBuilderElementValue",
"(",
"url",
",",
"su",
".",
"data",
",",
"\"",
"\"",
")",
"\n",
"SetBuilderElementValue",
"(",
"url",
",",
"su",
".",
"data",
",",
"\"",
"\"",
")",
"\n",
"SetBuilderElementValue",
"(",
"url",
",",
"su",
".",
"data",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"su",
".",
"opts",
".",
"pretty",
"{",
"doc",
".",
"Indent",
"(",
"2",
")",
"\n",
"}",
"\n",
"buf",
":=",
"poolBuffer",
".",
"Get",
"(",
")",
"\n",
"doc",
".",
"WriteTo",
"(",
"buf",
")",
"\n\n",
"bytes",
":=",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"poolBuffer",
".",
"Put",
"(",
"buf",
")",
"\n\n",
"return",
"bytes",
"\n",
"}"
] |
// XML is building xml.
|
[
"XML",
"is",
"building",
"xml",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_url.go#L95-L129
|
13,586
|
ikeikeikeike/go-sitemap-generator
|
stm/_adapter_s3.go
|
Write
|
func (adp *S3Adapter) Write(loc *Location, data []byte) {
var reader io.Reader = bytes.NewReader(data)
if GzipPtn.MatchString(loc.Filename()) {
var writer *io.PipeWriter
reader, writer = io.Pipe()
go func() {
gz := gzip.NewWriter(writer)
io.Copy(gz, bytes.NewReader(data))
gz.Close()
writer.Close()
}()
}
creds := adp.Creds
if creds == nil {
creds = credentials.NewEnvCredentials()
}
creds.Get()
sess := session.New(&aws.Config{
Credentials: creds, Region: &adp.Region})
uploader := s3manager.NewUploader(sess)
_, err := uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(adp.Bucket),
Key: aws.String(loc.PathInPublic()),
ACL: aws.String(adp.ACL),
Body: reader,
})
if err != nil {
log.Fatal("[F] S3 Upload file Error:", err)
}
}
|
go
|
func (adp *S3Adapter) Write(loc *Location, data []byte) {
var reader io.Reader = bytes.NewReader(data)
if GzipPtn.MatchString(loc.Filename()) {
var writer *io.PipeWriter
reader, writer = io.Pipe()
go func() {
gz := gzip.NewWriter(writer)
io.Copy(gz, bytes.NewReader(data))
gz.Close()
writer.Close()
}()
}
creds := adp.Creds
if creds == nil {
creds = credentials.NewEnvCredentials()
}
creds.Get()
sess := session.New(&aws.Config{
Credentials: creds, Region: &adp.Region})
uploader := s3manager.NewUploader(sess)
_, err := uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(adp.Bucket),
Key: aws.String(loc.PathInPublic()),
ACL: aws.String(adp.ACL),
Body: reader,
})
if err != nil {
log.Fatal("[F] S3 Upload file Error:", err)
}
}
|
[
"func",
"(",
"adp",
"*",
"S3Adapter",
")",
"Write",
"(",
"loc",
"*",
"Location",
",",
"data",
"[",
"]",
"byte",
")",
"{",
"var",
"reader",
"io",
".",
"Reader",
"=",
"bytes",
".",
"NewReader",
"(",
"data",
")",
"\n\n",
"if",
"GzipPtn",
".",
"MatchString",
"(",
"loc",
".",
"Filename",
"(",
")",
")",
"{",
"var",
"writer",
"*",
"io",
".",
"PipeWriter",
"\n\n",
"reader",
",",
"writer",
"=",
"io",
".",
"Pipe",
"(",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"gz",
":=",
"gzip",
".",
"NewWriter",
"(",
"writer",
")",
"\n",
"io",
".",
"Copy",
"(",
"gz",
",",
"bytes",
".",
"NewReader",
"(",
"data",
")",
")",
"\n\n",
"gz",
".",
"Close",
"(",
")",
"\n",
"writer",
".",
"Close",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n\n",
"creds",
":=",
"adp",
".",
"Creds",
"\n",
"if",
"creds",
"==",
"nil",
"{",
"creds",
"=",
"credentials",
".",
"NewEnvCredentials",
"(",
")",
"\n",
"}",
"\n",
"creds",
".",
"Get",
"(",
")",
"\n\n",
"sess",
":=",
"session",
".",
"New",
"(",
"&",
"aws",
".",
"Config",
"{",
"Credentials",
":",
"creds",
",",
"Region",
":",
"&",
"adp",
".",
"Region",
"}",
")",
"\n\n",
"uploader",
":=",
"s3manager",
".",
"NewUploader",
"(",
"sess",
")",
"\n",
"_",
",",
"err",
":=",
"uploader",
".",
"Upload",
"(",
"&",
"s3manager",
".",
"UploadInput",
"{",
"Bucket",
":",
"aws",
".",
"String",
"(",
"adp",
".",
"Bucket",
")",
",",
"Key",
":",
"aws",
".",
"String",
"(",
"loc",
".",
"PathInPublic",
"(",
")",
")",
",",
"ACL",
":",
"aws",
".",
"String",
"(",
"adp",
".",
"ACL",
")",
",",
"Body",
":",
"reader",
",",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// Write will create sitemap xml file into the s3.
|
[
"Write",
"will",
"create",
"sitemap",
"xml",
"file",
"into",
"the",
"s3",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/_adapter_s3.go#L30-L66
|
13,587
|
ikeikeikeike/go-sitemap-generator
|
stm/builder.go
|
URLJoinBy
|
func (u URL) URLJoinBy(key string, joins ...string) URL {
var values []string
for _, k := range joins {
var vals interface{}
for _, v := range u {
if v[0] == k {
vals = v[1]
break
}
}
values = append(values, fmt.Sprint(vals))
}
var index int
var v []interface{}
for index, v = range u {
if v[0] == key {
break
}
}
u[index][1] = URLJoin("", values...)
return u
}
|
go
|
func (u URL) URLJoinBy(key string, joins ...string) URL {
var values []string
for _, k := range joins {
var vals interface{}
for _, v := range u {
if v[0] == k {
vals = v[1]
break
}
}
values = append(values, fmt.Sprint(vals))
}
var index int
var v []interface{}
for index, v = range u {
if v[0] == key {
break
}
}
u[index][1] = URLJoin("", values...)
return u
}
|
[
"func",
"(",
"u",
"URL",
")",
"URLJoinBy",
"(",
"key",
"string",
",",
"joins",
"...",
"string",
")",
"URL",
"{",
"var",
"values",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"joins",
"{",
"var",
"vals",
"interface",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"u",
"{",
"if",
"v",
"[",
"0",
"]",
"==",
"k",
"{",
"vals",
"=",
"v",
"[",
"1",
"]",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"values",
"=",
"append",
"(",
"values",
",",
"fmt",
".",
"Sprint",
"(",
"vals",
")",
")",
"\n",
"}",
"\n",
"var",
"index",
"int",
"\n",
"var",
"v",
"[",
"]",
"interface",
"{",
"}",
"\n",
"for",
"index",
",",
"v",
"=",
"range",
"u",
"{",
"if",
"v",
"[",
"0",
"]",
"==",
"key",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"u",
"[",
"index",
"]",
"[",
"1",
"]",
"=",
"URLJoin",
"(",
"\"",
"\"",
",",
"values",
"...",
")",
"\n",
"return",
"u",
"\n",
"}"
] |
// URLJoinBy that's convenient.
|
[
"URLJoinBy",
"that",
"s",
"convenient",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder.go#L36-L57
|
13,588
|
ikeikeikeike/go-sitemap-generator
|
stm/sitemap.go
|
NewSitemap
|
func NewSitemap(maxProc int) *Sitemap {
log.SetFlags(log.LstdFlags | log.Llongfile)
if maxProc < 1 || maxProc > runtime.NumCPU() {
maxProc = runtime.NumCPU()
}
log.Printf("Max processors %d\n", maxProc)
runtime.GOMAXPROCS(maxProc)
sm := &Sitemap{
opts: NewOptions(),
}
return sm
}
|
go
|
func NewSitemap(maxProc int) *Sitemap {
log.SetFlags(log.LstdFlags | log.Llongfile)
if maxProc < 1 || maxProc > runtime.NumCPU() {
maxProc = runtime.NumCPU()
}
log.Printf("Max processors %d\n", maxProc)
runtime.GOMAXPROCS(maxProc)
sm := &Sitemap{
opts: NewOptions(),
}
return sm
}
|
[
"func",
"NewSitemap",
"(",
"maxProc",
"int",
")",
"*",
"Sitemap",
"{",
"log",
".",
"SetFlags",
"(",
"log",
".",
"LstdFlags",
"|",
"log",
".",
"Llongfile",
")",
"\n",
"if",
"maxProc",
"<",
"1",
"||",
"maxProc",
">",
"runtime",
".",
"NumCPU",
"(",
")",
"{",
"maxProc",
"=",
"runtime",
".",
"NumCPU",
"(",
")",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"maxProc",
")",
"\n",
"runtime",
".",
"GOMAXPROCS",
"(",
"maxProc",
")",
"\n\n",
"sm",
":=",
"&",
"Sitemap",
"{",
"opts",
":",
"NewOptions",
"(",
")",
",",
"}",
"\n",
"return",
"sm",
"\n",
"}"
] |
// NewSitemap returns the created the Sitemap's pointer
|
[
"NewSitemap",
"returns",
"the",
"created",
"the",
"Sitemap",
"s",
"pointer"
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/sitemap.go#L9-L21
|
13,589
|
ikeikeikeike/go-sitemap-generator
|
stm/sitemap.go
|
Create
|
func (sm *Sitemap) Create() *Sitemap {
sm.bldrs = NewBuilderIndexfile(sm.opts, sm.opts.IndexLocation())
return sm
}
|
go
|
func (sm *Sitemap) Create() *Sitemap {
sm.bldrs = NewBuilderIndexfile(sm.opts, sm.opts.IndexLocation())
return sm
}
|
[
"func",
"(",
"sm",
"*",
"Sitemap",
")",
"Create",
"(",
")",
"*",
"Sitemap",
"{",
"sm",
".",
"bldrs",
"=",
"NewBuilderIndexfile",
"(",
"sm",
".",
"opts",
",",
"sm",
".",
"opts",
".",
"IndexLocation",
"(",
")",
")",
"\n",
"return",
"sm",
"\n",
"}"
] |
// Create method must be that calls first this method in that before call to Add method on this struct.
|
[
"Create",
"method",
"must",
"be",
"that",
"calls",
"first",
"this",
"method",
"in",
"that",
"before",
"call",
"to",
"Add",
"method",
"on",
"this",
"struct",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/sitemap.go#L79-L82
|
13,590
|
ikeikeikeike/go-sitemap-generator
|
stm/sitemap.go
|
Add
|
func (sm *Sitemap) Add(url interface{}) *Sitemap {
if sm.bldr == nil {
sm.bldr = NewBuilderFile(sm.opts, sm.opts.Location())
}
err := sm.bldr.Add(url)
if err != nil {
if err.FullError() {
sm.Finalize()
return sm.Add(url)
}
}
return sm
}
|
go
|
func (sm *Sitemap) Add(url interface{}) *Sitemap {
if sm.bldr == nil {
sm.bldr = NewBuilderFile(sm.opts, sm.opts.Location())
}
err := sm.bldr.Add(url)
if err != nil {
if err.FullError() {
sm.Finalize()
return sm.Add(url)
}
}
return sm
}
|
[
"func",
"(",
"sm",
"*",
"Sitemap",
")",
"Add",
"(",
"url",
"interface",
"{",
"}",
")",
"*",
"Sitemap",
"{",
"if",
"sm",
".",
"bldr",
"==",
"nil",
"{",
"sm",
".",
"bldr",
"=",
"NewBuilderFile",
"(",
"sm",
".",
"opts",
",",
"sm",
".",
"opts",
".",
"Location",
"(",
")",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"sm",
".",
"bldr",
".",
"Add",
"(",
"url",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
".",
"FullError",
"(",
")",
"{",
"sm",
".",
"Finalize",
"(",
")",
"\n",
"return",
"sm",
".",
"Add",
"(",
"url",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"sm",
"\n",
"}"
] |
// Add Should call this after call to Create method on this struct.
|
[
"Add",
"Should",
"call",
"this",
"after",
"call",
"to",
"Create",
"method",
"on",
"this",
"struct",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/sitemap.go#L85-L99
|
13,591
|
ikeikeikeike/go-sitemap-generator
|
stm/sitemap.go
|
Finalize
|
func (sm *Sitemap) Finalize() *Sitemap {
sm.bldrs.Add(sm.bldr)
sm.bldrs.Write()
sm.bldr = nil
return sm
}
|
go
|
func (sm *Sitemap) Finalize() *Sitemap {
sm.bldrs.Add(sm.bldr)
sm.bldrs.Write()
sm.bldr = nil
return sm
}
|
[
"func",
"(",
"sm",
"*",
"Sitemap",
")",
"Finalize",
"(",
")",
"*",
"Sitemap",
"{",
"sm",
".",
"bldrs",
".",
"Add",
"(",
"sm",
".",
"bldr",
")",
"\n",
"sm",
".",
"bldrs",
".",
"Write",
"(",
")",
"\n",
"sm",
".",
"bldr",
"=",
"nil",
"\n",
"return",
"sm",
"\n",
"}"
] |
// Finalize writes sitemap and index files if it had some
// specific condition in BuilderFile struct.
|
[
"Finalize",
"writes",
"sitemap",
"and",
"index",
"files",
"if",
"it",
"had",
"some",
"specific",
"condition",
"in",
"BuilderFile",
"struct",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/sitemap.go#L108-L113
|
13,592
|
ikeikeikeike/go-sitemap-generator
|
stm/builder_indexfile.go
|
NewBuilderIndexfile
|
func NewBuilderIndexfile(opts *Options, loc *Location) *BuilderIndexfile {
return &BuilderIndexfile{opts: opts, loc: loc}
}
|
go
|
func NewBuilderIndexfile(opts *Options, loc *Location) *BuilderIndexfile {
return &BuilderIndexfile{opts: opts, loc: loc}
}
|
[
"func",
"NewBuilderIndexfile",
"(",
"opts",
"*",
"Options",
",",
"loc",
"*",
"Location",
")",
"*",
"BuilderIndexfile",
"{",
"return",
"&",
"BuilderIndexfile",
"{",
"opts",
":",
"opts",
",",
"loc",
":",
"loc",
"}",
"\n",
"}"
] |
// NewBuilderIndexfile returns the created the BuilderIndexfile's pointer
|
[
"NewBuilderIndexfile",
"returns",
"the",
"created",
"the",
"BuilderIndexfile",
"s",
"pointer"
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_indexfile.go#L6-L8
|
13,593
|
ikeikeikeike/go-sitemap-generator
|
stm/builder_indexfile.go
|
Add
|
func (b *BuilderIndexfile) Add(link interface{}) BuilderError {
bldr := link.(*BuilderFile)
bldr.Write()
smu := NewSitemapIndexURL(b.opts, URL{{"loc", bldr.loc.URL()}})
b.content = append(b.content, smu.XML()...)
b.totalcnt += bldr.linkcnt
b.linkcnt++
return nil
}
|
go
|
func (b *BuilderIndexfile) Add(link interface{}) BuilderError {
bldr := link.(*BuilderFile)
bldr.Write()
smu := NewSitemapIndexURL(b.opts, URL{{"loc", bldr.loc.URL()}})
b.content = append(b.content, smu.XML()...)
b.totalcnt += bldr.linkcnt
b.linkcnt++
return nil
}
|
[
"func",
"(",
"b",
"*",
"BuilderIndexfile",
")",
"Add",
"(",
"link",
"interface",
"{",
"}",
")",
"BuilderError",
"{",
"bldr",
":=",
"link",
".",
"(",
"*",
"BuilderFile",
")",
"\n",
"bldr",
".",
"Write",
"(",
")",
"\n\n",
"smu",
":=",
"NewSitemapIndexURL",
"(",
"b",
".",
"opts",
",",
"URL",
"{",
"{",
"\"",
"\"",
",",
"bldr",
".",
"loc",
".",
"URL",
"(",
")",
"}",
"}",
")",
"\n",
"b",
".",
"content",
"=",
"append",
"(",
"b",
".",
"content",
",",
"smu",
".",
"XML",
"(",
")",
"...",
")",
"\n\n",
"b",
".",
"totalcnt",
"+=",
"bldr",
".",
"linkcnt",
"\n",
"b",
".",
"linkcnt",
"++",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Add method joins old bytes with creates bytes by it calls from Sitemap.Finalize method.
|
[
"Add",
"method",
"joins",
"old",
"bytes",
"with",
"creates",
"bytes",
"by",
"it",
"calls",
"from",
"Sitemap",
".",
"Finalize",
"method",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_indexfile.go#L20-L30
|
13,594
|
ikeikeikeike/go-sitemap-generator
|
stm/builder_indexfile.go
|
XMLContent
|
func (b *BuilderIndexfile) XMLContent() []byte {
c := bytes.Join(bytes.Fields(IndexXMLHeader), []byte(" "))
c = append(append(c, b.Content()...), IndexXMLFooter...)
return c
}
|
go
|
func (b *BuilderIndexfile) XMLContent() []byte {
c := bytes.Join(bytes.Fields(IndexXMLHeader), []byte(" "))
c = append(append(c, b.Content()...), IndexXMLFooter...)
return c
}
|
[
"func",
"(",
"b",
"*",
"BuilderIndexfile",
")",
"XMLContent",
"(",
")",
"[",
"]",
"byte",
"{",
"c",
":=",
"bytes",
".",
"Join",
"(",
"bytes",
".",
"Fields",
"(",
"IndexXMLHeader",
")",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"c",
"=",
"append",
"(",
"append",
"(",
"c",
",",
"b",
".",
"Content",
"(",
")",
"...",
")",
",",
"IndexXMLFooter",
"...",
")",
"\n\n",
"return",
"c",
"\n",
"}"
] |
// XMLContent and BuilderFile.XMLContent share almost the same behavior.
|
[
"XMLContent",
"and",
"BuilderFile",
".",
"XMLContent",
"share",
"almost",
"the",
"same",
"behavior",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_indexfile.go#L38-L43
|
13,595
|
ikeikeikeike/go-sitemap-generator
|
stm/builder_indexfile.go
|
Write
|
func (b *BuilderIndexfile) Write() {
c := b.XMLContent()
b.loc.Write(c, b.linkcnt)
}
|
go
|
func (b *BuilderIndexfile) Write() {
c := b.XMLContent()
b.loc.Write(c, b.linkcnt)
}
|
[
"func",
"(",
"b",
"*",
"BuilderIndexfile",
")",
"Write",
"(",
")",
"{",
"c",
":=",
"b",
".",
"XMLContent",
"(",
")",
"\n\n",
"b",
".",
"loc",
".",
"Write",
"(",
"c",
",",
"b",
".",
"linkcnt",
")",
"\n",
"}"
] |
// Write and Builderfile.Write are almost the same behavior.
|
[
"Write",
"and",
"Builderfile",
".",
"Write",
"are",
"almost",
"the",
"same",
"behavior",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_indexfile.go#L46-L50
|
13,596
|
ikeikeikeike/go-sitemap-generator
|
stm/location.go
|
Directory
|
func (loc *Location) Directory() string {
return filepath.Join(
loc.opts.publicPath,
loc.opts.sitemapsPath,
)
}
|
go
|
func (loc *Location) Directory() string {
return filepath.Join(
loc.opts.publicPath,
loc.opts.sitemapsPath,
)
}
|
[
"func",
"(",
"loc",
"*",
"Location",
")",
"Directory",
"(",
")",
"string",
"{",
"return",
"filepath",
".",
"Join",
"(",
"loc",
".",
"opts",
".",
"publicPath",
",",
"loc",
".",
"opts",
".",
"sitemapsPath",
",",
")",
"\n",
"}"
] |
// Directory returns path to combine publicPath and sitemapsPath on file systems.
// It also indicates where sitemap files are.
|
[
"Directory",
"returns",
"path",
"to",
"combine",
"publicPath",
"and",
"sitemapsPath",
"on",
"file",
"systems",
".",
"It",
"also",
"indicates",
"where",
"sitemap",
"files",
"are",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/location.go#L30-L35
|
13,597
|
ikeikeikeike/go-sitemap-generator
|
stm/location.go
|
Path
|
func (loc *Location) Path() string {
return filepath.Join(
loc.opts.publicPath,
loc.opts.sitemapsPath,
loc.Filename(),
)
}
|
go
|
func (loc *Location) Path() string {
return filepath.Join(
loc.opts.publicPath,
loc.opts.sitemapsPath,
loc.Filename(),
)
}
|
[
"func",
"(",
"loc",
"*",
"Location",
")",
"Path",
"(",
")",
"string",
"{",
"return",
"filepath",
".",
"Join",
"(",
"loc",
".",
"opts",
".",
"publicPath",
",",
"loc",
".",
"opts",
".",
"sitemapsPath",
",",
"loc",
".",
"Filename",
"(",
")",
",",
")",
"\n",
"}"
] |
// Path returns path to combine publicPath, sitemapsPath and Filename on file systems.
// It also indicates where sitemap name is.
|
[
"Path",
"returns",
"path",
"to",
"combine",
"publicPath",
"sitemapsPath",
"and",
"Filename",
"on",
"file",
"systems",
".",
"It",
"also",
"indicates",
"where",
"sitemap",
"name",
"is",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/location.go#L39-L45
|
13,598
|
ikeikeikeike/go-sitemap-generator
|
stm/location.go
|
PathInPublic
|
func (loc *Location) PathInPublic() string {
return filepath.Join(
loc.opts.sitemapsPath,
loc.Filename(),
)
}
|
go
|
func (loc *Location) PathInPublic() string {
return filepath.Join(
loc.opts.sitemapsPath,
loc.Filename(),
)
}
|
[
"func",
"(",
"loc",
"*",
"Location",
")",
"PathInPublic",
"(",
")",
"string",
"{",
"return",
"filepath",
".",
"Join",
"(",
"loc",
".",
"opts",
".",
"sitemapsPath",
",",
"loc",
".",
"Filename",
"(",
")",
",",
")",
"\n",
"}"
] |
// PathInPublic returns path to combine sitemapsPath and Filename on website.
// It also indicates where url file path is.
|
[
"PathInPublic",
"returns",
"path",
"to",
"combine",
"sitemapsPath",
"and",
"Filename",
"on",
"website",
".",
"It",
"also",
"indicates",
"where",
"url",
"file",
"path",
"is",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/location.go#L49-L54
|
13,599
|
ikeikeikeike/go-sitemap-generator
|
stm/location.go
|
URL
|
func (loc *Location) URL() string {
base, _ := url.Parse(loc.opts.SitemapsHost())
for _, ref := range []string{
loc.opts.sitemapsPath + "/", loc.Filename(),
} {
base, _ = base.Parse(ref)
}
return base.String()
}
|
go
|
func (loc *Location) URL() string {
base, _ := url.Parse(loc.opts.SitemapsHost())
for _, ref := range []string{
loc.opts.sitemapsPath + "/", loc.Filename(),
} {
base, _ = base.Parse(ref)
}
return base.String()
}
|
[
"func",
"(",
"loc",
"*",
"Location",
")",
"URL",
"(",
")",
"string",
"{",
"base",
",",
"_",
":=",
"url",
".",
"Parse",
"(",
"loc",
".",
"opts",
".",
"SitemapsHost",
"(",
")",
")",
"\n\n",
"for",
"_",
",",
"ref",
":=",
"range",
"[",
"]",
"string",
"{",
"loc",
".",
"opts",
".",
"sitemapsPath",
"+",
"\"",
"\"",
",",
"loc",
".",
"Filename",
"(",
")",
",",
"}",
"{",
"base",
",",
"_",
"=",
"base",
".",
"Parse",
"(",
"ref",
")",
"\n",
"}",
"\n\n",
"return",
"base",
".",
"String",
"(",
")",
"\n",
"}"
] |
// URL returns path to combine SitemapsHost, sitemapsPath and
// Filename on website with it uses ResolveReference.
|
[
"URL",
"returns",
"path",
"to",
"combine",
"SitemapsHost",
"sitemapsPath",
"and",
"Filename",
"on",
"website",
"with",
"it",
"uses",
"ResolveReference",
"."
] |
c473e35ca5f0ce3059e2417fa95959adfd3428ce
|
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/location.go#L58-L68
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.